How do I fix "$'\r': command not found" errors running Bash scripts in WSL?

Question: I'm getting an error in WSL while trying to use junyanz/pytorch-CycleGAN-and-pix2pix.
I followed all the install steps successfully on Windows 10 x64 using the steps at PyTORCH on Windows 10: An instructional with screenshots, then Ubuntu for Windows with GitHub desktop How to Install and Use the Linux Bash Shell on Windows 10.
But I'm blocked at the latest steps.
It's where I trying to download or train the model in Windows. Using for example the Ubuntu Linux prompt, I navigate manually to the appropriate place and type a following command like the one below (I also tried in su mode)
bash pretrained_models/download_pix2pix_model.sh facades_label2photo

I get an immediate error, always the same, similar to these:
root@Azure:/mnt/c/Users/vincent/Downloads/vision/pytorch-CycleGAN-and-pix2pix# bash pretrained_models/download_pix2pix_model.sh facades_label2photo
pretrained_models/download_pix2pix_model.sh: line 2: $'\r': command not found
Note: available models are edges2shoes, sat2map, and facades_label2photo
pretrained_models/download_pix2pix_model.sh: line 4: $'\r': command not found
]pecified [facades_label2photo
pretrained_models/download_pix2pix_model.sh: line 6: $'\r': command not found
mkdir: cannot create directory './checkpoints/facades_label2photo\r_pretrained\r': No such file or directory
pretrained_models/download_pix2pix_model.sh: line 10: $'\r': command not found
WARNING: timestamping does nothing in combination with -O. See the manual
for details.

: No such file or directoryhphoto
pretrained_models/download_pix2pix_model.sh: line 12: $'\r': command not found
pretrained_models/download_pix2pix_model.sh: line 13: $'\r': command not found

Any idea?
Comment: I have no idea what you're doing, but `$'\r': command not found` strongly suggests the issue is that you have used a Windows text editor that has saved your files with DOS-style CRLF line endings - see for example [DOS vs. Unix Line Endings](http://www.cs.toronto.edu/~krueger/csc209h/tut/line-endings.html)
Comment: But Im just typing the command directly in the Window Ubuntu command prompt. Not passing by any text editor at all...
Comment: @VincentThomas This is a text file: `pretrained_models/download_pix2pix_model.sh`
Comment: Try the answer here: [How to change Windows line-ending to Unix version](https://askubuntu.com/q/803162/301745). If it works, let us know and we will close your question as a duplicate.
Comment: @wjandrea I don't think this is really a duplicate of [How to change Windows line-ending to Unix version](https://askubuntu.com/questions/803162/how-to-change-windows-line-ending-to-unix-version). The reasonable solution here is [to run `git clone` within the WSL system](https://askubuntu.com/a/969966/22949), and not to undertake extra effort attempting to convert each file. If the goal is to install software in Ubuntu, there is no reason to download it outside its filesystem first.
Comment: also you can do cat -v  to see the line endings as "^M" in your unix commandline.  When you have fixed it with the git settings you will see the "^M" gone.
Comment: @EliahKagan Yes, that's a better solution.
Comment: In VScode you can just change the CRLF to LF in right hand corner of the Status Bar.
Answer: Inside WSL:
sudo apt-get install dos2unix

Then,
dos2unix [file]

Full documentation:
man dos2unix

Saved my day, hope it helps.
Comment: [Another alternative](https://stackoverflow.com/a/32912867/8740349) would be `sed -i 's/\r$//' path/to/file`
Comment: If you get `E: Unable to locate package dos2unix` run `sudo apt-get update` first.
Comment: This works. I was using VSCode and had a shell script that executes some rsync and ssh command, and ran into this issue. I installed dos2unix inside WSL like Chaim said, and executed once, `wsl dos2unix deploy.sh` from Powershell, and now, everytime I type, `wsl ./deploy.sh` everything works perfectly! Thanks a lot.
Comment: @Chaim Eliyah you saved a lot of hours for me
Comment: Necromancy but the `sed` above would probably be safe, as all OSes except Windows have dropped usage of the character.
Comment: If you are getting `Failed to change the permissions of temporary output file` use `sudo dos2unix [file]`
Answer: If you are on Windows,

Open your shell file on NotePad++
Click on Edit on Top bar menu, then choose EOL Conversion --> Unix(LF)
Now copy this file in your Linux system and it should run without these errors.
Comment: Worked like a charm!
Comment: Perfect! I noticed bizzare behaviour when doing the conversion. Before this my simple `if` statement didn't see other file in the same folder (which was there). After doing your instruction `if` returned `true` while searching my second file.
Comment: Also using Find and Replace to replace \r with nothing worked for me, but this seems like a one-click version.
Answer: steeldriver is correct that the problem is that you have files with Windows line endings and bash cannot run them. $'\r' is a representation of the carriage return character (CR) that is part of traditional DOS and Windows line endings (CR LF), but which is absent in traditional Unix-style line endings (LF).
As you say, you're typing the command to attempt to run the script in bash, but notice that the script is actually stored outside your Ubuntu (WSL) system, in your Windows download directory:
/mnt/c/Users/vincent/Downloads/vision/pytorch-CycleGAN-and-pix2pix

WSL paths that start with /mnt/c, where c may be any Windows drive letter, are paths that access files and directories outside the Ubuntu system. As a Windows path, that is:
C:\Users\vincent\Downloads\vision\pytorch-CycleGAN-and-pix2pix

That a file is stored in your Windows system outside the area where Ubuntu is installed does not guarantee that it uses Windows-style instead of Unix-style line endings. However, if you downloaded the files with Git in Windows, its default configuration is to give you Windows-style line endings.
The easiest way to fix the problem is really to just download the files you need inside the Ubuntu system from your bash prompt. I recommend you fully update the Ubuntu system, then install git  in Ubuntu, as well as build-essential which provides useful tools that you need to compile most software from source code. For Python programs, you may not need build-essential; you can omit it if you like, but I suspect you'll end up needing it at some point.
sudo apt update && sudo apt upgrade && sudo apt install git build-essential

Then use the cd command to go to a directory where you would like to download the software.  This should be a directory within your Ubuntu system. For example, it could be your Ubuntu home directory or somewhere inside there. Once there, clone the repository from GitHub. I did it inside the src directory that I made inside my home directory.
cd ~/src
git clone https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix.git

Of course, you will most likely have to install the dependencies first. To do that, just follow all the official instructions. Do all those steps within the Ubuntu system.
Comment: also you can do cat -v  to see the line endings as "^M" in your unix commandline.  When you have fixed it with the git settings you will see the "^M" gone.
Answer: I was using VS code within my WSL environment to edit the bash script. Changing the setting from "CRLF" to "LF" on the bottom right corner fixed it for me.
Answer: I ran into this issue and the solution was to configure git to checkout specific files in Linux line-ending way.
You can add a file to your git root directory name .gitattributes which configure specific attributes for git (see full documentation).
Add the lines
# Convert to LF line endings on checkout.
*.sh text eol=lf

To configure git to checkout .sh files with LF line ending even on Windows machines.
Comment: also you can do cat -v  to see the line endings as "^M" in your unix commandline.  When you have fixed it with the git settings you will see the "^M" gone.
Answer: If you have vim handy, it'll fix you up quick.
vim $filename +"set ff=unix" +wq


Show bijectivity of simple map

Question: I know that the following can be done easier using different argument but I'd like to just proof it the "hard way" for learning experience.
$f_a: G\to G, \ \ x\mapsto a\star x,\quad a\in G$
Injectivity:
Claim: $a\neq b \Rightarrow f(a)=f(b)$
Proof: Choose $a,b,c \in G$ s.t. $b\neq c$
now: $f_a(b)=a\star b$ and $f_a(c)=a \star c$
since $b\neq c \Rightarrow f_a(b)=f_a(c)$
So the function is injective.
Surjectivity:
Claim: $\forall b \in G \ \exists c \in G : f(c)=b$
Proof: Choose $a, b, c \in G$ with with $b=a\star c$
Now: $b=a\star c = f_a(c)$
Which fullfilsl the claim, thus the function is surjective.
Since it is injective and surjective, it is also bijective.
Does that hold like that?
Comment: $G$ is a group?
Comment: What is $f$ here? Is it the function that sends $a$ to function $f_a$ maybe? Further if you want to prove injectivity of some function $g$ then you must prove that $a\neq b\implies g(a)\neq g(b)$. So I really do not understand your claim that says $a\neq b\implies f(a)=f(b)$.
Answer: What you did was wrong. There is also context missing, so I suggest you edit your post. I assume that $G$ is a group.
To show injectivity of a function $f: X \to Y$, you have to show:
$$\forall x,y \in X: (x \neq y \implies f(x) \neq f(y))$$
or equivalently (by the principle of contraposition):
$$\forall x,y \in X: (f(x) = f(y) \implies x =y)$$
So assume $f_a(x) = f_a(y)$ for $x,y \in G$. Then by definition of $f_a$ it follows that $a \star x = a \star y$ and by multiplying both sides (on the left) with the inverse $a^{-1}$ (which exists because $G$ is a group), it follows, using associativity and the definition of neutral element, that $x = y$. Hence, the function is injective.
In your proof of surjectivity, you say "choose $a,b,c \in G$ such that $b = a \star c$. You can't assume this! This is exactly what you have to prove! How do you know such elements exist?
So you should rather do the following:
Let $y \in G$. Let $x = a^{-1} \star y \in G$. Then $f_a(x) = f_a(a^{-1} \star y) = a\star a^{-1} \star y = y$
Again, I used associativity and the definition of neutral element implicitely. It's up to you to fill in the details.
So we have proven: $\forall y \in G: \exists x \in G: f_a(x) = y$, which means that $f_a$ is surjective.

Alternative method: You can notice that the mapping $g: G \to G: x \mapsto a^{-1}x$ is a well defined function and that it is the inverse of the given mapping. Hence, the function you are given is bijective (as it is invertible).

I don't want to sound harsh here, but you should maybe take a step back from group theory for some time, and revise some more basics about functions.  Make a lot of exercises on injectivity and surjectivity, because these are things that pop up all the time in every field of mathematics.
Answer: As there is a comment below your post which states that there is a little bit of confuison of what map you are considering, I will say few words about it before answering your question.
So you consider an action of a group $G$ on itself. That is, you take an element $a$ of a group, $a \in G$, and you consider the mapping
$$f_a \colon G \rightarrow G$$
given by multiplication on the right by this element, i.e. for arbitrary $g \in G$ we have
$$ f_a (g) = a \star g \ ,$$
where $\star$ is the binary operation of your group. It is not hard to show that this is a group homorphism and it follows directly from the axioms of a group. In a similar fashion we can show that this map is actually a bijection (and thus a group isomorphism).
Let us recall the definition of a bijection and injection for an arbitrary map $g \colon A \rightarrow B$ between sets
Definition of a bijection: A map $g$ is said to be a bijection if it is both surjective and injective.
Definition of an injection: A map $g$ is said to be an injection if the following implication holds for arbirary elements $b,c$ of the domain of $g$
$$ b \neq c \Rightarrow g(b) \neq g(c) $$
So in this definition you had a flow since you considered equality on the right side of the implication sign (such an implication, if satisfied, would violate the injectivity of the map)
The definition of a surjection you wrote is correct thus I will not write it again.
Now we proceed with checking your proof. 1) injectivity: this is wrong due to incorrect definition. let me show how this can be done considering proof by contrapositive, i.e. proving the following implication, equivalent to our original implication above (for more about proof by contrapositive see this wiki article)
$$ f_a (b) = f_a(c) \Rightarrow b = c \ .$$
Using the definition of $f_a$ we can write
$$ f_a (b) = a \star b   \text{  and   }\ \  f_a(c) = a \star c  \ ,$$
thus we have
$$ a \star b = a \star c \ . $$
Multiplying by $a^{-1}$ (the inverse of $a$ which we know exists due to the fact we work in a group) from the left we get
$$ a^{-1} \star a \star b = a^{-1} \star a \star c  $$
(recall that the group operation is associative so bracketing of terms is unnecessary). The above is equivalent to the desired equivality $$ b = c$$ (as $ a^{-1} \star a = e = a \star a^{-1}$ where $e$ is the neutral element of the group) and thus $f_a$ is injective.
2) surjectivity: You assumed that the element $b$ can be written as a product $a \star c$ for some $c$. This is not incorrect but may be considered as incomplete for you should show that such an element $c$ always exists. Once you do this you are OK. So how to find this $c$? (recall that $a$ is fixed an $b$ is arbitrary). You can always choose $c = a^{-1} \star  b$ since then $a \star c = a \star a^{-1} \star  b = b$. Then of course for each $b$ this element $c$ is the preimige with respect to $f_a$ since (as you wrote) $f_a (c) = a \star a^{-1} \star  b = b$ and thus $f$ is surjective.

Show bijectivity of simple map


Running a python script for indefinite time

Question: I have a python script that goes like this -
import..
def main ():
  some_condition check
  main() #calling main again
  some condition check
  main() #calling main again
main()

The idea here is to let the script run indefinitely and check for something.
This way of calling main() somehow seems incorrect.
I am quite new to Python scripting. Can someone guide me if this very inefficient and if yes then how do I achieve this?
Comment: i don't think you want recrusion here, something like `def main(): do_stuff` then `while True: some_check; main()` et.c
Comment: related: https://stackoverflow.com/questions/3754620/a-basic-question-about-while-true
Comment: Agree with @Chris_Rands. Recursion is bad in so many ways (memory, readability of code etc). If only python had tail recursion.. Anyway, use "while True" syntax.
Comment: What is incorrect? What exactly do you want?
Comment: @AttilaBognár nothing was incorrect. I just wanted to know the right way of doing it. As someone pointed out, running it indefinitely would cause stack overflow and instead of calling main from main, I can use while true :)
Comment: @RohitGupta I just wanted to know why it seemed incorrect.
Answer: What you are doing is called recursion. This is certainly not good for long running applications, since it would cause a stack overflow.
Do your checking like this:
quit = False
while not quit:
   do_your_check()
   #maybe sleep
   quit = should_i_stop()

