Multiple of one villager?

Question: I was actually wondering if it's possible to have two of the same villager on one island as I want Papi but my fiancé does too. I have one for her already as she doesn't like doing the online trading thing but someone is offering Papi for free. I have spent a good while looking online but unfortunately I have been unable to find an answer to this question and don't want to let this offer go to waste!
-edit
I would like to clarify, we both have our own switches and both want Papi, I am wondering if it's possible to have two of the same villager on my island at one time. One would go to my fiancés once she has a plot available and I would keep the other.
Comment: You may want to reword this a bit to clarify that you're playing on two Switches. The first time reading sounded like you meant 2 accounts on a single Switch.
Comment: Whyare you trying to send the second papi to your island, instead of just using your fiancée's switch to get them to her island? Why the extra step?
Comment: Potentially related question: [How do I get a specific villager on my island?](https://gaming.stackexchange.com/questions/128087/how-do-i-get-a-certain-villager)
Comment: I'm not sure I quite understand this. Why do you each need your own Papi on the island? Can't you share the one? Edit: Oh, I see now, you're trying to get a second one on your island until you can give her one of them!
Answer: This question is moot?
1- If you are playing on the same switch, you automatically have the same island, and then the same villagers. If you want a duplicata of the same villager, I'm pretty sure that is not possible but I wonder what would happen if you try to invite him from another island. Probably it just doesn't offer you the option.
2- If you are on different switches, your islands do not have anything tieing them together. And villagers can be on different islands without problem. Only thing that might break immersion is that that villager you have will not recognise you if you encounter it on another island. You are basically meeting his long lost twin.
So in both cases, no problem. You and your SO can have the same villager.

Multiple of one villager?


What is the smallest element of $A:=\{k\in N:k>nx\}$

Question: I am working on Lebi's Real Analysis textbook and I am running into a bit of a challenge. I am on the section about the Archimedean property, and from what I understand it means that for any $x,y\in R$ you could find a $n\in N$ such that $nx>y$.
The next part is a proof about the set of rationals being dense in the set of real. It begins with defining the set $A:=\{k\in N:k>nx\}$ and says that it is nonempty. This makes sense, because of the Archimedean property, but I am thought that one could make a claim about the smallest element in $A$. I can see that $\inf A=nx$ so why isn't $(nx+1)$ the least element in $A$?
Comment: If it is as you described, you are right. $A\subseteq\mathbb{N}$ and therefore has a minimal element. That element will not be $nx+1$ since $nx$ doesn't have to be a natural number. The minimum should be $\lfloor nx+1\rfloor$ (the smallest natural number strictly greater than $nx$). Also $\text{inf} A \neq nx$ since the infimum equals the minimum if it exists.
Comment: Yeah, I think my biggest mistake was assuming nx to be a natural number. You are right that they just defined it as $m$. Thanks for the help!
Comment: Well, $nx$ need not be an integer at all.  Also $nx$ could be negative.  But:  If $nx < 0$ then $\inf = 0$ (assuming your text claims $0$ is a natural number.  If not then $nx < 1$ then $\inf = 1$).  If $nx$ is an integer greater than or equal to $0$ then $\inf = nx+1$.  BUt if $nx$ is a positive number but not an integer then $\inf = \lceil nx \rceil$.  You can probably combine this to make it a single statement $\inf A = \max(0, \lfloor nx+1 \rfloor$ but... actually finding this exact expression of the value is not that important and worrying about it is actually a distraction.
Comment: @VincentBatens "The minimum should be ⌊nx+1⌋ (the smallest natural number strictly greater than nx)"  A slight nitpick.  $\lfloor nx+1\rfloor$ is the smallest *integer* strictly greater than $nx$.    But if $nx <-1$ such an integer need not but a natural number.  If $nx < -1$ then the smallest natural number strictly larger than $nx$ is $0$.  But.... it *is* a nitpick.  You comment is otherwise spot on.
Comment: I just checked in the book, they just call that minimum $m$, they don't make it explicit since making it explicit doesn't help.
Comment: Oh, by the way $nx$ is not $\inf A$.  $nx$ is *a* lower bound of $A$ but it is not the greatest lower bound.
Comment: @fleablood Ah yes, I wasn't paying too much attention to the details, since in the end, all of this is just distracting from the proof.
Answer: It's not correct to say that the infimum is $nx$, rather it will be $\lfloor nx\rfloor + 1$, with $\lfloor nx \rfloor$ the floor of $nx$. This is because $A$ is a subset of the natural numbers and any such set has a least element which will also be the infimum.
Comment: Although it seems obvious now, I didn't realize that the infimum for a subset of the natural numbers also has to be the least element, thank you!
Comment: @MusicalTaco $\frac1n$ is not an element of the natural numbers. So any subset of the naturals numbers contains its least element which is also its infimum but that doesn't hold for the rationals or even the integers. The set $\{\frac1n : n \in N\}$ does not have a least element, but $1$ is the maximum and also the supremum.
Comment: @MusicalTaco Subsets of the natural numbers are closed, so they contain all their limit points. That includes the infimum.
Comment: The next section makes the claim that infimum of $A:=\{\frac{1}{n}:n\in N\}$ is 0 but the least element is 1. So is the idea "if an infimum of a subset of the natural numbers is a natural number, than it has to also be the least element"?


Matlab: Running an m-file from command-line

Question: Suppose that;
I have an m-file at location:
C:\M1\M2\M3\mfile.m
And exe file of the matlab is at this location:
C:\E1\E2\E3\matlab.exe
I want to run this m-file with Matlab, from command-line, for example inside a .bat file. How can I do this, is there a way to do it?
Comment: you might find these useful: http://stackoverflow.com/questions/14495/how-can-i-stop-matlab-from-returning-until-after-a-command-line-script-completes, http://stackoverflow.com/questions/1857825/run-matlab-in-batch-mode
Answer: A command like this runs the m-file successfully:
"C:\\matlab.exe" -nodisplay -nosplash -nodesktop -r "run('C:\\mfile.m'); exit;"
Comment: That would be good if you add "exit" command at the end to make your answer more practical and helpful.
Comment: What if you want to pass arguments?
Comment: The single and double quotation marks in and around the "run" command are important!
Comment: Note that `-r` is [no longer recommended as of R2019b](https://stackoverflow.com/a/58358304/7328782).
Comment: Another similar question is here to reply : http://stackoverflow.com/questions/25102699/open-a-gui-directly-from-desktop-shortcut-in-matlab-enviroment
Comment: Does the Windows version support the -nodesktop option?  I thought not, but may be wrong.
Comment: This looks like the solution I'm searching for but I get "undefined variable or class" error on myFile.m.  I'm in the directory of my .m file.  The error is on this part "run(myFile.m); exit"
Comment: Update: Figured out that I needed to remove the .m from the command.  So this worked for me: "C:\\matlab.exe" -nosplash -nodesktop -r "mfile; exit;"
Answer: I think that one important point that was not mentioned in the previous answers is that, if not explicitly indicated, the matlab interpreter will remain open.
Therefore, to the answer of @hkBattousai I will add the exit command:
"C:\\matlab.exe" -nodisplay -nosplash -nodesktop -r "run('C:\\mfile.m');exit;"
Comment: For some reason if `mfile.m` triggers an error the explicit `exit` function is never called, making the whole process wait...
Answer: Here is what I would use instead, to gracefully handle errors from the script:
"C:\\matlab.exe" -nodisplay -nosplash -nodesktop -r "try, run('C:\\mfile.m'), catch, exit, end, exit"

If you want more verbosity:
"C:\\matlab.exe" -nodisplay -nosplash -nodesktop -r "try, run('C:\\mfile.m'), catch me, fprintf('%s / %s\n',me.identifier,me.message), end, exit"

I found the original reference here. Since original link is now gone, here is the link to an alternate newreader still alive today:

exit matlab when running batch m file
Answer: On Linux you can do the same and you can actually send back to the shell a custom error code, like the following:
#!/bin/bash
matlab -nodisplay -nojvm -nosplash -nodesktop -r \
      "try, run('/foo/bar/my_script.m'), catch, exit(1), end, exit(0);"
echo "matlab exit code: $?"

it prints matlab exit code: 1 if the script throws an exception, matlab exit code: 0 otherwise.
Comment: To display the error as MATLAB would do when not catching it, just do

`"try, run('/foo/bar/my_script.m'), catch e, disp(getReport(e)), exit(1), end, exit(0);"`
Answer: Since R2019b, there is a new command line option, -batch. It replaces -r, which is no longer recommended. It also unifies the syntax across platforms. See for example the documentation for Windows, for the other platforms the description is identical.
matlab -batch "statement to run"

This starts MATLAB without the desktop or splash screen, logs all output to stdout and stderr, exits automatically when the statement completes, and provides an exit code reporting success or error.
It is thus no longer necessary to use try/catch around the code to run, and it is no longer necessary to add an exit statement.
Comment: This seems to work well most of the time, but running `matlab -batch "disp('hello')"` on Windows with R2021b prints "hello" and then a Java error `Caused by: com.mathworks.util.ShutdownRuntimeException: Java is shutting down`.
Comment: @PaulWintz That sounds like something you should report as a bug to the MathWorks. You can probably circumvent that with `matlab -nojvm -batch "..."`, so that the Java VM is never started.
Comment: @Chis Luengo, including `-nojvm` does prevent the error. Thanks!
Answer: Here are the steps:

Start the command line.
Enter the folder containing the .m file with cd C:\M1\M2\M3
Run the following: C:\E1\E2\E3\matlab.exe -r mfile

Windows systems will use your current folder as the location for MATLAB to search for .m files, and the -r option tries to start the given .m file as soon as startup occurs.
Comment: It won't run inside a .bat file. I gave it as an example. Actually, I will run it by the Win32 API function `CreateProcessW()`.
Answer: cat 1.m | matlab -nodesktop -nosplash

And I use Ubuntu
Answer: Thanks to malat. Your comment helped me.
But I want to add my try-catch block, as I found the MExeption method getReport() that returns the whole error message and prints it to the matlab console.
Additionally I printed the filename as this compilation is part of a batch script that calls matlab.
try
    some_code
    ...
catch message
    display(['ERROR in file: ' message.stack.file])
    display(['ERROR: ' getReport(message)])
end;

For a false model name passed to legacy code generation method, the output would look like:
ERROR in file: C:\..\..\..
ERROR: Undefined function or variable 'modelname'.

Error in sub-m-file (line 63)
legacy_code( 'slblock_generate', specs, modelname);

Error in m-file (line 11)
sub-m-file

Error in run (line 63)
evalin('caller', [script ';']);

Finally, to display the output at the windows command prompt window, just log the matlab console to a file with -logfile logfile.txt (use additionally -wait) and call the batch command type logfile.txt
Answer: I run this command within a bash script, in particular to submit SGE jobs and batch process things:
/Path_to_matlab -nodisplay -nosplash -nodesktop < m_file.m

Answer: Since none of the answers has information about feeding input argument, it is important to
add it here. After some research, I found this link
Feeding the arguments is very similar to how we run a Matlab function.
matlab -r 'try myfunction(argument1,argument2); catch; end; quit'

If you are somehow getting an argument from bash/terminal, you simply need to insert that into the bash command as:
matlab -r 'try myfunction($MY_BASH_ARG,argument2); catch; end; quit'

(This is after a couple of trial and error)
Comment: You can use `matlab -r "addpath('/my/mfile/directory/'); my_mfilename(argument1, argument2)"` so you don't have to rely on the working directory which can be reset by `startup.m`
Answer: In the new releases of matlab, there is no need to specify the option "-nodisplay" in the command line mentioned by the accepted answer. Simply doing the following will work without any warning:
"C:\...\matlab.exe" -nosplash -nodesktop -r "run('<matlab-script>.m'); exit;"

Comment: In the new releases, use the `-batch` option, `-r` is no longer recommended. https://stackoverflow.com/a/58358304/7328782


Cannot change backlight brightness Ubuntu 14.04

Question: This morning I found that I cannot change the brightness of my Dell XPs 13 laptop's display anymore. I tried the following to change the brightness

Use keyboard brightness keys
Run the commands shown below
Boot with kernel option acpi_backlight=vendor. This resulted in a dell_something folder being present in the /sys/class/backlight folder. Changing the brightness file in that folder does not help.
Add 'intel_backlight' to xorg.conf
Set "load legacy option ROM" BIOS option to enabled and "secure boot" to disabled
Boot with kernel option i915.disable-pch_pwm=0
Boot from a fresh Ubuntu 12.04 USB stick installation. I can still not control the brightness. This is strange as the laptop came preinstalled with 12.04. Maybe this a hardware problem?
Install latest intel video driver

Any ideas why this broke suddendly? I've upgraded from 12.04 to 14.04 in April and till yesterday the brightness keys were working fine.
Thanks!
echo 100 > /sys/class/backlight/intel_backlight/brightness
echo 100 > /sys/class/backlight/acpi_video0/brightness

Comment: I used some help from this blog: http://itsfoss.com/fix-brightness-ubuntu-1310/ It worked on a dell. Not able to run it on an acer.Hope it works for you
Comment: Thanks for your help. I found that article myself but I figured that solve the problem. The changes in the xorg.conf just make the brightness buttons work by echoing the appropriate value in thebrightness file. My problem, however, is that even when I manually changethe value the brightness does not changed.
Answer: I got a fix for my dell 5521 laptop, working for Ubuntu 14.04 but will work for kernels v3.13+.

Open /etc/default/grub
sudo nano /etc/default/grub

to change the line
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"

to
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash video.use_native_backlight=1"

then save and exit and
run
sudo update-grub

then reboot

The explanation is that ACPI adds its own back light control even if one is already present which is intel_backlight, adding this line forces CPI to use the Intel back light.
Comment: I can conform, that this fix my problem in up-to-date Ubuntu 14.04.1 TLS version.
Comment: Perfect. worked under ubuntu 16.04 (Dell XPS 13).
Comment: It worked on ubuntu 16.10, too. Thanks!
Comment: Didn't work for me on Ubuntu 16.10.
Comment: This did the trick on first reboot, but not anymore. The line you suggested is still present on /etc/default/grub. Any idea?
Comment: @Soullivaneuh Did you update your grub after changing that line?
Answer: For me, solution listed on bug report #1249219.
Basically it works creating the /usr/share/X11/xorg.conf.d/20-intel.conf file with the following lines:
Section "Device"
        Identifier "card0"
        Driver "intel"
        Option "Backlight" "intel_backlight"
        BusID "PCI:0:2:0"
EndSection

Comment: It's very good answer :)
Comment: How can you do this without `xserver-xorg-video-intel` package?  The package is causing complications in some Zenbooks etc here http://askubuntu.com/a/816703/25388
Comment: This prevented my machine from booting
Answer: I created a simply script:
touch /usr/bin/brightness

The contents as follows:
#!/bin/bash
echo $1 | sudo tee /sys/class/backlight/intel_backlight/brightness

This allows you to then run the following from the command line:
brightness 100
brightness 4000

The values depend on your max brightness values which you can get by running:
cat /sys/class/backlight/intel_backlight/max_brightness

Don't forget to make the script executable:
chmod +x /usr/bin/brightness

I opted not to change the permissions of the brightness file and keep the sudo part for security reasons.
Answer:
Open Terminal, run gksudo gedit /etc/rc.local
It will ask for password. Type your password.
Then, the text editor will pop up with rc.local file opened. It contains some stuff and in the end exit 0.
Before that exit 0 line, add below commands to reduce brightness in Ubuntu:
echo x > /sys/class/backlight/intel_backlight/brightness
echo y | tee /sys/class/backlight/acpi_video?*/brightness # (optional) > /dev/null

where 0 ≤ x ≤ 4882 and 0 ≤ y ≤ 10.
That's it. Save and restart your machine.
Comment: how/where did you find the maximum value?
Comment: You can get maximum value for your monitor's brightness with `cat /sys/class/backlight/intel_backlight/max_brightness`
Answer: I have read A LOT of articles
Here is what I did, as I've been struggling with this for a long time...
Creating and modifying /usr/share/X11/xorg.conf.d/20-intel.conf file with the following lines...
Section "Device"
   Identifier "card0"
   Driver "intel"
   Option "Backlight" "intel_backlight"
   BusID "PCI:0:2:0"
EndSection

...didn't work at all
I was using xbacklight option for some time, but it didn't satisfy me, as I knew it must be possible with Linux native way.
I've tried many GRUB options without effect, so I was googling again and again, coming back to solve this issue.
Today I came to the solution, which is following:

You need to kill your display manager, to create new Xorg.conf file (because it runs X server):

Press Ctrl+Alt+F1 (Dont panic, while your Window system is runing, you can go back with Ctrl+Alt+F7)
typesudo service lightdm stop and press Enter(e.g. gdm, kdm, xdm)

Create new Xorg configuration file

type X -configure and press Enter
type mv xorg.conf.new /etc/X11/xorg.conf and press Enter

Start X Server (you can do it all without GUI via command line, but I was more comfortable with this aproach):

typesudo service lightdm start and press Enter(e.g. gdm, kdm, xdm)

Modify Xorg.conf file

navigate to /etc/X11/xorg.conf and open Xorg.conf (in my case latest was xorg.conf.05312015) via leafpad (e.g. gedit, pluma)
search for Section "Device" and then for Driver (on my PC it said Driver      "intel" by default, but it could be something else, so change it to intel)
add line Option "Backlight" "intel_backlight" after Driver "intel" (it doesn't really matter where, as long as it stays in Device Section)
save

Modify GRUB

sudo gedit /etc/default/grub (e.g. leafpad, pluma...)
set to GRUB_CMDLINE_LINUX_DEFAULT="quiet splash acpi_osi=" (acpi_osi= did it for me, other options didn't work...)
in terminal type sudo update-grub and press Enter
or use GRUB customizer:

sudo add-apt-repository ppa:danielrichter2007/grub-customizer
sudo apt-get update
sudo apt-get install grub-customizer

press Save in upper left corner, which will update GRUB for you

Restart and profit

Funny thing is, that code is exactly the same as in /usr/share/X11/xorg.conf.d/20-intel.conf, but that way it worked as expected!
Comment: Works for me!  In a Samsung ATIV Smart PC Pro XE700T1C
Answer: This worked for Acer 5830TG in Ubuntu 16.04 LTS

First make sure your system uses Intel Graphics card
$ ls /sys/class/backlight
intel_backlight

At least intel_backlight should be mentioned
Now download and install Intel graphics driver and follow instructions.
On the grub configuration file /etc/default/grub modify the following line:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"

to
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash acpi_backlight=vendor"

Then update grub
sudo update-grub

Create and open the file /usr/share/X11/xorg.conf.d/20-intel.conf:
gksudo gedit /usr/share/X11/xorg.conf.d/20-intel.conf

Add the following text:
Section "Device"
        Driver      "intel"
        Option      "Backlight"  "intel_backlight"
        Identifier "card0"
EndSection

Save and reboot.
Comment: adding of ` acpi_backlight=vendor` was enough (+restart). Ubuntu 18.04. Samsung R510
Answer: I used this solution, it's very simple and easy:

Install xbacklight
Open Startup Applications
Add a new startup item, (give it a name and in the command line type: xbacklight -set 50)

50 gave me the level of brightness I needed but you may need to experiment with the values for your particular system.
Comment: I find it easier to just use `xbacklight -set 50` in the terminal.
Comment: Doesn't work for me on mac dual boot ubuntu 14.04.3
Comment: This doesn't resolve the issue of `xbacklight` not being able to find the displays.
Answer: I had the same issue on my Samsung laptop with my Ubuntu 14.04 and kernel 3.19.
For me the solution was setting the line in the configuration file /etc/default/grub as following:
 GRUB_CMDLINE_LINUX_DEFAULT="quiet splash video.use_native_backlight=0"

and then updating settings:
sudo grub-update

If t will not help you can try to turn off Legacy (CMS) boot option in BIOS.

Before I was trying:

Setting /usr/share/X11/xorg.conf.d/80-backlight.conf file
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash acpi_backlight=vendor"
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash video.use_native_backlight=1"
Comment: For me, adding `video.use_native_backlight=1` to `/etc/default/grub` is working. But I need to control brightness by `xrandr`, there is no slider visible in display settings anyway.
Answer: It works for ubuntu 14.04 for me.
Minimum brightness setting:
echo 0 | sudo tee /sys/class/backlight/acpi_video0/brightness

Maximum:
echo 7 | sudo tee /sys/class/backlight/acpi_video0/brightness

Answer: I had the same problem on my Lenovo Ideapad Z500.
I found this trick that worked on my Ubuntu 16.04:
In the GRUB configuration file /etc/default/grub modify the following line:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"

by adding this string: acpi_backlight=vendor. In my case I removed acpi-osi=linux and replaced, so, in the end it was:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash acpi_backlight=vendor"

Update grub by running:
sudo update-grub

Then create an xorg configuration file like this:
sudo touch /usr/share/X11/xorg.conf.d/80-backlight.conf

and copy in it this text:
Section "Device"
     Identifier  "Intel Graphics"
     Driver      "intel"
     Option      "AccelMethod"     "sna"
     Option      "Backlight"       "ideapad"
     BusID       "PCI:0:2:0"
EndSection

Save the file, and reboot.

Also you can try to use Fn brightness keys outside of Ubuntu (before it starts or in the BIOS settings). It could work.
Comment: http://askubuntu.com/questions/575020/ubuntu-14-04-brightness-problem-lenovo-z500

here where i found my solution
Answer: I found solution after years of searching and it's works very well.
Just added in  /etc/default/grub GRUB_CMDLINE_LINUX_DEFAULT string acpi_backlight=video.
Lenovo Ideapad Z500: Intel HD4000, GeForce 740m
Comment: This one worked for me.  Mine is an Intel and nVidia combo on an HP Envy laptop.  There is no onscreen meter displayed by the OS as the brightness changes with this solution, and the brightness changes veeeeeerrrrry gradually for me.  I had to hold the button down for many seconds to cycle from fully dark to fully lit.
Answer: I have an answer that worked for me on Ubuntu 16.04, 18.04 and 20.04.
I believe this answer applies only if the following two statements apply to your system. Please don't waste your time if these statements aren't true:

ls /sys/class/backlight/ returns acpi_video0 and exactly one other, such as intel_backlight

echo 450 | sudo tee /sys/class/backlight/intel_backlight/brightness makes your brightness about half, and echo 900 | sudo tee /sys/class/backlight/intel_backlight/brightness makes full brightness.
(Here you should be replacing intel_backlight with whatever you found in step 1 and replacing 450 and 900 according to your device's maximum brightness setting, which is found by the command cat /sys/class/backlight/intel_backlight/max_brightness or your equivalent.)

In this case your problem is likely to be because the system has added the acpi_video0 module incorrectly, and the brightness keys use this instead of intel_backlight (or your equivalent).
To solve this, you need to add the boot option
acpi_backlight=none which will remove the directory acpi_video0  from /sys/class/backlight/. The brightness keys now apply their logic to the only directory in /sys/class/backlight/ which is what we want.
I gleaned this knowledge from this helpful page https://wiki.archlinux.org/index.php/backlight which states that "If you find that changing the acpi_video0 backlight does not actually change the brightness, you may need to use acpi_backlight=none."
Comment: Actually the following have made my screen black until I've got an idea that my laptop is going to sleep all the time `echo 900 | sudo tee /sys/class/backlight/intel_backlight/brightness`. A hard restart was a remedy.
Answer: For MANJARO 18 users:
I have a LENOVO with hybrid GPU, but I'm using just the NVIDIA card. Brightness buttons didn't work. The edition sugester elsewhere with a 10-nvidia-brightness.conf file didn't work. After reading a lot of, this solution, from Ubuntu users, worked for me.
Open a terminal and type:
ls /sys/class/backlight
For me, it pointed to intel_backlight. I don't know how this works for the acpi_backlight.
I createad the file
sudo <text_editor> /usr/share/X11/xorg.conf.d/20-intel.conf
Put your favourite text editor in <text_editor>, mine is xed.
Then write inside:
Section "Device"
        Identifier "card0"
        Driver "intel"
        Option "Backlight" "intel_backlight"
        BusID "PCI:0:2:0"
EndSection

The correct PCI should be that from the output of lspci | grep VGA (mine is 00:02.0). Save the file, then sudo pkill X (or reboot) and that's all.
Answer: Ubuntu 22.04
brightness-hotkey-fix: Intel Corporation Skylake GT2 [ HD Graphics 520 ] (rev 07)

sudoedit /etc/default/grub
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash acpi_backlight=video"

save and update grub: sudo update-grub

sudoedit /usr/share/X11/xorg.conf.d/20-intel.conf
Section "Device"
Driver      "intel"
Option      "Backlight"  "intel_backlight"
Identifier "card0"
EndSection

save and reboot
Answer: This worked for my eeepc seashell series:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash acpi_osi=Linux"

This is from http://ubuntuforums.org/showthread.php?t=1412922,
and they got it from http://wiki.debian.org/DebianEeePC/Model/1005pe.
Answer: Xubuntu 16.04 (Samsung N150 - Intel GMA3150):
Fixed brightness control issue by creating /usr/share/X11/xorg.conf.d/20-intel.conf with the following text:
Section "Device"
        Driver      "intel"
        Option      "Backlight"  "intel_backlight"
        Identifier "card0"
EndSection

Thanks to:
ArchLinux - Samsung_N150_Backlight
and
Daria
Answer: clone the following script and run it from a root terminal after pasting the script in /bin
git clone https://github.com/el-beth/backlight.sh.git
Comment: Can you **[edit]** this to expand it with an explanation of what you mean by "pasting the script in `/bin`"? Do you mean to copy it to that directory? Can you add instructions for the steps besides running `git clone`?
Answer: So I've just solved this problem in my Dell XPS 15 7590 (Ubuntu 18.04) with OLED screen after setting up dual boot with it.
The screen can dim (for example power-saving dimming) so it's definitely capable, and using brightness buttons operates the visual slider, so those are definitely recognised. But it was at full intensity and nothing I tried would control it.
I tried lots of other fixes I've seen here including: grub editing with acpi_backlight=vendor, installing brightness controllers, echoing values into backlight files, even tinkering with intel vs nvidia drivers in case that was the issue etc. No joy.
I came across this info on setting up my model (XPS 15 7590, OLED screen) with Arch Linux where the brightness was an issue there, and tried following that method: https://wiki.archlinux.org/index.php/Dell_XPS_15_7590#Backlight
There was a script based on that (https://github.com/lurwas/oled-brightness-ubuntu) which looked helpful but didn't work for me.
Until I realised that in the ArchLinux page it mentions

Please note: If you are using the xf86-video-intel driver, you will need to replace 'eDP-1' in the script above with 'eDP1'

Sure enough, my system seemed to be looking for instructions relating to 'eDP1' and everything else was telling it to change 'eDP-1'.  The dash made all the difference.
I set up that script as a start-up program, checking I had 'bc' and 'inotify-tools' installed as mentioned in the Arch Linux instructions (though note that page refers to 'itnotify-tool', and ubuntu required the 's' on the end to find/install it!) and made sure it had run permissions, and BOOM - "let there be LESS light!".
The script is run at start-up, and my backlight keys now actively change the screen brightness.
Hope this might be helpful, in case you have a similar underlying problem. I'm not sure if this fix is possibly just for an OLED-specific issue, so your milage may vary.
Answer: Installing GPU drivers fixed brightness control for me.
$ sudo apt install nvidia-detect
$ nvidia-detect
Detected NVIDIA GPUs:
01:00.0 VGA compatible controller [0300]: NVIDIA Corporation Device [10de:25b8] (rev a1)

Checking card:  NVIDIA Corporation Device 25b8 (rev a1)
Your card is supported by the default drivers.
Your card is also supported by the Tesla 460 drivers series.
It is recommended to install the
    nvidia-driver
package.

$ sudo apt install nvidia-tesla-460-driver
$ sudo reboot

Hardware: Dell Precision 7560 laptop, NVIDIA RTX A2000 / GA107GLM.
The packages require non-free to be enabled in sources.list.
I tried the options that yqbk mentioned, grub settings and xorg config, but none of these worked. I also couldn't read the correct brightness value from /sys/class/backlight/acpi_video0/{actual_,}brightness. After driver installation, the directory is gone and /sys/class/backlight/nvidia_0/ appeared in its place; now setting echo 10 > brightness works as expected.
Answer: It's technically NOT possible to adjust the default brightness of a standard terminal in Linux, but if it were possible to modify the /sys/backlight/*/brightness file, you could change the brightness.
The /sys filesystem will complain of input/output errors if you attempt to write to files in the /sys directory.  The system also may revert to other additional and unintentional settings if a user attempts to continue to write to files in the /sys directory and in my case and actually made my screen darker (without the option of allowing me to write or modify the aforemention brightness file in the /sys directory).
Bottom-line: If you're looking to do about anything graphical or sound related on your computing device, look elsewhere beyond the purveyors of electronic diarrhea and the developers of open source operating systems such as Linux.  Linux just "isn't there" in terms of a decent desktop multimedia experience.  Everyone knows that, including Linus.  However, if you're looking for a decent server experience, Linux may be for you.


Error while making CLucene for Max OS X 10.10

Question: I am trying to build CLucene in Max OS X 10.10. I followed the instructions here. The cmake .. command ran correctly, but after that, when I try to run make with the makefile generated, I get the following error:

I Googled it and found reports of similar errors in some forums, and even found a similar question in Stackoverflow as well: Error when Make CLucene, but nowhere did I find a canonical solution.
What should I do to fix this?
Comment: Assuming you have the `pthread` headers installed in a location where they can be found then I believe the commentor on the linked ticket is correct and this is an include header problem with the `CLucene` sources and you should take it up with them. But simply adding the include to either that file (or some common include file) will likely fix it if that is the case.
Comment: Suppose if the required header is not there in the correct location, how do I add it there? I mean, simply acquiring the header file and putting it in the appropriate location (where should this be? Somewhere in the list of locations specified by `$PATH`?) will do, or do I have to modify the source code to include that?
Comment: If you don't have the `pthread` headers on your system at all you would need to find out how to appropriately install them on OS X. Though I would imagine they might already be there. Unfortunately I don't know how to check or how to install them (I don't use OS X). And no, `$PATH` is unrelated.
Answer: There is a bug for the Mac OS X version. You need to patch 2 files (assuming that the current directory is the CLucene one):

src/shared/CLucene/LuceneThreads.h
src/shared/CLucene/config/repl_tchar.h

If you click the links you will get directly the patches. Let me know if you have problems applying the patches.
Comment: Thanks a lot!  Appreciate your help.. :)
Comment: Hi. Patched it, and the `libclucene-core.dylib` library has been generated. Will this be sufficient, or do I need to include the other `dylib`s that has been generated in the `bin` folder?
Comment: You should also add `libclucene-shared.dylib`, according to `src/shared/README`
Comment: **This package creates a library that is used in all the CLucene projects. It provides
cross-platform macros and functions that used to be inside CLucene. Since we need
to be able to link against the shared clucene-core library, we need these functions
to be seperate. They provide things like cl_* string macros, file handling functions,
replacement functions, etc.**. Where is it mentioned?
Comment: in the src there are lots of cl_* macros. If you don't include this, the code in the other library will not compile
Comment: Remember to include specific files, if you need them. For example, if you need the analyzer, you need also `#include "CLucene/analysis/Analyzers.h"`
Comment: Yes, yes, definitely. What I meant is, do I need to add the other `dylib`s as well?
Comment: So, these two will suffice :-)


What are the qualities / skills should an User Interface (UI) designer possess?

Question: 1. What are the qualities / skills  should an User Interface (UI) designer possess?
2. Please let me know the weightage (Out of 100%) of having Javascript and Jquery skills in UI designer?
Example: If UI is 100%,
Javascript weightage : 15%
Jquery weightage : 25%
Comment: I wish I could answer, but they closed the question.  I think, for many web applications, that knowledge of how it is built directly helps with designing it. Therefore, I give extra points to people who know how to build their own site.  I'd say more, but this box is too tiny.
Answer: I'm not sure your question makes a lot of sense (I'm sorry). UX is platform independant; you can design the UX of a chair, of a TV remote, for a POS terminal, as well as for a website. Even with website design, there are dozens of technologies that can be used to build the interaction of the site.
You need to be familiar with the capabilities of the technology you are using. That's it. The more familiar you are with your technology (whatever it may be), the better you will be able to design your interface around the trade-offs inherent to your platform.
You can't 'quantify' this kind of knowledge into some arbitrary percentage. You need to understand the technical limitations in order to be a good designer. The more knowledgeable about the capabilities of your technology you are, the better a designer you will be. But whether that technology is jQuery, Java, or plastic injection molding (for designing a TV remote) really is not relevant.
Answer:
What are the qualities / skills should an User Interface (UI) designer possess?

They should be good at graphic design. In addition, skills at interaction design, presentation layer development, user experience, copywriting, human factors studies, information architecture, computer science, all help.

of having Javascript and Jquery skills in UI designer?

There is no 'magic percentage' answer. A good UI designer is only going to be that much better at what they do if they also know how to build said UI, of course.


How can I represent objects as an interface

Question: How can I represent the following javascript object as an interface:
I did try using http://json2ts.com/, however did not give a clean and dynamic interface.
Hence, I do not want the id/codes (i.e. 6000, 6001, 6002) to be present in the interface.
<code>{
    "6000": {
        "id": 6000,
        "type": "text",
        "subType": "tileDynamicSection",
        "title": "Title 1",
        "description": "Description 1",
        "imageUrl": "https://prod.assets.domain.com/uploads/myimage.jpg"
    },
    "6001": {
        "id": 6001,
        "type": "text",
        "subType": "tileDynamicSection",
        "title": "Title 2",
        "description": "Description 2",
        "imageUrl": "https://prod.assets.domain.com/uploads/myimage.jpg"
    },
    "6002": {
        "id": 6002,
        "type": "text",
        "subType": "tileDynamicSection",
        "title": "Title 3",
        "description": "Description 3",
        "imageUrl": "https://prod.assets.domain.com/uploads/myimage.jpg"
    }
}
</code>
Answer: <code>export interface Images {
  [key: string]: {
      id: number;
      type: string;
      subType: string;
      title: string;
      description: string;
      imageUrl: string;
  }
}
</code>
Comment: This is TypeScript
Comment: Is that valid vanilla JS or is that TypeScript?


Not able to write the output of testbench to file

Question: LIBRARY IEEE;
USE IEEE.STD_LOGIC_1164.ALL;
USE IEEE.NUMERIC_STD.ALL;
use IEEE.STD_LOGIC_ARITH.all;
use IEEE.STD_LOGIC_SIGNED.all;
use std.env.all;
USE IEEE.STD_LOGIC_TEXTIO.ALL;
USE STD.TEXTIO.ALL;

ENTITY tb_top IS
END tb_top;

ARCHITECTURE behavior OF tb_top IS

-- Component Declaration for the Unit Under Test (UUT)

COMPONENT c4b
PORT(
     clock : IN  std_logic;
     reset : IN  std_logic;
     count : OUT  std_logic_vector(3 downto 0)
    );
END COMPONENT;

--Inputs
signal clock : std_logic := '0';
signal reset : std_logic := '0';

--Outputs
signal count : STD_LOGIC_vector(3 downto 0) := "0000";

-- Clock period definitions
constant period : time := 100 ns;

-- Opening the file in write mode
file myfile : TEXT open write_mode is "fileio.txt";

BEGIN
    -- Instantiate the Unit Under Test (UUT)
    uut: c4b PORT MAP (
        clock => clock,
        reset => reset,
        count => count
    );

clock_process :process      --providing clock to the counter
begin
    clock <= '1';
    wait for period/2;
    clock <= '0';
    wait for period/2;
end process;

write_process: process
    variable abd: LINE;
    --variable val1: integer;
    begin
        --val1 := CONV_INTEGER(count);          --saw this in another program. even they converted a std_logic_vector to integer. didn't work!
        loop                                                --tried the infinite loop to check for the value 1111,
            if (count = "1111") then                --so that as soon as count reaches the value 1111,
                finish (0);                             --it would stop, because i only need to write one entire sequence of the cycle to the file!!
            else
                write (abd, count);
                writeline (myfile, abd);
            end if;
        end loop;
    end process;

-- Stimulus process
stim_process: process
begin
    reset <= '0';                                   --because it only works when reset is 0!
    wait for 100 ns;
    if (count = "1111") then                        --the value is written to the text file in a continuous loop,
        finish (0);                                     --which makes he file size go to as much as 1 GB
    end if;                                             --thus to stop it at exactly one cycle!
end process;
END;

So, basically what I want to do here is let the counter count up from 0000 too 1111 and then write the entire sequence to a text file. But I only wish to write exactly just one cycle. Hence I've added a loop to check the same. Here in the code above I'm not able to simulate the testbench properly. When I don't include the write_process part of the code, the simulation works perfectly, giving me exactly just one cycle! (Simulator result w/o write_process picture no 1). But when I try to use the write_process, not only does it not simulate (Simulator result after adding the write_process) picture no 2, it also writes UUUU continuously to the file, until I close the ISim, and file size goes to at least a few hundred MBs! Please help!
Comment: Sounds like the testbench is working. It seems like a C4B (whatever that is) outputs `'UUUU'` until it has been reset. Perhaps you only want to output the `count` value once per clock cycle rather than in an infinite loop with no 'wait'. I would add 'wait for rising_edge(clock);` at te end of the loop...
Answer: Without the entity/architecture for c4b no one can duplicate your error, it's visible however.
Note that the write process has no sensitivity list nor wait statement and a loop statement that won't exit unless external stimuli is provided - if  (count = "1111") then ...
It doesn't seem proper to be using finish in both stim_process and write_process, there's no guarantee of execution order you can lose the last write (if you cure the write process defect).
You have four unused use clauses (numeric_std, std_logic_arith, std_logic_signed, std_logic_textio, with VHDL -2008).

So, basically what I want to do here is let the counter count up from 0000 too 1111 and then write the entire sequence to a text file.

There's nothing in your code that spools up output until your simulation finishes. Writing a line to file textio.txt occurs for events driving the write process.
Adding a model for c4b:
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std_unsigned.all;

entity c4b is
    port (
        clock:  in  std_logic;
        reset:  in  std_logic;
        count:  out std_logic_vector(3 downto 0)
    );
end entity;

architecture foo of c4b is
begin
    process (clock, reset)
    begin
        if reset = '1' then
            count <= (others => '0');
        elsif rising_edge (clock) then
            count <= count + 1;
        end if;
    end process;
end architecture;

Removing unused use clauses (not strictly necessary):
LIBRARY IEEE;
USE IEEE.STD_LOGIC_1164.ALL;
-- USE IEEE.NUMERIC_STD.ALL;
--  IEEE.STD_LOGIC_ARITH.all;
-- use IEEE.STD_LOGIC_SIGNED.all;
use std.env.all;
-- USE IEEE.STD_LOGIC_TEXTIO.ALL;
USE STD.TEXTIO.ALL;

Changing the write_process to not endlessly loop:
-- write_process: process
--     variable abd: LINE;
--     --variable val1: integer;
--     begin
--         --val1 := CONV_INTEGER(count);          --saw this in another program. even they converted a std_logic_vector to integer. didn't work!
--         loop                                                --tried the infinite loop to check for the value 1111,
--             if (count = "1111") then                --so that as soon as count reaches the value 1111,
--                 finish (0);                             --it would stop, because i only need to write one entire sequence of the cycle to the file!!
--             else
--                 write (abd, count);
--                 writeline (myfile, abd);
--             end if;
--         end loop;
--     end process;

write_process:
    process
        variable abd: LINE;
    begin
        wait on count;
        wait for 100 ns;
        write (abd, count);
        writeline (myfile, abd);
        if count = "1111" then
            finish (0);
        elsif IS_X(count) then
            report "count contains a metavalue and may not increment";
            finish (-1);
        end if;
    end process;

The wait 100 ns; accommodates a reset to insure the counter can increment. It's possible to provide a design description of c4b that doesn't depend on reset. For purposes here, the supplied c4b doesn't do that. The wait 100 ns also provides the sample interval for count, which from the component declaration for c4b is free running, driven by clock events.
Changing the stim_process to not finish and wait instead:
-- -- Stimulus process
-- stim_process: process
-- begin
--     reset <= '0';                                   --because it only works when reset is 0!
--     wait for 100 ns;
--     if (count = "1111") then                        --the value is written to the text file in a continuous loop,
--         finish (0);                                     --which makes he file size go to as much as 1 GB
--     end if;                                             --thus to stop it at exactly one cycle!
-- end process;
-- END;

stim_process:
    process
    begin
        reset <= '1';
        wait for 100 ns;
        reset <= '0';
        wait for 100 ns;
        wait;
    end process;

Notice this also provides a reset interval seen on the following waveform.
And that gives us:

With the contents of textio.txt:
more fileio.txt

0000
  0001
  0010
  0011
  0100
  0101
  0110
  0111
  1000
  1001
  1010
  1011
  1100
  1101
  1110
  1111

It's also possible to end simulation after detecting count is "1111" by stopping clock, avoiding the use of the finish procedure. Along with a write procedure supplied using the Synopsys package std_logic_texio:
procedure WRITE(L:inout LINE; VALUE:in STD_LOGIC_VECTOR;

This would allow the use of VHDL simulators complying to VHDL standard revisions earlier than -2008.


How to set value for hidden field type of Umbraco form

Question: I need to set the current page name to a hidden field value of Umbraco form.
I don't know where to give the value  for that hidden field.
Please any one share your answer. Thanks
Comment: Would you tell us how you are trying to achieve your goal. Is it Inside a macro? A Template in razor? What have you tryed soo far, please share your code so we can help you.
Comment: how it can b done in macro @GELR
Answer: Assuming you are using razor...
<input type="hidden" value="@CurrentPage.Name" />

Answer: This could also be set in codebehind file of your Usercontrol:

ascx.cs (usercontrol codebehind file)

Example Markup (ascx):
<asp:HiddenField ID="nameHiddenField" runat="server" />

Example Code (ascx.cs):
protected void Page_Load(object sender, EventArgs e)
    {
        var helper = new UmbracoHelper(UmbracoContext.Current);

        //set value as Name of Current Node
        nameHiddenField.Value = helper.AssignedContentItem.Name;

        //set value based on a property from the Current Node
        nameHiddenField.Value = helper.AssignedContentItem.GetPropertyValue<string>("examplePropert");

        //NOTE: You may want to add some Null-Checking for when accessing Properties of the CurrentNode.
    }

The "UmbracoHelper" class lives in the following namespace "Umbraco.Web", so you will need to add the below:
using Umbraco.Web;

Answer: I'm going to assume you're using Umbraco Forms/Contour? That being the case, in the form editor, click to edit the hidden field, then expand the extra settings and you can set the default value of the hidden field there.
Comment: It should do, it's a feature of Contour, not Umbraco. I've used this feature on sites as old as 4.7. I can't remember exactly when it was added to Contour, but it was a while ago.
Comment: All i get when i add hidden input is < input type="hidden" id="sample-gui" name="sample-guid" value>


Analyzing docker image size

Question: Checking inside the docker for folder sizes:
<code>bash-5.0# du -hs $(ls -d /*) | grep M
1.5M    /bin
1.2M    /etc
4.0M    /lib
168.5M  /root
636.9M  /usr
1.8M    /var
// about 900M
</code>
Checking on my computer for the size of the image:
<code>% docker images
container-name           version              id        37 minutes ago      1.33GB
</code>
I'm wondering how can I attribute the missing 400M?
Comment: A docker image is made up multiple layers. If an intermediate layer contains data that a lower layer deletes, it will still have to be stored somewhere. `docker history` will show you all layers and their sizes.
Comment: Does this answer your question? [docker container size much greater than actual size](https://stackoverflow.com/questions/31627772/docker-container-size-much-greater-than-actual-size)
Answer: docker history <image_name>
prints the size of each docker layer.
credit to Generous Badger comment.

Analyzing docker image size


iPad Mini background refresh not working, other devices also running iOS 8.1 work fine

Question: I am fetching the location in the background and sending it to a server. It seems like my code works fine for all devices except iPad Mini (all device are iOS 8.1). It's sending data only for 15 to 20 minutes.
Comment: When you say "background" do you mean background thread while the app is running in foreground or after the user has left the app and is doing something else? Also, perhaps you should show us how you're doing this background location fetching and sending it to the server. It's hard for us to offer suggestions if you don't tell us what you're doing and how you're doing it.
Comment: Also, you say "works fine for all device except iPad mini": What are the other devices (e.g. are you saying it works on full size iPad and not mini? or are you saying that it works on phones and iPod Touches, but not iPads?)?
Comment: HEY ROB thanks for responding ,its work on full size ipad , except ipad mini
Answer: Maybe your iPad mini doesn't have GPS, only cellular version have it
Comment: its cellular version , its sending data until 15 to 20 min later its stops sending data


How to Search 100,000 Edges Fast?

Question: I have a network DirectedGraph object G that contains around 2,0000 vertices and 120,000 edges in it.
I'd like to search the edge list and check which edge ends in the vertex 'deny'.(Oh the graph vertices are all an English word.)
I've just stupidly does as following, but it never stops.. I am waiting more than 10 mins from the very beginning.
How could I perform it fast?
 for i in range(len(G.edges())):
    if list(G.edges())[i][1] == 'deny':
        print(list(G.edges())[i])

Comment: I think just intuitively thinking, I should search every element in the list to check whether a edge finished in "deny".. so might be there's no other options to make it fast other than look up every element linearly..?
Answer: You can have dictionary of <end vertex, (start vertex, end)>. However, it depends on how frequent these operations would be performed.
If it's just one time operation then I would just go about looping my list otherwise implement the dictionary.

How to Search 100,000 Edges Fast?


tap:AMP.setState not working intermittently

Question: tap:AMP.setState not working at times but it works when i reload the page.

    Show more
    Show less

Here's my default state:
<amp-state id="model">

    </amp-state>

Is it something because of network that makes it behave like this?? Appreciate for any help! thanks!
Comment: Can you please post the full example. One thing: expand is never set to `true`.
Comment: I have two links actually one to set true and other one to set false like below
Comment: I have two links actually one to set true and other one to set false like below

Show more
Show less

On page load, i get show more link. Upon selecting show more link, i expect amp state to get updated there by show less link will be displayed.
Answer: You should try;
[class]="(model.nextStep.expand == 'true') ? 'hide' : 'show'"
and
[class]="(model.nextStep.expand == 'false') ? 'show' : 'hide'"
On page load, as soon as the DOM is loaded, your initial state (false) is fired and [class] is rendered because of amp-bind.
You didn't post much in terms of any console errors or validation errors you might be facing with AMP (which will affect the functionality if you did something weird/wrong)


Digits android integration HTTP Error: 403 Forbidden, API Error: 239, User Message: Try Again?

Question: Hello all recently i was integrating digits by twitter in android for login users, now previously it was working fine but now i don't know what happened but after few login's it show this error

HTTP Error: 403 Forbidden, API Error: 239, User Message: Try Again

Now can someone please tell me what i am doing wrong also can someone pls tell me that in consumer key and consumer secret do i have to pass dev.twiiter my app credentials OR fabrics consumer key and secret, this thing is really very confuing because in docs they mentoned twitter keys but on some stackoverflow questions people say to use digits keys ?? Also i am not extending my activity from Application would that cause any problem or not ??
my code is give below please tell me what i am doing wrong it will be really helpful for me
<code>public class Signup_firststageActivity extends AppCompatActivity {

private AuthCallback authCallback;

public AuthCallback getAuthCallback(){
     return authCallback;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_signup_firststage);
    TextView text = (TextView)findViewById(R.id.text);
    Bundle b = getIntent().getExtras();
    if (b.getString("error") == null) {

} else {
    if (b.getString("error") != null && b.getString("error").equals("server_down")) {
        text.setText("Error 503 Please Try Again");
    } else {

    }
}
//Twitter

TextView tryagain = (TextView)findViewById(R.id.tryagain);
tryagain.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Digits.authenticate(new DigitsAuthConfig.Builder().withAuthCallBack(authCallback).withPhoneNumber("+918972745648").build());
    }
});
final TwitterAuthConfig authConfig =  new TwitterAuthConfig("agfjgD6wetDXdjfjuC4ywwoeD", "BshdjfjfwGz8WLaofkjfjsfjjsjsfhKpv60hQxni60oZwAu");
Fabric.with(getBaseContext(), new TwitterCore(authConfig), new Digits());
authCallback = new AuthCallback() {
    @Override
    public void success(DigitsSession session, String phoneNumber) {
        Log.d("digits", "success phoneNumber: " + phoneNumber);
        Log.d("digits", "session " + session.getPhoneNumber() + " " + session.toString() + " " + session.isValidUser() + " " + session.getAuthToken() + " " + session.getId());
        //    TwitterAuthConfig authConfig = TwitterCore.getInstance().getAuthConfig();
        progressDialog = new ProgressDialog(Signup_firststageActivity.this);
        progressDialog.setIndeterminate(true);
        progressDialog.setMessage("Please Wait... ");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.getWindow().setGravity(Gravity.CENTER);
        progressDialog.show();
        TwitterAuthToken authToken = (TwitterAuthToken) session.getAuthToken();

        OAuthSigning oauthSigning = new OAuthSigning(authConfig, authToken);
        Map<String, String> authHeaders = oauthSigning.getOAuthEchoHeadersForVerifyCredentials();
        Log.d("digits", "authHeaders: 1" + authHeaders);
        Signup_MobileNumber_requestData(session.getPhoneNumber());
        Digits.getSessionManager().clearActiveSession(); // don't know should i write this here or not ??
    }

    @Override
    public void failure(DigitsException exception) {
        Log.d("digits", "failure");
        // Do something on failure
    }
};

DigitsAuthButton digitsButton = (DigitsAuthButton) findViewById(R.id.auth_button);
digitsButton.setCallback((this).getAuthCallback());
digitsButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Log.d("digits", "button click");

    }
});
</code>
}
Thank You in advance
Comment: We are getting the same issue:
E/Digits: HTTP Error: 403 Forbidden, API Error: 239
Answer: This problem is occurred because of Key and Secret. I was trying to copy the values from Fabric dashboard and i got the same error.
It worked when i get the values from Fabric-Android Studio Plugin->Digits->Install->Apply
Comment: also you can get Twitter Key and Secret values from Fabric Dashboard. Go to fabric.com, select app and open Digits tab.
Comment: Can you explain a bit more?


Select a button - webdriver Java

Question: How do I identify the button click button? Markup is this:
<button class="ProfileClick-actionButton  js-actionButton js-actionReClick" data-modal="ProfileClick-reClick" type="button">

      ReClick

  </button>

I tired this :
driver.findElement(By.className("js-actionClick")).click();

Answer: You can add an id to the button, and use that id to reference it.
<button id="myButton" class="ProfileClick-actionButton  js-actionButton js-actionReClick" data-modal="ProfileClick-reClick" type="button">
  ....
</button>

And in webdriver you would do
Actions actions = new Actions(driver);
actions.click(driver.findElement(By.id("myButton"))).perform();

you'll need to import org.openqa.selenium.interactions.Actions
Answer: Use an XPath as below:-
//button[@class='ProfileClick-actionButton  js-actionButton js-actionReClick']

OR
//button[@type='button']

code something like below:-
driver.findElement(By.xpath("//button[@class='ProfileClick-actionButton  js-actionButton js-actionReClick']")).click();

OR
driver.findElement(By.xpath("//button[@type='button']")).click();

Hope it will help you :)
Answer: You can find button by class
driver.findElement(By.className("js-actionButton")).click();

