Want to change colour of Xcode highlighted files in Project Navigator

Question: I have a rather simple question. For some reason, I have discovered that when I highlight a file in Xcode in the Project Navigator, the highlighted file is white, instead of dark black.  Is there a way for me to change this?
Here is an example of what is happening:

As you can see, the file that is selected is highlighted as white, and I want it to be black as it always used to be.  Is this possible?
Comment: It's a common Xcode issue. Somehow it doesn't draw selection background.
Answer: This Is a common Xcode problem.
You can easily fix it when it happens by pressing Cmd+0 two times (one to hide the Navigator and one to show it again).
Comment: Thanks very much for sharing this!
Answer: Turn off reduce transparency can fix it! It's works for me.
Comment: Thanks for your response.  How would I do this in Xcode?
Comment: Can't do it in Xcode. Open `System Preference` -> `Accessibility` -> `Display`
Answer: Go to > System Preference > Accessibility > Display
Check > Reduce transparency
By Default, its already turned off. You just need to turn it ON and back to OFF. It works.
Answer: System Preference -> Accessibility -> Display
Check > Reduce transparency
Answer: In my case I was using multiple tabs. I just closed all the tabs leaving only one opened. It's a very dangerous bug, it reverted my info.plist file to an older version.


PySide2 crash when creating QApplication subclass within main()

Question: I have a PySide2 (220.127.116.11) app on macOS 10.14.6 that works fine under Python 3.6 and 3.7 but crashes under Python 3.8. The minimal crashing example (seg fault 11) is:
from PySide2 import QtCore, QtWidgets
from PySide2.QtCore import Qt

class AppSubclass(QtWidgets.QApplication):
    def __init__(self, *args, **kwargs):
        QtWidgets.QApplication.__init__(self, *args, **kwargs)

def main():
    app = AppSubclass()

if __name__=="__main__":
    main()

Strangely, removing the main function results in no crash:
from PySide2 import QtCore, QtWidgets
from PySide2.QtCore import Qt

class AppSubclass(QtWidgets.QApplication):
    def __init__(self, *args, **kwargs):
        QtWidgets.QApplication.__init__(self, *args, **kwargs)

app = AppSubclass()

Is there something not right about how I'm subclassing QApplication?
Comment: Although the first script shouldn't segfault, it doesn't make much sense as a self-contained example, because `app` will be immediately garbage-collected after `main()` returns. In the other example, `app` will remain alive for the entire lifetime of the script. In general, python's garbage-collector does not guarantee any particular order when deleting objects, and this can sometimes cause problems if Qt tries to delete the underlying C++ parts in a different order. The usual fix is to re-structure the code so as to ensure the QApplication is the last object deleted (e.g. make `app` global).
Comment: Thanks @ekhumoro, that was a really helpful tip. It turns out to be a bug in PySide, but it's indeed related to garbage-collection as you suggested.
Answer: This turns out to likely be a bug in PySide, which has been solved. See https://bugreports.qt.io/browse/PYSIDE-1447


Where can I find resources on Gas Furnace manufacturers

Question: We are going to replace a 30 year old residential gas furnace. We have estimates for furnaces from Rheem, Trane and Bryant. This is a rental, so we aren't going for the 95% with tax rebate but standard 80. Looking for information about these three manufacturers.
Comment: Dear StackOverflow: we should be able to edit questions. I can't find a way. I'd like to add "furnace" as a tag... :-/
Comment: Hey @kegill! There should be an `edit` link just under the tags... Is it not there? (you need to be logged in)
Answer: Are you looking for reviews or just general information about the furnaces?
This website has consumer reviews:
http://www.consumersearch.com/furnaces
Here is information about Rheem furnaces:
http://www.rheem.com/products/heating_and_cooling/gas_furnaces/
Here is information about Trane furnaces:
http://www.trane.com/residential/products/furnaces
Here is information about Bryant furnaces:
http://www.bryant.com/products/furnaces/gas/index.shtml


Finding particulair solution to $y''-3y'+2y = \cos 2x + \sin x$

Question: $$y''-3y'+2y = \cos 2x + \sin x$$
To find the particulair solution to this problem I divide it to two subproblems:
$y_p = u_p + v_p$
I then apply $u = A \sin 2x + B \cos 2x = \cos 2x$ and $v = A \sin x + B \cos x = \sin x$
As the accepted answer in solve $y''-2y'-y=\sin{3x}$
However, $$u = A \sin 2x + B \cos 2x = \cos 2x$$ gives me http://www.wolframalpha.com/input/?i=u%27%27-3u%27%2B2u%3Dcos2x the answer should be $$\frac{1}{10} \left(\cos2x-2\sin 2x\right)$$
$v = A \sin x + B \cos x = \sin x$ on the hand gives me $v_p = 0$ when I do the math (which should be correct) but https://www.wolframalpha.com/input/?i=u%27%27-3u%27%2B2u%3Dsinx
Where do I fail? This doesn't seem to be a simple calculation error.
Comment: I got the same solution as W|A did. Perhaps, the 'correct' answer in your textbook is wrong.
Comment: That is of course possible, but I get this: https://www.wolframalpha.com/input/?i=y%E2%80%B2%E2%80%B2%E2%88%923y%E2%80%B2%2B2y%3Dcos2x%2Bsinx
Answer: Make sure to plug in $u_p'$ and $u_p''$ into the original equation and equate to the entire right-hand side $\cos 2x + \sin x$. Otherwise, you won't get the whole solution.
$$u_p=A \sin(2x)+B\cos(2x)$$
$$u_p'=2A\cos(2x)-2B\sin(2x)$$
$$u_p''=-4A\sin(2x)-4B\cos(2x)$$
Plug into original equation:
$$(-4A\sin(2x)-4B\cos(2x))-3(2A\cos(2x)-2B\sin(2x))+2(A \sin(2x)+B\cos(2x))=\cos(2x)+\sin(x)$$
Expand:
$$\sin(2x)(-4A+6B+2A)=\sin(2x)(1)$$
$$\cos(2x)(-4B-6A+2B)=\cos(2x)(1)$$
Simplify:
$$(-2A+6B)=1$$
$$(-6A-2B)=1$$
Solving for $A$, $B$:
$$A=-\frac{1}{5}, B=\frac{1}{10}$$
Plug into the assumed particular solution gives exactly what we expect:
$$u_p=-\frac{1}{5}\sin(x)+\frac{1}{10}\cos(2x)$$
$$u_p=\frac{1}{10}(\cos(2x)-2\sin(x))$$
Comment: Thanks for a good answer. However it's wrong (I think) you can't compare $\sin (2x) = \sin (x) $ like you do. However this made me study the question even harder and find that I wrote it wrong (it really should be 2x everywhere). So I was solving the wrong question, that's why the solution got wrong.
Comment: But the missing part of the solution should be in $v_p$
Comment: Yeah, sorry, was writing quickly. Will edit the post.


Why isn't the diff command working as I expect in this Bash script?

Question: I'm not understanding why the diff command is not working correctly in my script. Can anybody clarify it for me?
Here is the bash script:
#!/bin/bash

SRC="src-folder"
DST="dst-folder"
FILES=( a/ b/ c/ )

for f in ${FILES[@]}; do
  cmd="diff -q  $SRC/$f $DST/$f"
  echo $cmd  # row-9
  $cmd       # row-10
done

Script output seems like this:
diff -q src-folder/a/ dst-folder/a/
diff -q src-folder/a/ dst-folder/a/
diff -q src-folder/a/ dst-folder/a/
diff -q src-folder/a/ dst-folder/a/
diff -q src-folder/a/ dst-folder/a/
diff -q src-folder/a/ dst-folder/a/
diff -q src-folder/a/ dst-folder/a/
(until buffer overflow)

When I disable/remove/comment row-10 I can see correct output (when I run these commands in an interactive shell rather than in the script I get correct results):
diff -q src-folder/a/ dst-folder/a/
diff -q src-folder/b/ dst-folder/b/
diff -q src-folder/c/ dst-folder/c/

When I change diff to rsync, everything is working correctly (call from script).
So how can I use diff in scripts? What's the reason that diff called by my script is not working as expected?
I tried also a very simple script:
#!/bin/bash

diff -q  src-folder/a dst-folder/a
diff -q  src-folder/b dst-folder/b

But it doesn't work. When I change diff command to any other (e.g. rsync), everything is working.
Comment: @Dan, might be, but why then is it working fine in an interactive shell?
Comment: This site might and most likely will help you. https://www.geeksforgeeks.org/diff-command-linux-examples/
Comment: I understand `diff` command, but I don't understand why it is not working when I call it from bash script.
Comment: Try a fully qualified path
Comment: I tried it - the same result. The first iteration ( subfolder "a" again and again)
Comment: I do not see in your question where you have done that. Please post the fully qualified path example.
Comment: when I change row-10 from `$cmd` to `exec $cmd` first iteration is executed (correctly) but next iteration of the loop is not started.
Comment: All is executed in my $HOME folder.  script is executed like this: `./show-diffs`
Comment: I guess the path is not literally `src-folder/a` but something else we don't know and you don't want tell us but which is the source of the problem. Anyways, quote your paths and the array in the for-loop and you'll be fine.
Comment: Your script runs fine for me. The only reason I can think of is that your script is calling itself when running the `diff` command. Did you overwrite `diff` to call your own script or an alias or something like that? Change `diff` to `/usr/bin/diff` and see if you still face the issue.
Answer: tl;dr: Works for me.
Long answer: When I run the script from your question on one of my test machine, it behaves exactly as expected:
a-schmidt@s-laugz2repo01:~$ ./show-diffs
diff -q src-folder/a/ dst-folder/a/
diff: src-folder/a/: No such file or directory
diff: dst-folder/a/: No such file or directory
diff -q src-folder/b/ dst-folder/b/
diff: src-folder/b/: No such file or directory
diff: dst-folder/b/: No such file or directory
diff -q src-folder/c/ dst-folder/c/
diff: src-folder/c/: No such file or directory
diff: dst-folder/c/: No such file or directory
a-schmidt@s-laugz2repo01:~$

So apparently the diff command on your system is not the same as on mine.
There are several possibilities how this could happen, for example through shell aliases or local installation of a program of that name.
In order to find out what it is, enter the shell command:
type diff

On an unmodified Ubuntu system this will output:
diff is /usr/bin/diff

If it outputs something else, such as "diff is aliased to ..." or "diff is a function ..." then you need to look into your shell profile to find out where that change is made, and possibly correct it.
Answer: I think the problem is that within your command cmd="diff -q  $SRC/$f $DST/$f" there are options and after the expansion at row-10 the string contained in $cmd is not evaluated properly as a command by Bash.
When you are using the exec command the string contained in $cmd is evaluated properly. But what exec does is that it replaces the current shell with new one where the command is executed, so your loop no longer exists after the first iteration.
I've highlighted evaluated few times because in Bash have eval command which does exactly that - evaluates a string as a command. So I think the proper solution is to modify the script like this:
eval $cmd       # row-10

As a final note, if it is the entire script, why you need to assign the command to a variable which is evaluated immediately (at the next line)? I mean in this particular case you can simplify the loop in a way as this:
for f in ${FILES[@]}; do
  diff -q  "$SRC/$f" "$DST/$f"
