How to find tips about The Forgotten

Question: I would like to know how can I find out in the game how do I unlock The Forgotten?
I mean, I know there are plenty of places where they say how to unlock, but I would like to know if there is a way to find it playing.
The creator ( Edmund McMillen ) said

"You cheaters have no sense of adventure!"  "Just play the game and explore!"

But I have already played quite a bit and no clue so far, so I would appreciate a kick off.
Answer: The Forgotten is a secret character in BoI:Afterbirth+, only made available with the most recent "booster pack". As with several other secret characters in past expansions, there are almost no signs of his existence in-game. In fact, the only sign that there's something hidden at all is if manage to beat the first floor boss in under a minute, which will cause Mom to call out Isaac's name. Once you've done this, you need to explore (as Edmund mentioned in his tweet) the first floor very carefully and make note of any differences. Other than that, a typical player who doesn't already know about the Forgotten would probably never find out about it.
Comment: BTW, your previous answer was waaaaaay better, don't know why you changed it.
Comment: @carla I know it was way better. But I was downvoted because you specified in your question that the answer must come from in-game, and my answer came from outside sources. So after some discussion with others, I changed my answer to accommodate them.
Answer: You have to kill the first boss on the floor in 60 seconds and then after Mom yells "Isaac!" run back to the room you spawned in, drop a bomb in the middle, and it'll drop A Broken Shovel (which causes moms foot to drop down as long as you're holding it, until it's activated which pauses it for that room you're in) and then you have to proceed to kill Mom, pick up the negative, complete the Boss Rush, continue until you reach The Dark Room. From there, find an empty room with crumbling dirt in the center, use the shovel, and then boom. The Forgotten is unlocked.
Comment: The question is not asking for yet another set of instructions. It asks what hints there are in the game which help someone to figure out this sequence of steps on their own.

How to find tips about The Forgotten


An inequality that holds for every $\epsilon >0 $

Question:
For every $\epsilon > 0$ and $a,b \in \mathbb{R}$, we have
$$ |ab| \leq \epsilon a^2 + \frac{b^2}{4 \epsilon} $$

attempt:
I was thinking on using AM-GM inequality:
$$ \epsilon a^2 + \frac{b^2}{4 \epsilon} = \frac{ \frac{b^2}{2 \epsilon} + 2 \epsilon a^2 }{2} \geq \sqrt{ \frac{b^2}{2 \epsilon} (2 \epsilon a^2) } = \sqrt{a^2b^2} = |ab|$$
Is this corect? What other nice results can we derive from the inequality? thanks
Comment: Looks good to me.
Answer: Yes, it is correct. An equivalent way would be to use $2|xy|\leq x^2+y^2$ for $x=a\sqrt{\epsilon}$ and $y=\frac{b}{2\sqrt{\epsilon}}$


Using whitespace as a list separator

Question: I can successfully parse a comma-delimited list with dart-petitparser, but the same code fails when confronted with a space-delimited list:
class MyDefinition extends GrammarDefinition {
  @override
  Parser start() => throw UnsupportedError('Not yet.');

  Parser commas() =>
      ref0(number).separatedBy(char(','), includeSeparators: false);
  Parser spaces() =>
      ref0(number).separatedBy(char(' '), includeSeparators: false);
  Parser<int> number() => digit().plus().flatten().trim().map(int.parse);
}

  test('commas', () {
    var defn = MyDefinition();
    var parser = defn.build(start: defn.commas);
    expect(parser.parse("7,4,9,5").value, [7, 4, 9, 5]);  // PASS
  });

  test('spaces', () {
    var defn = MyDefinition();
    var parser = defn.build(start: defn.spaces);
    expect(parser.parse("7  4 9    5").value, [7, 4, 9, 5]); // FAIL
  });

It fails with the following:
  Expected: [7, 4, 9, 5]
    Actual: [7]
     Which: at location [1] is [7] which shorter than expected

What am I doing wrong? I've dug through a bunch of the example grammars, and didn't find a whitespace-delimited list anywhere.
Answer: The .trim() parser in your number parser is consuming whitespaces before and after the number. This prevents the space-delimited list parser from finding a separating whitespace.
I suggest to rewrite as:
Parser spaces() =>
    ref0(number).separatedBy(char(' ').plus(), includeSeparators: false);
//                           add this ^^^^^^^
Parser<int> number() =>
    digit().plus().flatten().map(int.parse);
//        remove trim, here ^

Using whitespace as a list separator


How to evaluate json member using variable ?

Question: Hi i've got a problem evaluating json. My goal is to insert json member value to a function variable, take a look at this
function func_load_session(svar){

var id = '';

$.getJSON('data/session.php?load='+svar, function(json){

  eval('id = json.'+svar);

});

return id;

}
this code i load session from php file that i've store beforehand. i store that session variable using dynamic var.
<?php
/*
* format ?var=[nama_var]&val=[nilai_nama_var]
*/

$var = $_GET['var'];
$val = $_GET['val'];
$load = $_GET['load'];

session_start();

if($var){
  $_SESSION["$var"] = $val;
  echo "Store SESSION[\"$var\"] = '".$_SESSION["$var"]."'";
}else if($load){
  echo $_SESSION["$load"];
}
?>

using firebug, i get expected response but i also received error
> uncaught exception: Syntax error, unrecognized expression: )

pointing at this
> eval('id = json.'+svar);

I wonder how to solve this
Answer: The correct code to use is:
id = json[svar];

You may also want to add alert(svar); to check that svar contains the correct value beforehand.
However, your code still won't work: the func_load_session function will return immediately, before the ajax call finishes and before the id variable is assigned.
what you need to do instead is to perform whatever you want to do with id from the ajax callback function:
function func_load_session(svar){
    $.getJSON('data/session.php?load='+svar, function(json){
        var id = json[svar];
        doSomethingWith(id);
    });
}

Answer: Also If I understand and have full part of your code Your json comes out like Store["var"]="var" ??
Does not appear valid json
I suggest using php function json_encode()
So php would be
 $var = $_GET['var'];
$val = $_GET['val'];
$load = $_GET['load'];

session_start();

if($var){
  $_SESSION["$var"] = $val;
  echo json_encode(array($var=>$_SESSION[$var])); // or something like that
}else if($load){
  echo json_encode(array('load'=>$_SESSION["$load"]);
}
?>


Does \W include the carriage return (\r) or line feed (\n) characters?

Question: IOWs, the negated form of the \w character class.  And should I expect different behavior from the different languages I'm using the regex in?
Comment: What do you mean IOWs? And I think the negated form of \w is \W..
Answer: Of course does \W include \r and \n.
\W is the negation of \w and \w contains letters, digits and connecting punctuation characters (like the underscore).
There are now 3 possibilities:

\w is ASCII based ==> [a-zA-Z0-9_]

\w is Unicode based ==> something like [\p{L}\p{Nd}\p{Pc}] means letters, digits from all languages and some more characters similar to the underscore See Unicode on regular-expressions.info

The flavour allows you to switch the behaviour of \w with a modifier.

But since newline characters are never included in \w they are in all cases included in \W
Comment: then 'split /[\W+\n+\r+]/, $multi_line_string;' should be equal to 'split /\W+/, $multi_line_string;'?  As I'm getting a different number of results from each of these.
Comment: This comes probably from `[\W+\n+\r+]`, you need to put the quantifier behind the character class, this way you add the + to the class. Compare `[\W\n\r]+` and `\W+`
Answer: \w is a short-hand for [a-zA-Z0-9_] so it will match only a-z (lower and upper), digits and underscore. The negated \w is \W will match everything besides \w
Read here more.
Basically there are 2 types of regex, POSIX and Perl. Theoretically posix regex should act same independent of programming language, but there are some known exceptions. See this thread for differences between Java and .NET (theoretically same posix, practically not same)
Are Java and C# regular expressions compatible?


Open Borders option not available

Question: I'm playing Endless Space (with Disharmony), and I'm slightly confused by the diplomacy mechanics. I've made peace with another faction (Horatio, if it matters; I'm Sophons myself). I'd like to offer them to open borders, but when the option is greyed out in the menu, and if I hover over it, I get

The terms you request cannot be fulfilled.

Now I know they also need to have researched that diplomacy option, but I know they've got the Relativistic Markets tech, because I gave it to them.
What other requirements are there to open borders with another faction?
Answer: I think that they need to discover at least one of your systems before you can get open borders with them.
I had the same problem and could only open borders when one of their scouts entered my system through a bordering wormhole.
Source: personal experience
Comment: I think I had come to the conclusion that I needed to wait a number of turns (7? 10?) after making peace before I was able to open borders, but I haven't played the game enough to confirm this (which is why I didn't get back to this post). Your observation sounds like a possibility, too, though. I'll keep an eye out for that!
Comment: I'm almost certain that @MartinBüttner is right, and you simply need to wait a few turns. Also, I don't think they don't need to have it researched. If you need to wait a few turns, it should show the number of turns left on the diplomacy screen when you are trying to talk to that empire. Something like "Peace (3 turns)" meaning you still have 3 turns after declaring peace before you can change your diplomatic status again.

Open Borders option not available


How to render mustache template locally

Question: I am trying to use mustache and jQuery to import a JSON and create a html template.
I have followed tutorials to get to this point, but nothing shows in the browser and there are no error messages.
HTML
div id="repeatcontent"/div

Script: I import mustache, greate the template script and then use javascript to import the JSON.

JSON
{
    "A_tutorials" : [
        {
             "Title" : "Binary",
        },
        {
             "Title" : "Clipping",
        }
     ]
}

There are no error messages, and the screen is completely blank. I have also used console.log to try and figure it out but it returns all the data I ask it for.
Comment: how are you serving this webpage? are you opening the file or using a webserver?
Comment: I'm just opening the file
Comment: You'll need to run a basic web server. You can't make `ajax` requests with the file protocol. Try using this: http://simbco.github.io/httpster/
Answer: Your mistakes are:

A_tutorials in json file while you use a_tutorials in js
Title in json file while you use title
your json file is incorrect. For instance this line
"Title" : "Binary",

must be changed with:
"Title" : "Binary"

You may test json online by yourself.
Mustache is case sensitive.

// $.getJSON('z.json', function(data) {
  var data = {
  "A_tutorials" : [
    {
      "Title" : "Binary"
    },
    {
      "Title" : "Clipping"
    }
  ]
};

  var template1 = $('#tutorials').html();
  var html = Mustache.to_html(template1, data);
  $('#repeatcontent').html(html);
// });

How to render mustache template locally


Get Specific Attribute from inline css

Question: i need to get specific attribute from inline CSS.

from above div i need to get transform:translate3d(0px,**222px**,0px);after getting previous  i need to get the **222px** value and store in a variable  using j query how to go forward.
Answer: I don't think you can really get that style?
Neither jQuery nor element.style seems to return the translate value set in the CSS like that, so the next option would be to get the elements style attribute as a string, and manipulate that to get the transform style, then split that up to get the middle value:
var style = document.getElementsByClassName('ABC')[0].getAttribute('style');
var trans = style.split('transform').pop().split(')').shift().split(',')[1].trim();

FIDDLE

Get Specific Attribute from inline css


Passing non-interleaved data to glBufferStorage without using glBufferSubData