Select a button - webdriver Java


Logging logarithmically 1, 10, 100, 1000, etc

Question: Is there a more efficient way of doing the following, something just feels wrong about it?  I'm looking for the most time efficient way of logging logarithmically.
    public bool Read()
    {
        long count = Interlocked.Increment(ref _count);
        switch (count)
        {
            case 1L:
            case 10L:
            case 100L:
            case 1000L:
            case 10000L:
            case 100000L:
            case 1000000L:
            case 10000000L:
            case 100000000L:
            case 1000000000L:
            case 10000000000L:
            case 100000000000L:
            case 1000000000000L:
            case 10000000000000L:
            case 100000000000000L:
            case 10000000000000000L:
            case 100000000000000000L:
            case 1000000000000000000L:
                _logger.LogFormattable(LogLevel.Debug, $"{count} Rows Read");
                break;
        }

        return _reader.Read();
    }

Update:
Here are my micro benchmark tests.

Method1: Übercoder's way with keep up with state
Method2: My way with the big switch statement
Method3: Markus Weninger's way with the nice Math Function

Since for me 100,000,000 records being read without logging takes around 20 minutes then an extra 4 seconds is nothing.  I'm going with the beautiful Math way of doing things.  Mathod3 wins in my scenario.
Run time for 100,000,000 iterations averaged over 100 attempts