done

Comment: Yes, I think the error lies in `cmd="diff -q  $SRC/$f $DST/$f"; echo $cmd` that outputs `diff -q src-folder/a/ dst-folder/a/`, but $cmd is just a string at that point. Two things that may help, `shellcheck` and running the script with `bash -x -v myscript.sh` (and removing the quiet flag, -q, from diff). Easiest fix I think is either `cmd=$("diff -q  $SRC/$f $DST/$f"); echo $cmd` where $cmd now holds the output of executing the diff (due to using -q, nothing if it matches) and deleting line 10; OR replace line 10 with "$($cmd)" to execute the string you placed in the $cmd variable.
Comment: Also, proper escaping is eg `"${FILES[@]}"` and `"$SRC"/"$f"` if you want to handle spaces in filenames and such. `shellcheck` is great for helping to identify improper escaping (you can use it [online](https://www.shellcheck.net/), or install from `sudo apt install shellcheck`.


cannot found icon app after installed on emulator

Question: I installed the file apk on emulator, but I cannot find icon application on screen emulator.
I do not understand why it appears in application manager without on screen emulator.
https://lh3.googleusercontent.com/DlsuQasA2uxHKFFBJI9abrBi38fich6Ap_sgzQQyqSs=w381-h512
Comment: please post your manifest file.
Answer: Have you specified the following pointed out components in the android manifest of your android project,
android:label in the application tag is the one for setting your application's icon,and do specify the activity you want to start on the click of the application's icon from home screen as launcher as in the image
Comment: my manifest here:

i resolved it, tks so much
Comment: if this resolved your issue than you can accept it as an answer
Answer: The main activity for your app must be declared in the manifest with an  that includes the MAIN action and LAUNCHER category. For example:
<activity android:name=".MainActivity" android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>


Best Practice for hiding specific variables from Github repository?

Question: I've got a public repo on Github.  And I want to set it up with a few services that would require personal API keys.
Of course, I want to share the codebase with whoever wants it, but not my personal keys.
Is there a pattern for this?
I'm thinking I could .gitignore a file of constants and only use them on my server itself.
Just not sure what the recommended practice is for this.
FYI: it is a javascript application in Meteor.  With both server and client-side javascript.
Thanks in advance.
Comment: Here's a similar question with some great suggestions:

http://stackoverflow.com/questions/4101568/making-a-git-project-open-source-when-you-have-secret-keys
Comment: Thanks Katherine, not sure how I missed that, looks like its the way to go...
Comment: Also, retrieving the API key values being from a JSON or YAML file might help you to seperate the Config info from the code and simply use .gitignore to hide it on public repos.
Comment: Thanks Cody.  I stored my configs in a javascript object and ignored it with GIT.  Worked fine for me.  If there's a distinct advantage to using JSON instead, I'd be happy to hear it.  Either way, thanks for the response...
Comment: possible duplicate of [How to open-source an application that uses API keys](http://stackoverflow.com/questions/1983990/how-to-open-source-an-application-that-uses-api-keys)
Answer: If you don't want to share your keys, don't commit them to the repository at first. To prevent yourself from committing them accidentally, I'd propose you exclude them through an entry in the .gitignore, as you suggested. This way you can even use
<code>git add .
git commit -a -m "commit everything"
</code>
safely, without having to worry about the keys.
Comment: Thanks maenu, looks like git-filter-branch is what i was looking for.
Answer: This is a bit late but I would recommend using the Dotenv package for meteor. https://github.com/okgrow/meteor-dotenv It is very well documented and is way better in terms of security.
One thing it forgets to mention though is to add the .env file to the .gitignore
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.


Joist hangers "droop" when installed?

Question: Whenever I use hangers I end up with something that looks wrong.
Hangers have two sets of screws. One, the "flat" screws, drive into the wood your hanging onto. The others, the "diagonals" drive into the wood you're hanging. Does that make sense? Do these have official names?
I install them by holding everything with one hand and then driving in one of the "flat" screws with my free hand. Then I switch and drive one in on the other flat side, so now it's not going anywhere.
The "problem" is that when I drive in the diagonal screws, the hangers pull in toward the studs. As the hanger is slightly wider than the studs, this causes the bottom of the hanger to bow out slightly, so it is no longer in contact with the bottom of the piece being hung.
Am I doing this wrong?
Answer: If the joist hanger is slightly wider than the joist ( joist, not stud )  then do not push it in towards the joist.
Fasten it parallel with one side up against the joist and a gap on the other side. Then fasten the gap side to the ledger board parallel so it does not bow at the bottom, ( do not push it in to the joist )    Before you fasten the gap side  to the joist put a filler shim in the gap between the joist and the hanger. A piece of thin plywood could work or two shims turned so the thin edge's are facing each other so they create a flat surface. ( This allows you to adjust the thickness of them by sliding them together or apart.   you may have to trim their length )
The connection of the hanger with ledger board is important as it is what is carrying the weight of the joist and the connection of the hanger to the joist help to keep it from pulling away from the ledger board. Use a longer screw or nail to account for the thickness of the shim.
Comment: Thanks Alaska! That last bit was my concern. But I have yet to find a hanger that doesn't have this problem, every joist I've used is always subject to this. Perhaps a canadian thing?
Answer: What about this method: https://www.youtube.com/watch?v=1hv27hrOz0g I have heard of people lightly toe nailing the joist in place and then placing the hanger.

Joist hangers "droop" when installed?


How can I join vinyl decking to metal door frame?

Question: Shoddy workmanship by a lousy contractor has left me with a vinyl deck that allows water to leak into the garage below.  I identified the location of the leak - where the vinyl meets the metal frame of the sliding door.  He had put some caulking over the joint (not visible in photo, removed by me) and then screwed a thin metal cover across it, but this "solution" failed to keep water out.  The caulking had split in several spots along the gap, and it didn't seem to have cured properly on the vinyl (dry to touch but sticky/gooey when manipulated).

Is there a proper way to seal this gap that will withstand the elements (northern climate, snowy winters, sun-facing)?  I thought maybe fiberglass tape and roll-on rubber or vinyl coating but I don't know if it will stick to either the metal or the vinyl... help?
EDIT
The deck is about 1/8 inch lower than the frame on the left side, and flush on the right side.
Head-on view:

Entire length view:
Comment: hard to see from directly above - at what level are the vinyl and the metal strip? Can you post another shot head on to the area in question?
Comment: How averse are you to removing the door frame to fix this?
Comment: On a side note - wood frame patio doors - wow - old!
Comment: Built in '89.  I've never removed a door frame but if it needs to be done I'd give it a try.  My only hesitation is the possibility of creating a bigger problem that I can't fix...
Comment: Curtis can you come into chat to talk about this? http://chat.stackexchange.com/rooms/111/home-improvement  I have more questions
Answer: Based on questions answered in chat you have a case where the contractor didn't measure the deck properly, and built it too high, could not flash properly under the door frame, and performed a "some genius" move putting a transition strip (meant for interior use) over top of the door frame and the vinyl, with caulk under neath.
Stupid.
Two options:  1 cheap and temporary, 1 expensive and proper.
Cheap: Use proper caulk (props to @tester101)

Option 2 - and the door is old so this isn't actually a terrible idea.
Replace the door.  In the process, raise the rough opening of the door frame half an inch or so - however much is necessary to be able to put a proper piece of flashing under the door frame and over the vinyl.
You will probably have to custom order a door to fit your new rough opening, but at least you can seal the door area properly.
And props to @bmitch for pointing out that flashing needs to run the entire width of the deck.
Comment: Instead of flashing the entire width of the deck, usually the vinyl would go up the wall several inches.

If this is not the case, and there is also no flashing, I would call a vinyl guy (not the same one who is responsible for this atrocity) to come in and do that. they should be able to look after this, heat-welding vinyl-to-vinyl, and use some good sealant at the doorway seam and do a better job and use a better product than most homeowner specials.
Answer: In regards to flashing the full width of the deck:
Instead of flashing the entire width of the deck, usually the vinyl would go up the wall several inches. If this is not the case, and there is also no flashing, I would call a vinyl guy (not the same one who is responsible for this atrocity) to come in and do that. they should be able to look after this, heat-welding vinyl-to-vinyl, and use some good sealant at the doorway seam and do a better job and use a better product than most homeowner specials. Below is an image of a this after I reinstalled some of the siding, but you can still see how the vinyl goes up the wall.

In regards to caulking as a solution:
Just to reiterate that there is no cheap way to fix this properly at this point. Whoever built your deck is not someone who should be charging people since they have no clue what they are doing.
You can use caulking for a temporary solution but you should know that it is something you need to check and replace as necessary.
Even then you should keep in mind that even if it looks okay it might be letting a small amount of moisture in that won't show up as a visible leak but can cause rot in your framing over time. I do a lot of repairs where this is the case.
Caulking being relied on for waterproofing usually ends up as an expensive repair at some point.
May be many, many years later, but may also be sooner than you wanted.
I have many photo examples of this, but here is my current project. A roof-top deck where caulking was relied on for sealing flashing seams.

Here is a beam underneath a sliding door at the corner of a house. It had sunk over 1/2" inch and was being held together by magic and pixie dust™. (the new section is what I added in while replacing.)

I have tons more, but this should be enough to reinforce the point.
Caulking is never a "fix", it is only a band-aid solution that will help delay or prolong the inevitable result of poor workmanship.
Comment: Thanks for the answer -- I agree I'll have to get this fixed properly or I'll regret it.  The vinyl does go up the wall on either side of the doorframe, but sadly the "deck expert" built the deck floor to the same height as the frame threshold so there is no wall to go up under the frame, hence the seam that is the source of my woe.  I'll probably take @TheEvilGreebo's advice to `Replace the door. In the process, raise the rough opening of the door frame half an inch or so - however much is necessary to be able to put a proper piece of flashing under the door frame and over the vinyl.`


How to fix a dead usb port on PS4?

Question: One of the front usb port on my PS4 suddenly stopped working.
Neither charging nor connecting works using a corded controller. The very same controller connects and charge fine when plugged into the other usb port.
Since i have one corded and one cordless controller i wish to have both the ports available to charge the wireless at anytime without unplugging the corded.
What can i try at home before sending it for repair?
Is there any expansion devices to obtain multiple usb ports from the one still alive? Would a powered usb hub work?
Comment: When inserting a USB device into the dead slot, what does it feel like? Is it smooth with relatively little resistance? Does the male end appear to insert as far as the working port? Shine a light in and see if there's any dust or dirt piled up.
Comment: Apparently the look and feel is right and similar to the other one. The connector goes down all the way to the end. Also the inside looks good and the contacts shiny. I will try to clean with compressed air though. thanks for the advice
Answer: First, to test if the USB is truly dead, I would try plugging a USB phone charger into the port. Plug your phone on the other end. If the phone charges, its alive. If the phone does not react (like if you plugged it to a wire that is not wired in anywhere), first check if there is gunk in the port. Flash a flashlight straight in and it should be relatively clean. If it looks relatively clean, your port is truly dead.
From there, you got a few options:

If on warranty, send your PS4 back to Sony for a repair.
If not, you could try replacing the port yourself or go to a local geek shop that does repairs. That will very probably void any warranty (its pretty much open heart surgery on your PS4), so the other option is preferable if you got one.

IMO, if you dont have warranty I would not risk it. A switch that big just to bring back a USB port (when you have others you can use) and has chances to kill your console seems very risky.
Comment: In any console service, it should be a kind of cheap repair. Replace USB port it is not rocket science, so you can not be afraid about the big costs of it.
Comment: Doesnt that usually involve connecting new stuff to the motherboard?
Answer: It happened to me too, i found the recommendations at the link below very useful
https://careergamers.com/how-to-clean-the-ps4-controller-usb-charging-port/
If the port turns out to be really broken and the problem is only charging two controllers with one port then you can take a look at dualshock twin charging station. There are many available and they are quite affordable.

How to fix a dead usb port on PS4?


Toggle between a select or text input?

Question: Trying to determine a feasible way for the user to use a select option as an input or a text if nothing is suitable.
Most of the time, the user will be using what has been pre-populated within the select options but may have various instances that an actual text input is needed.
I don't feel that having an "other" field on the select options works with a form field being displayed after so I've come up with this solution:
The wording will not stay how it's presented, this is purely for you to see what's there on a visual basis.

Seen working here:
http://codepen.io/brycesnyder/full/WoeVrY/
Are there any potential pitfalls with this design and functionality, or is there another way to represent this?
Comment: The text input adds an extra option and this would be the selected one, right?
Comment: https://tom-select.js.org and https://github.com/select2/select2 allow users to pick from the list or add a new item to the list by typing.  That's the approach I'm going with.
Answer: Why not use a combo box?
A combo box is a combination of both a drop-down list and a text box, and is a common control element across the web.
Examples:

Kendo UI - ComboBox Demo
Stack Overflow - HTML combo box with option to type an entry
Comment: As stated; I don't think the "other" select option will work in this use-case, based on users feedback.
Comment: @BryceSnyder *other* as in it's an option in the drop-down? You wouldn't need that since you have a text field to specify what *other* is.
Answer: One of the best arguments to using list-forms and lists in general is that human beings are very good at keeping track of top-to-bottom information that flows in a sensible way. Similarly, we're used to (at least in the west) to check for the most important information in the top right corner (hence the usual logo placement). It's both what we're used to (right to left reading) and what our brains happen to be efficient at (top to bottom tracking).
While I don't necessarily dislike your design, I think you are forcing the visitor to break from the usual top-bottom eye pattern by having her/him look to the right then back to the left to input before continuing along. Just think of your to-do lists: do you write them left to right or top to bottom?
You could make an A/B test with the text input/dropdown on right and text input/dropdown on left (following the top-bottom eye movement) and see what effects this has on users?
None of this is, of course, to say that you can't try something new and disprove a theory or two!
Answer: There is a risk that the user wont see the "Text input" option. And there's another risk that the user wont understand it (the term 'input' in my opinion is not very user friendly, but rather technical). A suggestion for your design could be to rename the "Text input" to "Other" indicating the option to add something that is not contained in drop down list.
Comment: Yes, wording convention that is placed there currently is just for people to understand the intention with this UX question. I would definitely want to change it to something else, looking to see suggestions overall.
Answer: It looks like users first decision is to choose betweeen:

Predefined option
Custom option

Depending on the predefined options importance I can think of several way of approaching it.

Select:
    Option A
    Option B
    Option C
    Option Other. Fill:
        Text input

(Selecting Option other would show the text input)

Radio:
    Option A
    Option B
    Option C
    Text input

(Only one can be selected)

Radio:
    Predefined option. Select:
        Option A
        Option B
        Option C
    Custom option. Fill:
        Text input

Select:
    Option A
    Option B
    Option C
Checkbox:
    Text input

(When checking "Enter custom option" the text input should appear)

Toggle between a select or text input?


Return async function in realtime firebase database

Question: I'm still starting to program and I'm a little confused with my async function.
I'm trying to fetch the last data from the last day in my firebase realtime database, I get it as you can see in my console.log inside the function
however when I try to return this value from within the function and it comes with all the data for that last day.
in my realtime firebase database is this way:

my function is:
public async findLatestWeatherStationRecord(): Promise<WeatherStation> {
  const RefR = database.ref('Prototipo0/Leitura/');

  const latestWeatherStationRecord = await RefR.limitToLast(1).once(
    'value',
    snapshot => {
      snapshot.forEach(child => {
        database
          .ref(`Prototipo0/Leitura/${child.key}`)
          .limitToLast(1)
          .once('value', snapshot => {
            snapshot.forEach(childSnapshot => {
              const lastMeasurements = childSnapshot.val();
              console.log(lastMeasurements);
              return lastMeasurements;
            });
          });
      });
    },
  );
  // console.log(latestWeatherStationRecord.val());
  return latestWeatherStationRecord;
}

the result of console.log inside the function looks like this:
{
  anemometro: 2.8,
  bh1750Luminosidade: 1185,
  bmp280Altitude: 653.58,
  bmp280Pressao: 94739,
  csmsv12Solo: 40.76,
  dht22Temperatura: 27.9,
  dht22Umidade: 31.7,
  mhrdMolhamento: -0.04,
  pluviometro: 0,
  timestamp: 1598554509834,
  uvm30aIndiceUv: 1
}

I'm breaking my head now, because the return of this function does not give the same result as the return inside the function (console.log). It returns all data for that day and not the last of the function
    ...,
    '-MFlG2p4zMPCC7iQ6Y1D': {
      anemometro: 3.73,
      bh1750Luminosidade: 1187,
      bmp280Altitude: 653.27,
      bmp280Pressao: 94742,
      csmsv12Solo: 40.81,
      dht22Temperatura: 28,
      dht22Umidade: 32.5,
      mhrdMolhamento: -0.04,
      pluviometro: 0,
      timestamp: 1598554389829,
      uvm30aIndiceUv: 1
    },
    '-MFlGHWOxi16Qc2HEPba': {
      anemometro: 2.8,
      bh1750Luminosidade: 1184,
      bmp280Altitude: 653.72,
      bmp280Pressao: 94737,
      csmsv12Solo: 40.79,
      dht22Temperatura: 27.9,
      dht22Umidade: 31.6,
      mhrdMolhamento: -0.04,
      pluviometro: 0,
      timestamp: 1598554450009,
      uvm30aIndiceUv: 1
    },
    '-MFlGW78ZQcHJ8reA0YD': {
      anemometro: 2.8,
      bh1750Luminosidade: 1185,
      bmp280Altitude: 653.58,
      bmp280Pressao: 94739,
      csmsv12Solo: 40.76,
      dht22Temperatura: 27.9,
      dht22Umidade: 31.7,
      mhrdMolhamento: -0.04,
      pluviometro: 0,
      timestamp: 1598554509834,
      uvm30aIndiceUv: 1
    }
  }
}

I wanted to know why the return inside the function is not the same as outside the function.
I would like the end result to be the same from within the function.
Can anyone give me a light?
Edit - Sorry again now my fuction is this way
public async findLatestWeatherStationRecord(): Promise<WeatherStation> {
  const Ref = database.ref('Prototipo0/Leitura/');
  const snapshot = await Ref.limitToLast(1).once('value');

  let latestWeatherStationRecord;

  snapshot.forEach(child => {
    database
      .ref(`Prototipo0/Leitura/${child.key}`)
      .limitToLast(1)
      .once('value', snapshot => {
        snapshot.forEach(childSnapshot => {
          latestWeatherStationRecord = childSnapshot.val();
          // console.log(latestWeatherStationRecord);
          return latestWeatherStationRecord;
        });
      });
  });
  console.log(latestWeatherStationRecord);
// I need to return the snapshot function, but I can't
  return latestWeatherStationRecord;
}

Comment: On Stack Overflow, don't show pictures of text and code.  Copy the text into the question itself and format it so that it's easy to read, copy, and search.
Comment: sorry, i think it's better now.
Answer: You're not using the promise that is returned by once(), but are using the callback to do your processing. This means your return still runs before your processing.
The solution is to separate the await from the rest of your processing:
const snapshot = await RefR.limitToLast(1).once("value");
let latestWeatherStationRecord;
snapshot.forEach((child) => {
  child.forEach(childSnapshot => {
    latestWeatherStationRecord = childSnapshot.val();
  });
});
return latestWeatherStationRecord;

Comment: "the cosole.log outside the function" Which `console.log` is that?
Comment: That means you're doing something else wrong after the `await`. If you update your question to show what you've done, I can have a look.
Comment: You're loading the data again, which is again an asynchronous operation. It's also not needed, so I updated my answer to contain the entire code that I think you need. If this doesn't work, step through this code in a debugger, and check what each line does, and where it goes wrong.
Comment: this way the cosole.log outside the function returns undefined.
Comment: if I make a console.log from "latestWeatherStationRecord" it returns me undefined.
Comment: I updated my question, I'm sorry for my inexperience.


Seeds to paper with lore

Question: So, I need seeds to change to paper when they come into play. I give a player a stick in gamemode adventure that can only break grass. When they get seeds, I have it change to paper. I want this paper to have a lore on it. How would I do that with my command:
/entitydata @e[type=Item,score_Seeds_min=1] {Item:{id:"minecraft:paper"}}

Comment: Possible duplicate of [Where do I put item tags on items inside a chest or your inventory?](https://gaming.stackexchange.com/questions/272179/where-do-i-put-item-tags-on-items-inside-a-chest-or-your-inventory)
Comment: You get answers when you get them.  We frown on bumping questions here; if you're not going to edit your question to clarify, then there's no reason to do so.  To that end, I have removed the parts that weren't relevant to asking your question.
Answer: The tag compound of the item format holds any data that is not the root id, Damage, Count, and Slot tags. The display compound holds the Lore list:
/entitydata @e[type=Item,score_Seeds_min=1] {Item:{id:"minecraft:paper",tag:{display:{Lore:["Lore line 1","Lore line 2"]}}}}

Seeds to paper with lore


Packaging an Angular library with i18n support

Question: Angular's i18n is great, and tools like ng-packagr makes component library packaging extremely easy, but can they be combined?
What if i want to package and distribute a component library having translatable components? Is it possible? How do I package such a library? Will translation files be shipped together with the package, or should they be defined in the main app?
It'd be great if someone could point me at some doc.
Thanks
Comment: I am facing the same problem now.
Have you found a solution?
Comment: Here's a simple solution I've found out! https://stackoverflow.com/a/67824442/2448200
Answer: When you generate a translation file for the main app with the CLI (with ng xi18n), elements with the attribute i18n in the library are imported in the translation file. You can then define the translations in the main app.
Comment: But what if I want to distribute official translations of my library with it? How do I approach this?
Comment: I have yet to start preparing my library for distribution, once I get to that stage I might come up with something. Will keep in mind posting here, although I'm not sure it would be any time soon :)
Comment: Also interested in this. Haven't found anything about distributing translations with an Angular library.
Comment: That is correct. But there is another way where you can define the translations in your component library, thats how some ng elements do, like ng bootstrap. It switch locale languages based on the server locale configuration.
Comment: How did you solve this warning "No name was provided for external module '@ngx-translate/i18n-polyfill' in output.globals – guessing 'i18nPolyfill'" ? I ahve tried to add it to paths but it won't work. If I add it to ng-package.json in umdModuleIds list then it will go away, but is this correct way to use it. Maybe this is new topic but I think you maybe have already solve it.
Comment: @waterplea did you find a way to do it?
Answer: There are two ways of doing so - statically providing the assets and bundling on build time or configuring translation path on runtime.

In order to statically include files on build time, you just use setTranslations in the code, as mentioned in https://github.com/ngx-translate/core docs. Then, you can just bundle your translations with the code.
Better would be to let consumer know what to use. In order to properly be able to provide path to translation files (assuming standard structure, where every translation is residing in a separate file containing language in the name), you can do something as follows:
interface TranslationsConfig {
  prefix: string;
  suffix: string;
}

export const TRANSLATIONS_CONFIG = new InjectionToken('TRANSLATIONS_CONFIG');

@NgModule({
  declarations: [],
  imports: [
    NgxTranslateModule,
  ],
  exports: [
    NgxTranslateModule,
  ]
})
export class TranslateModule {
  public static forRoot(config: TranslationsConfig): ModuleWithProviders {
    return {
      ngModule: TranslateModule,
      providers: [
        {
          provide: TRANSLATIONS_CONFIG,
          useValue: config
        },
        ...NgxTranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useFactory: HttpLoaderFactory,
            deps: [HttpClient, TRANSLATIONS_CONFIG]
        }
      }).providers
    ],
  };
}

}