Comment: Thanks! That's what I was looking for - "it would cause a stack overflow". Quitting the script and then restarting would avoid the stack overflow?
Comment: Yes, that would work. Stack overflow happens, because as you call a function the context of the caller function is saved on the stack, so when the called function returns, it can be continued, Since you never return, eventually your computer will run out of memory. At that point the OS will stop the program.
Answer: Just put the things you want to do in a while true loop.
import ...
def main():
  while True:
    some_condition check

Recursion is utilized when it is too complex/hard to write as iterative code. e.g. Tree traversals.


32bit TIFF to another format in Python

Question: I need to convert a 32 bit TIFF file (or the corresponding int32 array) to another format that Tkinter can display (like gif fe)
How do I do that? Converting the array to int16 or so completely blurs the picture...
Answer: PIL is your best friend.
Comment: could you elaborate a bit? i tried all kinds of conversions and nothing got my anywhere. but i am totally unexperienced when it comes to this, a few pointers which functions i can use would be great!
Comment: I haven't worked with Tiff or Tkinter, but I am guessing you can do something along the lines of [this](http://code.activestate.com/recipes/521918-pil-and-tkinter-to-display-images/)
Answer: You can use PIL, Image Magick, or GraphicsMagick
GraphicsMagic and ImageMagick are command-line programs and have python versions. I use Graphics Magic because it is simple. ImageMagick is almost a command-line version of photoshop...

32bit TIFF to another format in Python


.BAT file glitch minecraft effect genorator