Method1 Max: 00:00:00.3253789
Method1 Min: 00:00:00.2261253
Method1 Avg: 00:00:00.2417223

Method2 Max: 00:00:00.5295368
Method2 Min: 00:00:00.3618406
Method2 Avg: 00:00:00.3904475

Method3 Max: 00:00:04.0637217
Method3 Min: 00:00:03.2023237
Method3 Avg: 00:00:03.3979303

Comment: Using a `switch` statement like you do really is the fastest way to do this as it will be compiled into a series of processor-level hashtable instructions which are lightning fast. While the code is "ugly" (well, I think it's kind-of beautiful) I think you can improve it by moving it to a separate function (`IsExactlyPowerOf10(Int64 n)") and calling that from your `Read` function.
Comment: @Dai that is on floating point, which isn't the case here. Also the question is about c#, not c++. If you have a better, duplicate, let me know.
Comment: Thanks for the nice benchmarking of all the three methods :)
Answer: If performance is not a big problem, I would use the following
if(Math.Log10(count) % 1 == 0)
  _logger.LogFormattable(LogLevel.Debug, $"{count} Rows Read");

This question states the following:

For floating point numbers, n % 1 == 0 is typically the way to check if there is anything past the decimal point.

Edit: To complete my answer, it is also possible to keep track of the next logging value, as @Übercoder posted in his answer.
long nextLoggingValueForLogX = 1;
if (count == nextLoggingValueForLogX )
{
   nextLoggingValueForLogX *= 10; // Increase it by your needs, e.g., logarithmically by multiplying with 10
   _logger.LogFormattable(LogLevel.Debug, $"{count} Rows Read");
}