This code makes sure that when building library, AOT will be able to resolve types (hence InjectionToken etc.) and allows to create custom translations loader.
Now it's only up to you to implement loader factory or class that will use the config! This is mine (I'm using POs for my translations):
export function HttpLoaderFactory(http: HttpClient, config: TranslationsConfig) {
  return new TranslatePoHttpLoader(http, config.prefix, config.suffix);
}

Please do remember to export every class and function that you're using in the module as that's prerequisite for AOT (and libraries are built with AOT by default).
To use this whole solution, wherever you use your main library module or this translation module, you can just call TranslateModule.forRoot(/* Your config here */). If this is not the main module exported, more on using hierarchical modules with forRoot here:
How to use .forRoot() within feature modules hierarchy
Comment: Question was not about ngx-translate
Comment: Should still we use the `ng-packagr` tool in `Angular 7.2` when packaging a library ?


htaccess redirect: "example.com/?deletethis" to "example.com"

Question: I've trying to redirect (with .htaccess file) this:
http://www.example.com/?deletethis
to:
http://example.com
I try this:
    RewriteEngine On
RewriteCond %{QUERY_STRING} deletethis [NC]
RewriteRule . http://example.com/? [R=301,L]

But doesn't work, I try this:
    RewriteEngine On
Redirect 301 /?deletethis http://example.com