Question: I would like to use glBufferStorage to load data once into the vertex buffer. However sometimes I want to pass non-interleaved data from separate arrays like shown below.
glBufferStorage(GL_ARRAY_BUFFER, sizeVerts+sizeUVs, 0, 0);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeVerts, verts.data());
glBufferSubData(GL_ARRAY_BUFFER, sizeVerts, sizeUVs, uvs.data());

Because of this I have to specify GL_DYNAMIC_STORAGE_BIT flag, despite loading the data once, and thus use a less performant alternative.
Are there any workarounds to this problem?
Or does using GL_DYNAMIC_STORAGE_BIT not lead to a significant performance hit, and should I just use it despite loading data once?
Answer: You can put your data in one piece of memory on the CPU and then copy it in with glBufferStorage. It's just a bunch of memcpy calls.
With C++20's std::span (or the GSL version), you can even make a function to build byte-spans from any number of vector<T>s (even of different types) and do the building and memcpy's manually.

#include <vector>
#include <concepts>
#include <ranges>
#include
#include <cstdint>
#include <cstring>

using byte_range = std::span<std::byte const, std::dynamic_extent>;

template<std::ranges::contiguous_range Rng>
byte_range get_span(Rng const &rng)
{
    auto sp = std::span(rng);
    return std::as_bytes(sp);
}

template<std::ranges::contiguous_range ...Rngs>
    requires (sizeof...(Rngs) > 0)
GLuint upload_to_buffer(Rngs const &...rngs)
{
    std::array<byte_range, sizeof...(rngs)> spans =
        {get_span(rngs)...};

    std::size_t buffer_size = 0;
    for(auto const& sp : spans)
        buffer_size += sp.size();

    std::vector<std::byte> byte_buff(buffer_size);

    std::size_t offset = 0;
    for(auto const& sp : spans)
    {
        std::memcpy(&byte_buff[offset], sp.data(), sp.size());
    }

    GLuint buff;
    glCreateBuffer(&buff, 1);
    glNamedBufferStorage(buff, byte_buff.size(), byte_buff.data(), 0);
    return buff;
}