Yet this method will come up with a new variable for every log that shouldn't be executed every time. This will introduce extra code and also extra work if it has to be made thread-safe.
Comment: I will do a performance test of mine vs yours and see what comes out faster, I really hope it's your because it's much more beautiful.  Even if it's a little slower I will probably still use it.  Let me do some performance tests to see if I can mark this as the answer.
Comment: Yeah, I'm also interested in this. I hope it works out for you.
Answer: static long logTrigger = 1;

if (count == logTrigger)
{
   logTrigger *= 10;
   // do your logging
}

Comment: Yeah, I'm having to do a lot to make this thread safe too, since it's not.
Comment: I bet yours is the fastest, I'll let you know.  I would remove the static though from the trigger.
Comment: Yes, this will for sure be the fastest. But, on the other hand, it introduces a new variable for every log that should be executed logarithmically. That's the choice one has to make.


set -e subshell doesn't exit on the first command that fails if I capture the error code of the compound command using "||"

Question: I have a script.sh and I have to correctly diagnose any errors inside it, so the prova function in case of an error shouldn't stop midway but should continue to the end reporting its error message. To do this I have to capture any error code from a subshell using the OR operator || but doing so the subshell doesn't exit on the first command that fails, and that's not what I want.
Example:
Assuming I'm in the directory containing the script, from a shell I run the command:
./script.sh