But doesn't work either.
Answer: Try this:
RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} deletethis [NC]
RewriteRule ^ http://example.com/? [R=301,L]

Replace . with ^
Comment: Very thanks for your help. Your solution isn't very easy. I worked a few hours on it!!


Make a background image static?

Question: So, I'm trying to make the background image static, and have the foreground content move over it. Having some issues, what am I doing wrong? Here is my current code.
body
{
color: #000;
margin: 10px 0px 10px 0px;
background-color: #ffffff;
background-image:url('http://userlogos.org/files/backgrounds/Mafia_Penguin/Map1280x800.jpg');
background-repeat:no-repeat;
font-family: Arial, Helvetica, sans-serif;
}

Answer: You need to set the background-attachment property to fix the background image.
background-attachment: fixed;

Make a background image static?


Big-O notation calculation, O(n) * O(log n) = O(n log n)

Question: I need to design an algorithm that is able to do some calculations in given O notation. It has been some time since I last calculated with O notation and I am a bit confused on how to add different O notations together.
O(n) * O(log n) = O(n log n)

O(n) + O(n) = O(2n) = O(n)

O(n) * O(log n) + O(n log n) = O(n log n) + O(n log n) = O(n log n)

Are these correct? What other rules have I overlooked?
Comment: I have edited the title (formerly `O(n) + O(log n) = O(n log n)`) to be correct now.
Comment: My comment is tangential, but some may find it interesting.  The notation O(log n) occasions more confusion than almost anything I have seen in computer science.  Almost everybody seems to believe that O(log n) differs from O(1) -- except that it doesn't.  You can prove that it doesn't by application of L'Hospital's rule.  One should hesitate to abandon a clean algorithm to improve O(log n) to O(1), even if n == 1 billion.  The gains simply aren't there (you can run the numbers if you don't believe me), whereas the gains are indeed there if the abandoned algorithm is, say, O(sqrt(n)).
Answer: The rule for multiplication is really simple:
O(f) * O(g) = O(f * g)

The sum of two O terms is harder to calculate if you want it to work for arbitrary functions.
However, if f ∈ O(g), then f + g ∈ O(g).
Therefore, your calculations are correct, but your original title is not;
O(n) + O(log n) = O(n)

Comment: Why don't you just write "For f = O(g): O(f) + O(g) = O(g)"?
Comment: Thank you, i though so, but got a bit confused when trying to juggle the algorithm :D thank you for your quick response.
Comment: Wouldn't that make it ... *incorrect*? That is, `max(n, log n)` => `n`?
Comment: Yes, the relation in the title of the post is incorrect: `O(n) + O(log n) = O(n log n)`. But the relation he made in the post is correct: `O(n) * O(log n) = O(n log n)`.
Comment: @sch Oops, the rules are correct, but the conclusion is not, is what I should have said. It is hardly fair to say "correct" in this case.
Comment: Updated the answer. Since `O(log(n))` is a subset of `O(n)`, `O(n) + O(log n) = O(n)`
Comment: I have edited the title (formerly `O(n) + O(log n) = O(n log n)`) to be correct now.
Comment: Your definition of `max` is wrong. If `O(f) + O(g) = O(max(f, g))`, then `max` has to be defined *pointwise*. Consider f(n) = n, g(n) = 1 for even n and n^2 else. Then O(max(f, g)) = O(h), where h(n) = n for even n, and n^2 else.
Comment: @WolframH Doesn't `O(n)` allow "for all `n > N`"?
Comment: @WolframH Yeah, that definition was overly informal. Rectified it by defining max over the sets. It's technically correct, but makes it harder to read imho.
Comment: @pst I don't see how that would make a difference in my example.
Comment: @phihag It's still not right. O(f) + O(g) need not be O(f) or O(g), and you still seem to state that.
Comment: @WolframH You're right. I've restricted the definition to monotonic functions. It's correct for those, right?
Comment: @phihag It's wrong for all g, f where neither f = O(g) nor g = O(f). Take f(n) = n!, g(n) = sqrt(n) * n! for n odd, g(n) = g(n-1) for n even.
Comment: You're totally right. Sorry, I should've seen that. Changed to the union, with an explanation.
Comment: Still not correct. `O(x) + O(y) = O(x + y)`. If `|f| <= A*x` and `|g| <= B*y`, then obviously `|f+g| <= max(A,B)*(x+y)`. Conversely, if `|h| <= C*(x+y)`, let `f(t) = sign(h(t))*C*x(t)` if `|h(t)| > C*x(t)` and `f(t) = h(t)` otherwise, `g(t) = h(t) - f(t)`. Then `|f| <= C*x` by construction, and `|g| <= C*y` because 1. if `h(t) < -C*x(t)`, then `|g(t)| = |h(t) - (-C*x(t))| = |h(t)| - C*x(t) <= C*y(t)`; 2. if `-C*x(t) <= h(t) <= C*x(t)`, then `|g(t)| = 0 <= C*y(t)` and 3. if `h(t) > C*x(t)`, then `|g(t)| = |h(t) - C*x(t)| = |h(t)| - C*x(t) <= C*y(t)`.
Comment: I removed the third assertion, which was irrelevant to the question and indeed overly simplified, and linked to the Wikipedia article.
Comment: This answer links to the Wikipedia article, but still makes up its own (wrong) rules for the sum... -1
Comment: @WolframH Completely rewrote it.


Find probability of uniform distribution over interval [a, b]

Question: I am solving a uniform distribution with no real number value given to the interval. Therefore, I would like to seek comments for idea of problem solving. My question is in below:
Let  $X$  be a random variable with a uniform distribution over $[a,b]$, i. e. $X$ has a pdf given by:
$$
f(x)=
\begin{cases}
\tfrac{1}{b-a}\quad \text{for }a\leq x\leq b,\\
 0 \qquad\qquad\;\, \text{otherwise},
\end{cases}
$$
Let $\mu$ $= E(X)$ and $\sigma$ the standard deviation of $X$
Find:
a. $\quad {\mathrm Pr}( \mu-\sigma \;<\; X \;<\; \mu+\sigma ) \;\;\;\;$
b. $\quad {\mathrm Pr}( \mu-2\sigma \;<\; X \;<\; \mu+2\sigma ) \;\;\;\;$
My understanding of this question are in below:

$\mu$ $= E(X) = \tfrac{a+b}{2}$
$Var(X) = \tfrac{{(b-a)}^{2}}{12}$
$\sigma = \tfrac{b-a}{\sqrt{12}}$
$2\sigma = 2* \tfrac{b-a}{\sqrt{12}}$

My questions are in below:

With no real number value given in interval $[a,b]$, how to calculate $\mu\pm\sigma$ and $\mu\pm2\sigma$?
Also with no real number value given in interval $[a,b]$, how can we plug it into $f(x)$ to calculate the probability?
Comment: It is uniform distribution so the first one should be $2 \sigma / (b-a)$. Similarly the second one would be $4 \sigma / (b-a)$
Comment: Thanks @MathLover comment. May I know how to get 2σ/(b−a) ?
Comment: @HaRLoFei : did you look at my answer?
Comment: Thanks @tommik. I just got your answer when I refresh this page. Thank you very very much!
Comment: If it is uniform distribution, for any given interval, the probability is the interval multiplied by density or you can do this way $ \displaystyle \int_{\mu - \sigma}^{\mu + \sigma} 1 / (b-a) ~ dx = 2 \sigma / (b-a)$
Answer: The two questions are special cases of $P(\mu-k\sigma\le X\le \mu+k\sigma)$, for $k\in\mathbb R,$ where $X\sim\text{Uniform}(a,b)$.
Note that $[\mu-\sigma\sqrt{3},\mu+\sigma\sqrt{3}]=[a,b],$ so
$$k\gt\sqrt{3}\implies[\mu-k\sigma,\mu+k\sigma]\supset[a,b]\\
k\le\sqrt{3}\implies[\mu-k\sigma,\mu+k\sigma]\subseteq[a,b].$$
Therefore,
$$P(\mu-k\sigma\le X\le \mu+k\sigma)=\begin{cases}
0&\text{if }k<0\\[1ex]
{2k\sigma\over b-a}={k\over\sqrt{3}}&\text{if }0\le k\le\sqrt{3}\\[1ex]
1&\text{if }k\gt\sqrt{3} \end{cases}\tag{1}$$
This result for $k<0$ is self-evident, and the result for $0\le k\le\sqrt{3}$ follows because in that case $[\mu-k\sigma,\mu+k\sigma]\subseteq[a,b]$, and for a uniform distribution the probability of a subinterval of the support is just the length of the subinterval divided by the length of the support. The result for $k>\sqrt{3}$ follows because in that case $[\mu-k\sigma,\mu+k\sigma]\supset[a,b]$.
Note that since (1) happens to be a CDF as a function of $k$ and is equal to $P\left(\left|X-\mu\over\sigma\right|\le k\right)$, we have shown that $\left|X-\mu\over\sigma\right|\sim\text{Uniform}(0,\sqrt{3}).$
Answer: You correctly wrote your uniform density. Moreover, remember (you can easy calculate it) that
$$F_X(x)=\frac{x-a}{b-a}$$
thus
$$\begin{align}
\mathbb{P}[\mu-\sigma<X<\mu+\sigma]&=F_X(\mu+\sigma)-F_X(\mu-\sigma)\\
&=\frac{\mu+\sigma-a}{b-a}-\frac{\mu-\sigma-a}{b-a}\\
&=\frac{2\sigma}{b-a}\\
&=\frac{1}{\sqrt{3}}
\end{align}$$
... and similarly the second question
Comment: Since the cdf has that form only when $a\le x\le b$, we really need to establish whether $\mu\pm \sigma$ are in that interval (a little algebra shows they are, so your answer applies). Likewise, for the second question, we need to establish whether $\mu\pm 2\sigma$ are in that interval (they are not, so that probability is $1$).