Question: I have this code that is

    @echo off
    color a
    title Minecraft Effect Generator
    mode con: cols=114 lines=40
    :1
    cls
    echo -----------------------------------------------------------------------------------------------------------------
    echo                                            Minecraft Effect Generator
    echo -----------------------------------------------------------------------------------------------------------------
    echo /effect "USERNAME" "EFFECT ID" "TIME LASTS" "LEVEL"
    echo [ E  ] EXIT           - EXIT THE MINECRAFT EFFECT GENERATOR
    set /p "MCUsername=Username: "
    IF MCUsername==e exit
    IF MCUsername==E exit
    :2
    cls
    echo -----------------------------------------------------------------------------------------------------------------
    echo                                            Minecraft Effect Generator
    echo -----------------------------------------------------------------------------------------------------------------
    echo /effect %MCUsername% "EFFECT" "TIME" "LEVEL"
    echo [ 1  ] SPEED           - RUN FASTER  BY 20% EACH LEVEL
    echo [ 2  ] SLOWNESS        - RUN SLOWER  BY 15% EACH LEVEL
    echo [ 3  ] HASTE           - MINE FASTER BY 20% EACH LEVEL
    echo [ 4  ] MINING FATIGUE  - MINE SLOWER BY 20% EACH LEVEL
    echo [ 5  ] STRENGTH        - HIT HARDER  BY 130% EACH LEVEL
    echo [ 6  ] INSTANT HEALTH  - PLAYER GETS 4 ()() HEALTH . UNDEAD MOBS TAKE 6 ()()() DAMAGE -- DOUBLES BY EACH LEVEL
    echo [ 7  ] INSTANT DAMAGE  - PLAYER TAKES 6 ()()() HEALTH . UNDEAD MOBS TAKE 6 ()()() DAMAGE -- DOUBLES BY EACH LEVEL
    echo [ 8  ] JUMP BOOST      - JUMP HIGHER 1/2 BLOCK . REDUCES FALL DAMAGE BY 1 ( DAMAGE ON LEVEL 1
    echo [ 9  ] NAUSEA          - WOBBLES AND WARPS THE SCREEN . LEVEL DOES NOT EFFECT THIS EFFECT
    echo [ 10 ] REGENERATION    - REGENERATE 1 HEART ( PER 50 TICKS . EACH LEVEL CUTS THE TIME IN HALF (ROUNDED)
    echo [ 11 ] RESISTANCE      - RESIST BY 20% EACH LEVEL
    echo [ 12 ] FIRE RESISTANCE - IMMUNITY
    echo [ 13 ] WATER BREATHING - PREVENTS AIR BAR FROM DECREASING WHILE UNDERWATER . SLIGHTLY INCREASES SIGHT UNDER WATER
    echo [ 14 ] INVISIBLILTY    - MAKES PLAYER DISAPPEAR . MOBS WILL NOT ATTACK PLAYER / MOB UNLESS TOUCHED
    echo [ 15 ] BLINDNESS       - PLAYER SEES BLACK FOG . PREVENTS SPRINTING AND CRITICAL HITS . LEVEL DOES NOT EFFECT
    echo [ 16 ] NIGHT VISION    - INCREASES LIGHT LEVEL TO PLAYER TO 15 EVERYWHERE . DOES NOT AFFECT OTHER PLAYERS / MOBS
    echo [ 17 ] HUNGER          - ADDS 0.025 FOOD EXHAUSTION PER TICK EACH LEVEL
    echo [ 18 ] WEAKNESS        - MINUS 0.5 DAMAGE DEALT EACH LEVEL
    echo [ 19 ] POISON          - DEALS 1 ( DAMAGE EVERY 25 TICKS UNTIL PLAYER HAS 1 HEART LEFT . EA LV CUTS TIME IN HALF
    echo [ 20 ] WITHER          - DEALS 1 ( DAMAGE EVERY 40 TICKS AND CAN KILL PLAYERS / MOBS . EA LV CUTS TIME IN HALF
    echo [ 21 ] HEALTH BOOST    - ADDS 4 ()() BASE HEALTH PER LEVEL AND VANISHES WHEN EFFECT ENDS
    echo [ 22 ] ABSORBATION     - ADDS 4 ()() NON REGENERATEABLE HEALTH PER LEVEL AND VANISHES WHEN EFFECT ENDS
    echo [ 23 ] SATURATION      - REGENERATES 1 FOOD PER LEVEL
    echo [ E  ] EXIT           - EXIT THE MINECRAFT EFFECT GENERATOR
    set /p "effect=Effect ID: "
    IF effect==e exit
    IF effect==E exit
    :3
    cls
    echo ----------------------------------------------------------------------------------------------------------------
    echo                                            Minecraft Effect Generator
    echo ----------------------------------------------------------------------------------------------------------------
    echo /effect %MCUsername% %effect% "TIME" "LEVEL"
    echo [ U  ] UNLIMITED TIME - NEVER-ENDING EFFECT
    echo.
    echo [ E  ] EXIT           - EXIT THE MINECRAFT EFFECT GENERATOR
    set /p "time=Time: "
    IF time==e exit
    IF time==E exit
    IF time==u set /a "time=100000"
    IF time==U set /a "time=100000"
    :3
    cls
    echo ----------------------------------------------------------------------------------------------------------------
    echo                                            Minecraft Effect Generator
    echo ----------------------------------------------------------------------------------------------------------------
    echo /effect %MCUsername% %effect% %time% "LEVEL"
    echo LEVEL IS 1 - 255
    echo [ E  ] EXIT           - EXIT THE MINECRAFT EFFECT GENERATOR
    set /p "level=Time: "
    IF level==e exit
    IF level==E exit
    :end
    cls
    echo ----------------------------------------------------------------------------------------------------------------
    echo                                            Minecraft Effect Generator
    echo ----------------------------------------------------------------------------------------------------------------
    echo YOUR COMMAND IS:
    echo /effect %MCUsername% %effect% %time% %level%
    echo TYPE THIS INTO YOUR CHAT TO WORK
    echo [ C  ] COPY TO CLIPBOARD
    echo [ B  ] GO BACK AND TRY AGAIN
    echo.
    echo [ E  ] EXIT
    set /p "end=>"
    IF end==e exit
    IF end==E exit
    IF end==c echo /effect %MCUsername% %effect% %time% %level%| clip $goto end
    IF end==C echo /effect %MCUsername% %effect% %time% %level%| clip &goto end
    IF end==b goto 1
    IF end==B goto 1
    goto end

Basicly it generates a command. It seems to glitch at :end. The input seems to not work. How can i fix this?  Is my computer not working or is it the code that is glitched???
BTW: I am running Windows 7 x64
Thanks for reading this!
Answer: You have many, many errors.
First obvious one is that you have two labels :3 but that's nothing to do with the problem you raised.
IF end==e exit
IF end==E exit

end can never equal e. You need the contents of end which is %end% - similar problem repeated throughout the code.
The if statement allows the /i switch to make the comparison case-insensitive.
IF /i "%end%"=="e" exit

will suffice. Note the arguments are "quoted". This affords some protection against certain input characters (since the input is uncensored by cmd) which may cause cmd to have problems - an input such as hello there for instance. This scheme improves the input-handing, but it is not bullet-proof.
Comment: Thanks it worked. I have not programmed in 1 year so I have problems. XD  :D
Comment: OMG I just noticed i spelled generator wrong! I spelled it "genorator" instead of generator. --PALM SLAP--


Advance Installer Auto update issue

Question: Currently I am deploying auto updater service for my msi file.Auto update works fine and check for update correctly and download installation package from repository but when it installs it its .exe file is not extracted from installation package and shows error like :
Error:Update installation failed.
Some of th updates failed to install properly.
Please Help me to get rid out of this stuff !!
Answer: I experience this issue when I would want to determine if an update was available based on Configuration with File Size Check; my updates.txt file on the server side resembled this
;aiu;
[MLMS]
Name = MLMS
URL = http://servername/winapps/dev/mlms/ai/mlms.exe
Size = 15485915
Description = This update fixes issues related to ticket #999
Feature = Added comments section to Chemical Process
FilePath = c:\Program Files (x86)\YOVA\MLMS\MLMS.exe
Version = 18.104.22.168

When end users would trigger Check for updates on the client side - it would always assume an update was available and if you went through the update/repair process at the end they would get the error mentioned in this question.
My solution was to use the Configuration with Version Given by a Registry Value method. This actually worked better since my build server increments the version on every release. I updated my updates.txt by removing property values that did not apply to the configuration such as File Path and adding those mentioned in the documentation (e.g. RegistryKey); Adding unessary values yields weird behavior.
;aiu;
[MLMS]
Name = MLMS
URL = http://servername/winapps/dev/mlms/ai/mlms.exe
Size = 15485915
RegistryKey = HKLM\Software\Wow6432\YOVA\MLMS\Version
Version = 18.104.22.168
Description = This update fixes issues related to ticket #999
Feature = Added comments section to Chemical Process

Overwall I belive the issue may be how you have the updates.txt configured, also all settings on the updates.txt file must be valid or you get that error. For example, initially I had omitted the \Wow6432\ path from my registry value on my updates.txt server side file and this error would surface, once corrected the error went away and the update detection worked as expected.
Answer: I suggest you a two steps investigation:

you should first manually install the updates setup and see if the upgrade installation succeeds (also try to create an installation log too)
then you should try to deploy the updates setup through auto updater and launch the updates setup with a log command; then check the updates installation log file and make sure there is nothing wrong during upgrade
Comment: just add a command line like the above in your updates configuration project in the command line field of the updates installer. this way when the updater will launch the updates setup it will launch it with the specified command
Comment: I had checked update installation and it works correctly .. but will you please tell me how to maintain log file of installation ?
Comment: to create a log file all you have to do is to run the updates setup with a command line like this:
`/L*V \log.txt`
Answer: Modify the properties in update config. please refer the attach image.
enter image description here

Advance Installer Auto update issue


is there any way that you sync only files which are present in aws s3 bucket not the deleted one?

Question: I am working on a project and I need to follow the steps below:

syncing all the files that are present in a directory to an AWS S3 bucket.
reading the files.

I have a shell script that contains the lines below:
s3 sync s3://<bucket_name>/performance/input scripts/input --region <region_name>

input_files=`ls -ltr scripts/input/ | awk -F ' ' '{print $9}'

echo ${input_files}

I have created Jenkins jobs under Build section. I am running the shell script above using the docker run command.
Now the problem is when I am trying to sync from the bucket, the files which are present in bucket are coming along with the deleted files that I have manually deleted from the bucket.
I want only the files that are present in the bucket. Can anyone please help me to resolve this issue?
The output of the command echo ${input_files} is below:
+ input_files=

    <file_name>_2115.csv
    <file_name>_0001.csv
    <file_name>_0002.csv
    <file_name>_0003.csv
    <file_name>_0004.csv
    <file_name>_5444.csv
    <file_name>_1348.csv
    <file_name>_3914.csv
    <file_name>_5289.csv

This list contains files that I have manually deleted. These files end with _0001, 0002, 0003 and 0004. However, I still can see those files are coming.
Comment: See https://aws.amazon.com/premiumsupport/knowledge-center/s3-listing-deleted-objects/
Answer: Unless I'm missing something i cannot see where you are syncing your s3 files too? The command works as:
aws s3 sync <source> <destination>
If you are syncing the files to your active directory try adding '.' as destination also your s3 source had an additional '/', should be s3:// unless your bucket somehow starts with /.
aws s3 sync s3://{bucket}/{key} . --region

Comment: my destination folder is scripts/input. I am syncing all files to scripts/input dir.
Comment: whoop sorry, completely overlooked the space. Also it doesn't look as though your actually using syncs capability more then just a copy, why not use aws s3 cp instead? Otherwise do you have versioning turned on in your s3 bucket?
Comment: what versioning does? I don't have any idea. and also how to turn it on?
Answer: the issue was with jenkins history.
AWS sync was working fine.
i just added one remove command from that particular dir before sync.
rm -rf scripts/input/*


Failed to complete Gradle execution : cause

Question: Error:Failed to complete Gradle execution.
Cause:

Could not create parent directory for lock file C:\Program
  Files\Android\Android
  Studio\gradle\gradle-4.1\wrapper\dists\gradle-2.14.1-all\8bnwg5hd3w55iofp58khbp6yv\gradle-2.14.1-all.zip.lck

I install android for the first time and I get this problem when I don't to start my first project.
Any suggestion will be appreciated. Thanks in advance.
Answer: Remember that Android Studio supports Build.gradle version 3.0+ so you need to change the version into the build.gradle file of your project:
buildscript {
    repositories {
        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    }
    dependencies {

        //Android Studio 3.0
        classpath 'com.android.tools.build:gradle:3.0.0'

    }
}


WPF Binding when to use which

Question: Have read few articles on WPF and I notice that Binding is often used in different ways:

{Binding UserName} binds to the UserName property of the UserViewModel class.
{Binding Path=UserName} same as above.
{Binding}. Notice, it is used by itself, there is no Path or property name provided.  I have seen this but don't understand how does this bind to  anything?

For example, I have seen this in the article which has a DataTemplate defining this:
<ContentControl Margin="20,10" Content="{Binding Path=CurrentProduct}" />

, then in MainWindow.xaml, the Binding is used like this
<ContentControl Content="{Binding}" HorizontalAlignment="Center" Margin="10" />

Why it is only Binding by itself used here and what does it mean?
Comment: `{Binding UserName}` is short for `{Binding Path=UserName}` and `{Binding}` is short for `{Binding Path=.}`.
Comment: ... and {Binding Path=.} is what?  I am trying to understand how this works.  Thanks,
Comment: Related question: http://stackoverflow.com/questions/1906587/
Comment: Related question: http://stackoverflow.com/questions/5488014/
Answer: The Binding class has many properties, one of which is the Path property.

<ContentControl Content="{Binding Path=CurrentProduct}" /> -- The XAML engine will call the default (parameterless constructor) and assign the property Path with "CurrentProduct".
<ContentControl Content="{Binding CurrentProduct}" /> -- The XAML engine will parse the XAML provided that there is a constructor that can take that value, which the Binding class does have!
<ContentControl Content="{Binding}" /> -- The XAML engine will call the default (parameterless constructor), and since no value was assigned to the property path, it will use the value from DataContext.
Answer:
The following statements are equivalent:

{Binding UserName} binds to UserName property of UserViewModel
{Binding Path=UserName} same as above

because of the following points.

Such usage: {Binding …} — Binding markup extension usage. Please note the inheritance hierarchy of the Binding class: here is the MarkupExtension class.
The second statement uses implicit path:

Implicit Path
The Binding markup extension uses Binding.Path as a conceptual "default property", where Path= does not need to appear in the expression. If you specify a Binding expression with an implicit path, the implicit path must appear first in the expression, prior to any other bindProp=value pairs where the Binding property is specified by name. For example: {Binding PathString}, where PathString is a string that is evaluated to be the value of Binding.Path in the Binding created by the markup extension usage. You can append an implicit path with other named properties after the comma separator, for example, {Binding LastName, Mode=TwoWay}.
— Binding Markup Extension, MSDN.

So, it is a matter of choice which of them to use.
The following statement:

{Binding}

represents a binding to the current source:

Optionally, a period (.) path can be used to bind to the current source. For example, Text="{Binding}" is equivalent to Text="{Binding Path=.}".

<…>
As long as the binding already has a data context (for instance, the inherited data context coming from a parent element), and whatever item or collection being returned by that context is appropriate for binding without requiring further path modification, a binding declaration can have no clauses at all: {Binding}. This is often the way a binding is specified for data styling, where the binding acts upon a collection. For more information, see the "Entire Objects Used as a Binding Source" section in the Binding Sources Overview.
— Windows Presentation Foundation: Data  Data Binding (WPF): Binding Declarations Overview, MSDN.
Answer: What you ask is simply a XAML extension in WPF and it's usually named as WPF Data Binding.
Data Binding in WPF is quite complex, but you should already read in the MSDN Library documentation of WPF first, since it's quite detail and it's of course the official and the most definitive resource.
I suggest you visiting MSDN Library for WPF data binding first. You should start from this page: Data Binding (WPF).

WPF Binding when to use which


jquery custom events confusion

Question: I have read the custom events documentation of jQuery. Just when I started to understand that you can trigger those custom events yourself, and elements like a link or window own standard events like click, scroll or resize....
I was confused when I was reading the code from unveil.js
At the bottom there is the following code:
$w.on("scroll.unveil resize.unveil lookup.unveil", unveil);

What are those events doing and where are they set / triggered?
And what is a "lookup" event at lookup.unveil.
Answer: Those are namespaced jQuery events
In jQuery events can be namespaced to make them unique and easier to work with.
Generally you'd add a click event like this
$('.element').on('click', fn);

but what if you wanted to remove the event from just one element and you did
$('.element').off('click', fn);

you'd remove the event from all elements, so you can namespace the event instead
$('.element').on('click.custom', fn);

The names doesn't matter, it's still a click event, but now it can be removed without affecting other elements matching the selector that also has a click event by doing
$('.element').off('click.custom', fn);

to trigger such an event, one would just do
$('.element').trigger('click.custom');

and it would also be triggered by a regular click, just like any click handler.
In jQuery one can also define custom events, which you probably know if you're read the Custom Events docs, and it's as easy as doing
$('.elements').on('lookup.unveil', fn);

where .unveil is just the custom namespace for the plugin, and that event can be triggered at the appropriate time by doing
$('.elements').trigger('lookup.unveil');

and as it's not a native event, it doesn't really get triggered by anything else.

jquery custom events confusion


EventEmitter - Why does the scope of this differ when adding a listener?

Question: I have a custom EventEmitter object, which emits when messages are received. After receiving a message, I'll publish it to a message exchange from an object, which will use a callback defined from that same object. Sample of the exchange function below:
function Exchange() {
    this.events = {
        published: function (data) {
            console.log(data);
        }
    };
}

Exchange.prototype.publish = function (data) {
    this.events.published(data);
};

On my receiving side, I have the custom EventEmitter which emits data:
server.on('data', function (data) {
    exchange.publish(data);
});

This works, but since exchange.publish and the listener uses the same arguments, I wanted to use:
server.on('data', exchange.publish);

This does not work, as the scope of this inside of the publish method changes, resulting in this.events to be undefined. Why does this happen?
Answer: You are passing the function itself as the callback, so it's not called as method of the object and this won't refer to the object. See the MDN documentation for more information about this.
You can use .bind to explicitly bind the function to a certain object:
server.on('data', exchange.publish.bind(exchange));

Comment: That makes sense. I essentially use the publish function, but it's unaware where it came from. If I wrap it using `function (data) { exchange.publish..`, it also passes the object.


Run container with volume and entrypoint from docker command/

Question: I am trying to run a container with volume and customized entry point, and then execute a .sh script inside the volume I shared from the docker command.
I have a folder inside my primary machine on that location: ~/vol, and inside I have a script that I want to execute on the container.
[root@ilcepoc2457 vol]# pwd
/root/vol
[root@ilcepoc2457 vol]# ll
total 8
-rwxrwxrwx.  1 root root   17 Jan 29 17:11 startup.sh
dr-xr-x---. 14 root root 4096 Jan 29 17:11 ..
drwxr-xr-x.  2 root root   24 Jan 29 17:11 .

I am trying to create a container using this command:
docker run -i -t -d --volume /vol:/vol --entrypoint "/startup.sh"  mcr.microsoft.com/playwright
And this is the error I get:
docker: Error response from daemon: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "/startup.sh": stat /startup.sh: no such file or directory: unknown.

What am I missing here?
Comment: Please don't post images of text. Just post the text itself in your question, formatted as a code sample.
Comment: You want to be running `/vol/startup.sh`, not `/startup.sh`.
Answer: The directory you show is /root/vol, but you map /vol.
Your directory is mapped to the /vol directory, but your entrypoint /startup.sh says that it's in the root of the file system. Use /vol/startup.sh instead, like this
docker run -i -t -d --volume /root/vol:/vol --entrypoint "/vol/startup.sh"  mcr.microsoft.com/playwright

Comment: I am still getting the same issue:

`docker: Error response from daemon: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "/vol/startup.sh": stat /vol/startup.sh: no such file or directory: unknown.`
Comment: I've updated my answer based on the fact that your directory listing shows the `/root/vol` directory. Try the updated command.
Comment: I am receiving `standard_init_linux.go:228: exec user process caused: exec format error`, I have removed -d to see this error
Comment: That indicates that the image and your docker host aren't compatible. What type of machine is your docker host?
Comment: Actually, this in an machine i got from work, I will try with another one from out side the organization.
Comment: I was thinking if it was Windows, Mac or Linux and if Mac, what type of CPU


How can I get Eye of Gnome to open each figure in a new window?

Question: I frequently open several (~10) figures that I want to compare.  I have always generated them using an eps format then used evince to open the set I want to compare using something like
evince set1*.eps &

Unfortunately my figures are getting too many features to effectively use evince, e.g., 100000 circles.  I can just as easily generate them as a raster image, e.g., png, but when I open them using Eye of Gnome, it uses the same window for each one which does not work for comparing
eog set1*.png &

I know I can run something like
eog set1*1.png &
eog set1*2.png &
eog set1*3.png &
...

but is there a simple bash command to get a separate window for each?  I did not find anything on the Gnome help page.
Comment: You can always just run it all in one line: `eog set1*1.png & eog set1*2.png & eog set1*3.png...`
Comment: I realize that but I am looking for something more simple that works well with wild cards.
Answer: A simple loop could do the trick:
for i in set1*.png; do eog -n "$i" & done

Comment: This is perfect!  This essentially duplicates the functionality I like about `eps` files and `evince`.
Comment: @stvn66 you could make a function and add it to your `.bashrc`: `eogn () { for i; do eog -n "$i"; done; }`, and then call `eogn set1*.png`.
Comment: The `eogn` as written opens them one at a time.  I tried adding an `&` but that did not work.  I'm sure I could put it in a bash script but as is, the solution is  not too much to type I think.
Comment: @stvn66 ah, yes, it should have been `eog -n "$i" & done; }`, though I'm not sure why it didn't work after you corrected that.
Comment: That works.  I forgot to remove the `;` and only changed it to `eog -n "$i" &; done; } .  This is great, thanks!


Images of lines $y = k = \mbox{constant}$ under the mapping $w = \cos (z)$

Question: I want to solve this question: find the images of lines $y = k = \mbox{constant}$ under the mapping $w =\cos(z).$ I know that $w=\cos(z)=\cos(x)\cosh(y)-i\sin(x)\sinh(y)$ so $u=\cos(x)\cosh(y)$ and $v=-\sin(x)\sinh(y)$ but $y=k$ is only a line and how can i map it? I don't know what values should be given to x. I put k in $u=\cos(x) \cosh(k)$ and in $v=-\sin(x)\sinh(k).$ Lastly, I ask what should I do?
Comment: $x$ traverses $\mathbb{R}$. What sort of curve do you get from $x\mapsto a\cos x - ib\sin x$?
Comment: Related: http://math.stackexchange.com/questions/54713/complex-cosine-and-sine
Comment: i can solve it when y and x got boundaries like this $1<y<2$ and $2<x<3$ but i dont know how to solve this question
Comment: you have $\cos x = {u \cosh k}, \sin x = {-v \over \sinh k.}$ use the fact $\cos ^2 x + \sin ^2 x = 1$ that gives you bunch ellipses for level curves.
Answer: As Daniel Fisher suggested you should think of $\cosh(k)$ and $\sinh(k)$ as constants. For example $a$ en $b$.
The resulting function $x\mapsto a\cos x-i b\sin x$ should ring a bell.
Perhaps it's more clear if explicitly written as a coordinate.
$$w(t) = (a\cos t, -b\sin t) \qquad t\in [0,2\pi]$$
(since the function is $2\pi$ periodic)
If $a=b$ then you'd find a circle. When they are not equal you find an ellips. Perhaps you remember the cartians form. Just set $x=a\cos t$ and $y=-b\sin t$, then
$$\frac{x^2}{a^2}+\frac{y^2}{b^2} = 1$$
Here's a picture of the map. Bigger values of $k$ make the ellipse more circle-like. (since $\cosh k$ would be closer to $\sinh k$).


How to prohibit P2P GO to accept the other peer(second client) connect?

Question: I'm trying to create a P2P connection(group) it only has one owner and one client on android device.
The reason is that if my GO device accepts a second peer connect(just pressed the invited windows), it will receive the P2P CONNECTION CHANGED event(disconnection). I cannot distinguish between the normal P2P disconnection event and this situation.
My first solution is too ignore all connect/disconnect events after the first connection, but it will cause others site effects.
Answer: I think I have found a solution.
We can use the WifiP2pGroup to check if the GO and peer exist really when we receive the disconnection event.
It cannot find GO or any peer when we receive the real p2p disconnect event, and vice versa.
example:
<code>else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
...
WifiP2pGroup p2pGroup = intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_GROUP);
...
if ( p2pGroup != null ) {
    if ( p2pGroup.getOwner() != null ) {
        Log.d(TAG, "Go address: " + p2pGroup.getOwner().deviceAddress);
    }
    else {
        Log.d(TAG, "p2pGroup getOwner = null");
        return false;
    }

    Collection<WifiP2pDevice> peerList = p2pGroup.getClientList();
    ArrayList<WifiP2pDevice> list = new ArrayList<WifiP2pDevice>(peerList);

    Log.d(TAG, "p2pGroup list size = " + list.size());
    if ( list.size() <= 0 ) {
        return false;
    }

    ///*
    String host = null;
    for (int i = 1; i < list.size(); i++) {
    host = list.get(i).deviceAddress;
    Log.d(TAG, "peer #" + i + " address: " + host);
    }
    //*/
    }
    else {
        Log.d(TAG, "p2pGroup = null");
            return false;
    }
</code>
If I have any misunderstanding, please tell me.
Thanks for reading.


Getting the height of a div after setting it to auto in IE

Question: I'm writing some JavaScript that changes the size of some content.  To do this I need to know the size of a div within my content.  If I have the following html:

   ... other stuff ...

Some text in here

   ... other stuff ...

And the following JavaScript:
$('#inner').height('auto');
var height = $("#wrapper").height();

In FireFox and Chrome the height variable increases as the inner div expands to fit all the text.  In IE this stays the same.  I guess it doesn't redraw the div straight away.  Anybody know how to get the new correct height in IE?
Cheers
Comment: Are you running quirks or standards mode?
Answer: It the problem is that the element doesn't redraw right away, then you need to measure the height asynchronously - set a 0-millisecond timeout to measure it and continue execution.
Answer: Try it this way:
$(function() {
  $('#inner').height('auto');
  var height = $("#wrapper").height();
});

Wrapping it in $(function() { }); makes it wait for the DOM to render before running the script. It's probably a good idea to put anything that needs access to the DOM immediately after render inside that function.


How to search for string with beautiful soup

Question: I'm trying to parse the below URL. I would like to get the output of all the prices on this site. The first item would be £59.
I inspected the element and found out that the html looks as below. I believe the best way would be to search for a class 'sr_gs_rackrate_total' or alternatively for a title that starts with "Price for".
How can I do this in Beautiful Soup?

Total:
£59

http://www.booking.com/searchresults.en-gb.html?label=gen173nr-17CAEoggJCAlhYSDNiBW5vcmVmaFCIAQGYAS64AQTIAQTYAQHoAQH4AQs&sid=1a43e0952558ac0ad0061d5b6523a7bc&dcid=1&checkin_monthday=23;checkin_year_month=2016-1;checkout_monthday=24;checkout_year_month=2016-1;&city=-2601889&class_interval=1&csflt=%7B%7D&dtdisc=0&group_adults=7&group_children=0&highlighted_hotels=1192837&hlrd=0&hp_sbox=1&hyb_red=0&inac=0&label_click=undef&nflt=ht_id%3D201%3B&nha_red=0&no_rooms=1&redirected_from_city=0&redirected_from_landmark=0&redirected_from_region=0&review_score_group=empty&room1=A%2CA%2CA%2CA%2CA%2CA%2CA&sb_price_type=total&score_min=0&si=ai%2Cco%2Cci%2Cre%2Cdi&ss=London&ss_all=0&ssafas=1&ssb=empty&sshis=0&ssne=London&ssne_untouched=London&order=price_for_two
Answer: Here is one way to do that:
from bs4 import BeautifulSoup
soup = BeautifulSoup(yourhtml)
span = soup.find('span', {'class': 'sr_gs_rackrate_total'})
b = span.parent
b.span.extract()
b.text

In case there is more then one span with a price in it, use
for span in soup.find_all('span', {'class': 'sr_gs_rackrate_total'}):
  b = span.parent
  b.span.extract()
  print b.text

Comment: Do I need to put a for loop?
Comment: You have a bunch of items in one array. You need a for loop to go through those items one by one and print out their content


Alternate of ngx-translate-messageformat-compiler in Angular

Question: I am using ngx-translate-messageformat-compiler in Angular, but according to their documentation,
they require 'unsafe-eval' for the script-src.
Is there any alternative that anyone knows about?
I researched: https://formatjs.io/docs/intl-messageformat/
But it doesn't seem to have any API reference for Angular.
Anyone knows any better solution?
Comment: Since CSP is now more and more required this should get more attention
Answer: I just ran into the same problem and used FormatJs to use it in a TranslateCompiler. It supports Angular 13 and 14. If you are using an earlier Angular version, you can just copy this file into your code translate-format-js-compiler.ts and it should work.
Otherwise, this is the npm dependency: ngx-translate-formatjs-compiler
Answer: We had the same issue with building the project with webpack, maybe you can try to use ngx-translate-parser-plural-select
Instead of using a compiler like this...
compiler: {
     provide: TranslateCompiler,
     useClass: TranslateMessageFormatCompiler
}

...you have to define parser, like this:
parser: {
     provide: TranslateParser,
     useClass: TranslateICUParser
}

Everything else should be untouched.


showing topological invariance

Question: i am stuck in the following question:
"show that the property of a space E that every closed loop in E can be shrunk to a point in E is a  topological invariant property of E."
intuitively i am getting an idea that if E' is homeomorphic to E, the shrinking of a given path in E', can be carried out by copying, step by step, the shrinking of the corresponding path in E. but ,i am not able to prove it...
any help would be appreciated...
Comment: Do you know the correct notion of "shrink to a point" (namely homotopy) ?
Answer: Shrinking a path $c:I\rightarrow E$ to a point is equivalent to there exists a continuous function
$H:I\times I\rightarrow E$ such that $H(0,t)=c(t), H(1,t)=x\in E$.
Thus if $f:E\rightarrow E'$ is an homeomorphism, and every path in $E$ can be shrinked to a point, consider the path $c:I\rightarrow E'$, $f^{-1}\circ c$ is a path of $E$, so there exists $H$ like above, you can define $H'=f\circ H$ which allows to shrink $c$ to a point.

showing topological invariance


Using Apps Script to get the day of the month for a cell with a date in it

Question: This returns a date Logger.log(sht.getRange(1,1).getValue())
How do I get the day of the month for that cell?
I tried
Logger.log(sht.getRange(1,1).getValue()).date()
and
Logger.log(date(sht.getRange(1,1).getValue()))
neither worked
Comment: Unfortunately, I cannot know whether the cell value of `sht.getRange(1,1)` is the date object from your question. So, if `sht.getRange(1,1).getValue()` is the date object, I think that when you want to retrieve the date, your script can be modified to `Logger.log(sht.getRange(1,1).getValue().getDate())`. How about this?
Comment: Does this answer your question? [How to get year/month/day from a date object?](https://stackoverflow.com/questions/2013255/how-to-get-year-month-day-from-a-date-object)
Comment: Thanks Tanaike  The cell is formated as a date and sht.getRange(1,1).getValue() does return the date
Comment: Thank you for replying. I have to apologize for my poor English skill. Unfortunately, from `Thanks Tanaike The cell is formated as a date and sht.getRange(1,1).getValue() does return the date`, I cannot understand whether your issue was resolved by my comment. Can I ask you about the details of it?
Comment: function myFunction() {
  var ss = SpreadsheetApp.getActive();
  var sht = ss.getActiveSheet();
  var row = 2;

  Logger.log(sht.getRange(row, 1).getValue().getDate())
          while (sht.getRange(row, 1).getValue().getDate() !== 1) { row++ };
}
 I want to skip lines where the date is not the first day of the week.
  In the code above the Logger line works well, but the second line kicks the following   TypeError: sht.getRange(...).getValue(...).getDate is not a function.  ??
Comment: Hi! Welcome to StackOverflow. Would you be able to provide a copy of your sample sheet (with your initial output), so that we can further help you with your issue?
Comment: Sorry in my last post I meant to say "first day of the month"
Comment: So basically what you would want to happen is that you have a large list of dates, and you would only want to filter all dates on the FIRST day, of every MONTH, is that correct?
Comment: Here is a link to the google sheet  https://docs.google.com/spreadsheets/d/16BHj7ygqqgw2dqRehC3p7b4yMzs2UnJ0Uhq-_3z4bwk/edit?usp=sharing
Comment: Century Tuna  I am trying to hide all the rows before the first day of a month and all the days after the end of a month.   I have done this another way but I am trying to learn about how to correctly use this getDate function as part of making my whole sheet cleaner.
Comment: So just to clarify, basing off on your spreadsheet, you want to hide all the rows on the sheet before September 1st, and then once that date arrives, hide all the rows after it? So all the rows that contain August will be hidden, then the rows for September will be shown.
Answer: ALTERNATE SOLUTION
Using your sample spreadsheet as a guideline, and based on one of your comments:

I am trying to hide all the rows before the first day of a month and all the days after the end of a month. I have done this another way but I am trying to learn about how to correctly use this getDate function as part of making my whole sheet cleaner.

You can try to follow this:

First, I've created separate functions for hiding and showing rows depending on the day of the month. One thing that I noticed on your sample sheet is that, for weekdays there are 4 rows populated for different times, while on weekends there are 6 rows populated.
As such, I've taken those into consideration in creating the two functions which executes by using the hideRows() and showRows() function, respectively.
Now, we can go to the main function, where the other functions will be called to perform the hiding (or unhiding) of rows. For this, I've also used a separate date variable, which calls the current date to compare with the other dates on the spreadsheet, and check if they are to be shown or hidden.

You can refer to the following scripts for your reference:

The two functions for hiding and showing rows:
function hideRows(date, index) {
  var ss = SpreadsheetApp.getActive();
  var sht = ss.getActiveSheet();
  // checks if the date is a weekend
  if (date[index].getDay() == 0 || date[index].getDay() == 6) {
    sht.hideRows(index + 2, 6);   // you can change the 2nd integer depending on the number of rows populated on weekends
    return index += 5;
  }
  // if the date is a weekday
  else {
    sht.hideRows(index + 2, 4);   // you can change the 2nd integer depending on the number of rows populated on weekdays
    return index += 3;
  }
}

function unhideRows(date, index) {
  var ss = SpreadsheetApp.getActive();
  var sht = ss.getActiveSheet();
  // checks if the date is a weekend
  if (date[index].getDay() == 0 || date[index].getDay() == 6) {
    sht.showRows(index + 2, 6);   // you can change the 2nd integer depending on the number of rows populated on weekends
    return index += 5;
  }
  // if the date is a weekday
  else {
    sht.showRows(index + 2, 4);   // you can change the 2nd integer depending on the number of rows populated on weekdays
    return index += 3;
  }
}

The main function:
function myFunction() {
  var ss = SpreadsheetApp.getActive();
  var sht = ss.getActiveSheet();
  var row = 2;
  var date = sht.getRange(row, 1, sht.getLastRow() - (row - 1), 1).getValues().flat();
  var today = new Date();

  for (i = 0; i < date.length; i++) {
    // a ternary operator that checks if
    // a) the date on the spreadsheet is in the same month as today's date (to show the rows), or;
    // b) hide all rows before the 1st date of the next month, or dates after the end of the previous month
    date[i] != "" ? date[i].getMonth() == today.getMonth() || (date[i].getMonth() == today.getMonth() + 1 && date[i].getDate() == 1) ? i = unhideRows(date, i) : i = hideRows(date, i) : false;
  }
}

For the ternary operator, its logic is similar to this if-else statement:
if (date[i] != "") {
    if(date[i].getMonth() == today.getMonth() || (date[i].getMonth() == today.getMonth()+1 && date[i].getDate() == 1)){
      unhideRows(date,i);
    }
    else{
      hideRows(date,i);
    }
  }

REFERENCES

getDay()
getMonth()
getDate()
hideRows() and showRows()
Comment: Let me know if this answers the issue addressed on one of your comments, or if there are some clarifications needed so that I can adjust my answer accordingly.


How to access a PRIVATE PUBLIC interface in Fortran?

Question: I have the following code:
SUBROUTINE test
USE mp, only: mp_bcast
integer :: B = 0
logical :: A
...
CALL mp_bcast (A, B)
END SUBROUTINE test

The problem is that the module mp goes as follow:
MODULE mp
IMPLICIT NONE
PRIVATE

PUBLIC :: mp_bcast
!
INTERFACE mp_bcast
  MODULE PROCEDURE mp_bcast_i1, mp_bcast_r1, mp_bcast_c1, mp_bcast_l  ! etc
END INTERFACE

SUBROUTINE mp_bcast_l(msg,source,gid)
  IMPLICIT NONE
  LOGICAL :: msg
  INTEGER, INTENT(IN) :: source
  INTEGER, INTENT(IN) :: gid
END SUBROUTINE mp_bcast_l

It is private but the interface is public. I cannot modify the module mp (belong to another software I want to interface to).
I use the following Makefile:
MODS = ../../Modules_mp/libmod.a
prog : prog.o test.o $(LD) $(LDFLAGS) -o prog.x $(MODS)

This way I though I could access the public interface in the module libmod.a that contains the module 'mp'.
It does not work and I get this error:
test.f90(38): error #6285: There is no matching specific subroutine for this generic subroutine call.   [MP_BCAST]
  CALL mp_bcast (A,B)
-------^

What would be the correct way to proceed?
Thank you,
Samuel
Comment: From the error message, it looks like the problem is that you're just calling `mp_bcast`  with arguments of the wrong type, i.e. there is no procedure which can handle `A` and `B` whatever they are on the call from subroutine `test`. `mp_bcast` actually *is* public in module `mp`, so, you have to provide more context.
Comment: I think you're missing a third argument. The second and third arguments seem to be integers for all procedures under that interface.
Comment: Oh you are correct ! In version QE 4 the gid was optional but not anymore !
Thank you !!
Answer: If you are calling a generic routine, the compiler goes through all its specific routines to find one that matches the type of the arguments. If it doesn't find one, this is the error message you get.
Have a close look at what types your A and B are, and see whether one of the specific routines matches it.
Updated due to more information
The specific subroutine you think matches has three dummy arguments (one logical, two integer), but you are only supplying two (logical and one integer).
Note: below is my original answer, which some people commented on, so I'll leave it it.
Maybe A is of type REAL and B is type INTEGER, so the compiler would search for a specific routine that has one REAL and one INTEGER, in that order, and doesn't find one. In that case, it might be necessary to convert one of the variables, like so:
CALL mp_bcast(A, float(B))

Note: From what you are writing:
MODULE PROCEDURE mp_bcast_i1, mp_bcast_r1, mp_bcast_c1  ! etc

I deduce that the _i1 might stand for INTEGER(KIND=1), and so forth, though I don't think that there is such a thing as REAL(KIND=1).
Comment: I agree with this answer but, to be pernickety, *I don't think that there is such a thing as REAL(KIND=1)*  is a very compiler-dependent statement.  And wrong for at least one compiler currently in widespread use.
Comment: It is my guess that [this](http://qe-forge.org/gf/project/q-e/scmsvn/?action=browse&path=%2Ftrunk%2Fespresso%2FModules%2Fmp.f90&view=markup) is the relevant source file. If so, the number 1 signals a scalar, not the kind.
Comment: It is from QE source code indeed.
I have updated the question. The subroutine 'mp_bcast_l' should match but I still have the compilation problem.
Answer: Your use of private and public is correct, as is the text of the error message. The problem appears to be your invocation with only two arguments. Here's an example using genericswap.f90 (available online without the additions of PRIVATE and PUBLIC swap which I've added):
module swap_module
  implicit none
  PRIVATE
  PUBLIC swap
  interface swap
    module procedure swap_reals, swap_integers
  end interface

The compiler will look through the module procedures listed and identify the one that matches the signature. Your list mp_bcast_i1, mp_bcast_r1, mp_bcast_c1, mp_bcast_l appears to have no match with (A,B) (whatever type they are). I can't be entirely certain, as you've only given the source for one routine.
I know this is an old post, but I just wanted to make sure the information was available to others who wander down this path. It may also be necessary to check what is implemented by the compiler you're using. In my case I'm using gfortran version 7.1.0 (Ubuntu 7.1.0-5ubuntu2~16.04).
Comment: Hi, don't use  for code blocks formatting. Use the icon in the editor which adds 4 spaces of indentation.


Pass context to Async class

Question: I'm calling an Async class from my main activity class. When the POST has been executed I want to return the result back to the main activity.
public class MainActivity extends Activity implements OnClickListener, AsyncResponse{
    public Context context;
    PostKey asyncTask = new PostKey(context);

    public void onCreate(Bundle savedInstanceState) {
        asyncTask.delegate = this;
    }

    public void onClick(View v) {
        asyncTask.delegate = this;
        new PostKey(context).execute(keyValue);
    }

    public void processFinish(String output){
        //this you will received result fired from async class of    onPostExecute(result) method.
        Log.d("Result", output);
    }
}

public class PostKey extends AsyncTask<String, String, String> {
    public AsyncResponse delegate = null;
    public Context context;

    public PostKey(Context context){
        this.context = context.getApplicationContext();
    }

    @Override
    protected String doInBackground(String... params) {
        return postData(params[0]);
    }

    @Override
    protected void onPostExecute(String result){
        this.context = context.getApplicationContext();
        delegate = (AsyncResponse) context;
    }

    delegate.processFinish(result);
}

public interface AsyncResponse {
    void processFinish(String output);
}

Whenever I try to run the app I immediately get a fatal error caused by a nullpointer exception. The nullpointer refers to the following:
public PostKey(Context context){
    this.context = context.getApplicationContext();
}

&
PostKey asyncTask = new PostKey(context);
In the second case I can get that context is empty, but I have to pass the variable here.
Comment: In your main activity, `public Context context;` is declared but never given a value? It is null.. so trying to call the PostKey constructor, which attempts to invoke the `getApplicationContext()` function on a null object will definitely give you a NullPointerException.
Comment: possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it)
Comment: @Gosu In every code snippet I found the `context` variable was set in the async class. Because of `private PostKey(Context context){}` I have to pass the variables in the main activity
Answer: Activity is already a Context, so you don't to keep a reference to it. Just use this. On the other hand the Activity has to go through its lifecycle before you can use the context. Remove
public Context context;
PostKey asyncTask = new PostKey(context);

and add
PostKey asyncTask = new PostKey(this);

in your onCreate. And please, add super.onCreate(savedInstanceState); as first thing in your onCreate
Answer: Hello Oryna you passing null context value as in parameter just replace these lines with this
 new PostKey(context).execute(keyValue);

to
 new PostKey(MainActivity.this).execute(keyValue);

and the constructor for the async task replace the code
    public PostKey(Context context){
    this.context = context.getApplicationContext();
}

with
public PostKey(Context context){
    this.context = context;
}

Answer: try to use this.context = getApplicationContext(); instead

Pass context to Async class


polymorphism java q from a test

Question: I have a question regarding to polymorphism
public class A
{
 protected int _i;

 public A(int i)
 {
 _i = i;
 }
}

//----------------------------------------------------------//
public class B extends A
{
 public B(int i)
 {
 super(i+1);
 }
}

//----------------------------------------------------------//
public class C extends B
{
 public C(int i)
 {
 super(i);
 }

 public boolean equals (Object other)
 {
 return ((other!=null) &&
 (other instanceof C) &&
 (_i==((C) other)._i));
 }
}

//----------------------------------------------------------//
public class D extends B
{
 public D(int i)
 {
 super(i+1);
 }

 public boolean equals (D other)
 {
 return ((other!=null) &&
 (_i==((D) other)._i));
 }
}

public class tester {
    public static void main (String [] args) {
         A a = new A(1);
         B b = new B(1);
         C c = new C(1);
         D d = new D(1);
         B b1 = new D(1);
         Object c1 = new C(1);
         Object d1 = new D(1);

    System.out.println (d1.equals(d));

    }
}

Why the printed result is false ?
when I change the equals method in D to receive Object instead of D it's printing True but way?
Please help Thanks
Answer: You already got half the answer. "when I change the equals method in D to receive Object instead of D it's printing True" is actually the key part of this problem. What you need to understand is the difference between overriding and overloading.
public boolean equals (D other)
{
  return ((other!=null) &&
     (_i==((D) other)._i));
}

This method will create a version of equals(D d) specific to the D class, in addition to the preexisting equals(Object o) in Object. This is because they have different method signatures, and is called overloading. This, however, works perfectly:
public boolean equals (Object other)
{
  return ((other!=null) &&
     (_i==((D) other)._i));
}

This is because it overrides the superclass version of equals(Object o). One final note. I know you didn't write this code, but it's good practice to write this method more like this:
public boolean equals (Object other)
{
  if(other instanceof D)
        return ((other!=null) && (_i==((D) other)._i));
  return false;
}

This way you can avoid a ClassCastException if you try to compare a D to an unrelated object, or one that is lower in the inheritance tree.

polymorphism java q from a test


File size stated is bigger than expected

Question: The Ubuntu file system says my file is 5.2MB.
When I right click on the file I can see the file size in bytes is stated as 5,154,017.

Doing some simple maths we can calculate that in MB:
5154017 / 1024 = 5033.219726562KB
5033.219726562 / 1024 = 4.915253639MB
How does Ubuntu determine the 'rounded' value of the file size displayed in the files dialog? - This question may not be Ubuntu specific.
It does not appear to be using normal rounding e.g. half up which would display as 5MB.
Comment: Related: [What file size units do applications on Ubuntu use?](https://askubuntu.com/q/222649/301745)
Answer: Ubuntu uses the
bytes > kilobytes > megabytes system
(1000 bytes = 1 kilobytes, 1000 kilobytes = 1 megabytes)
instead of the
bytes > kibibytes > mebibytes system
(1024 bytes = 1 kibibytes, 1024 kibibytes = 1 mebibytes).
So 5154017 bytes = 5.154017 megabytes ≈ 5.2 megabytes.
Answer: Ubuntu always makes the distinction between base-10 prefixes (kilo, mega, giga, etc) and base-2 prefixes (kibi, mebi, gibi, etc). That is, you will never see mebibytes (mis)labeled as megabytes. So in this case, 5.154 MB rounds to 5.2 MB.
See Units Policy on the wiki for more details.
Comment: In context of file sizes in an operating system, "MB" and the term "megabyte" has pretty much exclusively meant 1024x1024 bytes throughout computing history.  While I can appreciate the logic and "correctness" of the push to switch to 1000x1000 instead, it's taking it a bit far to label all previous usage of "MB" and "megabyte" as 1024x1024 bytes in computing history as incorrect.  Remember that "mebibyte" is a much more recent term for that quantity and acts as a disambiguator because "megabyte" has meant both.
Comment: @thomasrutter Hey, don't look at me, I didn't write the Units Policy ;)
Comment: I don't disagree with the units policy, I disagree that everyone who has used MB/megabytes to refer to 1024x1024 has misused the term.  The units policy itself acknowledges how this is standard practice in a lot of contexts.
Comment: @thomasrutter Oh, I see what you mean. I wrote "(mis)labeled" because in Ubuntu, the words are strictly defined.


Prove $\cot\frac{\theta}{2} - 2\cot\theta = \tan\frac{\theta}{2}$

Question: This is a math exercise I am doing for my year 10 math class. Basically I would like to show how I would prove that $\cot\frac{\theta}{2} - 2\cot\theta = \tan\frac{\theta}{2}$
I was able to expand the LHS and was able to use fractions to get that $$\cot\frac{\theta}{2} - 2\cot\theta = \tan\frac{\theta}{2} = \frac{\cos\frac{\theta}{2} - 2\cos\theta}{\sin\theta}$$
I do not know what I would do from here.
Any help will be appreciated. Thanks :)
Answer: suppose $\quad x=\frac \theta 2\quad$so that $\quad \theta=2x$:
$$\cot x-2\cot 2x=\frac {\cos x}{\sin x}-2\frac{\cos 2x}{\sin 2x}=\frac {2\cos^2x-2(\cos^2x-\sin^2x)}{\sin 2x}=\cdots $$
Comment: @verygood101 encourage yourself to take any and all alternative pathways you can envision with algebra.  It's liberating
Comment: I forgot you could do that! Thank you very much.
Answer: $\cot \theta=\frac {\cos \theta} {\sin \theta}=\frac {\cos^{2}\frac {\theta} 2 -\sin^{2}\frac {\theta} 2} {2\sin (\frac {\theta} 2) \cos (\frac {\theta} 2)}$. Split this into two terms.
Answer: An easier method...
Use the identities $\displaystyle \cot \frac {\theta}{2} = \csc {\theta} + \cot \theta$ and $\displaystyle \tan \frac {\theta}{2} = \csc {\theta} - \cot \theta$  and replace as needed.
The answer follows very quickly.
Answer: $\begin{align}\frac{1}{2}(\cot\frac{\theta}{2} - \tan\frac{\theta}{2})&=\frac{1}{2}\frac{1-\tan^2\frac{\theta}{2}}{\tan\frac{\theta}{2}}\\&  =\frac{1}{\frac{2\tan\frac{\theta}{2}}{1-\tan^2\frac{\theta}{2}}}\\&=\frac{1}{\tan\theta} \\&=\cot\theta\end{align}$


Restarting with new account on iOS/GameCenter

Question: I downloaded Clash of Clans to my iPad (iOS 7) this past weekend and started playing.
Of course, after a couple of hours I realized I made some newbie mistakes that are fatal to my future success.  I wanted to restart, but it seems the only way to do so is to reset the device which I really would like to avoid.
After some Googling I tried the option of logging out of Game Center and logging in with a different Apple ID.  But, sadly, CoC re-launched back into the existing game.
Is there any way I can start over? Or at least start a new game under a different account on the same device?
Comment: Stupidly and cleverly SuperCell linked the game to a specific device. So even upon deletion of the game that old village your trying to get rid of will not go away. If you contact the developers directly they may be able to delete your village upon request.
Comment: I have gotten over 3000 gems from clearing obstacles. A new obstacle appears every 8 hours up to a limit of 40. The amount of gems given has recently been increased tremendously. Coupled with the new addition of gem boxes and your early gem losses should not be a problem. If you want to contribute to SuperCell's success, each gem is only worth one US penny ($0.01) so it won't break the bank to buy a few.
Answer: At first, you must log out from your existing game center account "Before" you wipe all of your data. After you do that, you install the game and after you install it, play it. After you do all of that, you will be noticed to sign in to your game center id. You just use your game center id without having a new GC id.  After you sign in, you will be noticed again with another pop up saying do you want to reload your village at town hall level "X"? If you want to totally reset your village, just tap the no button. And if you want to reload it, just tap yes :) simple, right? And 1 more thing... don't use backed up data if you are still in the "New user" page, you must get it back "AFTER" your device already passes through the new setting ("New user" page) of your new device. (Back it up after you install clash of clans)
Comment: In iOS 10, there is no feature anymore to logout from the Game Center, because there is no Game Center app any more. So that doesn't seem to work anmore.
Answer: The only way to start a new Clash Of Clans village is to restore your iPad to factory default as a new device, not from a backup. If you restore from a backup, it will not work.
See this Apple Support page on how to do this.
Then you will need to create a new game center account. This is because your old game center account is tied to your old village.
Finally, you can download Clash Of Clans, and start your new village. Make sure to choose a village name you like, as you can only change it once.
Answer: As others have said, you have to factory restore your device in order to start over. I can't speak for Jailbreaking because I don't jailbreak my devices.
Some of the advice here doesn't work. You can't just delete the app and remove it from game center because once you re-install the game, it will still bring back your old game. This is because it's within your system file that appears to be saved in the ipad. Jailbroken device may have something that allows you to delete the files completely.
When you do a factory restore, Do NOT restore from back up as it will bring up your old game, so you have to set it up as a new device. This is the only option. Yes it is annoying, as some of you don't want to lose everything. But if you want to start over, then you have to sacrifice one thing or the other.
However, there is a way to get the new account and then get your back up so you don't lose other important stuff:

Back up your device.
Factory restore and select "Set up as New"
Install Clash of clans
You have to create a new game center account.
open CoC
Finish the tutorials.
Once the tutorials is finished and you created a in-game name, then perform another factory reset and this time "Restore from backup"
Once your restoration is complete, immediately go to game center and log out of your old one and log in with the new game center you just created.
Open CoC and it will detect that your new game.
Read the direction carefully and type "CONFIRM" Viola, you now have a new account and not lose your back up.
Answer: I'm not sure what you're considering stupid mistakes but the game is pretty forgiving whatever you do.
All placed structures can be moved at any time by long-pressing them and dragging them to a new position and there aren't really any game breaking decisions you can take.  As long as you have resource buildings up and running (which you will do) then you can always make progress.
If you want to erase your entire map that is possible too from town hall level 4.  Tap the "village edit mode" button (hand with arrows in both directions*) and then click "remove all".  This resets your village back to a plain field but puts all your buildings into inventory so you can replace them in a new layout easily whilst not having to go through upgrading them all again.
*
Comment: Just keep playing, you'll get them back sooner or later through gem boxes and other things appearing on your map. I've bought 2 extra builders with my gems so far and I've never paid anything.
Comment: If you use gems you're given in the beginning, it's impossible for you to get that back.
Comment: @SachinShekhar you can do this by clearing obstacles and complete challenges if you are looking to avoid paying.
Comment: It has limit...
Comment: yeah it's the gems lost on bad noob decisions early on that I would like to recover from...one really should be able to start over again with a clean slate.
Answer: You can uninstall the game and choose to remove all game data. If you re-install the game again you can play on your own account and you can start all over.
Comment: Nope, I tried that first (sorry I didn't mention it), but after the re-install, the game launched right back to the same spot where I was. Very sad.
Comment: In that case i'm afraid there is no other way. Indeed i found that syncing your device to itunes and resetting it to factory defaults works, but i understand that this is not a prefered way to achieve such a thing. Source : https://answers.yahoo.com/question/index?qid=20130317163432AANyqgd
Answer: Remove your Clash of Clans from Game Center (Select the Clash of Clans icon and swipe to the left - and it will show the REMOVED action) and it will notify "Removed Data from Game Center'.
Answer: There is a much better way to do this than jailbreaking or restoring. I have done it myself and actually I use it daily to switch Clash of Clans accounts on my iPod. Steps to creating a new account:

Make a new Gamecenter account that has not ever been linked to any other Clash of Clans account.
Borrow a family member's or friend's iPod or iPad or iPhone (but make sure they have never played and don't plan on playing Clash of Clans).
Log into the new Gamecenter account on the device you have borrowed.
Download Clash of Clans on the borrowed device.
Go through the tutorial of Clash of Clans on the borrowed device. After completing the tutorial, switch over to your personal iPad.
On your iPad, switch Gamecenter accounts in your iPad settings to the new one you just used on the borrowed device.
When you launch Clash of Clans on your iPad, it will ask you "Do you want to load Chief _____'s village with Town Hall level _? Warning: progress in the current game will be lost." Choose the "Load" option.
It will then ask you to type "CONFIRM" to confirm your selection.
After typing confirm, it will load the other Clash of Clans account!

If you ever want to get back to your first account, just repeat steps 6 through 9 with your old Gamecenter. Even though it says you will lose your progress, you actually will not.
If you would like me to provide screenshots of the process or explain more in depth how to do this process, please let me know I am happy to help.
Comment: The clincher here is the "borrow a family member's (device)". Effectively that device will never be able to play their own Clash of Clans - because it will be linked to your (new) account. Logging out of GameCenter on the borrowed device helps, of course.
Answer: For completeness, I am adding the steps you should take if you have a JAIL BROKEN device. Assuming you have cydia and iFile installed here is what you do to start over.
You need to create a NEW gamecenter account. A gamecenter account is merely an Appleid, by the way. I recommend creating it online in a browser on a computer rather than on a device.
Sign OUT of the gamecenter account on the device.

Open iFile and navigate to /var/Keychains/
Click on keychain-2.db to open it in sqlite3 viewer
Click on SQL (top left hand corner of the screen).
Using the search bar above search, enter the following and press Search:
select * from genp where agrp like '%supercell%'
The above shows you what will be deleted. Next enter this
delete from genp where agrp like '%supercell.magic%'
After pressing Search to do the deletion respring or reboot your device and open up clash of clans where you will find you are starting over from the beginning.

Play for a while then sign in to your new gamecenter account and you now have TWO games saved in TWO gamecenter accounts and you can switch back and forth between them, however beware that things can go wrong.
Note I have performed exactly these steps and they worked - though not in about a year. Most of my information came from this YouTube.
Answer: You have to restore your device unless you want to jailbreak your device, which is much more laborious and troublesome. I put together a guide last year and you'll have a new village with your phone and all your media  just as it was before in less than twenty minutes. You can see it here http://clashofclansblog.paulbrucesamson.com/2013/09/how-to-restart-your-clash-of-clans.html
Comment: Please summarize the relevant information from the link.  That will ensure your answer is still valid, even if the site goes down.  Besides, it saves readers a click.
Comment: And indeed the above link is broken. Server no longer available.


Windows Phone 7 EMULATOR Crash Dump or Debugging

Question: I want to debug a default application like Internet Explorer on WP7 Emulator. Is there a way to attach it to debugger ? Or how can I access the crash dumps when a crash occurs on WP7 Emulator??
Answer: You cannot debug system applications with the default toolset available from Microsoft. You can, however, keep track of events that occur in the emulator by enabling the verbose mode (aka to show the console).
To do this, open regedit and go to HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\XDE (for 64bit systems) or HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\XDE (for 32bit systems) and create a new DWORD key, named EnableConsole. Set its value to 0x00000001 (1).
Now, every time the emulator starts, there will be a console window that will show you the system events that are going on.
Comment: Hi Dennis Thanks for your reply and tip.. Its not possible to debug on emulator but is it possible to debug system applications on a real device??
Comment: Also, this is not possible with the default toolset.


Does variable declaration initializes function?

Question: Alright, this is probably a very basic question but I am new to programming (javascript = 1st language) and I couldn't find the answer on stackoverflow, so please be kind.
Does variable declaration initializes function?
For example:

I thought we needed to do myVar(); as well but apparently not as the time keeps updating on the page.
http://jsfiddle.net/PHu52/1/
Comment: You answered your own question...
Comment: setInterval is evaluated (called) as the parenthesis are present, and the result of the function is returned to the variable.
Comment: @adeneo That clarifies it. So if I had only declared a function instead of calling it with parenthesis, THEN I would have to specifically call the function with myVar();
Comment: Google "mdn setinterval" : https://developer.mozilla.org/en-US/docs/Web/API/Window.setInterval.
Answer: setInterval takes two parameters: a function and an integer. It then sets an interval to execute the function every <integer> microseconds. setInterval returns an identifier for the interval it just set, so you can later cancel the running interval using clearInterval.
So, only this will set and run the interval:
setInterval(myFunc, 1000);

This is how you use the returned id to cancel the interval:
var interval = setInterval(myFunc, 1000);
clearInterval(interval);


How do I change the indicator menu labels?

Question: I use Ubuntu 12.10 and Unity theme.
I wanted to change some of the labels like Shut Down... to Turn Off or something else. Wanted to know where such labels are stored so I can could change a few of them. Is it possible to edit a few files and get this change done?
Thanks in advance.
Comment: Aren't these stored in some text files, so that it would be easy for translation and all, wouldn't changing that file be enough(if there is a file, which should be the case)? Normally, thought for L10N, it would be a simple text sort of file. I am not sure whether I am correct, please correct me, if the case be.
Answer: You'll have to create a custom translation, or edit the code (which will break existing translations), to change the string.
The code that creates these menu items is here
Comment: Can you add instructions on how you would change this?  Or at least a link?
Comment: I believe you have to look here `/sbin/shutdown` and work from there. You could easily walk the system in one day and find all the references, now couldn't you?
Comment: No. That command is totally irrelevant to this.
Comment: Thanks @dobey for your efforts. I thought it might not have been hard-coded, though it is not, it seems to be quite risky and adventurous and may be i'll have to be content with "Shut down..." :P


Proof of compatible $[Y_1,Y_2](g) =Y_1[Y_2(g)]-Y_2(Y_1(g)) =X_1[X_2(g\circ \Phi)]-X_2(X_1(g\circ \Phi))$

Question: Quote:

"Let $X_1,Y_1$ and $X_2,Y_x$ be two pairs of vectors fields compatible by $\Phi$.
  Then $[X_1,X_2]$ and $[Y_1,Y_2]$ are compatible by $\Psi$. Consider $P\in M$ and $Q=\Phi(P)$, and let $g$ be a $C^2$ function in a neighborhood of $Q$. Then $
[Y_1,Y_2](g)
=Y_1[Y_2(g)]-Y_2(Y_1(g))
=X_1[X_2(g\circ \Phi)]-X_2(X_1(g\circ \Phi))
=[X_1,X_2](g\circ \Phi)
$."

During the step $Y_1[Y_2(g)]-Y_2(Y_1(g))
=X_1[X_2(g\circ \Phi)]-X_2(X_1(g\circ \Phi))$,
looking at the term $Y_1[Y_2(g)]
=X_1[X_2(g\circ \Phi)]$.
By the definition of compatible,
$[(Y_{2})_Q](g)
=[(Y_2)_{\Phi(P)}](g)
=[(\Phi_*)_PX(P)](g)
=X_P(g\circ\Phi)$
That I could understand. However, how did $Y_1\rightarrow X_1$ in the expression?
Answer: Suppose $X$ and $Y$ are vector fields compatible by $\Phi$, i.e. $Y\circ \Phi = T\Phi\circ X$, or equivalently $Y_{\Phi(P)} = T_P\Phi(X_P)$ for all $P$. Then $Y_{\Phi(P)}g = T_P\Phi(X_P)(g) = X_P(g\circ \Phi)$, or in other words,
$$Y(g)\circ\Phi = X(g\circ\Phi).$$
Applying this twice
$$
Y_1(Y_2(g))\circ \Phi = X_1(Y_2(g)\circ\Phi) = X_1(X_2(g\circ\Phi)),
$$
and so
$$
[Y_1,Y_2](g)\circ\Phi = [X_1,X_2](g\circ\Phi).
$$
If you're being sloppy, you can leave out the $\Phi$ on the left hand side, as done in your quote.


Better way to assert data type of all values in a Python dictionary

Question: I'm building a unit test that asserts/checks if all values in a dictionary has the same data type: float.
Python version 3.7.4
Suppose I have four different dictionaries as such:
dictionary1: dict = {
    "key 1": 1.0,
}

dictionary2: dict = {
    "key 1": "1.0",
}

dictionary3: dict = {
    "key 1": 1.0,
    "key 2": 2.0,
    "key 3": 3.0
}

dictionary4: dict = {
    "key 1": "1",
    "key 2": "2",
    "key 3": 3
}

And a unit test case as such:
class AssertTypeUnitTest(unittest.TestCase):

    def test_value_types(self):
        dictionary: dict = dictionary
        self.assertTrue(len(list(map(type, (dictionary[key] for key in dictionary)))) is 1 and
                            list(map(type, (dictionary[key] for key in dictionary)))[0] is float)

if __name__ == "__main__":
    unittest.main()

The expected result would be that it throws an AssertionError if there's one value in the dictionary that is not float, i.e. it would do that for dictionary2 but not for dictionary1.
Now while the test does work for 1 key-value pair, how would I do that for multiple key-value pair in cases such as dictionary3 and dictionary4 without having to add another for loop?
i.e.
for type in list(map(type, (dictionary[key] for key in dictionary))):
    self.assertTrue(type is float)

Thanks!
Comment: maybe use `assertIsInstance` instead of checking for the boolean values.
Answer: You can convert the types of the items to a set and assert that it is equal to a set of float:
self.assertSetEqual(set(map(type, dictionary.values())), {float})

Answer: Let's break the assert you wrote to understand what it is actually doing.
self.assertTrue(
    len(list(map(type, (dictionary[key] for key in dictionary)))) is 1  #
    and  #
    list(map(type, (dictionary[key] for key in dictionary)))[0] is float
)

You have two conditions there that must be true for the assert to pass. The first one is
len(list(map(type, (dictionary[key] for key in dictionary)))) is 1

This creates a list with the type of each value in the dictionary, computes its length and check that it is one. Well, this list will always have the same number of elements that you dictionary has. Checking that this length is equal to one has nothing to do with what you are asking.
The second condition is
list(map(type, (dictionary[key] for key in dictionary)))[0] is float

This will create a list with the type of each value in the dictionary as before, then check that the first element of this list is float. That does not necessarey means all elements in the original dictionary are float.
Using what you already wrote, the easy way to check is get the list of types, take the first element and then check that all elements are equal to the first element.
l = list(map(type, (dictionary[key] for key in dictionary)))
for t in l:
    self.assertTrue(t==l[0])

But there are many ways to do the test. You can also convert this list into a set and check that its length is equal to one (since set will only keep unique values)
self.assertTrue(len(set(l)) == 1)
# or self.assertEqual(len(set(l)), 1)

Comment: Ah, thanks for breaking things down! I `(len(list(map(type, (dictionary[key] for key in dictionary)))) is 1 and list(map(type, (dictionary[key] for key in dictionary)))[0] is float)` works in my project since the dictionary **only** contains 1 key-value pair. Seems I forgot to test the example case.
Comment: It is always a good idea to break things down into simpler pieces for checking, even if you think the problem is elsewhere.
Answer: I had a similar problem but wanted to solve it in a more general fashion using the typing module of the python standard library. It uses the package pydantic, which seems like a reasonable dependency. Here is my approach.
import unittest
import typing
import pydantic

def check_type(obj, expected_type):

    class Model(pydantic.BaseModel):
        data: expected_type

    # convert ValidationError to TypeError if the obj does not match the expected type
    try:
        Model(data=obj)
    except pydantic.ValidationError as ve:
        raise TypeError(str(ve.errors()))

    return True  # allow constructs like assert check_type(x, List[float])

class TestCase1(unittest.TestCase):

    def test_check_type(self):

        obj1 = [3, 4, 5]
        obj2 = [3, 4, "x"]

        check_type(obj1, typing.List[int]) # pass silently

        with self.assertRaises(TypeError) as cm:
            check_type(obj2, typing.List[int])

        obj3 = {
                "key 1": 1.0,
                "key 2": 2.0,
                "key 3": 3.0
                }

        check_type(obj3, typing.Dict[str, pydantic.StrictFloat])

        obj3["key 3"] = "3.0"

        with self.assertRaises(TypeError) as cm:
            check_type(obj3, typing.Dict[str, pydantic.StrictFloat])

        # note that this passes:
        check_type(obj3, typing.Dict[str, float])

        # allow for multiple types:
        check_type(obj3, typing.Dict[str, typing.Union[int, float, str]])


Deserealization not working properly

Question: I've create a class for deserialize this JSON
public class Self
{
    public string href { get; set; }
}

public class Team
{
    public string href { get; set; }
}

public class Links
{
    public Self _self { get; set; }
    public Team team { get; set; }
}

public class Player
{
    public int id { get; set; }
    public string name { get; set; }
    public string position { get; set; }
    public int jerseyNumber { get; set; }
    public string dateOfBirth { get; set; }
    public string nationality { get; set; }
    public string contractUntil { get; set; }
    public string marketValue { get; set; }
}

public class RootObject
{
    public Links _links { get; set; }
    public int count { get; set; }
    public List<Player> players { get; set; }
}

public struct Player_Struct
{
    public string id;
    public string name;
    public string position;
    public int jerseyNumber;
    public string dateOfBirth;
    public string nationality;
    public string contractUntil;
    public string marketValue;
}

So I made a function to create an HttpRequest and the relative object:
 string requestUrl = teams.link_teams;
 string responseText = parser.Request(requestUrl);
 var obj = JsonConvert.DeserializeObject<Players.RootObject>(responseText);

Now the problem's that the compiler return this exception:

Unhandled exception 'Newtonsoft.Json.JsonSerializationException' in Newtonsoft.Json.dll
Ulteriori informazioni: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'SF_DebugProject.API.Players+Links' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '_links', line 1, position 11.

So with the fix hint I've tried to repair the error change the object into:
List<Players.RootObject> obj = JsonConvert.DeserializeObject<List<Players.RootObject>>(responseText);

but in this way I can't see any attribute of the rootobject when I do the foreach. What I doing wrong?
Comment: Where's the json? The message says that the input shape doesn't match the target types. Deserialization can't change the shape of the data. If your input contains an array of players with no other data, you can't force it to become a `RootObject`
Comment: The json is here: http://api.football-data.org/alpha/teams/19/players
anyway, with this object I can see the parameter of the RootObject:
var obj = JsonConvert.DeserializeObject(responseText);
but for a strange reason an exception is returned.
Answer: From what I understand you want to deserialize a JSON string in a RootObject that contains a list of players.
The classes should look like this:
public class Rootobject
{
    public _Links _links { get; set; }
    public int count { get; set; }
    public Player[] players { get; set; }
}

public class _Links
{
    public _Self _self { get; set; }
    public Team team { get; set; }
}

public class _Self
{
    public string href { get; set; }
}

public class Team
{
    public string href { get; set; }
}

public class Player
{
    public int id { get; set; }
    public string name { get; set; }
    public string position { get; set; }
    public int jerseyNumber { get; set; }
    public string dateOfBirth { get; set; }
    public string nationality { get; set; }
    public string contractUntil { get; set; }
    public string marketValue { get; set; }
}

So what you should do is something like the following :
var obj = JsonConvert.DeserializeObject<RootObject>(response);
foreach(var player in obj.players)
{
     // some stuff
}

Comment: he is exactly doing this
Comment: In fact I already do this. My problem is that I can not see the parameters of each players. The parameters are those contained in the Player class. Referring to the first obj instead I can see the parameters (variable), the point is that during the execution of the function I get an exception.
Comment: Ok, I edited my answer to show the C# classes to be used.
Comment: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'SF_DebugProject.API.Players+_Links' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Comment: I tried it on my machine and it works. Are you sure the JSON string you pass to JsonConvert is ok ?
Comment: Okay, sorry for the mistake the link of my struct passed in the function was incorrect. Thank you :)

Deserealization not working properly


What are the exact rewards from the mission "Priority - Eden Prime"

Question: After I finished the mission and spoke with Javik, I remember there were three "popups" with rewards from it. One was the assault rifle and another one a biotic power. But I forgot what was the last reward, I only remember it had the "Information" header in the popup.
I tried to load a save and finish the mission again but only got one "popup" with the assault rifle reward.
Comment: IGN's video walkthrough just shows two: http://www.youtube.com/watch?v=w9kXbkNB5Uk
Comment: It was probably either a new upgrade from glyph or just some credits from the alliance.
Answer: The exact reward for this mission is, obviously reputation for talking to someone new. More notably is the Slam Power unlocked for your purchase in the medical bay and the Particle Rifle. There is no third reward that i could find in my research.
Proof