If I don't use the OR || operator, the function doesn't continue to the end and therefore doesn't produce the error message:
#!/bin/bash -e
...
prova () {
    local function_name="${FUNCNAME[0]}"
    local exit_code=0
    (
        set -e
        prova1
        prova2
        prova3
    )
    echo "$function_name: An error has occurred." >&2
    return $exit_code
}
prova
...

StdErr:
./script.sh: line 7: prova1: command not found

if I use the OR || operator, it executes all 3 commands when it should still stop at the first one capturing its exit code:
#!/bin/bash -e
...
prova () {
    local function_name="${FUNCNAME[0]}"
    local exit_code=0
    (
        set -e
        prova1
        prova2
        prova3
    ) || exit_code=$?
    if [[ $exit_code -ne 0 ]]; then
        echo "$function_name: An error has occurred." >&2
    fi
    return $exit_code
}
prova
...

StdErr:
./script.sh: line 7: prova1: command not found
./script.sh: line 8: prova2: command not found
./script.sh: line 9: prova3: command not found
prova: An error has occurred.

I want this StdErr instead:
./script.sh: line 7: prova1: command not found
prova: An error has occurred.

How do I get it?
Answer: Because the compound command is part of a || list, and not the last in that list, -e option does not have an effect in that compound command.
See the documentation of the set builtin in bash's manual:
-e    Exit  immediately  if  a  pipeline  (which  may  consist of a single simple
      command), a list, or a compound command (see SHELL  GRAMMAR  above),  exits
      with  a non-zero status.  The shell does not exit if the command that fails
      is part of the command list immediately following a while or until keyword,
      part  of  the  test  following  the  if or elif reserved words, part of any
      command executed in a && or || list except the command following the  final
      &&  or  ||,  any  command  in  a pipeline but the last, or if the command's
      return value is being inverted with !.  If a compound command other than  a
      subshell  returns  a  non-zero status because a command failed while -e was
      being ignored, the shell does not exit.  A trap on ERR, if set, is executed
      before  the  shell exits.  This option applies to the shell environment and
      each subshell environment separately  (see  COMMAND  EXECUTION  ENVIRONMENT
      above),  and  may cause subshells to exit before executing all the commands
      in the subshell.

      If a compound command or shell function executes in a context where  -e  is
      being ignored, none of the commands executed within the compound command or
      function body will be affected by the -e setting, even if -e is set  and  a
      command  returns a failure status.  If a compound command or shell function
      sets -e while executing in a context where -e is ignored, that setting will
      not  have  any  effect until the compound command or the command containing
      the function call completes.