Branches Ahead/Behind based only on Code Changes

Question: For our projects have Integration and Master branch. For deployment we cut a RC branch off Integration. Once deploy is complete we create Pull request for RC to Master.
However, now Master shows as 1 ahead because it has a commit that does not exist in Integration. I considered to create Pull request RC to Integration as well, but TFS does not allow it since there are no changes.
Is there a way to avoid this situation with Master? Can behind/ahead only check the code changes and not commits? To fix this I now have to create Pull Master to Integration, and that is a pain for all the projects we do.
Answer: Afraid not able to avoid this situation. It's also not possible to make behind/ahead only check the code changes and not commits. Since you are using Pull Request (which execute git merge --no-ff).
To be honest, it's not necessary to resolve Integration branch behind/ahead master.
you can have two mostly independent branches without any problems. The important measure of differences between branches is given by git diff. If this reports no differences, then it's Ok.
You could also take a look at this similar question: VSTS Git: Is it necesary to resolve dev branch behind/ahead master and if so how?
If you insist on avoid the ahead on Master, you may have to create Pull Master to Integration as you have pointed out in the question.


How to prevent user for access inner page if not loggged in Using Reactjs

Question: I am working with Reactjs and using nextjs framework,I am working on Login and logout module,I want if any user trying to access inner page without "loggged in" then he should redirect to "index/login" page,How can i do this ? Here is my current code if someone login with correct credentials
 const handleSubmit = (e: any) => {
          sessionStorage.setItem("email", response.data.email);
          const email = sessionStorage.getItem("email");
          router.push('/dashboard');
       }

Answer: I think for checking user authentication it's better to store email or token in cookie and in getServerSideProps check cookie (because you have no access to localStorage in it)
and in getServerSideProps you can access cookie via req.cookies or use cookies package
sth like this :
import Cookies from 'cookies';

export const getServerSideProps = async ({ req, res, locale, ...ctx }) => {
  if (req) {
   // const posts = axios.get...
    const cookies = new Cookies(req, res);
    const token = cookies.get('email');
    if (!token) {
      return {
        redirect: {
          destination: '/login',
          statusCode: 401
        }
      }
    }
    return {
      props: {
        posts,
        // your other props
       },
    };
  }
}

and in client code to set cookie you can use js-cookie package
forexample :
import Cookies from 'js-cookie'

 const handleSubmit = (e: any) => {
      const email = response.data.email
      Cookies.set('email', email )
      router.push('/dashboard');
   }

Comment: Sir in which file should i use this code ( getServerSideProps  ) , index.js  (login page) right ?
Comment: in any page that you don't want user see if he is not authenticated
Comment: forexample dashboard,profile, etc
Comment: On Every page ?
Comment: yes, pages that guest user cannot see
Comment: @AliSattarzadeh FYI, req.cookies is available and there is no need for external libraries.
Comment: you are right, let me up answer @Amirhossein
Comment: @AliSattarzadeh I am already using "serversideprops" or "staticprops" in some files so in that case what should i do ?
Comment: append them there and return props with other value, let me update my answer again
Comment: @AliSattarzadeh Sir, can you update your answer one more time, means please explain how to append two serverside or static props , ( just give me example )
Comment: I dont think getStaticProps would be ok for these kind of pages and I think it's better to change them to getServerSideProps .
I update the answer
Comment: @AliSattarzadeh Sir, actually in some pages i used "staticprops" so i want to know that can we us "server sideprops" in that file ?
Comment: no you cannot have both of them in same page , it's better to move codes from getStatisProps to getServerSideProps
Comment: @AliSattarzadeh How can we use multiple (2 times) serverside props in single page ? with above code ( in req, res line) i am getting erors like "req.implicity has an any type"
Comment: no not using that twice, combine them.
I added posts in my answer and axios.get to show you how to combine
Comment: @AliSattarzadeh your code giving me error sir ""req.implicity has an any type""
Comment: r u using typescript?
Answer: Well you can do this by holding a context in your whole project or a state or props in specific pages that need permission to view.
So let's assume you have a Dashboard page. You can handle your login in getServerSideProps for better experience and also redirect your user with redirect property before even letting the user to see your page:
export const DashboardPage = (props) => {
  console.log(props.data);
  return /* ... */;
};

export async function getServerSideProps(context) {
  const res = await fetch(`Your Login URL`)
  const data = await res.json()

  if (!data) {
    return {
      redirect: {
        destination: '/login',
        permanent: false,
      },
    }
  }

  /* The rest logic of your getServerSideProps */

  return {
    props: {
      data: data,
      /* other props */
    }
  }
}

In this way you should use the logic in every page you have.
Instead you can send the login request from client and set the response to a context value and use that context in every other pages and components.
Context File:
import React, { useState, useEffect } from 'react';

export const UserContext = React.createContext();

export function UserProvider({ children }) {
    const [userData, setUserData] = useState(null);
    const [isLoggedIn, setIsLoggedIn] = useState();

    const value = { userData, setUserData, isLoggedIn, setMode };

    const handleLogin = async () => {
        const res = await fetch(`Your Login URL`);
        if(res.status === 200) {
            const data = await res.json();
            setUserData(data);
            setIsLoggedIn(true);
        } else {
            setIsLoggedIn(false);
        }
    }

    useEffect(() => {
        handleLogin();
    }, []);

    return (
        <UserContext.Provider value={value}>
            { children }
        </UserContext.Provider>
    );
}

And then use the values in your pages, for example Dashboard:
export const DashboardPage = (props) => {
  const { isLoggedIn } = useContext(UserContext);

  useEffect(() => {
    if(isLoggedIn === false) {
      router.push('/login');
    }
  }, [isLoggedIn]);
  return /* ... */;
};

Comment: please explain 2nd point, How can i use 2 different props
Comment: I edited my code and added some comments to the first section. You should write a single `getServerSideProps` and then in its return data, return your props like `return { props: { data: data, a: a, b: b, ... } }`
Comment: Sir, First of all Thank you so much for reply,Actually i am new in Nextjs so i have 2 questions
1) what is "url" in await.fetch line ?
2) let suppose i want to restrict user to see dashboard page but in dashboard page there is already "getserversideprops" or "staticprops" exist then what should i do ? can we use 2 "serversideprops"  in same file ?
Comment: You're welcome. I also updated my answer to use a new way to reach your purpose. About your questions: 1) url is the url that you're trying to call to login the user. 2) you can't have 2 `getServerSideProps`. Instead you should add the logic to the previous one.


Generating function from recurrence relation of binomial distribution

Question: Hello i have given recurrence like this :
$$p_{n,k}=(1-q)p_{n-1,k-1}+qp_{n-1,k}$$
my question is how to get (step by step) generating function from this recurrence?
we know that it's some king of distribution and from how it looks we can say it's binomial distribution.
Comment: Which kind of generating function do you want? Probability, moment, cumulant?
Comment: i think Probability would be the best one
Answer: The probability generating function is $G_n(t):=\sum_{k=0}^n p_{n,\,k}t^k$, so $G_0=1$ and for $n\ge 1$ we have $$G_n(t)=q^n+\sum_{k=1}^n ((1-q)p_{n-1,\,k-1}+qp_{n-1,\,k})t^k\\=q^n+(1-q)tG_{n-1}(t)+q(G_{n-1}(t)-q^{n-1})\\=(q+(1-q)t)G_{n-1}(t).$$Hence $G_n(t)=(q+(1-q)t)^n$ for all $n$.


Upscaling 720p to 1080p vs upscaling 768p to 1080p

Question: Suppose I can run some graphics in 1366x768 equally well as 1280x720, and I have a 1920x1080 monitor.
There are more pixels in 1366x768 than in 1280x720.  However, in 1280x720, a 2x2 grid of pixels fits exactly within a 3x3 grid of physical pixels in my monitor.
So which should look better, and is there any theoretical basis for which one looks better?  Does the 3:2 ratio mean anything at all?
Comment: Think of it like this which one looks more sharp one that is blurred more versus one that is blurred less.
Answer: With a good-quality upscaling filter (bicubic, for example), there's no particular importance to the 3:2 ratio. Starting from a higher-resolution source will produce a better-looking final image.
It's true that if you're programming the upscaler from scratch, making one for a fixed ratio like 3:2 is much simpler than making one that handles arbitrary ratios. But image-processing software, monitors, etc probably have arbitrary-ratio upscaling built in anyway.
Comment: Which filters do most monitors use?


What type of fixing is this, and how do I remove it?

Question: I've been trying to remove floating shelves fixed onto a masonry wall with no visible screws. After cutting into it with a saw, I've found it is held up with the following fixing:

The exposed part of it was screwed into the wood of the shelf, and it appears the part in the wall has perhaps been set with some sort of mortar.
What type of fixing is this, and how do I remove it from the wall?
Also, I still have a bunch of shelves still in the wall that I need to take down. So far I've just been going at it with my reciprocating saw, as both my hammer drill and oscillating multitool seemed to have no impact on them. However, even with the saw, I've broken a few blades so far (possibly due to the awkward angles involved).
Is there something better I should be using to remove shelves fixed in this manner?
Comment: It looks like a lag bolt, but with the pointy end shorten by grinding at an angle.  Don't know how well it would screw in like that.
Comment: Given the shank to threads relationship, I think you might have the (large) head of the lag set in mortar. Try hitting it with a big sledgehammer. Then patch the big hole.
Comment: Experiment: Try to use a hammer drill to ream out a larger hole around the bolt in the wall, full depth of the bolt, then a sledge hammer to loosen the bolt in the now-weakened hole in the wall.  If that's not too difficult it leaves the bolts in the shelves, you don't have to cut the shelves or the bolts.
Answer: My guess is it'e some type of hanger bolt, with an expansion shield embedded in the wall similar to the one shown below from Harfington,https://www.harfington.com/products/p-1039484. I'd think about getting a rotary tool, Dremel, with a cutoff wheel and just cut them off. An angle grinder would work too. Try grabbing the protruding screw with some vise grips and see if you can turn it.
Comment: It is expected that your answer provide attribution to where / whom the picture came from. Please update your answer to comply with SE policies.
Comment: @MichaelKaras   Done
Answer: If you like to cut them all flush with the wall, the simplest and quickest way is to use a grinder with a cut off blade.
You will cut all of them without struggle and fast.
Images courtesy of Harbor Freight.
I would think there is no need to remove them from the wall.
Comment: It is expected that your answer provide attribution to where / whom the picture came from. Please update your answer to comply with SE policies.
Answer: Chemical anchor
From your photo it's fairly likely that this is a chemical anchor: a bolt that is basically glued into the wall using a really strong polyester resin (you can see the slightly differently coloured material surrounding the bolt in the hole). These are much stronger than anything purely mechanical, so they are typically used where mechanical (expansion/toggle) anchors won't do. Once the resin cures, there's nothing in the world that will remove the bolt; the wall will probably give way before the resin does.
I suspect the author screwed the bolts into the shelves first, injected the resin into the holes in the wall and then just pushed the bolts into the holes and waited a little for the resin to set.
Given all this, cutting the bolts flush with the wall is probably your only option. Because they are typically made from really tough steel (to match the strength of the resin), you will probably need brute force in the shape of an angle grinder (a plasma cutter or oxyacetylene torch would do, too).


How do you unlock the Tog_ImLame achievement?

Question: How do you, then, unlock this achievement?
I am reluctant to make this post, but the cat is out of the bag now.
Answer: The short version is:

Enable the console (Options → Enable Console)
Start a game
Hit Tab
Type in Tog_ImLame SUPER0451LOL
Hit Enter.
Pat yourself on the back for your leet googling skills.

"Ah, badp. But whenceforth dost that gibberish come? Surely there must have been a way to find out!"
That's the long version of the answer, and since that is not a story that is mine to publish, I'm holding my tongue. :)
Comment: *"since that is not a story that is mine to publish..."* - So how about providing a source?
Comment: I don't have the game, but not mentioning how the code is obtained makes this answer incomplete.
Comment: @BlueRaja-DannyPflughoeft How about you try it for yourself and see that it works? :)


Removed rows containing missing values (geom_errorbarh) in R

Question: I have a csv file which is separated by tab space. Note: The confidence_interval column has values (lower and upper) which is separated by space.
Clusters vs regions
#Cluster        total_cluster_markers   total_gene_list overlap confidence_interval     p-value odds_ratio
cluster0_fisher 512     5840    209     1.7182382746801 2.47748441988708        1.481417e-14    2.064883
cluster1_fisher 425     5840    151     1.32891483798265 2.00728239610416       2.765814e-06    1.635712
cluster2_fisher 2339    5840    778     1.39944144525363 1.68467086400037       2.828628e-19    1.535827
cluster3_fisher 745     5840    294     1.68442891430663 2.28721533485484       1.176685e-17    1.96402
cluster4_fisher 960     5840    359     1.57334775537734 2.06762614937187       4.882507e-17    1.804544
cluster5_fisher 1038    5840    401     1.6771709720448 2.17858158866511        7.620883e-22    1.91242
cluster6_fisher 601     5840    258     1.91504755165867 2.67872178784458       3.390846e-21    2.266055
cluster7_fisher 914     5840    365     1.75583321881608 2.31518016906748       8.043077e-23    2.017119
cluster8_fisher 1144    5840    435     1.6468354153442 2.11561394952237        4.589145e-22    1.867252
cluster9_fisher 2390    5840    870     1.64540029553634 1.97088684681019       1.797583e-36    1.801035
cluster10_fisher        2564    5840    952     1.72111579504647 2.04939671061079       2.037412e-44    1.87854
cluster11_fisher        510     5840    212     1.77408302607108 2.55721196987857       7.082665e-16    2.131412
cluster12_fisher        1692    5840    654     1.76451430192618 2.17296718053884       1.0919e-35      1.958701
cluster13_fisher        3083    5840    1134    1.73401721793267 2.03895922438595       2.043825e-51    1.880658
cluster14_fisher        733     5840    276     1.55077148161245 2.11642986931938       1.094299e-13    1.812898
cluster15_fisher        1373    5840    377     0.988223149703785 1.26730522269035      0.07333463      1.119935
cluster16_fisher        703     5840    273     1.62824034204187 2.23248738568041       1.911082e-15    1.908004

I need to make errorbar plot using odds ratio and CI, here is the code I am using:
library('ggplot2')
args <- commandArgs(TRUE)
cluster_file <- args[1]
headers=read.csv(cluster_file, skip = 1, sep='\t', header = F, nrows = 1, as.is = T)
boxLabels = c("C0","C1", "C2", "C3",
          "C4", "C5", "C6",
          "C7", "C8", "C9",
          "C10", "C11","C12",
          "C13", "C14","C15",
          "C16")

dat <- read.csv(cluster_file, header=FALSE, sep='\t' ,skip=2,
                 stringsAsFactors = FALSE)
colnames(dat)=headers

dat <- cbind(dat, do.call("rbind", strsplit(dat[, 5], " ")))
pdf("rplot.pdf")
boxCILow=c(dat$"1")
boxCIHigh=c(dat$"2")
(p <- ggplot(dat, aes(x = odds_ratio, y = boxLabels)) +
    geom_vline(aes(xintercept = 1), size = .25, linetype = "dashed") +
    geom_errorbarh(aes(xmax = boxCIHigh, xmin = boxCILow), size = .5,
 height =
            .2, color = "gray50") +
 geom_point(size = 2, color = "orange") +
 scale_x_continuous(breaks = seq(1.0, 3.0, 0.1), labels = seq(1.0, 3.0, 0.1),
                   limits =  c(0.9,3.0)) +
 theme_bw()+
 theme(panel.grid.minor = element_blank()) +
 ylab("") +
 xlab("Odds ratio") +
 ggtitle(tools::file_path_sans_ext(cluster_file))
)
dev.plot()

Here is the warning I get:
Removed 15 rows containing missing values (geom_errorbarh).
The graph does not look right. I have manually input 3 vectors using same data to the ggplot2 code and the graph looks right. So I am wondering if I have parsed the information from csv file correctly?
Comment: Have you print the columns you got to check if it what parsed correctly or not ? I mean, `print(dat$C4)`, `print(dat$C5)`... ?
Comment: There is no C4, C5 in the CSV file. boxLabels is only a vector where I define what labels I want on the y-axis. I have however printed dat$"#Cluster" and that looks ok
Comment: Ok, sorry for the unclarity, but I meant `dat[,4]`, `dat[,5]`... to verify how the column vectors looks like, if it's the correct list of numbers and if they are detected as numeric vectors and not list of strings.. Not only the first column
Comment: Yes, CI gets detected as strings - "1.7182382746801 2.47748441988708 "   "1.32891483798265 2.00728239610416 ". I converted it after cbind line like this: boxCILow=c(as.double(dat$"1")), but I get the same result.
Comment: Could be related to the axis scale then: https://stackoverflow.com/questions/32505298/explain-ggplot2-warning-removed-k-rows-containing-missing-values
Comment: I used the same dataset but input it as vectors, df <- data.frame(yAxis = length(boxLabels):1,
             boxOdds = (c(2.064883,1.635712,1.535827,1.96402,1.804544,1.91242,2.266055,2.017119,1.867252,1.801035,1.87854,2.131412,1.958701,1.880658,1.812898,1.119935,1.908004)),).. and the correct plot was generated. So I am thinking it is to do with formatting of data when it goes into ggplot2
Answer: Making use of library('tidyverse') solves the formatting issues for me.


Control how many times a TableViewCell is outputted to the TableView

Question: regarding UITableView's I am having some problems. Putting it simply, I have a data array with user inputted numbers and a table view with 2 sections: one section for total count of the array, and the other for each of the numbers in the array. This project's code is too long and complex for me to slap up and ask for a simple code fix, so this will be a more generalized question.
When the cells output to the screen, they are in the correct format (outputting to the proper section and cell in the TableView). The second section outputs each number in the array with one number in each row, but the top section repeats "The total amount of numbers is: _" in a new row every time a new number is inputted or written in the second section below it.
For example:
The table should look like -
The total amount of numbers is: 3
1
2
6
But what actually ends up happening is:
The total amount of numbers is: 3
The total amount of numbers is: 3
The total amount of numbers is: 3
1
2
6
How do I control the amount of times the first section is outputted, while still leaving the second section determined by [array count] in the numberOfRowsInSection: method?
**If you need further clarification feel free to ask, I know it is pretty vague.
**UPDATE**
Now I need to get rid of the "index 0 beyond bounds of empty array" error message when the user inputed array is nil. Here is the code for the numberOfRowsInSection: method thus far:
       if (timeline != nil){
       int a = 0;
       switch (section) {
           case 0:
               a = 1;
               break;

           case 1:
               a = timeline.count;
               break;
       }

       return a;
    }

    else {
        return 1;
    }

What should I change further to prevent both problems from occurring?
Comment: Without seeing your relevant table view data source methods there is no good answer to give you.
Comment: There are too many files used in this `UIViewController` from a `#import` that the variables in my code would only clutter and distract the readers from my actual question. This is why there is no sample code, as it would take too long to explain where all the variable names are coming from, how they are inputted, etc.
Comment: I said "relevant code". All you needed to post was your `numberOfRowsInSection:` method.
Answer: You've defined two sections, so inside
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
if (section == 0) {
        return 1;
    } else {
        return [SomeArray count];
    }

In case you want to add separate headers for each table section, the pattern is similar:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if (section ==0 ) {
    return @"Title For Section 1";
} else {
    return @"Title For Section 2";
}

}
Comment: I'd say it's preferable to use a `switch`-`case` statement for this purpose, but otherwise, this is the right idea.
Comment: I'll agree with Isaac and leave it to momodude22 to determine his coding style :). Otherwise, the main idea is that you can determine how many rows for each section, by checking the section number (beginning with 0 of course).
Comment: this is the best way.
Comment: Thank you, I knew I was on the brink of it, but thank you soooooo much!
Comment: One more tip. You can add separate titles for each section too. I'll edit my answer to include.
Comment: So the answer you provided works, but there was a hidden error I overlooked. My array that I am using is user inputted, so as long as the array is not nil, it works. But now, if the user simply does not enter values, I get an error stating "index 0 beyond bounds of empty array". If I simply change the `return 1;` line back to `return [someArray count];` there is no error, but the doubling in the `UITableView` returns. Any idea what I could do to satisfy both situations?
Comment: I've been down that road before too. :) You need to make - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView conditional!
{
    if (some Bool) {
        return 1;
    } else {
        return 2;
    }
}
Comment: I have added the updated code in the problem, please take a look at it. And seriously, thank you so much for all of the help! I really do appreciate it :)
Answer: It sounds like you want to output only 1 cell in the first section, so you could do something like:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return section == 0 ? 1 : arrayName.count;
}

This would output 1 cell in the first section, and a number equal to the array length for the second section. Hope this helps you!


How can I split an animated .gif file into its component frames?