```

Comment: The answer is very helpful. But the code example feels way too complicated, maybe needlessly so.
Comment: @LennyWhite: Outside of some of the newer features of C++, what is complicated about it? You get the range of bytes for each buffer, build a big buffer, copy all of the byte ranges into that buffer, and send it to OpenGL.


Cutting out and re-constructing string in javascript with substring

Question: I'm struggling with the logic...suppose I have this string:
var s = 'foo bar
blah blah blah';

What I want to do is cut out the sources of each image and reconstruct the "s" string without the image sources.  Here's what I have so far but it's wrong...
numImgs = s.match(/ 0) {
        var imgSrc, startSrc = 0, endSrc = 0;
        for (var i = 0; i < numImgs; i++) {
            (function() {
                startSrc = s.indexOf('<img src="', endSrc);
                endSrc = s.indexOf('"', startSrc + 10);
                imgSrc = s.substring(startSrc+10, endSrc);
                s = s.substring(0, startSrc+10) + s.substring(endSrc, s.length);
                console.log("start: " + startSrc + " end: " + endSrc + "\n" + s);
            })(i);
        }
    }

I understand I can't use s.indexOf('<img src="', endSrc) for the start because second time the "s" string has changed and endSrc is way off.  How can I achieve what I'm trying to do here, to get the second, third, fourth img?
The result would be:
var s = 'foo barblah blah blah';

SOLUTION: this is probably a very dirty way of doing this but for what I have, I added startSrc = s.indexOf('<img src="data'); so it will find the first occurrance of a src which is not empty.
Answer: var s = 'foo barblah blah blah';

var srcArray = [];
var result = s.match(/()/gi);

for(var i = 0; i < result.length; i++){
    var src = result[i].match(/src=\"(.+?)\"/);
    srcArray.push(src[1]);
}
s = s.replace(/()/gi,'');
console.log(srcArray, s); //["www.foo.bar", "www.blah.blah"] "foo barblah blah blah"

Comment: Edited my answer. Now the src attributes stored in an array
Comment: That would work if I didn't need to get the image sources before...but I need them (base64 image src which need to be uploaded...big files)


How do I reinstall Ubuntu?

Question: I have Ubuntu 10.04 on my computer, with Windows 7 next to it. Instead of upgrading to 10.10, I feel like doing a clean install. However, I don't want to erase my Windows, even though I barely ever use it. My question is: how would I remove Ubuntu 10.04 from my drive and install Ubuntu 10.10 in place, without losing any space or anything, or losing Windows 7?
Comment: Hey, have to resolved your problem yet?
Comment: Yes, I have. I used a combination of all methods, and it's perfect. Thanks everyone!
Answer: This option actually exists in the installer. When it comes to the partitioning section of the installation, there is an option to overwrite an existing Linux distro and replace it with the new one. Just select that and you're on your way.
Comment: During the partitioning stage just choose 'manual'/'advanced' partitioning, select your partition for installation and do _not_ tick 'format'. It will erase all of /bin, /usr, /var and so on, but not /home.
Comment: @Lyrositor: Yes, checking "format" would completely remove the old installation (including /home, assuming you didn't create separate /home partition) and reinstall Ubuntu. (I'm not sure about "Use Entire Partition" (it probably does just that), but note that there is absolutely nothing hard in using the "advanced" tool for this either.)
Comment: Thanks, I'll do that. But where in the installer is that option?
Comment: I want to get rid of my /home. I want to start all over again. If I tick "format" will it do that?
Also, I saw from the new 10.10 installer that when you have the "easy" partitioning tool, you can select the option "Use Entire Partition". If I select my old Ubuntu and then click that, will it effectively erase 10.10 and replace it with 10.10? Sounds a lot easier that way.
Answer: First, make a back up of Windows to an external device such as a DVD or USB hard drive, if you have not already done so.  You'll be installing an operating system, which has inherent risks, and I'd hate for you to lose important data.
Start up the Ubuntu 10.10 desktop CD installer, and click through all of the steps until you get to partitioning.  Select advanced partitioning and continue to the next page.
Now, select the partition that was created for Ubuntu 10.04.  It will be an ext4 filesystem, and, if you don't have a recovery partition for Windows, it is likely to be /dev/sda2.  Hit edit, then select / for the mountpoint and make sure the format button is not checked.  Dismiss the dialog and press next.
You should see a warning that continuing will remove the contents of system directories, but will preserve the contents of /home.  Press continue and complete the rest of the installation.
Answer: But if you wanted to know the manual way of doing it, you would just reformat your linux partition, and then install to it. That's why it is recommended to keep personal data (e.g. home directory) on separate partition.

How do I reinstall Ubuntu?


mvc4 how to make a function in controller with null able parameter

Question: I have a login form and if the user enter correct login information,he/she will go into my website.
However, if he/she enters not correct information, i want to return him to the same page that he/she enters his/her information with the fields filed in already.
I mean, i want to the page where he could see his/her username and password that he/she has entered in the fields, not to start typing from the zero.
I tried that
public ActionResult(Login ?login = null){}

so i call this function when i want to show the login page with null parameter. and i call it when the user enters a not correct informatoin. However, i go exception

The type 'Login' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable'

have you help me in this problem please?
if there is second solution tell me, but please not about member ship and these guys because i have my own way to asure the users
Edit
when the user press on login button, i go to this controller function
public ActionResult Index()
        {
            return View();
        }

when he submit his/her form in login page i go to this function
public ActionResult Login(Login login) {}

i want in the login function above, if the user enters not correct informatoin to return to the index page where he/she saw the data that he/she has submitted
Comment: "Login" seems to be a class so it's already nullable
Comment: @jim `login` is my model class in model forlder
Answer: Create a new MVC Internet application (a VS template) and see how "Model.IsValid" is used inside controllers. This is the most common approach. When some model comes into controller, you check if it's valid (redirect to Homepage or whatever), otherwise you just show the same view providing it with this model that is already (partially) poplated by user.
This is the one:
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {
        // do things
        return RedirectToAction("Index", "Home");
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

Model errors can occur during implicit model binding (say if some required properties not present in incoming data) or be set explicitly in the code by using of ModelState.AddModelError. Putting html validators on the page makes user know what kind of constraints are applied to the field value.
Comment: +1 to you, i apprecitae your help and support and efforst, and really i am sorry cos i can't select just one answer, i really thank you very very very very very much and please forgive me to not select ur answer, i loke you
Comment: what is returneURL? please?
Comment: @user2208349 when you use FormAuthentication mechanism (ASP.NET integrated) you specify Login page url in web.config file (search for "loginUrl" string). When anonymous user tries to open url that is only allowed for authenticated users (see "AuthorizationAttribute") then server automatically redirects user to specified login page. By default its url is ~/Account/LogOn (see web.config) and in terms of MVC routing this means Account controller, LogOn action.
Comment: @user2208349 ...When redirecting, server also adds an extra parameter - returnUrl so your controller action can know the initially accessed page Url and is able to redirect user back in case of successfull login.
Comment: that is compeletely not my qestion, i want to return to the login page with information already field in when the users enters not correct informaton
Comment: @user2208349 the answer to THIS question is above comments. My comments were about "what is returneURL". Create a new default MVC Internet Application and see how things like you want are done.
Comment: @user2208349 the cycle: 1. user enters information and pushes button 2. Values go to server and are bound to view model 3. Controller action tests if view model is OK or not 4. If not, return the same login view supplied with model that came from user.
Comment: As Index action doesnt have params so you aren't able to pass any data into there (im not talking of controller-scoped variables), but the Login action canreturn any view you want with the incorrect user's data. I would use Login() and [HttpPost]Login(Login login) actions.
Answer: You just use this:
// [HttpPost] and any other attributes necessary
public ActionResult YourAction(Login login)
{
    ...
}

But considering general idea of the logic you want to achieve, I would say that you don't need the login to be null.
The action just does what it does: it processes the login (after a postback done on client part). So, it always must contain any data.
If you want to redirect after some checks of login info, you receive them, check and then do RedirectToAction(...) or any other type of redirection you want.
Then in view you would have (for Index action, for instance):
@model Login

@using(Html.BeginForm("YourAction", "home"))
{
        @Html.LabelFor(model => model.UserName)
        @Html.TextBoxFor(model => model.UserName)
        @Html.ValidationMessageFor(model => model.UserName)

        @Html.LabelFor(model => model.Password)
        @Html.PasswordFor(model => model.Password)
        @Html.ValidationMessageFor(model => model.Password)

        <input type="submit" value="go"/>
}

EDIT:
Just imagine that your YourAction is Login:
[HttpGet]
public ActionResult Login()
{
    // this one is called on the first entering of login and shows the form to fill
    return View(new Login()); // for instance
}

[HttpPost]
public ActionResult Login(Login login)
{
    // this one is called on PostBack after filling the form and pressing 'Login' (or something) button
    // todo:  here you to validate the login info
    // and then either do your redirect to some other page or showing the login form again

    // if(something)
    //    return RedirectToAction(...);

    return View(login);
}

Comment: but in your way when the user first ask for the login page, it shows with the error message that his infroation is not correct
Comment: Login page must be created with another action: for instance, `[HttpPost]public ActionResult Login()` without any parameters and for GET HTTP method. Then you render some form, which would send the postback to YourAction (might be also Login one (another method), but with a parameter and a POST HTTP method).
Comment: in your edit answer you said this `either do your redirect to some other page or showing the login` so what should i code to redirect to my page that contains the already fieled filds?
Comment: all the majec comes from making the two methos as the same name
Comment: Yes. And don't forget to use Post/Get specification attributes to prevent diffirent negative situations.


vue.js reuse of 3d.js

Question:
New to Vue.js (using version 2).
I would like to reuse the bubble-chart project in vue js.
It has allot of goodies inside like 3D.js and some jQuery but it's ok for me for now (not being Vue.js).
I understand that one way is to create parallel component of Vue.js from scratch.
What is the correct way to import/reuse none Vue projects?
Answer: Here is an example of JQuery date picker wrapped in vue component. This way you created reusable component where you can use 'props' for passing values from rest of vue project. Same thing you can do for bubble chart. This is the easiest implementation for your needs.
<code> <template>
    <input class="datepicker-input btn-gray-gredient" type="text" readonly/>
</template>
<script>

    export default {
        props: ['value'],
        mounted: function () {
            /**
             * Getting today's date
             */
            var today = new Date();
            today.setHours(0, 0, 0, 0);
            today = ((today.getDate() < 10) ? ('0' + today.getDate()) : today.getDate()) + '-' + ((today.getMonth() + 1) < 10 ? '0' + (today.getMonth() + 1) : (today.getMonth() + 1)) + '-' + today.getFullYear();
            /**
             * JQuery wrapped date picker
             */
            var self = this;
            $('.datepicker-input').on('click', function() {
                $('.fa-calendar').click();
            });

            /**
             * Setting up datepicker with default properties
             */
            $(self.$el)
                .datepicker({ value: today, iconsLibrary: 'fontawesome', format: 'dd-mm-yyyy' }) // init datepicker
                .trigger('change')
                .on('change', function () { // emit event on change.
                    self.$emit('input', this.value);
                });
        },
        watch: {
            value: function (value) {
                $(this.$el).val(value);
            }
        },
        destroyed: function () {
            $(this.$el).datepicker('destroy');
        }
    }
</script>
</code>

vue.js reuse of 3d.js


I want to run a bash script when an scp connection ends

Question: I am building a server that accepts scp connections and then adds the files that have just been transferred to a git repository.  I have tested the .bash_logout script, and it does not execute when the scpd session ends.  Is there another hook that I can use to run a script when scpd exits?
Alternatively, I can use at(1) command in the .bashrc file to execute the script that does the work, say, 5 minutes after.  I think, but I am not sure, that I need not worry about races because I think the files will come in infrequently.
Thank you
Answer: If scp always copies to the same place then this approach way work.
It has the added bonus that copy via samba, CIFS etc... will work too.
Also, you could spawn the inotifywait shell script from the then nohup it so it executes after the shell exits. The other would be to start a process at boot time to monitor the directory using inotifywait and use that to add to git.
Of course, you could simply setup a git server, but I assume there is a good reason that is not desirable.
inotifywait
inotifywait can trigger upon changes to a directory.
It can wait for changes,additions,moves in a directory
<code>  if inotifywait -e modify -e move -e create -r somedirectory ; then
   #  wait wile more activity occurs, up to 30 seconds
   while inotifywait -e modify -e move -e create -t 30 -r somedirectory ; do echo "waiting" ; done
   # do git add with the new files in somedirectory

   # delete the files from somedirectory

 fi
</code>
Answer: You could run this script as a cronjob:
<code>#!/bin/sh
targetdir="whereever your files are going"
[ "$targetdir" -nt "~/flag" ] && your_script.sh
touch ~/flag
</code>


Redirect to packaged HTML file

Question: When using browser.webRequest.onBeforeRequest, I would like to return a redirect to an HTML file packaged in the extension.
I have the extension activated as a temporary extension.
Example of what I'm trying to accomplish:
let pattern = "https://developer.mozilla.org/*";
let targetUrl = "/src/index.html";

function redirect(requestDetails) {
  return {
    redirectUrl: targetUrl
  };
}

browser.webRequest.onBeforeRequest.addListener(
  redirect,
  {urls: [pattern]},
  ["blocking"]
);

If I use an URL like https://example.com, it works. I also tried to use tabs.update("/src/test.html") inside the redirect function, but no luck.
Do I need some permission for this?
Comment: use browser.runtime.getURL('src/index.html') and declare it in `web_accessible_resources`.
Comment: Sorry for the late reply, but it worked! I'll answer my question using your comment, but if you want the solution, you can answer it and I will mark it as the solution.
Answer: Refer to this comment by wOxxOm for the solution.

Redirect to packaged HTML file


can ubuntustudio compose music (e.g. play guitar then auto write notation note)

Question: can ubuntustudio software can compose music(e.g. play guitar via audio input then auto write notation note)?  Or is there any software can compose music in Linux?
Answer: You may compose with Tuxguitar and MuseScore for example, but these are for writing notation, then playing them as MIDI. However you have to write the notation yourself, they won't do it for you.
For guitars I recommend Tuxgitar because it has tablatures, but for everything else I recommend MuseScore.
Both software is readily available in Ubuntu, you just have to install it through the package manager.


Why do top season crusaders on 4-person team leaderboards have dexterity and intelligence items?

Question: As season 3 is drawing to a close, I am looking forward to season 4 and starting a new character - and was considering crusader. When looking at the 4-person team leaderboards, I noticed that the top crusaders had many Dexterity and Intelligence items.
Since the crusaders seem to be building for all out crowd control and defense stats (cd reduction, resource cost reduction, armor), I can understand maybe some int stacking for the all-resistance, but the dexterity stat is confusing to me - wouldn't it be better to have strength since they will gain some damage from it, even if its just a little?
I would imagine by now they would have found strength items which could be competitive with the dexterity items they have in terms of defensive stats, and I double-checked to make sure dexterity still only gives armor (not dodge, like it used too)
Why do these crusaders have Dexterity on their armor?
Comment: Do you mean gems? Because rolling anything other than str/vit on crusader items is next to impossible.
Comment: @Chippies No, I mean the stat on the armor. You can verify yourself by going into Diablo3 and checking out the leaderboard, but it is also [similar to the items for the crusader in this link.](http://www.diabloprogress.com/hero/karti-1837/ShinyShield/61116897)
Comment: Pretty sure those items are used because of their legendary effects and/or the 8% cooldown reduction until they find the same items with str on them. The 8% (highest possible roll, afaik) cooldown reduction and the legendary effects are more important to their build than the couple hundred str they lose by using non-str gear.
Answer: In the Greater Rifts that top leader board players are running, every enemy will kill you very very quickly. To counter this, they dedicate 1 player out of 4 to crowd controlling the enemy by stunning, freezing, fearing etc. This Player will forgo the ability to cause damage in the attempt to prevent their team mates from taking damage.
The builds that you are seeing are known as Zero Damage Per Second or ZDPS for short.
If you were to look at the Crusader solo Greater Rift leader boards you would see very different set ups. This is the number 1 Crusader on the 4 player leader boards and this is the number 1 Crusader on the solo leader boards, notice that the 4 player Crusader has 3194 strength and 2768 dexterity whereas the solo Crusader has 13760 strength and only 77 dexterity.
This is because 100% of your dexterity and strength is added to your Armor with every 10 points of intelligence adding 1 point to All Resistance.
Since they are not doing any damage, their main stat (strength) is interchangeable with dexterity as it provides the same bonus. This means that the priority for an item is how well rolled the other attributes such as cooldown and resource reduction are and not on the type of main stat it has. Also since they will usually be in a group with high dps classes that have dexterity as their main stat (Demon Hunters, monks) there is a higher chance for an item to drop with dexterity.
Their role is to keep the others alive, this is why they prioritise these stats.
Comment: As far as I know, strength also gives armor (at the same rate as dexterity), so there is no need to prioritize dexterity over strength. However, since both essentially give the same benefit, a dexterity item with great rolls is better than a strength item with average rolls. Considering how many demon hunters and/or pull monks may be involved, there will be a lot of dexterity gear dropping. But if two items were exactly the same, the strength one would be marginally better for a crusader.
Comment: @OrcJMR They need armor to be able to tank a lot more damage so that they can stay alive longer, in turn providing CC for the _others_ in the group, which is keeping them alive. It would be pointles to have the 'tank' die instantly. Also thanks Svjohn you're correct i'll edit that in.
Comment: If "their role is to keep others alive" it is absolutely irrelevant how much armor *they* have, isn't it?
Comment: Strictly speaking, yes, a tank should be able to withstand blows, but ZDPS classes are not just tanks, they are valued for their crowd control and buffs. Also, WizLiz is wrong about 30% - Dexterity is identical to Strength defense-wise. Also, he never stated that only 30% of *Strength* is added to Armor.
Comment: I have worded my yesterday's comment very wrong considering what I wanted to convey :-) What I meant is - the amount of Armor (not even only Strength) a ZDPS character has is irrelevant to their effectiveness. The amount of Tougness is important, but swapping Strength to Dexterity changes nothing, and swapping to Intelligence can even be beneficial to Toughness (if character's Armor is more than ten times their Resistance, trading Str/Dex to Int would increase Toughness)
Comment: Although not releant to your point, Orc JMR pointed in my now deleted answer that since patch 2.1, 100% of dexterity is added to your armor and not 30%. So 1 point in dext = 1 point in armor.
Comment: @OrcJMR On your newly worded comment I agree with you, armor is not everything. I was just using it as an example so to avoid repeating the same spiel about intelligence, as it all adds to your overall toughness! If either of you wish to continue I suggest we get to chat :)


Dim (NEARLY blank) laptop screen, secondary screen works - why?

Question: My laptop screen is (almost) black while my secondary screen is fine. I believe it to be backlight / brightness related.
Problem description

it starts when I start the laptop
system loads and works fine, just screen has problems
I can see the screen though very faintly / dimly - it's hard to see anything which ain't very white e.g. starting screen has big Thinkpad logo in white, large font - I can see it, though very dimly
second screen works very well

Official backligtht debugging:

using acpi setting as prescribed there for Thinkpads didn't help
I can see an entry in /sys/class/backlight/ and it changes when I press hotkeys for brightness (current backlight power for instance goes up or down)
acpi-off didn't helpm neither did acpi_backlight=vendor

Hardware data
Laptop is Thinkpad Edge with glossy screen. 4 processors, 2 cores, exemplary CPU data from cat /proc/cpuinfo reports Genuine Intel i5 (M 480  @ 2.67GHz).
OS is Ubuntu Lucid, 10.04 LTS, 64-bit, with Linux generic kernel (2.6.32-44) and GNOME 2.32.2 (though I doubt there lies the problem).
$ lspci | grep VGA
01:00.0 VGA compatible controller: ATI Technologies Inc M92 [Mobility Radeon HD 4500 Series]

$ lshw -C display
*-display
   description: VGA compatible controller
   product: M92 [Mobility Radeon HD 4500 Series]
   vendor: ATI Technologies Inc
   physical id: 0
   bus info: pci@0000:01:00.0
   version: 00
   width: 32 bits
   clock: 33MHz
   capabilities: pm pciexpress msi bus_master cap_list rom
   configuration: driver=radeon latency=0
   resources: irq:33 memory:c0000000-dfffffff(prefetchable) ioport:2000(size=256) memory:f0300000-f030ffff memory:f0320000-f033ffff(prefetchable)

Driver
I was NOT running any proprietary drivers, just checked with "Hardware drivers". There is one for ATI that is suggested there, though I didn't need it so far.
UPDATE: changing the driver to proprietary one (ATI/AMD FGLRX) didn't help.
Tried and failed
Resetting / running on power or battery / charging / getting rid of static electricity / warming up _doesn't help_
This is NOT a blank-screen problem, at least it isn't following official Ubuntu black-screen diagnostics - I can see my screen, though barely.
What I will try next:
    - check last updates I've made
    - IIRC I am running on nomodeset already, but will verify this
Any ideas how to proceed best? What is most probable cause?
Comment: What happens if you disconnect the secondary screen ?
Comment: Thanks, Suhaib. Unfortunately - nothing. I just lose a screen that displays things well. No change on laptop screen - it stays near-black as it was. I plugged other monitor to see if it's a graphics problem or just my laptop screen problem - originally I worked only on my laptop, without secondary monitor.
Comment: please provide some details on your system: platform type (desktop / laptop), computer model, graphics card and drivers installed etc., in addition, it may help to see the output of `lshw -C display`.
Comment: Thanks Eliran for spotting this. Certainly. I've edited my question with both hardware/driver data and with my new findings.
Answer: In the end it was a backlight problem. What led me to it, was that if I had a strong light source pointed at the screen - I could see well what was on it.
I took the laptop to service and it was fixed - backlight connection was loose.


How can I connect a WIFI thermostat to a Honeywell R845A switching relay?

Question:
I'm trying to install a wifi thermostat and it won't power up. The old thermo was battery operated 2 wire but there were spare wires. At the R845A relay, red and white whites connect to terminals 5 and 6, red and white also connect to the 2 T terminals. I ran a jumper connecting the blue (common). In the relay, I get 24 volts across 5-6. and 24v between the white wire and common. 0v between red and common. At the thermostats I get 4-10 v between red and common,14v white-common, and 24v r-w.
As I say the thermo doesn't work and any help will be greatly appreciated.
Comment: Did it work with connecting common to rear of transformer, or did you have to get different relay?
Answer: According to this document, the internal wiring of that relay looks like this.

It sounds like it's connected something like this.

When the thermostat calls for heat, the T terminals are connected through the thermostat. This causes the relay to energize, which closes the contact between terminals 5 and 6 (It also closes a contact between 3 and 4). When terminals 5 and 6 are connected, the heater, pump, valve, etc. turns on.

Because the transformer is built into this device, it's going to be difficult (possibly impossible) to connect a C wire. You'd have to connect the wire to the other side of the transformer, something like this.

You'll also have to check with the manufacturer, to determine if the transformer can handle the additional load of the thermostat.

You might want to contact Honeywell, to see if they offer a similar relay that exposes the C terminal.  If they do, you could replace this device with the one with the proper terminals.

What you're trying to do, is something like this.

Which as you can see in the diagram, is not going to work so well.
Comment: I was able to get this working over the weekend. I removed the board and soldered a jumper wire to the back side of the transformer as indicated in the fourth image above.  I connected the C wire to the jumper wire using a wirenut.  I have photos but unfortunately I don't have 10 reputation points so I cannot post them.
Comment: @user24601 FYI I happen to be the hypothetical person trying to do the same thing :)  Though your description in the comment may be enough to go no. Thanks
Comment: @AlmostSurely I did what is shown in the other answer (https://diy.stackexchange.com/a/153387/41781) - and its worked great since then.
Comment: @user24601 You should post your photos, and the steps you took, as an answer.  It could help somebody in the future, who is in the same situation.
Comment: I would love to.  However, it appears I'm prevented from answering this question because it is protected and I do not have enough reputation.  I could post a new question, reference this one, and answer that.  Do you have other ideas?  Thanks.
Comment: @user24601 You could try answering some other questions on the site, until you gain enough reputation to answer this one.  An up vote on an answer is worth 10 reputation points, so you'll only have to get one up vote. I thought you were the original owner of this question, but I guess I was mistaken.
Comment: @DaveInCaz Have you had any issues since doing this?
Answer: I had the same problem with the same model switching relay and following the encouraging description given in a comment on Tester101's answer, made the same modification to expose a connection which provides the 'C' terminal.
This is shown in the photo below. This is a view of the rear of the modified back of the circuit board (not normally visible without disassembly):

The green insulated wire is the addition, which now provides the 'C' connection. It is connected to the second terminal of the 'secondary' side of the transformer so that it always provides the necessary return path for the low voltage circuit. Conveniently it fit through an existing opening in the board, passing by the contactor.
(Yeah, my soldering is kind of ugly).
The transformer is actually labeled "PRI" and "SEC" which was helpful. (Only "PRI" is visible in the photo).
I tested this with a Honeywell RTH8500 thermostat and it works correctly.

CAUTION #1: This thing has live 120V power to it. Make sure the power is off when working on it.
CAUTION #2: If you wired it wrong, you could run 120V to your thermostat by mistake. This could cause damage or injury.  (I tested all the voltages before any wires left the box to the rest of the house, and I've done lots of DIY electrical work before so I was confident with this one.)
Comment: Thanks - finally implemented this today. Something to be aware of should anyone else care to try it is my transformer was rotated by 90 degrees. It also lacked a backplate with labeling like yours, but I was able to see the windings as a result to determine the secondary side.


Gnome - Cannot click between windows or click on UI elements with Mad Catz R.A.T. 3 mouse

Question: I recently switched to Linux. Everything went fine, but when I installed the gnome-shell, it started to ignore clicks outside the focused window. I cannot click on another window to focus it or click on any gnome UI elements. The super key also does nothing. I installed gnome-tweaks and I use a user theme, but that shouldn't be the problem because the problem remained even when I had a fresh install. Also, sometimes when I reboot it works normally. But after another reboot, it comes back.
PS- I found a very temporary fix: If I move the focused (or sometimes other windows) it will start recognizing my keystrokes. On Firefox I need to move the window by the bar with open tabs, as I cannot move it with the title bar.
I read this thread by someone who had a very similar issue, but the solution did not work for me. I think it has to do something with NVidia drivers, because if I change them then the frequency of this happening changes.
Sorry if something is weirdly written. English is not my native language.
Comment: Hi, welcome to Linux! English shouldn't be a barrier in the way of solution as long as you can adequately explain your troubles. Cheerios! :)
PS - Windows key is supposedly refered to as the Super Key.
Comment: Thanks, I approved the edit. And changed the 'windows key' to super key.
Comment: Did you try *all* the answers posted to the [question you mentioned](https://askubuntu.com/questions/971647/17-10-mouse-cant-click-on-gnome-elements-keyboard-misbehaving)? For example are you in a Wayland session? What is the output of the following command in Terminal: `echo $XDG_SESSION_TYPE`?
Comment: @pomsky The output of the command is x11. So I'm not in a Wayland session. I guess? EDIT 1 and 2: I'm dumb
Comment: Also, yes I did try all the answers. The second one even booted me to a black screen.
Comment: I have exactly the same problem but don't have your mouse... I posted a more general question here https://askubuntu.com/questions/1143824/how-to-troubleshoot-gnome-on-ubuntu-18-04
Comment: My issue was also with my wireless mouse and once I saw this answer I just decided to unplug the USB dongle and plug it back in. This solved the problem
Answer: So after doing some more research, I stumbled upon a thread with the same question. It turned out to be a problem with my Mad Catz R.A.T. 3 mouse. I didn't realise that i didn't have any drivers for it. Here's how you can fix this issue.
Write this section to /etc/X11/xorg.conf:
Section "InputClass"    Identifier "Mouse Remap"
    MatchProduct "Madcatz Mad Catz R.A.T.3 Mouse"
    MatchDevicePath "/dev/input/event*"
    Option "ButtonMapping" "1 2 3 4 5 6 7 8 0 0 0 0 0 0 0 0 0 0 0"
EndSection

PS: Here's a link to ArchWiki. It has all the information you need to set up your mad catz mouse.
Comment: Please do not delete your question!  Links to outside website may not work in the future, and you have attributed your answer to these outside sources *and* included the relevant bits to the answer that you have provided.
Answer: I had the same issue with my Kingsis Peripherals Evoluent VerticalMouse 4.  Appending the following to the bottom of xorg.conf file fixed it for me.  Thanks!
Section "InputClass"
    Identifier       "Mouse Remap"
    MatchDevicePath  "/dev/input/event*"
    MatchProduct     "Kingsis Peripherals Evoluent VerticalMouse 4"
    Option           "ButtonMapping"   "1 2 3 4 5 6 7 8 0 0 0 0 0 0 0 0 0"
EndSection

Answer: I contracted the same issue on ubuntu 20.04 a few days after I started using a new mouse (Razer DeathAdder Elite). Perhaps it's related to the mouse. Or perhaps it's related to an system update that maybe didn't work out well today.
I was afraid I'd have to reinstall ubuntu, since it was mostly unusable, but this thread suggested reinstalling compiz.
Compiz is a window manager, of which there are a few.
You can find out what your window manager is:
How to determine which window manager is running
For me it turned out to be gnome-shell. Reinstalling it + restart did the trick, now everything is usable again. The Gnome-UI looks a bit different, so I don't know if perhaps the update was the issue (or just reinstalling deleted my previous config).
I'll see if it holds up, since I'm still using the new mouse.
I'm also thinking about starting a file-backup in case I do have to do a re-install some day...
Comment: Welcome to Ask Ubuntu! Thanks for posting an answer. Can you specify how did you reinstalled Gnome Shell? This would help others with the same issue. Also, I recommend including some information from the link you posted in case it becomes 404. You can find more information on how to write a good answer [in the help center](https://askubuntu.com/help).


If w is not in span($u,v$) and $v$ is not in span($u$), are {$u,v,w$} linearly independent

Question: Let u, v, w be vectors in $R^4$. Suppose that w is not in span($u, v$) and $v$ is not in span($u$) and $u$ /= 0. Are {$u, v, w$} linearly independent? (Give a proof or a counterexample.)
Unsure how to tackle this one. I think its true but its the proof part I'm unsure what to do
Answer: Suppose there are scalars $a, b, c$ such that $au+bv+cw=0$.  If $c\neq 0$, then $w$ can be written as a linear combination of $u$ and $v$, so $w$ would be in their span; contradiction.  So $c=0$ and we have $au+bv =0$.  If $b\neq 0$, then similarly, $v$ is in the span of $u$.  Contradiction, so $b=0$.  Then we have $au=0$, and since $u\neq 0$, we must have $a=0$.  Since $a=b=c=0$, the vectors ar linearly independent.
Comment: Ah I get it now. Thank you very much!


Bathroom exhaust fan heat loss

Question: How much HEAT is lost in the winter by a bathroom exhaust fan running ALL of the time?  Conversely, in the summer time how much COOL air is lost by the fan running continuously?  It seems to me this would be like leaving a window or door open!
Comment: In the vast majority of cases where a vent fan is running "all the time" it's doing so by design, and reflects a total building approach that's much "tighter" than average, such that forced ventilation is required for occupant health and comfort. There's usually also a deliberate air intake built into such a system. Be sure you understand the actual house system before disabling the designed operation.
Comment: To answer this, you need to know how much air you're moving and how much you'll need to heat the air that replaces it. Air movement is a consequence of the fan's airflow (typically listed in CFM) and any restrictions imposed by its particular ductwork and damper. Once you know the air movement volume and how much hotter you'll be making the new air, you can then use the Heat Capacity (see https://en.wikipedia.org/wiki/Heat_capacity) of air to figure out how much energy you'll spend heating up the new air.
Comment: I am not sure where the close requesters are coming from. This is a good question even if it does not relate directly to some DIY home activity.
Comment: @Ecnerwal makes a good point but that might not be what we're dealing with.  A fan with a long run-on (mine were set to max -- over an hour -- when supplied) and a frequently-used bathroom could easily cause the fan to run much more than it should.  Or if a bathroom light is left on overnight (perhaps for a child) the fan will run constantly.  Even if it is intended to run flat out, that's based on certain assumptions about occupancy and use that may or may not be valid. BEra in mind that we don;t knwo where the OP is and therefore what's common construction there
Answer: This isn't typically calculated, but here are a couple of gross estimates of the heat loss.
Method 1:

Air requires in the ballpark of 0.24 BTU per pound to raise it 1 degree F.
1 CF of air weighs about 0.0807 lb, so it takes roughly 0.0194 BTU per cf per degree.
A typical small bathroom fan exhausts about 70 CFM or 4,200 CF per hour.  That would take roughly 81.5 BTU per hour to change it 1 degree.
The exhausted air will be replaced by outside air infiltrating through leakage.  Say you're in an area where the outdoor temperature is 40 degrees colder than indoor temperature in the winter.  That would require roughly 3,260 BTU per hour to make it the same temperature as the indoor air.
If you're heating with electricity, 1 watt = 3.412 BTU/hr, so this example would be roughly equivalent to a load of 1 KW.  Running it continuously would  add about 700 KWH per month to your electric bill in the winter if that temperature difference was an average (roughly $100), not including the electricity to power the fan.

Method 2:

There are online BTU calculators, like this one.  They're used to estimate HVAC requirements, which is slightly different.  In the calculation above, I just looked at the heat (or cooling) required for the replacement air.  HVAC sizing considers maintaining a temperature difference inside insulated walls, HVAC duty cycling, and other factors.  But it's another crude estimation.
For HVAC purposes, turning over room air 8 times per hour is a rough rule of thumb.  So 4,200 CF per hour would represent a 525 CF room.
Using assumptions of "normal" insulation and the same 40 degree temperature difference, the calculator comes up with a 5,840 BTU/Hr HVAC unit.

These are very crude estimates, but you can play with the assumptions to get a ballpark idea of the heating and cooling load created by running the fan continuously.
Answer: To answer your question in a concrete fashion, we'd need to know how many cubic feet per minute (CFM) are actually being moved by the fan (usually less than it is "rated" at due to being rated with no duct attached, but used with a duct attached.)
Say it's 100 (it's probably not.) 60 minutes to the hour, so 6000 cubic feet per hour, or 6000/13.9  (so, 431.6) pounds of air per hour. Air has a specific heat of 0.24, so 103.5 BTU's per hour per degree Fahrenheit (working in "English" units mostly only used in the USA.)
So, if it's -20F out and 68F in, 9120 BTUs/hr
If it's 68F in and 98F out, 3110 BTUs/hr - also if it's 38F out, just heating, not cooling.
Any other temperature differential, do the math. Got a different airflow rate - do the other math further up the page, I've exposed the factors that most people don't learn (cubic feet per pound and specific heat) so you can figure out exactly how many BTUs/hr your ventilation requires. Incidentally, unless your house is very well insulated, 100CFM of ventilation is peanuts .vs. the radiative heat loss of your windows alone, much less the rest of the house.
As noted in my comment, this is almost always a designed operation, not a "builder mistake" - the operating cost is not all that great, particularly as contrasted with the costs of inadequate ventilation, such as a mold problem that requires gutting and disinfecting the house, or the cost of excessive passive ventilation (leaks, drafts) from sloppy construction.
Answer: Yes, it's expensive to remove "conditioned" air and replace it with "unconditioned" air and then pay to "condition" it.
Exhaust fans are rated by CFM's. That is, cubic feet per minute. So, if a fan is on 24/7, it won't take long for the exhaust fan to exhaust several room air changes every hour.
When air is removed from your house, "make-up" air must be brought into your house. That air will be drawn in around doors, cracks around windows, etc.  and that air will be the outside air temperature. This causes your heater or air conditioner to "work" to make it conditioned air.

Bathroom exhaust fan heat loss


How to push a view from inside a UITableViewCell that is in a UICollectionViewCell?

Question: I have a UITableView inside of a UICollectionViewCell and I'm trying to push a new view from the UITableViewCell inside of the tableView(_:didSelectRowAt:) method. However, I cannot access navigationController. How would I go about navigating to the new view?
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    var item = Item(name: "")

    switch indexPath.section {
    case 0:
        item = array1![indexPath.item]
    case 1:
        item = array2![indexPath.item]
    default:
        break
    }

    let layout = UICollectionViewFlowLayout()
    let newView = NewCollectionView(collectionViewLayout: layout)
    newView.itemOfInterest = item

    // Can't reference navigationController
}

Comment: You can make your delegate method which will be fired in didSelect and it should be implemented in your viewcontroller where you can push.
Comment: You can also implement delete method of tableview delegate in to your ViewController. And You have also options of implement custom delegate which are called at your ViewController.
Answer: Get parent controller of current View -
//MARK: get parent controller...
extension UIView {
    var parentViewController: UIViewController? {
        var parentResponder: UIResponder? = self
        while parentResponder != nil {
            parentResponder = parentResponder!.next
            if let viewController = parentResponder as? UIViewController {
                return viewController
            }
        }
        return nil
    }
}

Usage:-
Get navigationController reference as parentViewController?.navigationController
let viewController = GymLearnMoreViewController(nibName: "GymLearnMoreViewController", bundle: nil) //Your View controller instance
parentViewController?.navigationController?.pushViewController(viewController, animated: true)

Source Apple:-
https://developer.apple.com/documentation/uikit/uiresponder/1621099-next
https://developer.apple.com/documentation/uikit/uiresponder?changes=_9
Answer: for this
1 . You need to declare a protocol in the collectionviewcell where the tableview is added
2 . implement the protocol method on the class where the collectionview is added. and handle the navigation on click from here
3 . set the collectionview cell delegate when the collectionviewCellForrow at indexpath method is invoked and call the delegate method when the tableview item is clicked within the collectionview cell
Answer: One way is using NotificationCenter which you can write in ParentViewController :
override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(methodNavigate(notification:)), name: NSNotification.Name(rawValue: "NavigateToSecondView"), object: nil)
}

@objc func methodNavigate(notification: NSNotification) {
    Write your push segue code here.
}

Don't forget to remove observer in viewDidDisappear:
override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)

    NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "NavigateToSecondView"), object: nil)
}

You can pass data through this too.
Then in didSelectRowAt :
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "NavigateToSecondView"), object: "Send Data Here")

But I will suggest using protocol is much better and elegant way.
You can get lots of tutorials and samples on internet:

https://medium.com/@abhimuralidharan/all-about-protocols-in-swift-11a72d6ea354
https://docs.swift.org/swift-book/LanguageGuide/Protocols.html

Hope it helps. Happy coding.


Nucleolus core element?

Question: I dont know how to get started with the following question:
How do I show that in a game with a nonempty core the nucleolus always is a core element?
I mean, if the core is nonempty its quite obvious there is a core element....
Think it has something to do with the sign of the excesses of core/non-core elements but I can't exactly figure it out.... Guess I cant do much more than that....
Someone a hint/suggestion or an example would be nice?
Thanks!
Answer: If a payoff-vector $x$ is in the core, the excess $v(S)-\sum_{i\in S}x_i$ must be nonpositive for every coalition $S$, for otherwise, the coalition could block the payoff-vector and the absence of the possibility to block characterizes the core.
Now a payoff-vector is in the nucleolus if the largest excess of any coalition is minimized. If the core is nonempty, there must be a payoff-vector at which the excess of every coalition is at most $0$. In particular, a payoff-vector in which the largest excess of any coalition is minimized (an element of the nucleolus), must have an excess of no more than $0$ and therefore be in the core.
Comment: Oh ofcourse :/
Just didnt link a negative number to a "block" and therefore not in core.....
Thanks!

Nucleolus core element?


Trying to send push notification to Azure Notification Hub via Rest API using specific device tag

Question: Basically I want to be able to send a push notification for a specific registered device (using a tag) to the Azure Notification Hub which will then send that notification out to the device. I do have some c# code that will do this but I'd like to make use of an API if possible.
I found an article (computer restarted tho so I don't have the link) that explained how to send notifications using an API but it looks like it sends the notification to every device registered with the hub so I want to see if it would be easy to modify the body or even the pre-request script to include a specific device tag.
Or if any of you smart people know of an easier way to do this through an API then I'm all ears.
Here's my code (taken from Postman) that I currently have that's sending the notification to all hub devices.
POST endpoint: https://{namespace_name}.servicebus.windows.net/{hub_name}/messages/?api-version=2015-01
Headers:

Authorization - {{azure-authorization}}
Content-Type - application/json
ServiceBusNotification-Format - gcm

Request body:
<code>{"data":
    {
        "gcm.notification.body":"Hi",
        "gcm.notification.title":"Hi",
    }
}
</code>
Pre-request Script:
<code>function getAuthHeader(resourceUri, keyName, key) {

    var d = new Date();
    var sinceEpoch = Math.round(d.getTime() / 1000);
    var expiry = (sinceEpoch + 3600);
    var stringToSign = encodeURIComponent(resourceUri) + '\n' + expiry;
    var hash = CryptoJS.HmacSHA256(stringToSign, key);
    var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
    var sasToken = 'SharedAccessSignature sr=' + encodeURIComponent(resourceUri) + '&sig=' + encodeURIComponent(hashInBase64) + '&se=' + expiry + '&skn=' + keyName;
    console.log(sasToken);

    return sasToken;
}
postman.setEnvironmentVariable('azure-authorization', getAuthHeader(request.url,"DefaultFullSharedAccessSignature", "<full_shared_access_signature>"));
postman.setEnvironmentVariable('current-date',new Date().toUTCString());
</code>
Comment: Is [this document](https://learn.microsoft.com/en-us/rest/api/notificationhubs/use-rest-api-backend#sending-notifications) you are looking for? ServiceBusNotification-Tags (optional): Specifies the tag (or tag expression) defining the targeted set of registrations. If this header is not present, the notification hub broadcasts to all registrations.
Comment: @JackHua-MSFT that looks to be exactly what i needed. add it as a reply and ill mark it as the answer :)
Answer: The REST API for sending notifications is a simple POST on /yourHub/messages, with special headers. When sending notifications in a platform-native format, the body is the platform-specific body to be sent. The additional headers are:

ServiceBusNotification-Format: Specifies that the platform (if
sending a native notification) or "template" is to send a template
notification.
ServiceBusNotification-Tags (optional): Specifies the tag (or tag
expression) defining the targeted set of registrations. If this
header is not present, the notification hub broadcasts to all
registrations.

Other headers are supported for platform-specific functionality, as specified in the Notification Hubs REST APIs documentation.
Refer: Use REST APIs from a backend


UIButton/UIView.animate make buttons blink in sequence

Question: I'm making a simon game in swift where the signals are given in enum [Green,Yellow,Red,Red,Blue]... and I want to make the buttons blink as the signals are given. The code I used to make the buttons blink is
extension UIButton {
    func blink() {
        self.alpha = 0.0;
        UIView.animate(withDuration: 0.6, //Time duration you want,
            delay: 0.0,
            options: [.curveEaseInOut, .autoreverse],
            animations: { [weak self] in self?.alpha = 1.0 },
            completion: { [weak self] _ in self?.alpha = 1.0 })
    }
}

and in my give signal function, I am doing
    func giveSignal() {
        disableButton()
        signals = []
        for _ in 0...levelNum  {
//            stopBlinkAll()
            let randomSignal:Int = randomSource.nextInt(upperBound: 4)
            switch randomSignal {
                //Green
                case 0:
                    green.blink()
                    signals.append(Block.green)
//                    green.stopBlink()
                //Red
                case 1:
                    red.blink()
                    signals.append(Block.red)
//                    red.stopBlink()
                //Yellow
                case 2:
                    yellow.blink()
                    signals.append(Block.yellow)
//                    yellow.stopBlink()
                //Blue
                case 3:
                    blue.blink()
                    signals.append(Block.blue)
//                    blue.stopBlink()
            default:
                break
            }

        }
        let finalSeq:String = makeString()
        statusBar.text = finalSeq
    }

But if the signals are given as [Green,Yellow,Red] for example, all the green, yellow, red buttons blink at the same time. How can I fix this to make the buttons blink one after the other?
Answer: First, add a completion handler to blink, because we are only going to start the next blink after the previous blink has finished.
extension UIButton {
    func blink(completion: @escaping () -> Void) {
        self.alpha = 0.0;
        UIView.animate(withDuration: 0.6, //Time duration you want,
            delay: 0.0,
            options: [.curveEaseInOut],
            animations: { self.alpha = 1.0 },
            completion: { _ in
                UIView.animate(withDuration: 0.6,
                    delay: 0.0,
                    options: [.curveEaseInOut],
                    animations: { self.alpha = 0.0 },
                    completion: { _ in completion() })
             })
    }
}

Then, write a function that takes in a [Block] and an index, that blinks the button at that index. Note how I pass the closure that calls blink(at:in:) again as the completion of the blink() calls:
func blink(at index: Int, in signals: [Block]) {
    guard index < signals.count else { return }
    let completion = { blink(at: index + 1, in: signals) }

    switch (signals[index]) {
        case .green: green.blink(completion: completion)
        case .red: red.blink(completion: completion)
        case .yellow: yellow.blink(completion: completion)
        case .blue: blue.blink(completion: completion)
    }
}

Now, we can rewrite giveSignal:
func giveSignal() {
    disableButton()
    signals = []
    for _ in 0...levelNum  {
        let randomSignal:Int = randomSource.nextInt(upperBound: 4)
        switch randomSignal {
        //Green
        case 0:
            signals.append(Block.green)
        //Red
        case 1:
            signals.append(Block.red)
        //Yellow
        case 2:
            signals.append(Block.yellow)
        //Blue
        case 3:
            signals.append(Block.blue)
        default:
            break
        }

    }
    blink(at: 0, in: signals) // This starts the sequence of blinks
    let finalSeq:String = makeString()
    statusBar.text = finalSeq
}

Comment: Thank you, it works! Also my blink animation is quite choppy and blinks like twice. do you know how to make it more clean? I just want one simple blink.
Comment: @JiwooLee Apparently, `autoreverse` [must be combined with `repeat`](https://developer.apple.com/documentation/uikit/uiview/animationoptions/1622639-autoreverse). So I think you should run 2 animations in the `blink()` method instead of using `autoreverse`.
Comment: @JiwooLee See the edit. I have changed `blink` to not use `autoreverse`.
Comment: Works perfectly! Thank you again :)


Connecting the Dots between Tomcat, Solr and sunspot_rails

Question: Throughout multiple tutorials on how to install Solr so I can start using sunspot_rails in my app, I've become very confused as to actually how to get a singular Solr application to be utilized by my Rails app in multiple environments (dev, test, prod). I'll try and lay out my attempt at understanding the entire setup as far as I've gotten it.

Rails Application

makes requests to http://samedomain.com:8981/solr* through the sunspot_rails gem
where :8981 is set by sunspot_rails in sunspot.yml (so 8981 can be production, 8982 is development, 8983 is test).
why does sunspot.yml specify a data directory? Is that not handled by the Tomcat/Solr installation config files? I think the major disconnect for me is that you can A) Set up Solr on its own as a standalone installation or B) Run Solr via rake sunspot:solr:start and it runs the app from within the gem. When I have a working standalone installation of Solr through Tomcat, do I not need to execute the rake task? What then is the point of specifying path: /solr/./production in sunspot.yml?

Tomcat

Handles running the Solr instance(s) on boot (Tomcat is in init.d startup script), and runs on port 8080 (currently, this port is the only way to access the Solr interface)
How do I map ports 8981-8983 to this running instance of Solr, and map each to its respective data directory?
Should I be storing the Solr data directory under my rails app directory, or keep it in a completely separate location?

Solr

It just seems like there's a config for all of these applications but I don't know where the precedence lies.

I'm using CentOS (web host), Ubuntu VM (local dev machine), tomcat7 and latest version of Solr.
Answer: Whelp, I figured it out. I set up a multicore environment following this article (definitely don't use spaces in the core name), and using the sunspot_rails configuration found here. For clarification, the path: reference in sunspot.yml is essentially what gets tacked on to the URL when referencing a 'core': i.e., http://mydomain.com:8080/solr/production (emphasis to indicate my point).
So now I don't have to care about running the rake task to start Solr because it's always running all 3 cores on boot through a single instance of Solr via Tomcat.


Android TelephonyManager And PhoneStateListener

Question: I want to Pop up an new View on Top when a  call is received and is in Ringing Mode..But i am unable To Do this.
I am posting my code but also consider the code in comment.
<code>package com.android.CallIntent;

import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

public class Listener extends PhoneStateListener {
    Context Context;
    public Listener(Context context)
    {
        this.Context = context;
    }

    @Override
    public void onCallStateChanged(int state, String incomingNumber) {
        // TODO Auto-generated method stub
        super.onCallStateChanged(state, incomingNumber);

        switch(state)
        {
            case TelephonyManager.CALL_STATE_OFFHOOK:

                break;
            case TelephonyManager.CALL_STATE_RINGING:

                Log.d("message","Ringing");
                Intent intent = new Intent(Context, CallOptions.class);
                // I want to start my new Activity From here please Help me.

                //I am unable to access StartActivity
                break;

        }
    }

}

// My BroadcastReceiver class is here
public class Receiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        TelephonyManager manager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        Listener phoneStateListener= new Listener();
        manager.listen(phoneStateListener, Listener.LISTEN_CALL_STATE);

    }
</code>
Please someone help me out please please please.
Thanks in Advance.
Comment: Have you tried using `context.StartActivity()` to start the activity?
Answer: Look here.... It must help you ...
<code>   case TelephonyManager.CALL_STATE_RINGING:
            Toast.makeText( context, "incoming call", Toast.LENGTH_LONG).show();
            IntentService = new Intent(context, PlayService.class).setAction("incoming_call");
            IntentService.putExtra("phone_number",intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER) );
            if (SmsReceiver.bool)
            context.startService(IntentService);
            break;
</code>


Validation New Form MVC

Question: I need your help.I am doing a project in MVC and have downloaded a new Register form from Internet. All works fine, but I want to create in this form the error message when the user insert th e data(e.g. for wrong email,password etc.).I created new layout for my form:
    @model WebApp.Models.User

@{
    Layout = null;
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Register</title>
    <link rel="stylesheet" href="~/UsefullBox/fonts/material-icon/css/material-design-iconic-font.min.css">
       <link rel="stylesheet" href="~/UsefullBox/css/style.css">

Register Form

                @using (Html.BeginForm("Register", "Home", FormMethod.Post, new { @class = "register-form", @id = "register-form" }))
                {
                    @Html.AntiForgeryToken()
                    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                        @Html.TextBoxFor(m => m.User_login, new { @placeholder = "Your Name" })

                        @Html.ValidationMessageFor(m => m.User_login, "", new { @class = "text-danger" })

                        @Html.TextBoxFor(m => m.User_Email, new { @placeholder = "Your Email" })

                        @Html.ValidationMessageFor(m => m.User_Email, "", new { @class = "text-danger" })

                        @Html.PasswordFor(m => m.User_password, new { @placeholder = "Password" })

                        @Html.ValidationMessageFor(m => m.User_password, "", new { @class = "text-danger" })

                        @Html.PasswordFor(m => m.User_password_1, new { @placeholder = "Repeat your password" })

                        @Html.ValidationMessageFor(m => m.User_password_1, "", new { @class = "text-danger" })

                        <input type="submit" name="signup" id="signup" class="form-submit" value="Register" />

  }

                I am already member

And this is my class:
     public partial class User
        {
            public int User_Id { get; set; }
        [Required(ErrorMessage = "Please enter the login")]
        public string User_login { get; set; }

        [Required(ErrorMessage = "Please enter the password")]
        [DataType(DataType.Password)]
        public string User_password { get; set; }

        [Required(ErrorMessage = "Reenter the password")]
        [DataType(DataType.Password)]
        [Compare("User_password")]
        public string User_password_1 { get; set; }

        [Required(ErrorMessage ="Please enter email")]
        [EmailAddress(ErrorMessage ="Invalid Email Address")]
        public string User_Email { get; set; }
    }

what i have to insert more in my code that when the client insert e.g. a wrong email, the form show the Error Message.Thank you!!! Exemple: https://learn-the-web.algonquindesign.ca/courses/web-dev-4/designing-form-errors/
Comment: Have you check in Action `ModelState.Isvalid`?
Answer: Try this
[DataType(DataType.EmailAddress)]
public string User_Email { get; set; }

Or you can use Regex
[RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage = "Please enter a valid e-mail adress")]

Validation New Form MVC


Checkmarx scan through CLI plugin team ID error

Question: I am running the CLI plugin to test the scanning of my project. Here's the sample command:
runCxConsole.cmd Scan -v -ProjectName "CxServer\Test" -CxServer https://test -cxuser uname -cxpassword pword -locationtype folder -locationpath "C:\Users\Test" -preset "Checkmarx Default"

When I run this command I'm getting this error:
[2020-07-16 16:48:32,960 INFO ] Initializing Cx client [2020.2.20.SCA]
[2020-07-16 16:48:38,108 INFO ] Checkmarx server version [220.127.116.11085]. Hotfix [3].
[2020-07-16 16:48:38,109 INFO ] Logging into the Checkmarx service.
[2020-07-16 16:48:40,906 ERROR] Could not resolve team ID from team name: /CxServer

Answer: The parameter value for ProjectName typically is in this format "\projectName". You can get the the project name from the General Properties tab
runCxConsole.cmd Scan -v -ProjectName "**\projectName**" -CxServer https://test -cxuser uname -cxpassword pword -locationtype folder -locationpath "C:\Users\Test" -preset "Checkmarx Default"


ModuleNotFoundError: No module named 'pytorch_lightning.core.decorators' | Google Colab GPU session

Question: In my Google Colab GPU runtime, I try to install pytorch_lightning. So I do the following in the order:
!pip list | grep torch
torch                         2.0.0+cu118
torchaudio                    2.0.1+cu118
torchdata                     0.6.0
torchsummary                  1.5.1
torchtext                     0.15.1
torchvision                   0.15.1+cu118

Then using !pip install pytorch_lightning, I manage to install 2.0.1 version:
Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/
Collecting pytorch_lightning
  Downloading pytorch_lightning-2.0.1-py3-none-any.whl (716 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 716.4/716.4 KB 34.0 MB/s eta 0:00:00
Requirement already satisfied: fsspec[http]>2021.06.0 in /usr/local/lib/python3.9/dist-packages (from pytorch_lightning) (2023.3.0)
Requirement already satisfied: PyYAML>=5.4 in /usr/local/lib/python3.9/dist-packages (from pytorch_lightning) (6.0)
Collecting torchmetrics>=0.7.0
  Downloading torchmetrics-0.11.4-py3-none-any.whl (519 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 519.2/519.2 KB 48.1 MB/s eta 0:00:00
Requirement already satisfied: typing-extensions>=4.0.0 in /usr/local/lib/python3.9/dist-packages (from pytorch_lightning) (4.5.0)
Collecting lightning-utilities>=0.7.0
  Downloading lightning_utilities-0.8.0-py3-none-any.whl (20 kB)
Requirement already satisfied: numpy>=1.17.2 in /usr/local/lib/python3.9/dist-packages (from pytorch_lightning) (1.22.4)
Requirement already satisfied: tqdm>=4.57.0 in /usr/local/lib/python3.9/dist-packages (from pytorch_lightning) (4.65.0)
Requirement already satisfied: torch>=1.11.0 in /usr/local/lib/python3.9/dist-packages (from pytorch_lightning) (2.0.0+cu118)
Requirement already satisfied: packaging>=17.1 in /usr/local/lib/python3.9/dist-packages (from pytorch_lightning) (23.0)
Collecting aiohttp!=4.0.0a0,!=4.0.0a1
  Downloading aiohttp-3.8.4-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (1.0 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.0/1.0 MB 71.8 MB/s eta 0:00:00
Requirement already satisfied: requests in /usr/local/lib/python3.9/dist-packages (from fsspec[http]>2021.06.0->pytorch_lightning) (2.27.1)
Requirement already satisfied: triton==2.0.0 in /usr/local/lib/python3.9/dist-packages (from torch>=1.11.0->pytorch_lightning) (2.0.0)
Requirement already satisfied: filelock in /usr/local/lib/python3.9/dist-packages (from torch>=1.11.0->pytorch_lightning) (3.10.7)
Requirement already satisfied: jinja2 in /usr/local/lib/python3.9/dist-packages (from torch>=1.11.0->pytorch_lightning) (3.1.2)
Requirement already satisfied: networkx in /usr/local/lib/python3.9/dist-packages (from torch>=1.11.0->pytorch_lightning) (3.0)
Requirement already satisfied: sympy in /usr/local/lib/python3.9/dist-packages (from torch>=1.11.0->pytorch_lightning) (1.11.1)
Requirement already satisfied: lit in /usr/local/lib/python3.9/dist-packages (from triton==2.0.0->torch>=1.11.0->pytorch_lightning) (16.0.0)
Requirement already satisfied: cmake in /usr/local/lib/python3.9/dist-packages (from triton==2.0.0->torch>=1.11.0->pytorch_lightning) (3.25.2)
Collecting multidict<7.0,>=4.5
  Downloading multidict-6.0.4-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (114 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 114.2/114.2 KB 17.2 MB/s eta 0:00:00
Requirement already satisfied: attrs>=17.3.0 in /usr/local/lib/python3.9/dist-packages (from aiohttp!=4.0.0a0,!=4.0.0a1->fsspec[http]>2021.06.0->pytorch_lightning) (22.2.0)
Collecting yarl<2.0,>=1.0
  Downloading yarl-1.8.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (264 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 264.6/264.6 KB 32.6 MB/s eta 0:00:00
Requirement already satisfied: charset-normalizer<4.0,>=2.0 in /usr/local/lib/python3.9/dist-packages (from aiohttp!=4.0.0a0,!=4.0.0a1->fsspec[http]>2021.06.0->pytorch_lightning) (2.0.12)
Collecting async-timeout<5.0,>=4.0.0a3
  Downloading async_timeout-4.0.2-py3-none-any.whl (5.8 kB)
Collecting frozenlist>=1.1.1
  Downloading frozenlist-1.3.3-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl (158 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 158.8/158.8 KB 23.9 MB/s eta 0:00:00
Collecting aiosignal>=1.1.2
  Downloading aiosignal-1.3.1-py3-none-any.whl (7.6 kB)
Requirement already satisfied: MarkupSafe>=2.0 in /usr/local/lib/python3.9/dist-packages (from jinja2->torch>=1.11.0->pytorch_lightning) (2.1.2)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in /usr/local/lib/python3.9/dist-packages (from requests->fsspec[http]>2021.06.0->pytorch_lightning) (1.26.15)
Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.9/dist-packages (from requests->fsspec[http]>2021.06.0->pytorch_lightning) (3.4)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.9/dist-packages (from requests->fsspec[http]>2021.06.0->pytorch_lightning) (2022.12.7)
Requirement already satisfied: mpmath>=0.19 in /usr/local/lib/python3.9/dist-packages (from sympy->torch>=1.11.0->pytorch_lightning) (1.3.0)
Installing collected packages: multidict, lightning-utilities, frozenlist, async-timeout, yarl, aiosignal, aiohttp, torchmetrics, pytorch_lightning
Successfully installed aiohttp-3.8.4 aiosignal-1.3.1 async-timeout-4.0.2 frozenlist-1.3.3 lightning-utilities-0.8.0 multidict-6.0.4 pytorch_lightning-2.0.1 torchmetrics-0.11.4 yarl-1.8.2

Here's also to double check, if it's installed:
!pip list | grep torch
pytorch-lightning             2.0.1
torch                         2.0.0+cu118
torchaudio                    2.0.1+cu118
torchdata                     0.6.0
torchmetrics                  0.11.4
torchsummary                  1.5.1
torchtext                     0.15.1
torchvision                   0.15.1+cu118

However, I have a compatibility issue of importing a module:
import pytorch_lightning # works without error!
from pytorch_lightning.core.decorators import auto_move_data # ERROR!

which returns the following error:
ModuleNotFoundError                       Traceback (most recent call last)

<ipython-input-6-2a2afba7b5b2> in <cell line: 1>()
----> 1 from pytorch_lightning.core.decorators import auto_move_data

ModuleNotFoundError: No module named 'pytorch_lightning.core.decorators'

I believe this module has been deprecated in the current version, does anyone know how to fix this compatibility issue?
Cheers,
Answer: in my case I downgraded pytorch_lighting:
$ pip install pytorch_lightning==1.6.0

Answer: auto_move_data has been deprecated with this PR.
Here is the upgrade guide.
With PL 2.0, you need to import it like -
import lightning L

class Model(L.LightningModule):
    ...

trainer = L.Trainer()
trainer.fit(Model(), dataloader)


PHP Table echo empty td

Question: Why would it empty an empty td and work properly.  If there are is no data, it pushes the next row data up the column. Please suggest me how to fix it.
for($i = 0; $i < count($cheads[$keys[0]]); $i++){
    echo "
";
    for($k = 0; $k < count($keys); $k++){
        echo "";
        if(array_key_exists($i, $cheads[$keys[$k]])){
            echo $cheads[$keys[$k]][$i]['Data'];
        }else{
            echo "N/A";
        }
        echo "	";
    }
    echo "
";
}

Data set:

Array ( [Last Name] => Array ( [0] => Array ( [Field] => Last Name [Data] => 1 [User] => 5 ) [1] => Array ( [Field] => Last Name [Data] => 1 [User] => 5 ) [2] => Array ( [Field] => Last Name [Data] => 1 [User] => 5 ) [3] => Array ( [Field] => Last Name [Data] => Yo [User] => 5 ) [4] => Array ( [Field] => Last Name [Data] => Test [User] => 5 ) ) [Phone Name] => Array ( [0] => Array ( [Field] => Phone Name [Data] => 2 [User] => 5 ) [1] => Array ( [Field] => Phone Name [Data] => 2 [User] => 5 ) [2] => Array ( [Field] => Phone Name [Data] => 2 [User] => 5 ) [3] => Array ( [Field] => Phone Name [Data] => Yo [User] => 5 ) [4] => Array ( [Field] => Phone Name [Data] => [User] => 5 ) ) [Address Name] => Array ( [0] => Array ( [Field] => Address Name [Data] => 3 [User] => 5 ) [1] => Array ( [Field] => Address Name [Data] => 3 [User] => 5 ) [2] => Array ( [Field] => Address Name [Data] => Yo [User] => 5 ) [3] => Array ( [Field] => Address Name [Data] => [User] => 5 ) ) [Description] => Array ( [0] => Array ( [Field] => Description [Data] => 4 [User] => 5 ) [1] => Array ( [Field] => Description [Data] => 4 [User] => 5 ) [2] => Array ( [Field] => Description [Data] => 4 [User] => 5 ) [3] => Array ( [Field] => Description [Data] => Yo [User] => 5 ) [4] => Array ( [Field] => Description [Data] => [User] => 5 ) ) [Fruit Type] => Array ( [0] => Array ( [Field] => Fruit Type [Data] => Peanuts [User] => 5 ) [1] => Array ( [Field] => Fruit Type [Data] => Apple [User] => 5 ) ) )

Comment: You use `count($cheads[$keys[0]])` in the first loop and in the echo, but in the second for loop you use `count($keys)`. Is that correct?
Comment: Counts are used correctly, if I do -1 in any of the count, it stops displaying last columns or last rows which has some data
Comment: I have attached the data set I have
Comment: Probably just an HTML issue. Some browsers won't use up the room for empty ``'s. You'll probably have to put some type of space or 1px image and check for empty. Are you looking to show the empty rows in ``'s with empty lines throughout, is that the goal here? If not, then I haven't grasped the question.
Comment: @Fred-ii- I am echoing N/A if index not exist
Answer: There's actually nothing wrong with your PHP. The problem is stemming from how your array was generated.
You're identifying rows based on their numeric array key index, so when a row is missing, instead of skipping the numeric index it uses the next in line causing everything to get out of sync.
Based on your diagram, you're expecting all the 'Yo' records to belong together, so you'd have to keep the array keys in sync. That would mean skipping index 2 in 'Phone Name' and also skipping indices 0, 1, and 2 in 'Fruit Type'
This
  'Address Name' => Array (
    '0' => Array ( 'Field' => 'Address Name', 'Data' => 3, 'User' => 5 ),
    '1' => Array ( 'Field' => 'Address Name', 'Data' => 3, 'User' => 5 ),
    '2' => Array ( 'Field' => 'Address Name', 'Data' => 'Yo', 'User' => 5 ),
    '3' => Array ( 'Field' => 'Address Name', 'Data' => null, 'User' => 5 )
  ),

and
 'Fruit Type' => Array (
    '0' => Array ( 'Field' => 'Fruit Type', 'Data' => 'Peanuts', 'User' => 5 ),
    '1' => Array ( 'Field' => 'Fruit Type', 'Data' => 'Apple', 'User' => 5 )
  )

would become
  'Address Name' => Array (
    '0' => Array ( 'Field' => 'Address Name', 'Data' => 3, 'User' => 5 ),
    '1' => Array ( 'Field' => 'Address Name', 'Data' => 3, 'User' => 5 ),
    '3' => Array ( 'Field' => 'Address Name', 'Data' => 'Yo', 'User' => 5 ),
    '4' => Array ( 'Field' => 'Address Name', 'Data' => null, 'User' => 5 )
  ),

  'Fruit Type' => Array (
    '3' => Array ( 'Field' => 'Fruit Type', 'Data' => 'Peanuts', 'User' => 5 ),
    '4' => Array ( 'Field' => 'Fruit Type', 'Data' => 'Apple', 'User' => 5 )
  )

Because there's no other identifying information in each record, then it's impossible to solve it otherwise (it's odd that every User is 5).
One alternative solution would be to change to using an associative key index, but then your whole PHP row construction method falls apart because it depends on numeric keys.
Another alternative that may solve your problem is that I noticed the data you provided contains an additional row than what is in your diagram. In this extra row, instead of missing data, the values are actually inserted as null so if you clear out the first records, then your script should work so long as new data coming in is created the same way (by inserting nulls). However, then your "N/A" column will never be populated because it's shown as a blank cell.
You script as is:
<?php

$cheads = Array (
  'Last Name' => Array (
    '0' => Array ( 'Field' => 'Last Name', 'Data' => 1, 'User' => 5 ),
    '1' => Array ( 'Field' => 'Last Name', 'Data' => 1, 'User' => 5 ),
    '2' => Array ( 'Field' => 'Last Name', 'Data' => 1, 'User' => 5 ),
    '3' => Array ( 'Field' => 'Last Name', 'Data' => 'Yo', 'User' => 5 ),
    '4' => Array ( 'Field' => 'Last Name', 'Data' => 'Test', 'User' => 5 )
  ),
  'Phone Name' => Array (
    '0' => Array ( 'Field' => 'Phone Name', 'Data' => 2, 'User' => 5 ),
    '1' => Array ( 'Field' => 'Phone Name', 'Data' => 2, 'User' => 5 ),
    '2' => Array ( 'Field' => 'Phone Name', 'Data' => 2, 'User' => 5 ),
    '3' => Array ( 'Field' => 'Phone Name', 'Data' => 'Yo', 'User' => 5 ),
    '4' => Array ( 'Field' => 'Phone Name', 'Data' => null, 'User' => 5 )
  ),
  'Address Name' => Array (
    '0' => Array ( 'Field' => 'Address Name', 'Data' => 3, 'User' => 5 ),
    '1' => Array ( 'Field' => 'Address Name', 'Data' => 3, 'User' => 5 ),
    '2' => Array ( 'Field' => 'Address Name', 'Data' => 'Yo', 'User' => 5 ),
    '3' => Array ( 'Field' => 'Address Name', 'Data' => null, 'User' => 5 )
  ),
  'Description' => Array (
    '0' => Array ( 'Field' => 'Description', 'Data' => 4, 'User' => 5 ),
    '1' => Array ( 'Field' => 'Description', 'Data' => 4, 'User' => 5 ),
    '2' => Array ( 'Field' => 'Description', 'Data' => 4, 'User' => 5 ),
    '3' => Array ( 'Field' => 'Description', 'Data' => 'Yo', 'User' => 5 ),
    '4' => Array ( 'Field' => 'Description', 'Data' => null, 'User' => 5 )
  ),
  'Fruit Type' => Array (
    '0' => Array ( 'Field' => 'Fruit Type', 'Data' => 'Peanuts', 'User' => 5 ),
    '1' => Array ( 'Field' => 'Fruit Type', 'Data' => 'Apple', 'User' => 5 )
  )
);

$keys = ['Last Name', 'Phone Name', 'Address Name', 'Description', 'Fruit Type'];
?>

      <?php
        foreach ($keys as $key)
          echo "$key	";
      ?>

<?php
for($i = 0; $i < count($cheads[$keys[0]]); $i++){ // foreach 'Last Name'
    echo "
";
    for($k = 0; $k < count($keys); $k++){ // foreach $keys
        echo "";
        if(array_key_exists($i, $cheads[$keys[$k]])){
            echo $cheads[$keys[$k]][$i]['Data'];
        }else{
            echo "N/A";
        }
        echo "	";
    }
    echo "
\n";
}
?>

      Last Name	Phone Name	Address Name	Description	Fruit Type

1	2	3	4	Peanuts

1	2	3	4	Apple

1	2	Yo	4	N/A

Yo	Yo		Yo	N/A

Test		N/A		N/A

When using the array constructed with synchronized numeric keys.
$cheads = Array (
  'Last Name' => Array (
    '0' => Array ( 'Field' => 'Last Name', 'Data' => 1, 'User' => 5 ),
    '1' => Array ( 'Field' => 'Last Name', 'Data' => 1, 'User' => 5 ),
    '2' => Array ( 'Field' => 'Last Name', 'Data' => 1, 'User' => 5 ),
    '3' => Array ( 'Field' => 'Last Name', 'Data' => 'Yo', 'User' => 5 ),
    '4' => Array ( 'Field' => 'Last Name', 'Data' => 'Test', 'User' => 5 )
  ),
  'Phone Name' => Array (
    '0' => Array ( 'Field' => 'Phone Name', 'Data' => 2, 'User' => 5 ),
    '1' => Array ( 'Field' => 'Phone Name', 'Data' => 2, 'User' => 5 ),
    '2' => Array ( 'Field' => 'Phone Name', 'Data' => 2, 'User' => 5 ),
    '3' => Array ( 'Field' => 'Phone Name', 'Data' => 'Yo', 'User' => 5 ),
    '4' => Array ( 'Field' => 'Phone Name', 'Data' => null, 'User' => 5 )
  ),
  'Address Name' => Array (
    '0' => Array ( 'Field' => 'Address Name', 'Data' => 3, 'User' => 5 ),
    '1' => Array ( 'Field' => 'Address Name', 'Data' => 3, 'User' => 5 ),
    '3' => Array ( 'Field' => 'Address Name', 'Data' => 'Yo', 'User' => 5 ),
    '4' => Array ( 'Field' => 'Address Name', 'Data' => null, 'User' => 5 )
  ),
  'Description' => Array (
    '0' => Array ( 'Field' => 'Description', 'Data' => 4, 'User' => 5 ),
    '1' => Array ( 'Field' => 'Description', 'Data' => 4, 'User' => 5 ),
    '2' => Array ( 'Field' => 'Description', 'Data' => 4, 'User' => 5 ),
    '3' => Array ( 'Field' => 'Description', 'Data' => 'Yo', 'User' => 5 ),
    '4' => Array ( 'Field' => 'Description', 'Data' => null, 'User' => 5 )
  ),
  'Fruit Type' => Array (
    '3' => Array ( 'Field' => 'Fruit Type', 'Data' => 'Peanuts', 'User' => 5 ),
    '4' => Array ( 'Field' => 'Fruit Type', 'Data' => 'Apple', 'User' => 5 )
  )
);

      Last Name	Phone Name	Address Name	Description	Fruit Type

1	2	3	4	N/A

1	2	3	4	N/A

1	2	N/A	4	N/A

Yo	Yo	Yo	Yo	Peanuts

Test				Apple

Answer: The trick was to change how I was getting data in my array. I used associated arrays with a different approach.
Before:
cheads:    Array (
[Last Name] => Array (
    [0] => Array ( [Field] => Last Name [Data] => 1 [User] => 5 )
    [1] => Array ( [Field] => Last Name [Data] => 1 [User] => 5 )
    [2] => Array ( [Field] => Last Name [Data] => 1 [User] => 5 )
    [3] => Array ( [Field] => Last Name [Data] => Yo [User] => 5 )
    [4] => Array ( [Field] => Last Name [Data] => Test [User] => 5 ) )

[Phone Name] => Array (
    [0] => Array ( [Field] => Phone Name [Data] => 2 [User] => 5 )
    [1] => Array ( [Field] => Phone Name [Data] => 2 [User] => 5 )
    [2] => Array ( [Field] => Phone Name [Data] => 2 [User] => 5 )
    [3] => Array ( [Field] => Phone Name [Data] => Yo [User] => 5 )
    [4] => Array ( [Field] => Phone Name [Data] => [User] => 5 ) )

[Address Name] => Array (
    [0] => Array ( [Field] => Address Name [Data] => 3 [User] => 5 )
    [1] => Array ( [Field] => Address Name [Data] => 3 [User] => 5 )
    [2] => Array ( [Field] => Address Name [Data] => Yo [User] => 5 )
    [3] => Array ( [Field] => Address Name [Data] => [User] => 5 ) )
[Description] => Array (
    [0] => Array ( [Field] => Description [Data] => 4 [User] => 5 )
    [1] => Array ( [Field] => Description [Data] => 4 [User] => 5 )
    [2] => Array ( [Field] => Description [Data] => 4 [User] => 5 )
    [3] => Array ( [Field] => Description [Data] => Yo [User] => 5 )
    [4] => Array ( [Field] => Description [Data] => [User] => 5 ) )
[Fruit Type] => Array (
    [0] => Array ( [Field] => Fruit Type [Data] => Peanuts [User] => 5 )
    [1] => Array ( [Field] => Fruit Type [Data] => Apple [User] => 5 ) ) )

After:
Matrix:   Array (
[D2AA0FA4-4F91-4757-9D27-9F65E0390EF1] => Array ( [Last Name] => 1 [Phone Name] => 1 [Address Name] => 1 [Description] => 1 )
[182EDD25-89CE-40F0-87AE-53D218CD0A1F] => Array ( [Last Name] => 2 [Phone Name] => 2 [Address Name] => 2 [Description] => 2 )
[59EF4DA3-0D3B-4F37-A415-10DD414351A7] => Array ( [Last Name] => 3 [Phone Name] => 3 [Address Name] => 3 [Description] => 3 [Fruit Type] => Apple )
[1C7B67E2-9230-4215-B990-C366077DA6C3] => Array ( [Last Name] => 5 [Phone Name] => 5 [Address Name] => 5 [Description] => 5 ) )

I had an extra Identifier field for identifying each data by user. I made them parent keys and for each identifier I added all fields data under them making field-type key as well for each child data.
Before this I had collect all the keys in another array, I iterated through it and simply echoed like this:
foreach ($matrix as $key => $value) {

    echo "
";

    for($i = 0; $i < count($cheads); $i++){

        $head = $cheads[$i];

        if(isset($value[$head])){
            echo "";
            echo $value[$head];
            echo "	";
        }else{
            echo "";
            echo "NA";
            echo "	";
        }

    }
    echo "Edit	";
    echo "
";

}

Result:

Using associative key and a different approach did it for me.
Thanks.

PHP Table echo empty td


Do roads count as improvements for Weather Controller Sats?

Question: Weather Controllers Generate 1 to 2 new Basic Resources on unimproved tiles across its lifespan.
Do Roads/Magrail count as improvements for this purpose?
Comment: I don't think roads/magrails count, since they can be built on top of, and thus coexist with, other improvements. But I cannot confirm it's interaction with weather controllers because I've yet to use that satellite.
Answer: Magrails do NOT count as improvements for Orbital Fabricators which are basically the same thing as weather controllers, except they generate Strategic Resources instead of Basic Resources. Seems likely you can build roads/mag under your weather sats too!