To exit the subshell after the first failing command you could use code like this:
prova () {
    local exit_code=0
    (
        prova1 &&
        prova2 &&
        prova3
    ) || exit_code=$?
    return $exit_code
}

You might not even need to use a subshell in the function.
If you need to use -e in the compound command in the function, you could use something like this:
#!/bin/bash

prova() {
    (
    set -e
    prova1
    prova2
    prova3
    )

    local exit_code=$?
    if [[ $exit_code -ne 0 ]]; then
        echo "${FUNCNAME[0]}: An error has occurred." >&2
    fi
    return $exit_code
}

prova

Comment: Looks great, thanks @muru!


Rails association with same model

Question: I have a model Article and model User. In users, there will be one creator of the article and many readers. How do I link these together?
I was thinking:
class Article < ActiveRecord::Base
  has_and_belongs_to_many :users
  has_one created_by, through: :user (????)
end

class User < ActiveRecord::Base
  has_many :articles
end

Comment: Why it has `has_and_belongs_to_many` association with users?
Comment: And also why your `User` model has `has_many :articles` while your `Article` model having `has_and_belongs_to_many :users`?
Comment: Because I want the user to have many articles and one article can be owned by many users
Answer: You can do like this
class Article < ActiveRecord::Base

has_and_belongs_to_many :users
has_one created_by_user,:class_name => 'User'

end

If you want to specify a custom foreign_key(which is useful in these cases),you can specify a foreign_key option
class Article < ActiveRecord::Base

has_and_belongs_to_many :users
has_one created_by_user,:class_name => 'User',:foreign_key =>'your_custom_fkey'

end

Rails association with same model


test kitchen salt_solo passing in variables from platforms

Question: I am running test kitchen with salt using salt_solo and I cannot pass variables into the formula if I declare them in the platform.
For example if this was my .kitchen.yml
---
driver:
  name: vagrant

platforms:
  - name: ubuntu-14.04
    grains:
      org:
        bat: batz

suites:
  - name: binary
    provisioner:
      name: salt_solo
      state_top:
        base:
          '*':
            - binary
      formula: binary
      grains:
        org:
          foo: bar

Then my formula is not able to access {{grains['org']['bat']}}, but it is able to access {{grains['org']['foo']}}.
Answer: The solution is to add provisioner: before the platform variables.  This fix to the example .kitchen.yml from above will solve the issue:
---
driver:
  name: vagrant

platforms:
  - name: ubuntu-14.04
    provisioner:
      grains:
        org:
          bat: batz

suites:
  - name: binary
    provisioner:
      name: salt_solo
      state_top:
        base:
          '*':
            - binary
      formula: binary
      grains:
        org:
          foo: bar


set the results of facebook integration to labels

Question: Im working on a project in Swift 3.0 and I have an authentication sign up procedure using Facebook. So basically I've done the FB integration part and once logged in to an account as a result I'm getting the user's email address, name,Id and the url of the profile pic as bellow since i have requested them (this is what I get in my console). The format that I receive as bellow.
Optional({
    email = "firstname.lastname@example.com";
    id = xxxxxxxxxx;
    name = "xxxxxx xxxx";
    picture =     {
        data =         {
            "is_silhouette" = 0;
            url = "https://scontent.xx.fbcdn.net/v/t1-1/c18.104.22.168/p50x50/10441341_10201209786847369_5426097469926927988_n.jpg?oh=1b4d8709be17338bc7e877d411b96eee&oe=58CE5B13";
        };
    };
})

My requirement is to assign these email, name, id field in to labels and print them out.
The code of my relevant view controller as bellow. What should I add ??
import UIKit
import FBSDKLoginKit

class ViewController: UIViewController,FBSDKLoginButtonDelegate{

    @IBOutlet weak var displayLabel: UILabel!
    @IBOutlet weak var loginButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        let loginButton = FBSDKLoginButton()
        view.addSubview(loginButton)
        //frame's are obselete, please use constraints instead because its 2016 after all
        loginButton.frame = CGRect(x: 16, y: 50, width: view.frame.width - 32, height: 50)

       loginButton.delegate = self
        loginButton.readPermissions = ["email", "public_profile"]

    }
    func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {
        print("Did log out of facebook")
    }

  @IBAction func loginButtonPressed(_ sender: AnyObject) {
        FBSDKLoginManager().logIn(withReadPermissions: ["email"], from: self) { (result, err) in
            if err != nil {
                print("Custom FB Login failed:", err)
                return
            }
            print("FB login Sucess")
            print(result?.token.tokenString)

            self.showEmailAddress()
        }
    }

    func showEmailAddress() {
        FBSDKGraphRequest(graphPath: "/me", parameters: ["fields": "id, name, email,picture"]).start { (connection, result, err) in

            if err != nil {
                print("Failed to start graph request:", err)
                return
            }
            print(result)

//            self.displayLabel.text = result["email"]as? NSMutableArray
        }
    }

}

Comment: `result["email"]as? NSMutableArray` why as NSMutableArray? `as String`, no?
Comment: despite of what you put it gives an error message saying 'Type Any has no subscription members'. Thats why I have commented that line sir. Just wants to assign that result to the label as i have tried and failed
Comment: You have to tell the compiler, that `result` is a dictionary (in our case: `[String:Any]`).
Answer: First specify the type of your result object to [String: Any] and then get value from it.
if let dic = result as? [String: Any] {
    self.displayLabel.text = dic["email"] as? String
    self.displayNameLabel.text = dic["name"] as? String
    self.displayIdLabel.text = dic["id"] as? String
}


Maven - Check a local dependency on Windows

Question: I'm must verify a maven local dependency into a python script. I succeed to do it on linux using this command (from  this thread).
mvn dependency:get -Dartifact=g:a:v -o -DrepoUrl=file://~/.m2/repository

My problem is that I'm working with a team using Windows, Linux and Mac, under Windows I'm unable to execute this command, the repo path is the one from mvn configuration maybe the problem is coming from the way I'm calling it as parameter.
mvn dependency:get -Dartifact=g:a:v -o -DrepoUrl=file://C:\Users\user\.m2\repository