Question: How can I easily split an animated .gif file? I want to see each frame.
I would really prefer to not to export every frame to a directory. I'd like to view them individually in one application if possible.
Is this possible on Linux?
Answer: Try opening them with The Gimp; I believe it will open animated gifs with one layer per frame.
You say you don't want to dump all frames to files on a directory, but I'll tell you how to do it anyway :) install either ImageMagick or graphicsmagick, then:
for ImageMagick:
convert animation.gif target.png

for graphicsmagick:
gm convert animation.gif target.png

it'll write frames to target0.png,target1.png,... and so on. You can then enter the directory and run eog, it'll show you all the frames on the same application. When you no longer need the frames, just rm target*.png.
Comment: GraphicsMagick needs to be of the form `gm convert some-image.gif +adjoin some-image%d.png` to work. Or, `gm convert some-image.gif -coalesce +adjoin some-image%d.png` for varied sized subframes with varying offsets.
Comment: The specified `convert` misses the `-coalesce` option, which is required for what a user would expect.
Comment: imagemagick is just awesome!!
Comment: imagemagic convert failed for me, since it seems that each image of the gif was represented as a new transparent backgrounds layer, and convert gave those transparent layers: http://upload.wikimedia.org/wikipedia/commons/5/5d/AstarExample.gif
Comment: I opened my gif in gimp, but I still don't know how to view each frame individually - I just see the last frame.  I'm working with this animation: /tmp/Non-Native-American-Nations-Territorial-Claims-over-NAFTA-countries-1750-2008.gif
Answer: If the various frames have transparent areas and build upon each other, you can use the convert command with the "-coalesce" option to produce a set of files target-0.png, target-1.png etc, each of which merges the sequence of previous images:
convert -coalesce animation.gif target.png

Comment: you can specify the output file names via something like: `convert -coalesce animation.gif target.%04d.png`
Comment: It should be noted that (as of ImageMagick version 6.7.7) there seems to be some memory leak: **do not attempt `-coalesce` with long `.gif` screencasts**, it would probably consume all available memory and possibly hang your entire system.
Comment: Great comment but needs explanation.  Basically it solves the problem @cirosantilli had with ImageMagick returning what looked liked updates to specific screen areas.  -coalesce merges those updates to give you a finished rendering.
Answer: for me, with ImageMagick (version info: 6.8.9-9 Q16 x86_64 2017-07-31)
convert gif.gif gif.pdf

makes a pdf with each page being a frame of the input gif, then you can just page through the frames in the pdf viewing application of your choosing
Comment: That seems overly complicated and unlike what OP wants.
Comment: To get each frame as a page in a .pdf is a great idea, just take into consideration that this method might be buggy, and you need to [tweak the application](https://stackoverflow.com/questions/42928765/convertnot-authorized-aaaa-error-constitute-c-readimage-453#48869031).
Answer: Use mpv . Open it on desktop . Drag gif into it. Take a screenshot of your desired/single frame with s key. You may even pause if your gif is fast. Very Quick way.
===========
you may want to use these settings first [once set you do not have to do again]:
gedit ~/.config/mpv/mpv.conf

and enter and save:
--screenshot-format              Choices: jpg jpeg png (default: jpg)
for highest png quality:
--screenshot-format=png
--screenshot-png-compression=9

or if you want jpg
--screenshot-jpeg-quality        Integer (0 to 100) (default: 90)
Use mpv --list-options    for other details
Comment: Hi :) back andrew.46.  tried Gimp and got frustrated. there is not much that mpv cannot do :]


What is name of this object, how can i use it?

Question: In some video i see this screen shot.
What is name of this object?
http://www.valar.ru/gallery/1110/screen_shot_20101109_at_102020_pm.png
Answer: It is not a standard UI component. But you can easily replicate it using 1 UIView as a background and container for a number of UIButtons + some controller code to ensure that only one button is selected at a time (if I understand correctly how it is supposed to work).
Probably you can find a 3rd party library that already implements this kind of control - have a look at TTTabGrid class in three20 library (although it is not exactly the same as you have on your screenshot)


PROC SQL left join on id and date not working

Question: I am trying to merge two tables with below code:
proc sql;
create table test as
select a.*, b.*
from aaa a
left join bbb b on a.id=b.id and a.date1<=b.date2;
quit;

But the output shows blanks in columns from table b.
However if I change it to a.date1>=b.date2 it seems to work. Why would this be happening?
Checks I have done to be sure: 1) date formats are ok; 2) there are dates in table aaa which are less and more than table b dates.
Please help!
Comment: A left join can theoretically have blanks (null values) in its output. Do you have some data where the _id_ matches but you would expect records with _date2_ values on either side of the _date1_ value?
Comment: yes I have checked the spreadsheets manually there are dates on either side.
Answer: proc sql;
create table test as
select a.*, b.*
from aaa a
left join bbb b on a.id=b.id and datepart(a.date1)<=datepart(b.date2);
quit;

ok so looks like when I add datepart to both dates it works perfectly fine. Hopefully this will come in handy to someone.


Serializing DataAnnotations

Question: I would like to store DataAnnotations inside a database. How can I retrieve a string representation of a DataAnnotation by reflection (or by other means)?
Example
<code>public class Product
    {
        [DisplayName("Price")]
        [Required]
        [RegularExpression(@"^\$?\d+(\.(\d{2}))?$")]
        public decimal UnitPrice { get; set; }
    }
</code>
Result could be XML or JSON data as long as it is stringified.
Comment: The reason is I'm building a CMS and I want to build "Content Types" from DTO classes.
Comment: Can you explain why you actually want this?
Answer: this is very similar to retrieve-custom-attribute-parameter-values, i'd use it as a basis for your solution
Comment: The problem is I don't know the specific type of DataAnnotation so I can't access the properties as in this example (by casting the ValidationAttribute to a specific type).
Answer: You'd be better off writing your own validation provider, and then just store the validation rules in your database in a more convenient form. Parsing the strings to try to instantiate the attributes seems like more work than necessary. :)
Sample validation provider: http://bradwilson.typepad.com/blog/2009/10/enterprise-library-validation-example-for-aspnet-mvc-2.html
Comment: Thank you! Very pleased that you try helping me with this. The problem with the solution you provided is that I need it to work for all kind of DataAnnotations. I use custom attributes to store more than just validation rules. I can't explain all the concept here but I need it to do exactly what I demonstrated in the example.
Comment: You can also write a model metadata provider for non-validation attributes.

Serializing DataAnnotations


How to build an array by dates

Question:

const DATA = [{
    "entityId": 4307832,
    "eventNumber": 0,
    "scheduleId": 1,
    "divisionId": 10,
    "shutInDates": [{
        "shutInStart": "08/01/2020",
        "shutInEnd": "08/31/2020",
        "groupId": 0,
        "shutInTypeId": 7,
        "factorTypeId": 0
      },
      {
        "shutInStart": "10/01/2020",
        "shutInEnd": "10/31/2020",
        "groupId": 0,
        "shutInTypeId": 5,
        "factorTypeId": 0
      },
      {
        "shutInStart": "11/01/2020",
        "shutInEnd": "11/30/2020",
        "groupId": 0,
        "shutInTypeId": 5,
        "factorTypeId": 0
      }
    ]
  },
  {
    "entityId": 33756087,
    "eventNumber": 0,
    "scheduleId": 1,
    "divisionId": 10,
    "shutInDates": [{
        "shutInStart": "06/01/2020",
        "shutInEnd": "06/30/2020",
        "groupId": 0,
        "shutInTypeId": 7,
        "factorTypeId": 0
      },
      {
        "shutInStart": "07/01/2020",
        "shutInEnd": "07/31/2020",
        "groupId": 0,
        "shutInTypeId": 7,
        "factorTypeId": 0
      }
    ]
  },
  {
    "entityId": 34543593,
    "eventNumber": 0,
    "scheduleId": 1,
    "divisionId": 30,
    "shutInDates": [{
      "shutInStart": "10/01/2020",
      "shutInEnd": "10/31/2020",
      "groupId": 0,
      "shutInTypeId": 7,
      "factorTypeId": 0
    }]
  },
  {
    "entityId": 34543634,
    "eventNumber": 0,
    "scheduleId": 1,
    "divisionId": 30,
    "shutInDates": [{
      "shutInStart": "10/01/2020",
      "shutInEnd": "10/31/2020",
      "groupId": 0,
      "shutInTypeId": 7,
      "factorTypeId": 0
    }]
  },
  {
    "entityId": 34544797,
    "eventNumber": 0,
    "scheduleId": 1,
    "divisionId": 30,
    "shutInDates": [{
      "shutInStart": "10/01/2020",
      "shutInEnd": "10/31/2020",
      "groupId": 0,
      "shutInTypeId": 7,
      "factorTypeId": 0
    }]
  }
]

const groupConsecutive = (monthsNumbers) => monthsNumbers.reduce((r, n) => {
  const lastSubArray = r[r.length - 1];
  if (!lastSubArray || lastSubArray[lastSubArray.length - 1] !== n - 1) r.push([]);
  r[r.length - 1].push(n);
  return r;
}, []);

const result = DATA.map(x => {
  const shutInDates = [];
  if (x.shutInDates.length === 1) {
    shutInDates.push(x.shutInDates);
  } else {
    const monthsNumbers = [];
    const start = [];
    const end = [];
    let obj = {};
    x.shutInDates.forEach(s => {
      obj = {
        ...obj
      };
      obj = s;
      monthsNumbers.push(new Date(s.shutInStart).getMonth())
      start.push(new Date(s.shutInStart))
      end.push(new Date(s.shutInEnd))
    })

    const differenceAry = monthsNumbers.slice(1).map((n, i) => n - monthsNumbers[i])
    const isConsecutive = differenceAry.every(value => value == 1)

    if (isConsecutive) {
      const sortedStart = start.sort((a, b) => a - b)
      const sortedEnd = end.sort((a, b) => b - a)
      obj.shutInStart = sortedStart[0]
      obj.shutInEnd = sortedEnd[0]
      shutInDates.push(obj);
    } else {
      const consecutiveMonths = groupConsecutive(monthsNumbers);
      const currentYear = new Date().getFullYear()
      consecutiveMonths.forEach((arry, i) => {
        arry.forEach(m => {
          obj = {
            ...obj
          };
          obj.shutInStart = new Date(currentYear, m, 1);
          obj.shutInEnd = new Date(currentYear, m + 1, 0);
          shutInDates.push(obj)
        })
      });
    }
  }
  x.shutInDates = shutInDates;
  return x;
})

console.log(result);

If the dates are in consecutive order I need to take the first month for the start date and the take last month for the end date. So here in this snippet, I have October and November as consecutive dates so I Need to combine those. I am almost there, just need help with finishing it. Note* there can multiple consecutive months I need to account for. There could be Jan-Mar, May, July-Sept, etc...
This first object looks like this:
    {
    "entityId": 4307832,
    "eventNumber": 0,
    "scheduleId": 1,
    "divisionId": 10,
    "shutInDates": [{
        "shutInStart": "08/01/2020",
        "shutInEnd": "08/31/2020",
        "groupId": 0,
        "shutInTypeId": 7,
        "factorTypeId": 0
      },
      {
        "shutInStart": "10/01/2020",
        "shutInEnd": "10/31/2020",
        "groupId": 0,
        "shutInTypeId": 5,
        "factorTypeId": 0
      },
      {
        "shutInStart": "11/01/2020",
        "shutInEnd": "11/30/2020",
        "groupId": 0,
        "shutInTypeId": 5,
        "factorTypeId": 0
      }
    ]
  }