Is someone already use this command on Windows and have any hints to solve this problem ?
Thank you .
Comment: What error do you get when you call the command on the Windows command line?
Comment: I got a "Building failure" and maven error output is about the plugin "dependency" -> [ERROR] No plugin found for prefix 'dependency' in the current project and in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the repositories [local (C:\Users\user\.m2\repository), central (https://repo.maven.apache.org/maven2)] -> [Help 1]
Answer: Finally I reached a solution.
I'm not sure to understand but on windows firstly I must run :
mvn dependency:get

before running :
mvn dependency:get -Dartifact=g:a:v -o

I think the problem about 'dependency plugin' is solved by the first command.


Why PHP Cookie variable is not saved after closing Chrome

Question: i'm learning to use cookies in PHP. I was expecting that every time i set a cookie, the cookie and all of his variables are stored on the client site so i could use them again next time the user will visit the site. Anyway in the next example (a web application with a sign in option, i use cookies to store a unique string so i could implement "Remember me" option) i can access the id of the stored cookie but the variables data seem lost. Here is example of the code i use and screenshots of what i get.
 Setting up a Cookie
 if (isset($_POST['remember_me'])) {
    $token=uniqid($_SESSION['id']);
    $sql="UPDATE users SET token='$token' WHERE id='".$_SESSION['id']."'";
    $conn->query($sql);
    setcookie("remember_me", $token, time()+30*24*60*60*1000);
}
else{
    setcookie("remember_me","",time()-1000);
}

User page
On the user page it just simply prints out the $_COOKIE and $_SESSION array.
<?php
    echo "SESSION: ";
    print_r($_SESSION);
?>

<?php
    echo "COOKIE: ";
    print_r($_COOKIE);
?>

Process:

First i delete all the cookies using the advice i found here:
how to delete all cookies of my website in php
Then log inside Log in screen (this form call a script that execute the code for setting a cookie i gave at the beginning, then redirect to the user-page) User page before closing
Close the browser and open it again directly at the user-page (without executing other scripts  /localhost/MIAFormApp/script/db/HTML_PROBA/user-page.html.php   User page after re-opening

What did i get wrong and why the cookies array after re-opening is empty?
 EDIT:
The second time i open browser the script for seting the cookie is not executed. I just set the url to go to the user-page.php .
 Examp:
/localhost/MIAFormApp/script/db/HTML_PROBA/user-page.html.php
Comment: I think this is problem `if (isset($_POST['remember_me'])) {` When it is false, it's expiring cookie.
Answer: Try deleting the else statement in your sample code - meaning go from:
This
if (isset($_POST['remember_me'])) {
    $token=uniqid($_SESSION['id']);
    $sql="UPDATE users SET token='$token' WHERE id='".$_SESSION['id']."'";
    $conn->query($sql);
    setcookie("remember_me", $token, time()+30*24*60*60*1000);
}
else{
    setcookie("remember_me","",time()-1000);
}

To this
if (isset($_POST['remember_me'])) {
    $token=uniqid($_SESSION['id']);
    $sql="UPDATE users SET token='$token' WHERE id='".$_SESSION['id']."'";
    $conn->query($sql);
    setcookie("remember_me", $token, time()+30*24*60*60*1000);
}

When you re-open your browser, the if statement is going to check whether or not the POST variable remember_me was found. The only time that it will be found is when someone logs in because the login form is sending that information on form submit. In every other instance ( such as re-opening the browser), the else statement will be executed which isn't what you want. The reason being that setting an empty value on a cookie will delete said cookie.
Comment: Well actually the second time i open the browser i don't execute that script. i set the url to show directly to the user-page
Comment: @NVelichkovski Ah! Gotcha. Have you tried checking whether your browser is configured to delete cookie data on browser close? ( This is an option on all major browsers as far as I know ). I tested your sample code and I'm able to see the cookie when I re-open the browser, which then suggests that the issue might not be related to your code.


Angular build cannot find module with relative path (on azure dev ops)

Question: I have a problem getting a mid-sized Angular 7 project to build on Azure Dev Ops Pipelines. So I created a minimal project to recreate the issue.
Using Angular CLI (7.2.4) I created a new project
ng new minimal-app

It builds locally and on Azure just fine. I edited app.component.ts to use my UserModel, lines 2, 11 & 14
import {Component} from '@angular/core';
import {UserModel} from '../Models/User.model';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'minimal-app';
  user = new UserModel();

  constructor() {
    this.user.name = 'Jo';
  }

}

the User.model.ts file contains
export class UserModel {
  id: number;
  name: string;
}

This also compiles on local and Azure just fine. The issue comes when trying to add a nested model, see Action.model.ts
export class ActionModel {
  id: number;
  datetime: string;
}

and changing the UserModel
import {ActionModel} from './Action.Model';

export class UserModel {
  id: number;
  name: string;
  actions: ActionModel[];
}

This works locally but on Azure Dev Ops I get
ERROR in src/Models/User.model.ts(1,27): error TS2307: Cannot find module './Action.Model'.

##[error]Bash exited with code '1'

I've not changed any Angular config files, they are all default for new project. The azure pipelines yml is
# Node.js with Angular
# Build a Node.js project that uses Angular.
# Add steps that analyze code, save build artifacts, deploy, and more:
# https://learn.microsoft.com/azure/devops/pipelines/languages/javascript

trigger:
- master

pool:
  vmImage: 'ubuntu-latest'

steps:
- task: NodeTool@0
  inputs:
    versionSpec: '10.x'
  displayName: 'Install Node.js'

- script: |
    npm install -g @angular/cli
    npm install
    ng build --prod
  displayName: 'npm install and build'

Comment: Maybe try to add `.` to `./Action.Model` (`../Action.Model`)
Comment: @ShaykiAbramczyk Sadly that doesn't help :( The models are in the same folder as each other though, so I guess it was a longshot, but I am confused with this
Comment: You can fix it when you try to build your application By using baseHref  AND deployUrl
Answer: According to your code, I notice that you are using Ubuntu agent which is case sensitive.
And also, the module you configured is "Action.model", but while import, the name you used is "Action.Model". For ubuntu and linux, it could not be identified as same because of its case sensitive.
I think you may execute these script locally with windows which is case insensitive. That's why it's worked locally.
So, for solved, you need to change your script as :
import {ActionModel} from './Action.model';

export class UserModel {
  id: number;
  name: string;
  actions: ActionModel[];
}

Comment: That fixed it! Thanks, and well spotted :)


How do I delete my clash of clans village and start over?

Question: I started a few days ago but after reading around a few forums, I realize I could have done much better on my village.
So, how do I delete my clash of clans village and start over?  There does not appear to be any option in-game.
I have not linked it to any game center account if that helps.  I did see a warning somewhere saying you should link it to game center to avoid the risk of accidentally losing your data.  This could be quite useful considering that I do want to lose my data right now.
Comment: @JK01 what device are you using? I.e. Android or iOs
Answer: One of the answers isn't correct. Deleting just the game and reinstalling the game won't do anything as it will still bring back your old game. Even logging out of game center and logging back on won't help.
The only way to do this is to do a factory restore and set up as a "NEW" device. Unless your have a jailbroken idevice then it may be possible if there is an app that let's you clear data within the system file for Coc. But i wouldn't risk it.
Comment: The app that will let you clear your data on a jailbroken iPhone is iFile and you use an SQL statement to delete the data. I will create a question and answer describing this process, as it's what I've done.
Comment: The description about how to use iFile on a jailbroken phone is [in this answer](http://gaming.stackexchange.com/a/291494/139609)
Answer: You can't. If you open the game then click the gears. Then click Help and support, then scroll down to the section Can I reset the game and start again from the beginning.  It says you can't do it.
EDIT: According to This Video, just create a new Google+ account and make a new base on that account while also keeping your old base.
If you are on android, go to the apps in the settings, find Clash of Clans and tap 'Clear Data
Answer: There isn't a way to reset your village but this is what you could do:
 1. Log out of Game Center and Log in using another account
 2. Reinstall CoC
Then you should be starting with a new village
Hope I helped.
Comment: This will not create a new account. The old village will persist unless you factory-reset your device.
Answer: To me, there would never be any reason to completely delete your village. You can really only improve your village through putting builder time into it, and you would lose all the time you spent so far if you were to delete your village.
Instead, just start focusing on the buildings that you want to improve, and the troops you want to level up. There really is no benefit to destroying your current village.
Comment: Sure it is... We have a level 2 account attached to an Google account and an none attached high level. Deleting the first would avoid recreating an new useless Google account.
Comment: Is "an none attached" supposed to be "a non-attached"? As in, you have a high level village on your device that is not attached to a Google account?
Answer: Ok hopefully this works so delete the game then you will have to change your Game Center to another account log out of the one that you are currently in and log into another or create a new one then reinstall clash of clans hopefully this helps you!!
Comment: Unfortunately, this doesn't work.  See [user83189's answer](http://gaming.stackexchange.com/a/178031/139609)
Answer: Delete your Game And reinstall, if you however want to keep it as backup, I think you can add that account to another with a link device feature but I'm not certain
Comment: This won't work if it's linked to any accounts like Facebook and Google+.
Comment: this doesn't work.
Comment: -1: Even if you haven't linked your game to Facebook or Google+ this doesn't work.


Three quaternions interpolation with barycentric coordinates

Question: I have three quaternions A, B, C.
I also have a 3D vector P which describes the barycentric coordinate to interpolate.
I want to interpolate the three quaternions with respect to the barycentric coordinate P
This Image shows how to do it would A, B and C be usual vectors.

but how to calculate the quaternion interpolation?
Can I use the "slerp" command somehow?
How would the glm code look like?
Comment: See: https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions/
There is no analytic solution, you'll have to use an iterative one.
Answer: Defining the problem
The weighted arithmetic mean $\mu$, of a set of vectors, minimizes squared L2 norm of the error ($v_i$) to all elements of the set.
$$
\begin{equation}
\begin{split}
v_i &= \mu - x_i \\
\mu &= \underset{\mu \in \mathbb{R^n}}{\text{argmin}} \; \frac{1}{2}\sum\limits_{v_i} w_i ||v_i||^2_2 \\
\end{split}
\end{equation}
$$
This empowers us to define special means, where we use different notions of distance.
Specializing for rotations
A reasonable notion of distance for SO(3) is the angle separating two rotations. That's $||\log(\mu \ q^{-1})||$ Your geometry library probably implements this $log$, and expressions for it can be found here. It is not the log one is accustomed to on the real numbers.
Intuition: Recall that every sequence of rotations corresponds to a single rotation about a single axis, so the difference between a pair of rotations can always be summarized by a single angle.
$$
\begin{equation}
\begin{split}
v_i &= log(\mu \ x_i^{-1}) \\
\mu &= \underset{\mu \in \mathbb{SO3}}{\text{argmin}} \sum\limits_{v_i} w_i || v_i||^2_2 \\
\end{split}
\end{equation}
$$
There's no analytical form for this minimum for more than two rotations. We can, however, treat this as a least squares problem and compute the result by Gauss-Newton.
To apply Gauss-Newton in general, for some error, we need to be able to find $\mathbf{J_i} = \frac{d}{d\mu}v_i(\mu)$, which requires differentiating $v_i$. Then we can take a step as
$$
\begin{equation}
\begin{split}
\Delta \mu &= \sum\limits_{i}(w_i \mathbf{J_i}^T \mathbf{J_i})^{-1} \sum\limits_{i} w_i \mathbf{J_i}^T v_i
\end{split}
\end{equation}
$$
Our error function cannot readily be differentiated, since its argument is a rotation $\mu$ and not a vector. We invent a parameter $\delta \in \mathbb{R^3}$ which we will $Exp$ into a rotation. This, we can differentiate
$$
\begin{equation}
\begin{split}
v_i &= log(Exp(\delta)\; \mu \ x_i^{-1}) \\
\mathbf{J_i} &= \frac{d}{d\delta} v_i = \mathbf{I} \\
\end{split}
\end{equation}
$$
So the update to $\mu$ is
$$
\begin{equation}
\begin{split}
\delta &= \sum\limits_{i}(w_i \mathbf{J_i}^T \mathbf{J_i})^{-1} \sum\limits_{i} w_i \mathbf{J_i}^T v_i\\
\delta &= \sum\limits_{i} w_i \sum\limits_{i} w_i v_i \\
\delta &= \sum\limits_{i} w_i v_i
\end{split}
\end{equation}
$$
Conclusion
$$
\begin{equation}
\begin{split}
\delta = \sum\limits_{i} w_i v_i &= \sum\limits_{i}w_i log(\mu_{k}^{\mathstrut} x_{i}^{-1}) \\
\mu_{k + 1} &= Exp(\delta) \mu_{k}\\
\end{split}
\end{equation}
$$
This will converge quadratically to a mean.
Caveat emptor: for rotations, there may be many "means". By analogy: What is the average point, on Earth's surface, of the north and south poles? Every point on the equator has equal right to be called the average. This is the case for all equispaced rotations.


Apache dynamic IP whitelist for specific directory and files

Question: I am trying to whitelist IPs dynamically to grant access to a specific directory. A php script will be constantly modyfying the whitelist.txt file to add/remove entries.
I know the proper way handle this is with RewriteMap, but I am not sure how to set this up.
For example, I want users to access my site normally when they visit example.com, however I want to deny access to ALL users visiting anything in the block path/directory "http://example.com/block" EXCEPT for those IP addresses in whitelist.txt, additionally, those IP addresses in whitelist.txt will only have access to a specific folder and file inside the "block" directory, request e.g:
http://example.com/block/123/123.txt
I have tried the code below (this is a rough sketch, it is completely off and wrong I am sure, but just to get the idea):
RewriteEngine on

RewriteCond %{THE_REQUEST} ^\/block+\ ##apply rules only for /block directory

RewriteMap ipmap txt://var/whitelist.txt

RewriteCond ${ipmap:%{REMOTE_ADDR}} ^\/([0-9]*).txt$ $1 [NC] ##check whitelist for matching IP AND specific dir and file

RewriteRule .* - [F,L]

Of course this does not work. When I visit example.com my website goes to a infinite redirect loop.
The whitelist.txt file would look like this:
184.108.40.206 123
220.127.116.11 43
18.104.22.168 2345
22.214.171.124 32
22.214.171.124 533

So IP address 22.214.171.124 will have access to http://www.example.com/block/123/123.txt
IP address 22.214.171.124 will have access to http://www.example.com/block/43/43.txt
... and so on.
Comment: Look like, people doesn't look at `htaccess` question anymore, i'm looking at some question about `htaccess`, they have no answer even comments for months, glad anyone could help..
Answer: I've played around a bit starting from your rules and got to this:
RewriteEngine On

RewriteCond %{THE_REQUEST} \/block\/?
# apply rules only for /block directory

RewriteMap ipmap txt:/var/whitelist.txt

RewriteCond ${ipmap:%{REMOTE_ADDR}} ^$ [NC]
RewriteRule .* /block [R=403,L]
# redirect to /block with 403 when IP address not in the whitelist

RewriteCond %{REQUEST_URI} /+[^\.]+$ [NC]
# stops when the request finds a dot '.', assuming a file
RewriteCond ${ipmap:%{REMOTE_ADDR}} ^\d+$ [NC]
# does the redirect only when the IP is in the whitelist
RewriteRule .* /block/${ipmap:%{REMOTE_ADDR}}/${ipmap:%{REMOTE_ADDR}}.txt [R=permanent,L]
# will redirect everything from /block to /block/x/x.txt -> x = numeric value corresponding to the request IP from the whitelist.txt file

When tested it worked like this:

accessed http://example.com -> no redirect, got to the index page
accessed http://example.com/block -> redirected to http://example.com/block/123/123.txt and displayed txt file contents
accessed http://example.com/block from different device on the network -> redirected to the corresponding entry from the whitelist file

Hope this helps.
EDIT:

when IP is not found in the whitelist.txt then a redirect to /block with 403 code is performed

EDIT 2:
At the moment any user with an IP from the whitelist.txt file can access other users directory. I've tried to find a condition for that but didn't really find anything. So what I can think of at the moment is having .htaccess files at directory level like this:
deny from all
allow from 126.96.36.199
#188.8.131.52 is arbitrary

Comment: Thanks, I will test this and get back to you. Do you know if it possible to use a wildcard IP such as 18.104.22.168/24 ? Sometimes the last group of numbers vary.

Maybe using 170.172.100.* in the whitelist, but then how do I use that with the RewriteRule?
Comment: Also, with your solution, when accessed from a different device - what do you mean when it is redirected to the entry in the whitelist file? I want it to return a 403 access denied, but not redirect?
Comment: Different device in the network means different IP address. This way I tested how from a different IP its corresponding entry from the whitelist.txt file is feed into the RewriteRule.
Comment: I came up with this to work the way I want, but I have a small problem: the capture %1 is not working in the RewriteCond, I cannot figure out why.

Test url: http://example.com/block/0/1/file.txt
whitelist.txt: 188.8.131.52 1

`RewriteEngine On
RewriteCond %{THE_REQUEST} \/block\/?
RewriteMap ipmap txt:/var/www/html/block/whitelist.txt
RewriteCond %{THE_REQUEST} \/block\/[0-9]\/([0-9]*)\/
RewriteCond ${ipmap:%{REMOTE_ADDR}} !^%1$ [NC]
RewriteRule .* - [F,L]`
Comment: @user969622 I have no idea why my solution is not working for you, I've tested it on OSX Apache 2.4.18 and Ubuntu Apache 2.4.7. Which OS / Apache version do you use?
Comment: Your solution is not doing what I need it to. I need to be able to access the file directly by going to "http://example.com/block/123/123.txt", also if the IP address is not in the whitelist it should be returning a 403 error. In your case it will not deny access rendering the whitelist pointless.
Comment: @user969622 I've edited my answer with a 403 error for when the IP is not in the whitelist


Return count of processed rows with mysql dynmic query

Question: I have written a mysql dynamic query to insert data from a database to another database. here is the query.
CREATE DEFINER=`Definer1`@`%` PROCEDURE `PushData`()
BEGIN
Set @SqlQuery = 'Insert Into Table_A (Column1,Column2,Column3)
                    Select Column1,Column2,Column3
                    From Table_B
                    Where Table_B.Column1=1;';
PREPARE  Statement From @SqlQuery;
EXECUTE Statement;
DEALLOCATE PREPARE Statement;
Select Count(*); -- Count of Inserted Rows
End

This Query will send data from Table_B to Table_A. in last i want to return the count of inserted rows.
How do i do it.
I know it is easy when i am not using dynamic query.
it's just assign the count to a variable and use it with select syntax.
but i have no idea how to do it with dynamic query.
can someone suggest?
Answer: To return the number of rows affected by an INSERT or an UPDATE query, use ROW_COUNT(). So replace
Select Count(*);

with
SELECT ROW_COUNT();

Answer: SQL%rowcount can be used to fetch the number of records inserted. May be below link could be of help.
https://community.oracle.com/thread/2370954?start=0&tstart=0


Drilling in bedrock

Question: I need to drill five 2.5" holes 1 foot deep in bedrock to accept 2" pipe that will be used to anchor the footings for my deck on a steep hill. I have a Bosch SDS Max rotary hammer drill.
I'm not sure if I can shut off the hammer part. The rock is in solid layers many feet deep.
Do I use a 2.5" rotary hammer bit, or a 2.5" diamond core bit?
I will be drilling on a 50-degree slope, so anchoring a wet core drill is not an option.
If I use a long core bit how do I get the core out?
Any tips, tricks, or advice would be appreciated.
Comment: Drill a bit and clean out the hole, or else you might cement the bit in.
Comment: This situation seems like the stakes are high enough and the tooling is exotic enough to eclipse the DIY aspects and "call a professional" is the right call here.
Comment: thank you. i just bought the Bosch 2 weeks ago it's at camp where the project is. i figured as much, but i took it out of the box and it was already set for drilling rebar so i haven't explored any further settings at this point.
Comment: 1) This is far too many questions all in one - please take the [tour]. 2) I've stood on my 12:12 pitch roof which is a 45° slope - I wouldn't want to be hanging on to a rotary hammer while doing so. 3) _Why_ do you want to disable the hammer action on your drill? I would think that this will be vital to you drilling a hole an hour vs a hole a day (roughly). 4) Why haven't you looked at the instructions for your drill to find out how to disable this feature? You have internet access, you can find the instructions...
Comment: Virtually all SDS can just drill, or just hammer, or hammer and drill. Consult your owner's manual.
Comment: thank you. i just bought the Bosch 2 weeks ago
Comment: @Ecnerwal: disagree on that, I think most do hammer-drill and hammer only (at least for SDS max that I'm familiar with), and few do drill only. I looked up three random models, a Milwuakee, bosch, and hilti, the first two don't drill only, and the hilti only does with some separate add-on components.
Comment: Normally the footings get fixed with rebar, not pipe. Are we talking here about concrete footings? If you are using rebar then it gets easy: Drilling into bedrock up to 3/4" should doable even with SDS plus
Comment: I really think you should get a professional. The stakes are too high.
Answer: Don't know about your local market, but in our regions a matching SDS-max tool for roughly 63mm+ bedrock is more costly than the estimanted rent for an diamond wet core drill.
It isn't impossible with an SDS max tool, they exist. But the core drill option might cost less and go faster.
I don't think that you need to anchor a core drill in this size. I had two guys make an 100mm hole with an handheld drill. On dude held the drill, the other pumped the water. Perhaps you could chisel a step into the bedrock to provide an even starting point for the core drill.
Answer: I'd use a quad carbide bit.  I've done 2" diameter hole in concrete with my bosch sds-max.  The bit I used wasn't great in rebar so when it hit rebar I spent a lot of time (15m instead of 1m for a similar hole).  You want the hammer and the drill mode.  Depending on the rock type you might want some kind of vacuum or powered air to clear out the debris as you drill.  Use a plunge up and down motion can help clear the dust as well.
I've used these previously on a rock to do a feather and wedge split.  Granite I made holes in no time.  Some other rock I kept breaking the carbide cutting edges off the bit.  It was my first time doing that kind of work though so I didn't realize why the bit wasn't working until I inspected the head and saw the cutting edges were gone.  So using these kind of bits generally works well but I guess there are certain rock types that eat carbide like crazy - I broke 3 bits ( the cutting edges ) before I gave up and just used a 60# jack hammer for 8 hours to break the rock into pieces.  Bring more than 1 bit !!
The core bit will take longer and you'd have to keep clearing the cores assuming you have enough extensions to keep drilling.  If you get out of plumb you are also kind of stuck.
1' is pretty deep your challenge is going to be drilling more or less plumb unless you don't care so much and only need so much projection into your footing or can bend the projection to be the proper edge setback from your concrete surface.  You don't need to buy the 18" carbide bits as you can get sds max extensions - though they are pricey !
Be interested to hear how it goes.  Good luck !

Drilling in bedrock


Script sending events to Google Analytics

Question: Hello,
I´m trying to track events on a great deal of websites, all made in Wordpress.
Previously I've been using GTM to track events, but I am looking to make a script to automate the process of sending events directly to Google Analytics.
I want to create and send an event every time a click happens on:
'tel:' -  'mailto:' - and external links.
<button onclick="ga('send', 'event', [eventCategory], [eventAction], [eventLabel], [eventValue], [fieldsObject]);">phonenumber</button>

I have used a modified version of this script, but I want to automate the process, so I dont have to scan the site for phonenumbers etc:
This is what I got so far, but I cant get it to work - I'm not getting any events in GA:

(I'm applying the script to the 'Tracking Code' area of my themes)
Any help regarding such script would be very much appreciated!
Answer: Try this:
$(document).ready(function(){
  $("a[href^='tel']").on('click', function (){
      ga('send', 'event', 'download', 'click');
  });
});

Comment: Thank you @michele Pisani - That worked perfectly!
(Only I had to change the $ to jQuery)