The Desired Result needs to look like this:
    {
    "entityId": 4307832,
    "eventNumber": 0,
    "scheduleId": 1,
    "divisionId": 10,
    "shutInDates": [{
        "shutInStart": "08/01/2020",
        "shutInEnd": "08/31/2020",
        "groupId": 0,
        "shutInTypeId": 7,
        "factorTypeId": 0
      },
      {
        "shutInStart": "10/01/2020",
        "shutInEnd": "11/30/2020",
        "groupId": 0,
        "shutInTypeId": 5,
        "factorTypeId": 0
      }
    ]
  }

Comment: I inserted it in the post
Answer: Here's what I came up with. You might be able to clean it up a bit but it seems to work.

function mergeShutInDates(obj) {
    let previousEndDate = null;
    let shutInPeriod = null;
    let theDayAfterThePreviousShutInEnd = null;
    let currentStartDate = null;
    let finalStartDate = null;
    const finalShutInDates = [];
    for (let i = 0; i < obj.shutInDates.length; i++) {
        shutInPeriod = obj.shutInDates[i];
        if (previousEndDate != null) {
            currentStartDate = new Date(shutInPeriod.shutInStart);
            theDayAfterThePreviousShutInEnd = new Date(previousEndDate);
            theDayAfterThePreviousShutInEnd.setDate(new Date(previousEndDate).getDate() + 1);
            if (sameDay(theDayAfterThePreviousShutInEnd, currentStartDate)) {
                if (i == obj.shutInDates.length - 1) {
                    finalShutInDates.push({
                        shutInStart: finalStartDate,
                        shutInEnd: shutInPeriod.shutInEnd,
                        groupId: shutInPeriod.groupId,
                        shutInTypeId: shutInPeriod.shutInTypeId,
                        factorTypeId: shutInPeriod.factorTypeId
                    });
                }
            } else {
                if (finalStartDate) {
                    finalShutInDates.push({
                        shutInStart: finalStartDate,
                        shutInEnd: previousEndDate,
                        groupId: shutInPeriod.groupId,
                        shutInTypeId: shutInPeriod.shutInTypeId,
                        factorTypeId: shutInPeriod.factorTypeId
                    });
                    finalStartDate = shutInPeriod.shutInStart;
                }

                if (i == obj.shutInDates.length - 1) {
                    finalShutInDates.push(shutInPeriod);
                }
            }
        } else {
            finalStartDate = shutInPeriod.shutInStart;
        }
        previousStartDate = shutInPeriod.shutInStart;
        previousEndDate = shutInPeriod.shutInEnd;
    }
    obj.shutInDates = finalShutInDates;
}

function sameDay(date1, date2) {
    return date1.getFullYear() === date2.getFullYear() &&
        date1.getMonth() === date2.getMonth() &&
        date1.getDate() === date2.getDate();
}

let obj1 = {
    "entityId": 4307832,
    "eventNumber": 0,
    "scheduleId": 1,
    "divisionId": 10,
    "shutInDates": [{
        "shutInStart": "08/01/2020",
        "shutInEnd": "08/31/2020",
        "groupId": 0,
        "shutInTypeId": 7,
        "factorTypeId": 0
    },
    {
        "shutInStart": "10/01/2020",
        "shutInEnd": "10/31/2020",
        "groupId": 0,
        "shutInTypeId": 5,
        "factorTypeId": 0
    },
    {
        "shutInStart": "01/01/2021",
        "shutInEnd": "01/31/2021",
        "groupId": 0,
        "shutInTypeId": 5,
        "factorTypeId": 0
    },
    {
        "shutInStart": "11/01/2020",
        "shutInEnd": "11/30/2020",
        "groupId": 0,
        "shutInTypeId": 5,
        "factorTypeId": 0
    },
    {
        "shutInStart": "12/01/2020",
        "shutInEnd": "12/31/2020",
        "groupId": 0,
        "shutInTypeId": 5,
        "factorTypeId": 0
    }
    ]
}

let obj2 = {
    "entityId": 4307832,
    "eventNumber": 0,
    "scheduleId": 1,
    "divisionId": 10,
    "shutInDates": [{
        "shutInStart": "08/01/2020",
        "shutInEnd": "08/31/2020",
        "groupId": 0,
        "shutInTypeId": 7,
        "factorTypeId": 0
    },
    {
        "shutInStart": "09/01/2020",
        "shutInEnd": "09/30/2020",
        "groupId": 0,
        "shutInTypeId": 5,
        "factorTypeId": 0
    },
    {
        "shutInStart": "10/01/2020",
        "shutInEnd": "10/31/2020",
        "groupId": 0,
        "shutInTypeId": 5,
        "factorTypeId": 0
    },
    {
        "shutInStart": "11/01/2020",
        "shutInEnd": "11/30/2020",
        "groupId": 0,
        "shutInTypeId": 5,
        "factorTypeId": 0
    },
    {
        "shutInStart": "12/01/2020",
        "shutInEnd": "12/31/2020",
        "groupId": 0,
        "shutInTypeId": 5,
        "factorTypeId": 0
    }
    ]
}

let obj3 = {
    "entityId": 4307832,
    "eventNumber": 0,
    "scheduleId": 1,
    "divisionId": 10,
    "shutInDates": [{
        "shutInStart": "08/01/2020",
        "shutInEnd": "08/31/2020",
        "groupId": 0,
        "shutInTypeId": 7,
        "factorTypeId": 0
    },
    {
        "shutInStart": "10/01/2020",
        "shutInEnd": "10/31/2020",
        "groupId": 0,
        "shutInTypeId": 5,
        "factorTypeId": 0
    },
    {
        "shutInStart": "01/01/2021",
        "shutInEnd": "01/31/2021",
        "groupId": 0,
        "shutInTypeId": 5,
        "factorTypeId": 0
    },
    {
        "shutInStart": "11/01/2020",
        "shutInEnd": "11/30/2020",
        "groupId": 0,
        "shutInTypeId": 5,
        "factorTypeId": 0
    },
    {
        "shutInStart": "03/01/2020",
        "shutInEnd": "03/31/2020",
        "groupId": 0,
        "shutInTypeId": 5,
        "factorTypeId": 0
    }
    ]
}

let obj4 = {
    "entityId": 4307832,
    "eventNumber": 0,
    "scheduleId": 1,
    "divisionId": 10,
    "shutInDates": []
}

let obj5 = {
    "entityId": 4307832,
    "eventNumber": 0,
    "scheduleId": 1,
    "divisionId": 10,
    "shutInDates": [{
        "shutInStart": "08/01/2020",
        "shutInEnd": "08/31/2020",
        "groupId": 0,
        "shutInTypeId": 7,
        "factorTypeId": 0
    },
    {
        "shutInStart": "10/01/2020",
        "shutInEnd": "10/31/2020",
        "groupId": 0,
        "shutInTypeId": 5,
        "factorTypeId": 0
    },
    {
        "shutInStart": "01/01/2021",
        "shutInEnd": "01/31/2021",
        "groupId": 0,
        "shutInTypeId": 5,
        "factorTypeId": 0
    },
    {
        "shutInStart": "04/01/2020",
        "shutInEnd": "04/30/2020",
        "groupId": 0,
        "shutInTypeId": 5,
        "factorTypeId": 0
    },
    {
        "shutInStart": "05/01/2020",
        "shutInEnd": "05/30/2020",
        "groupId": 0,
        "shutInTypeId": 5,
        "factorTypeId": 0
    }
    ]
}

mergeShutInDates(obj1);
console.log(obj1);

mergeShutInDates(obj2);
console.log(obj2);

mergeShutInDates(obj3);
console.log(obj3);

mergeShutInDates(obj4);
console.log(obj4);

mergeShutInDates(obj5);
console.log(obj5);

How to build an array by dates


TensorFlow on multiple machines with multiple GPUs?

Question: I'm a new in machine learning and Tensorflow. I have a question about distributed training in TensorFlow. I've read about multi GPUs environments and it looks that it is quite possible (https://www.tensorflow.org/guide/using_gpu).
But what about multiple machines with multiple GPUs?  Is it possible to divide machine training tasks between few machines? Is there a specific algorithms/tasks, which require such distribution or multiple GPUs are enough for machine learning? Will there be demand on this?
Thanks
Comment: Of course it is possible. You would have to connect your machines (socket connection) and create different worker classes. Also, create a master class that will assign work to the workers (for example, the first 20% of the training to one worker-machine, the next 20% to the next worker-machine and so on). Your workers should be the same code in each of your machines and they should be parametrized.
Answer: It is possible.
You can run same model on multiple machines using data parallelism with distributed strategies or horovod to speed up your training. In that case you are running the same model across multiple machines to emulate a larger batch.
You can also go for a little less conventional way with GPipe or TF-Mesh to split a single model across multiple machines to increase number of model layers or even split individual layers across multiple workers.


How do I acces the windows network?

Question: I have ubuntu 13.04 64 bit and windows 8 dual booted. I have a network that is a windows one. in recent versions of ubuntu, i wasn't able to acces it. i hoped that ubuntu 13.04 would fix that but it did not. When i go to network and click on windows network
Unable to access location
Failed to retrieve share list from server: No such file or directory
i do not know how to make it work.
Please help
Answer:
When i go to network and click on windows network Unable to access location Failed to retrieve share list from server: No such file or directory

Network -> Windows network is for when you have more than 1 computer and 1 of them is a Windows system. You can connect those 2 systems and copy things over using that connection. An example where you have a network would be: Desktop with Ubuntu <-> router <-> notebook with Windows.
This has -no- relation with a dual boot system since a dual system only supports 1 OS at a time.
What you need to do is mount your Windows disc. Example:
Comment: Are you sure that is all I have to do?
Comment: That's what worked for me when I installed 13.04. I did nothing else. 2 things: 32 bit so not 64 bits and Windows 7 so not 8. But... both differences do not matter :)

How do I acces the windows network?


How can I stop opencv from making calls to qDebug?

Question: I've just started using OpenCv 3.1 and have encountered the following annoying behavior. Whenever I make an initial call to imshow (actually cv2.imshow, since I'm using the Python interface), I get this output to my screen:
init done
opengl support available

It seems to be due to the following method in window_QT.cpp:
static int icvInitSystem(int* c, char** v)
{
    //"For any GUI application using Qt, there is precisely one QApplication object"
    if (!QApplication::instance())
    {
        new QApplication(*c, v);
        setlocale(LC_NUMERIC,"C");

        qDebug() << "init done";

#ifdef HAVE_QT_OPENGL
        qDebug() << "opengl support available";
#endif
    }

    return 0;
}

All I can think of to do is to comment out the qDebug calls and recompile OpenCV. Is there any less drastic solution that would either automatically redirect qDebug's output to stderr, or just turnoff debug information unless I actively want it?
Answer: qDebug is a preprocessor-controlled, but it has its own special macro, QT_NO_DEBUG_OUTPUT. If you add that to your Release build defines, it will be removed.