text:
Q: Ubuntu 16 or 18 on a new laptop (Dell Precision 7730) I am coming back to linux after using mac for a while. I will use my laptop for work, doing a lot of demanding computations. The laptop ships with 16.04 and i am wondering if to do a clean install of 18.? or upgrade or stay on ubuntu 16.04.
I was looking for information before asking and have read that 18.04 and 18.10 lack in performance and stability. However these information seem to be old so I would greatly apreciate feedback from the community. If performance and stability are my main concerns, rather then fancy new features what version should i install?
Laptop is Dell Precision 7730, if anyone has first hand experience it would be greatly apreciated!

A: I was on 16.04 and did a clean install on my ASUS laptop. When on 16.04 everything was running perfectly. With 18.04 there are a few problems, the sleep button is sort of hidden and sometimes computer freezes on restart. I did not revert to 16.04 and problems can be regarded as minor inconvenience. But if I knew I'd stay with 16.04 for now.

A: One of the most interesting things about Linux is how rarely things go sideways during upgrades such as from one LTS to another. This is no exception. Canonical dumped Unity and returned to GNOME (Ubuntu 18.04: Unity is gone, GNOME is back—and Ubuntu has never been better).
Unity was no Windows Vista. Some people liked Unity; I thought it was abysmal, but I was part of a small majority or very large plurality, since some were 'on the fence' about Unity. However, enough users complained about Unity and wanted GNOME back that Canonical listened to the market and put GNOME back in place (What's New in Ubuntu 18.04 LTS "Bionic Beaver", Available Now).
That's the biggest — and the best — change. There are some others, but they are smaller improvements.
As soon as I have the time and opportunity, I will be upgrading my desktop and Laptop to a variant of Ubuntu 18.04, which is Ubuntu 18.04 Mate, which uses the Mate Desktop Environment instead of GNOME. That's a personal preference. I don't care for what GNOME's become after GNOME 2.x
But do upgrade, it appears well worth it.


text:
Q: Docker run failed to run the container I'm new to docker, trying to build my the first docker container on AWS free tier account t2.micro instance
I am able to build my docker based on below Dockerfile.
FROM java:8
COPY content-service /
RUN chmod +x /bin/start.sh

CMD bash -C '/bin/start.sh'

EXPOSE 8081

MAINTAINER Velu

It's failing and exits while is trying to run the container command following error message is getting.
[ec2-user@ip-172-31-30-38 cis-docker]$ sudo docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
content-service     latest              9fa3ca5a8ac3        10 minutes ago      705.7 MB
docker.io/java      8                   d23bdf5b1b1b        8 months ago        643.1 MB

[ec2-user@ip-172-31-30-38 cis-docker]$ sudo docker --debug run -p 8082:8082 content-service
DEBU[0000] framesize: 18
Starting service.
DEBU[0000] Corrupted prefix: []
DEBU[0000] [hijack] End of stdout

Any help would be appreciated.

A: I ran your docker file by copying a simple shell script which prints "hello" on to console. It ran successfully.
Also, it does not seem like your docker container is exiting. Docker is running your shell script and exiting gracefully. To verify, check the exit code of your docker run command by running the below command as soon as your docker run is finished.
echo $?
If the above command prints "0" on to the screen then docker did not fail.
If you are expecting your shell script to run as a background daemon you need to make sure that your script does not exit. The reason why docker container is exiting as soon as your shell scriptspecified in CMD line your Dockerfile  is finished executing is because Docker's design philosophy is to run one process per container. In your case that single process is your shell script. So start whatever service you are starting in your shell script as a foreground process and the container will keep running as long as that service is running. As soon as that service dies your container dies which is what you might want.
Hope that helps.

A: I found and fixed this issue.
In my start.sh script last line I have this below line.
java -cp $CLASS_PATH $JVM_OPTIONS $CLASS_NAME ${ARGUMENTS[@]} & echo $! > $PID_FILE

In that line, I did remove this & echo $! > $PID_FILE,
Working:
  java -cp $CLASS_PATH $JVM_OPTIONS $CLASS_NAME ${ARGUMENTS[@]}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Connection to remote mysql server through ssh using python mysqldb connector passwordless Python 3.8
Mysql  8.0.23-0ubuntu0.20.04.1 for Linux on x86_64 ((Ubuntu))
Hi,
I want to connect to a distant mysql server using python's mysqldb connector and paramiko's sshtunnelforwarder.
I can connect to the database remotely without any problems by executing the following:
Connecting to database using mysql password authentication
server = new_ssh_server(config)
with server:
   print('Connection', server.local_bind_address)
   cnx = MySQLdb.connect(host = '127.0.0.1',
   port = server.local_bind_port,
   user = config['user'],
   passwd = config['password'],
   db = config['db'])

Queries work, I can read/write to database, no problem.
I would like to connect to database without supplying mysql password, by using mysql auth_socket authentication method, through ssh.
My attempts at this can be resumed by the following code:
Connecting to database using mysql auth_socket authentication
with server as tunnel:
    print('Tunnel:', tunnel.local_bind_address)
    cnx = MySQLdb.connect(host = 'localhost', user = 'hillbilly', password = '', db='tutut')#, unix_socket="/tmp/mysql.sock")
    res = pd.read_sql('select * from users;', cnx)
    print(res)

Which throws the following error:
File "connect_ssh_mysql_auth_socket.py", line 12, in <module>
    cnx = MySQLdb.connect(host = 'localhost', user = 'hillbilly', password = '', db='rsotest2')#, unix_socket="/tmp/mysql.sock")
  File "...../lib/python3.8/site-packages/MySQLdb/__init__.py", line 84, in Connect
    return Connection(*args, **kwargs)
  File "...../lib/python3.8/site-packages/MySQLdb/connections.py", line 179, in __init__
    super(Connection, self).__init__(*args, **kwargs2)
MySQLdb._exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)")

I have and existing mysqld.sock on the distant server that I symlinked to /tmp/mysql.sock, but the error remains. I have also added the next line to /etc/mysql/mysql.conf.d/mysql.cnf:
socket=/run/mysqld/mysqld.sock

But I still get the same error when trying to connect remotely.
Specifying the unix_socket='/run/mysqld/mysqld.sock' to mysqldb connector (commented in Connecting to database using mysql auth_socket authentication) does not fix the issue.
I seem to misunderstand the use of mysql.sock, mysqld.sock.
I was not able to find nor create a mysql.sock socket.
Is what I am trying to do possible? I remember reading somewhere that unix sockets only work locally, does this mean it is not achievable?
Any help/explanation would be appreciated.
(EDIT AND CLOSING)
So this is not possible. Following this thread, auth_socket needs local access to the socket file (usually /tmp/mysql.sock) to run autentication tests, so not accessible through ssh tunneling.

A: Authentication to remote mysql server using auth_socket plugin is not possible through sshtunnel, as the plugin requires local access to the socket file. See this thread for more information.


text:
Q: Gnome Shell integration native host connector will not work with Firefox 58 Ubuntu 17.10 (xorg), gnome 3.26.2, Firefox 58.0 (64 bit).  I have installed gnome-shell-extensions, chrome-gnome-shell, and the browser add ons for both Google Chrome and for Firefox.  In Firefox the only add on/extension I have installed is gnome-shell-integration.
The integration with https://extensions.gnome.org works just fine with Google Chrome.  However, with Firefox, I keep getting this error message:  "Although GNOME Shell integration extension is running, native host connector is not detected. Refer documentation for instructions about installing connector."
What must I do to make this work with Firefox?

A: maybe - the easiest way is to install:
sudo apt install chrome-gnome-shell

Then
cd ~/.local/share/gnome-shell

if there is NO such folder, then please:
mkdir ~/.local/share/gnome-shell

then:
cd ~/.local/share/gnome-shell
mkdir extensions

and extract your downloaded .zip file from the homepage of gnome-extensions to the extensions folder by clicking on the zip file and show hidden files and folders by either pressing ctrl+h or clicking on the upper right symbol with the 3 lines and choosing show all files/hidden files (I do not exactly know the English text version).
Then open up your files - choose other locations - look for hidden files and folders again and click on .local and then upon share and then upon gnome-shell and then upon extensions and RIGHT-click upon the file metadata.json and open with some text-editor and at the bottom after uuid please enter /home/username/.local/share/gnome-extensions/ where username is your real username... or in your sub-folder you MAY have created in case you want to use several extensions more..
Then, please restart your computer.
Although this sounds a little weird this got my gnome-extensions (in this case suspend-button) to work properly (after 1 hour work , haha :))

A: I don't know if I should mark this as an answer.....
For the past couple months, I could not get the browser add-on to work in Firefox as I described in my original post.  Day after day I would try, but it would not work.  Now, today (March 11, 2018) it works for some unknown, mysterious reason.


text:
Q: Confused over template method specialization I have been trying to understand this but can't get it to work. My impression is that this should work:-
template <int I> struct banana {
    int getNumber() { return 5; }

    int getNumber<0>() { return 6; }
};

So if I make a new banana with any template parameter other than 0, getNumber() should return 5 and if the parameter is 1, it should return 6. Why is it not working?

A: Because that's not the way to specialize. What you need is
#include <iostream>

template <int I> struct banana {
    int getNumber() { return 5; }

    //int getNumber<0>() { return 6; } // WRONG
};

template<> int banana<0>::getNumber(){ return 6;} // CORRECT WAY OF SPECIALIZING

int main()
{
    banana<42> foo;
    banana<0> bar;

    std::cout << foo.getNumber() << std::endl; // outputs 5
    std::cout << bar.getNumber() << std::endl; // outputs 6
}

Live on Coliru

A: There are 2 ways to get what you want... depending on what you want.
expanding on vsoftco's answer:
#include <iostream>

template <int I>
struct banana {
    int getNumber() { return 5; }
};

template<>
struct banana<0>
{
    int getNumber() { return 6; }
};

struct banana2
{
    template<int I> int getNumber() { return 5; }
};

template<>
int banana2::getNumber<0>() { return 6; }

using namespace std;

auto main() -> int
{
    banana<42> foo;
    banana<0> bar;

    std::cout << foo.getNumber() << std::endl;
    std::cout << bar.getNumber() << std::endl;

    banana2 b2;
    std::cout << b2.getNumber<400>() << std::endl;
    std::cout << b2.getNumber<0>() << std::endl;

    return 0;
}

expected output:
5
6
5
6


text:
Q: With elastic bounce Chrome/Safari knows when my fingers leave the trackpad. Can JS know? When you overscroll a page in Chrome or Safari you can hold the page "overscrolled" and it will bounce back only after you lift your fingers from the trackpad. I would like to recreate this event, can JS detect when you lift your fingers from laptop's trackpad?

A: No.  It looks like trackpad touch events cannot be detected in the browser.

*

*JQuery - Can I query the MacBook Pro Trackpad?

*Touch events available in Safari?

Aside
This is a reference for all browser events:
https://developer.mozilla.org/en-US/docs/Web/Events


text:
Q: Why won't Travis CI run the CodeClimate script for my Node app? I have followed the instructions to add CodeClimate to my .travis.yml file:
language: node_js
script:
  - gulp
  - npm test
after_script:
  - codeclimate < coverage/**/lcov.info
addons:
  code_climate:
    repo_token: [ my token ]

Everything in my build runs without error, except the codeclimate script at the end:
[0K$ codeclimate < coverage/**/lcov.info
/home/travis/build.sh: line 41: codeclimate: command not found

What am I missing?

A: I added my CODECLIMATE_REPO_TOKEN to my Travis-CI > Settings > Environment Variables and removed it from my .travis.yml file.
I don't want it installing if the build failed (for performance), so I only install it on success in my .travis.yml file, like so:
after_success:
  - npm install codeclimate-test-reporter
  - codeclimate-test-reporter < coverage/lcov.info

I think the codeclimate-test-reporter binary was renamed from codeclimate to codeclimate-test-reporter and perhaps Travis-CI didn't notice the change yet. This must be why it's broken all of the sudden (I had the same issue).

A: I got this working by installing CodeClimate locally:
npm install --save-dev codeclimate-test-reporter

I guess Travis CI's Code Climate addon isn't working, or I'm just not specifying it correctly.


text:
Q: How to reset Host Only Adapter Networking for Oracle VirtualBox VM Manager My Host Only Networking stopped working, how do I reset it ?
I tried disabling and re-enabling Local Area Connection and VirtualBox Host-Only Network but VirtualBox Host-Only Network is still showing on Unidentified Network / not getting internet, making all my VM's on 10.0.3.15 and not able to communicate with one another.
Any suggestions?
Original Oracle Virtual Box VM Manager Networking Setup Instructions

*

*In the VirtualBox Manager, go to your VM's Settings.

*Click on Network.

*Change your settings to the following: Attached to: Host-only Adapter, Name: VirtualBox Host-Only Ethernet Adapter, Promiscuous Mode=Allow All, Check Cable Connected, click OK, then close this window.

*Select File > Preferences.

*Click Network.

*Click the Properties button (screwdriver).  Enter the following IPv4 Address 192.168.137.1 and IPv4 Network Mask 255.255.255.0 and Click on the DHCP Server tab to make sure it is not enabled.

*On the host machine, go the Network and Sharing Center and select Change Adapter Settings.

*Right-click and select Properties. Click on Sharing tab.

*Your settings should look like the following: Check Allow other network users to connect through this computer's Internet Connection Home Networking connection: VirtualBox Host-Only Network, Check Allow other network users to control or disable the shared Internet Connection

*Click OK.  Click Yes on next screen.

*Reset network connections on VMs and you should be good to go!

Thanks!

A: Blindly using vboxnet0 as your interface name will not work for everyone, or even most people.

*

*Use ifconfig to get a list of your network adapters.

*On my machine it was the ethernet I wanted to restart, but yours may be wlan. The ethernet interface on my machine was enp0s3.

*Use the ifconfig commands @encgoo mentioned. sudo ifconfig enp0s3 down && sudo ifconfig enp0s3 up. Replace enp0s3 with your own interface name of course.

A: This trick helps.
From the host machine:
sudo ifconfig vboxnet0 down
sudo ifconfig vboxnet0 up


text:
Q: What is an example of an orbifold which is not a topological manifold? In Thurston's book The Geometry and Topology of Three-Manifolds it is proven that the underlying space of a two-dimensional orbifold is always a topological surface.
Are there any easy examples of higher dimensional orbifolds whose underlying spaces are not topological manifolds?

A: To give a compact version of Igor's example, consider the antipodal map in the tangent space of a round 3-sphere at a point.  This extends to an isometry of the 3-sphere with a pair of fixed points.  The quotient by the isometry is a manifold with two conical singularities which is not homeomorphic to a topological 3-manifold.

A: It is quite easy to give an example in real dimension $4$.
In fact, it was shown by D. Mumford in the paper
The topology of normal singularities of an algebraic surface and a criterion for simplicity, Inst. Hautes Etudes Sci. Publ. Math. (1961), no. 9, 5 -
22
that a normal algebraic surface over $\mathbb{C}$, whose underlying topological space (in the usual topology) is a topological manifold, must be nonsingular.
Now take the orbifold $X:=\mathbb{C}^2/G$, where $G$ is the group of order $2$ whose generator $\xi$ acts as $\xi \cdot (x, \, y) = (-x, \, -y)$.
The $G$-invariant subalgebra is generated by $A:=x^2, \, B=xy, \, C:=y^2$, so the underlying algebraic surface $X$ is isomorphic to the affine quadric cone $\{B^2-AC=0 \} \subset \mathbb{C}^3$, which has a $A_1$-singularity at its vertex. Such a singularity is normal, because it is a codimension two hypersurface singularity.
Then $X$ cannot be a topological manifold  by Mumford's result mentioned above.


text:
Q: echo foreach from 2 arrays I have 2 arrays containing the following values from mysql query
$Array1 =
(
[0] => john
[1] => nick
[2] => mike
[3] => eva
[4] => mary
)

$Array2 =
(
[0] => Array ( [name] => john [color] =>black )
[1] => Array ( [name] => john [color] =>red )
[2] => Array ( [name] => mike [color] =>yellow )
[3] => Array ( [name] => eva [color] =>purple )
[4] => Array ( [name] => eva [color] =>green )
[5] => Array ( [name] => mary [color] =>orange )
[6] => Array ( [name] => mary [color] =>white )
[7] => Array ( [name] => george [color] =>purple )
[8] => Array ( [name] => phil [color] =>green )
[9] => Array ( [name] => toni [color] =>orange )
[10] => Array ( [name] => amanda [color] =>white )

)

I want to echo for each person in $array1 all colors in $array2.

A: You can try something like this :
foreach($Array1 as $value)
    foreach($Array2 as $v)
       echo $v['name'] === $value ? $v['color'] : '';

Example

A: Use the code below
<?php
$Array1 = array
(
0 => "john",
1 => "nick",
2 => "mike",
3 => "eva",
4 => "mary",
);

$Array2 =array
(
0 => Array ( "name" => "john" ,"color" =>"black" ),
1 => Array ( "name" => "john" ,"color" =>"red" ),
2 => Array ( "name" => "mike" ,"color" =>"yellow" ),
3 => Array ( "name" => "eva" ,"color" =>"purple" ),
4 => Array ( "name" => "eva" ,"color" =>"green" ),
5 => Array ( "name" => "mary" ,"color" =>"orange" ),
6 => Array ( "name" => "mary" ,"color" =>"white" ),
7 => Array ( "name" => "george" ,"color" =>"purple" ),
8 => Array ( "name" => "phil" ,"color" =>"green" ),
9 => Array ( "name"=> "toni" ,"color" =>"orange" ),
10 => Array ( "name" => "amanda" ,"color" =>"white"),

);
            foreach($Array1 as $t){
                foreach($Array2 as $p){
                   if($p['name'] == $t) {
            echo $p['color'];
            }
            }
}

Hope this helps you

A: $Array1 = array("john", "nick", "mike", "eva", "mary");

$Array2 = array(
        array ("name" => "john", "color" => "black" ),
        array ( "name" => "john", "color" => "red" ),
        array ( "name" => "mike", "color" => "yellow" ),
        array ( "name" => "eva", "color" => "purple" ),
        array ( "name" => "eva", "color" => "green" ),
        array ( "name" => "mary", "color" => "orange" ),
        array ( "name" => "mary", "color" => "white" ),
        array ( "name" => "george", "color" => "purple" ),
        array ( "name" => "phil", "color" => "green" ),
        array ( "name"=> "toni", "color" => "orange" ),
        array ( "name" => "amanda", "color" => "white")
);

foreach($Array1 as $val1)
    foreach($Array2 as $val2)
       echo $val2['name'] === $val1 ? $val2['color'] . "<br>" : '';


text:
Q: ABC Push Value Return I got a question. I have an AS3 code (gotten from AS3 sorcerer)
protected function get _-64():String {
    if (_-0Xg < _-1FT.length)
    {
        return (_-1FT[_-0Xg]);
    };

    return ("");
}

In ABC code it's (used to decompile + recompile the SWF):

  trait getter QName(ProtectedNamespace("_-0t4"), "_-64")
   method
    refid "_-0iF:_-0KH/_-0t4:_-64/getter"
    returns QName(PackageNamespace(""), "String")
    body
     maxstack 2
     localcount 1
     initscopedepth 4
     maxscopedepth 5
     code
      getlocal0
      pushscope

      getlex              QName(PrivateNamespace("", "_-0iF:_-0KH"), "_-0Xg")
      jump                L10

      pushfalse
      pushwith
      subtract
      multiply_i
      coerce_a
      istypelate
    L10:
      getlex              QName(PrivateNamespace("", "_-0iF:_-0KH"), "_-1FT")
      getproperty         QName(PackageNamespace(""), "length")
      ifnlt               L17

      getlex              QName(PrivateNamespace("", "_-0iF:_-0KH"), "_-1FT")
      getlex              QName(PrivateNamespace("", "_-0iF:_-0KH"), "_-0Xg")
      getproperty         MultinameL([PrivateNamespace("", "_-0iF:_-0KH"), PackageNamespace(""), PackageInternalNs("_-0iF"), ProtectedNamespace("_-0t4"), StaticProtectedNs("_-0t4"), StaticProtectedNs("Object"), Namespace("_-tc")])
      returnvalue

    L17:
      pushstring          ""
      returnvalue
     end ; code
    end ; body
    end ; method
    end ; trait

However, I want to edit the ABC code so the method (AS3) would look like:
protected function get _-64():String {
    return "icon_" + _-0Xg;
}

But I have no clue how to push "icon_" + _-0Xg in ABC format. Can somebody please help me?

A: Try this code:
getlocal0
pushscope
pushstring "icon_"
getlex QName(PrivateNamespace("", "_-0iF:_-0KH"), "_-0Xg")
add
returnvalue


text:
Q: $L^{p}(\mathbb R)\subset L^{1}(\mathbb R) \ast L^{p}(\mathbb R), (1< p< \infty)$? Let $\mathbb T$ be a circle group.
In 1939, Salem, has shown that, every member of $L^{1}(\mathbb T)$ can written as a product(convolution) some other two members of $L^{1}(\mathbb T),$ that is,   $L^{1}(\mathbb T)\subset L^{1}(\mathbb T)\ast L^{1}(\mathbb T);$ other way one can get by Fubini's theorem, so we have, $L^{1}(\mathbb T)=L^{1}(\mathbb T)\ast L^{1}(\mathbb T).$
I have learn from the book(R. E. Edwards, Fourier Series A  Modern Introduction Volume 1, p.124), $L^{p}(\mathbb T)=L^{1}(\mathbb T)\ast L^{p}(\mathbb T), (1\leq p < \infty).$
In 1959, Walter Rudin has shown  for the real line that, $L^{1}(\mathbb R)=L^{1}(\mathbb R)\ast L^{1}(\mathbb R).$
By Young's inequality, we have, $L^{1}(\mathbb R)\ast L^{p}(\mathbb R) \subset L^{p}(\mathbb R), (1\leq p < \infty).$
My Question is: Is it well-known in a literature that, $L^{p}(\mathbb R)\subset L^{1}(\mathbb R) \ast L^{p}(\mathbb R), (1< p< \infty)$ ? If answer is yes, please let me know some references; If not, what one can expect ?
Thanks,


text:
Q: Is This The Right Way To Change Drives Using Terminal? Well I am a newbie in Linux world. Everyday learning by working. I use dual booting and in one drive Windows 7 is installed and in another drive Ubuntu 14.04 LTS is installed. My first O/S was windows 7. There was few drives like Workshop, Movies, Soft etc. Now I was about to change drives in terminal to access files stored in different drives. After spending couple of hours I discovered a way to access different files in different drives. What I did is first of all I mounted lets say /dev/sda2 drive in /media/username folder using this command....

$ sudo mount /dev/sda2/ media/username

Once mounted then I can easily change directories by using cd command.
Now my questions are...

*

*Is this really a correct way to change drives to access files?

*I can go forward like $cd /media/username but how to go backward?
I mean go back to root or go back to media? In windows CMD I am
using cd.. to go one folder back. Is there any similar command for
terminal?

*What is the difference between drive and partition?

*How to unmount a drive or any file?

*My last question is as far as I know in Linux files are arranged
under root / directory. If so then it might don't respect windows
drive systems. If so then all files should be accessed without
mounting any drive to /media/username folder?

A: First, note there is a typo in mount your command. It should be:
$ sudo mount /dev/sda2 /media/username

Here /dev/sda2 is the device (in this case, a hard drive's partition) you want to access, and /media/username is your mountpoint, i.e., the location in the filesystem where you want to mount the device.
To answer your questions:

*

*Yes, using cd is the normal way to change directories. And mount is perfectly fine to mount devices that are not already mounted. If you mount it often, you may want to make an entry in /etc/fstab so that in the future you can mount a particular device to a particular mountpoint with self-defined options, e.g., by simply writing mount /media/username. You may even want to consider mounting it automatically, at boot time. There is a lot of excellent documentation on the subject. Just search for fstab.

*I guess you want to do a bit of reading about the Linux filesystem. There's also good documentation for this, see, e.g., here for a short overview. / is the root folder in which everything is contained, organized in various subfolders. Here's a few hints concerning cd:

*

*cd (without arguments) will get you to your home folder, typically /home/username

*cd - will get you to the previous folder (where you were before you changed to the current folder)

*cd .. will get you to the parent folder (one level up). This is equivalent to cd.. in Windows CMD.

*cd / will get you to the root folder, though I personally rarely need that.

*A (hard) drive is actually a disk that you can store data on. It is usually divided into several partitions. Perhaps confusingly, in the Windows world these partitions are also called drives. This is not the case in the Linux world, though. We simply  call them partitions, or perhaps "devices" in a technical context.

*To unmount a mounted device, use the command sudo umount <MOUNTPOINT>, e.g., in your example,
sudo umount /media/username

...where /media/username is a mounted partition (you could also use sudo umount /dev/sda2, though this is perhaps less intuitive). Simply write mount (without arguments) to see a list of all currently mounted devices with their mountpoints.

*In Linux, you have to mount each of your Windows "drives" on a separate mountpoint. You are completely free to choose where, and you already know how to do it, as you showed with your mount command. :)


text:
Q: how to solve derivative of a function including two absolute functions So I don't understand how to solve the derivative of a function with two absolute functions.
$$f(x) = |x - 1| + |x^2 - 2x|.$$
Here is the function. I need to solve the maximum and minimum values in the domain $[0,2]$ but can't figure out the derivative.

A: If you want to solve by derivative, one way is to break it into smaller domains where signs remain the same.
For $0 \le x \le 1$, $f(x) =  -(x-1) - (x^2-2x) = 1+x-x^2$
For $1 \le x \le 2$, $f(x) =  (x-1) - (x^2-2x) = 3x-x^2-1$
Now when you differentiate, you get max of $f(x) = \frac{5}{4}$, at $x = \frac{1}{2}$ and $x = \frac{3}{2}$.


text:
Q: In bigquery how can I check if at least one elemnt from one array is in another array? I have two arrays. lets call them arr1 and arr2.
what I want to do is to find all the rows with the following condition: if at least one element from arr1 is in arr2 I want to get this row
Any ideas?
Maybe with left join?


text:
Q: Razor - editable grid - what approach? I am very much wondering and don't know yet what to decide to use.
So I want to have grid and to edit its row's data.
I am working with MVC3 Razor, i know for these posibilities:
- jqGrid Razor
- knockout grid Razor - i don't know how to make it editable grid? Is it possible at all, or is this just for displaying data.
- web grid , Razor
I don't like to use Telerik controls!
Would you pls advice me what is the best approach to make editable grid and what if i don't need editable grid? Why to use one or other of the ways?
And all that in Razor page.

A: ShieldUI's grid also supports a lot of editing modes, scenarios and sending the updates locally or to any remote endpoint.
A good example to start can be found here:
http://demos.shieldui.com/mvc/grid-editing/editing-restful-web-service

A: jqGrid definitely does support editing, you can see some examples at http://www.trirand.com/blog/jqgrid/jqgrid.html or read the documentation at http://www.trirand.com/jqgridwiki/doku.php?id=start

A: Use The Following Code For Editing and Same as Add, Delete.
For View,
@(Html.Telerik().Grid<CustomerOrderDetails>()
                       .Name("gvCustomerOrderDetails")
                       .DataKeys(keys => keys.Add(k => k.ItemID))
                       .Columns(column =>
                       {
                           column.Bound(i => i.ItemID).Hidden(true);
                           column.Bound(i => i.SalesSequenceNumber).Hidden(true);
                           column.Bound(i => i.ItemSequence).Hidden(true);
                           column.Bound(i => i.ItemName).Title("Item Name").ReadOnly();
                           column.Bound(i => i.Quantity).Title("Order Quantity").HtmlAttributes(new { @class = "gridTextAlignRight" });
                           column.Bound(i => i.ItemUnitPrice).HtmlAttributes(new { @class = "gridTextAlignRight" }).ReadOnly();
                           column.Bound(i => i.ItemUnitPrice).Hidden(true);
                           column.Bound(i => i.TotalPrice).HtmlAttributes(new { @class = "gridTextAlignRight" }).ReadOnly();
                           column.Command(command =>
                           {
                               command.Edit().ButtonType(GridButtonType.Image);
                           }).Width(80).Title("Commands");
                       })
                       .Selectable()
                       .DataBinding(dbBindings =>
                           {
                               dbBindings.Ajax().Select("__CustomerOrderDetailsGridBind", "CustomerInfo")
                                                .Update("__CustomerOrderDetailsUpdate", "CustomerInfo");
                           })
                       .ClientEvents(events =>
                        events.OnDataBinding("onDataBinding")
                              .OnError("onError")
                       )
                       .Scrollable(scroll => scroll.Height(300))

                 )

For Control Use the following Code,
    [AcceptVerbs(HttpVerbs.Post)]
    [GridAction]
    public ActionResult __CustomerOrderDetailsUpdate(CustomerOrderDetails objCustomerOrderDetails)
    {
        SalesItem objSalesItem = new SalesItem();
        objSalesItem.SalesSequenceNumber = objCustomerOrderDetails.SalesSequenceNumber;
        objSalesItem.ItemSequence = Convert.ToByte(objCustomerOrderDetails.ItemSequence);
        objSalesItem.ItemID = objCustomerOrderDetails.ItemID;
        objSalesItem.Quantity = objCustomerOrderDetails.Quantity;
        objSalesItem.ItemUnitPrice = objCustomerOrderDetails.ItemUnitPrice;
        objSalesItem.TotalPrice = objCustomerOrderDetails.ItemUnitPrice * objCustomerOrderDetails.Quantity;
        objSalesItem.SalesDate = DateTime.Now;
        objSalesItem.EntryBy = objLoginHelper.LogInID;
        objSalesItem.EntryDate = DateTime.Now;

        customerDal.UpdateSalesItem(objSalesItem);

        return View(new GridModel<CustomerOrderDetails>
        {
            Data = customerDal.CustomerOrderDetailsInfo(objCustomerOrderDetails.SalesSequenceNumber, Helper.Active)
        });
    }

you can also use your Model specific Class for Add, Edit & Delete. Here ReadOnly() is used for unedited column. If you need the column value in control then use same column without ReadOnly() and just Hidden.
I think all are enjoy using this code.


text:
Q: How to get nearest lat long in array PHP I have following array and according to my "Lat,Long" (dynamic) i want to get nearby locations from array,how can i do this ?
Here is my lat long
$lat="30.741190";
$lng="76.806343";

Here is my array
<pre>Array
(
    [0] => Array
        (
            [CityName] => Jaunpur
            [distance] => 1.2316498252150263
            [latitude] => 30.741190
            [longitude] => 76.764381
            )

    [1] => Array
        (
            [CityName] => Def
            [distance] => 3.710097860029201
            [latitude] => 30.740700
            [longitude] => 76.806343
             )
)

A: I use a function :
function distance($lat1, $lon1, $lat2, $lon2, $unit) {

  $theta = $lon1 - $lon2;
  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
  $dist = acos($dist);
  $dist = rad2deg($dist);
  $miles = $dist * 60 * 1.1515;
  $unit = strtoupper($unit);

  if ($unit == "K") {
      return ($miles * 1.609344 );
  } else if ($unit == "N") {
      return ($miles * 0.8684);
  } else {
      return $miles;
  }
}

Now loop over array
$distances = array();
    foreach($arrayname as $ind => $entry){
    $dist=distance($entry["latitude"],$entry["longitude"],$lat,$lng,"K");
    echo $dist;
$distances[$entry["cityname"]]=round($dist);
    }

//now sort distances array in ascending:
$distances = sort($distances);


text:
Q: Compare timestamps based on multiple criteria from multiple rows and columns I have two data frames with timestamps (in as.POSIXct, format="%Y-%m-%d %H:%M:%S") as below.
df_ID1
 ID         DATETIME               TIMEDIFF                 EV
  A         2019-03-26 06:13:00    2019-03-26 00:13:00      1
  B         2019-04-03 08:00:00    2019-04-03 02:00:00      1
  B         2019-04-04 12:35:00    2019-04-04 06:35:00      1

df_ID0
  ID         DATETIME
  A         2019-03-26 00:02:00
  A         2019-03-26 04:55:00
  A         2019-03-26 11:22:00
  B         2019-04-02 20:43:00
  B         2019-04-04 11:03:00
  B         2019-04-06 03:12:00

I want to compare the DATETIME in df_ID1 with the DATETIME in df_ID0 that is with the same ID and the DATETIME is "smaller than but closest to" the one in df_ID1,
For the pair in two data frames that matches, I want to further compare the TIMEDIFF in df_ID1 to the matched DATETIME in df_ID0, if TIMEDIFF in df_ID1 greater than the DATETIME in df_ID0, change EV 1 to 4 in df_ID1.
My desired result is
 df_ID1
 ID         DATETIME               TIMEDIFF                 EV
  A         2019-03-26 06:13:00    2019-03-26 00:13:00      1
  B         2019-04-03 08:00:00    2019-04-03 02:00:00      4
  B         2019-04-04 12:35:00    2019-04-04 06:35:00      1

I've checked how to compare timestamps and calculate the time difference, also how to change values based on criteria...
But I cannot find anything to select the "smaller than but closest to" timestamps and cannot figure out how to apply all these logic too..
Any help would be appreciate!

A: You can do this with a for loop keeping in mind that if your actual data base is very big then the overhead would be quite bad performance wise.
for(i in 1:nrow(df_1)){
  sub <- subset(df_0, ID == df_1$ID[i]) # filter on ID
  df_0_dt <- max(sub[sub$DATETIME < df_1$DATETIME[i],]$DATETIME) # Take max of those with DATETIME less than (ie less than but closest to)
  if(df_0_dt < df_1$TIMEDIFF[i]){ # final condition
    df_1[i, "EV"] <- 4
  }
}

df_1
# A tibble: 3 x 4
  ID    DATETIME            TIMEDIFF               EV
  <chr> <dttm>              <dttm>              <dbl>
1 A     2019-03-26 06:13:00 2019-03-26 00:13:00     1
2 B     2019-04-03 08:00:00 2019-04-03 02:00:00     4
3 B     2019-04-04 12:35:00 2019-04-04 06:35:00     1

A: One option using nested mapply, is to first split df_ID1 and df_ID0 based on ID. Calculate the difference in time between each value in df_ID1 with that of df_ID0 of same ID. Get the index of "smaller than but closest to" and store it in inds and change the value to 4 if the value of corresponding TIMEDIFF column is greater than the matched DATETIME value.
df_ID1$EV[unlist(mapply(function(x, y) {
                   mapply(function(p, q) {
                     vals = as.numeric(difftime(p, y$DATETIME))
                     inds = which(vals == min(vals[vals > 0]))
                     q > y$DATETIME[inds]
                    }, x$DATETIME, x$TIMEDIFF)
                 }, split(df_ID1, df_ID1$ID), split(df_ID0, df_ID0$ID)))] <- 4

df_ID1
#  ID            DATETIME            TIMEDIFF EV
#1  A 2019-03-26 06:13:00 2019-03-26 00:13:00  1
#2  B 2019-04-03 08:00:00 2019-04-03 02:00:00  4
#3  B 2019-04-04 12:35:00 2019-04-04 06:35:00  1

data
df_ID0 <- structure(list(ID = structure(c(1L, 1L, 1L, 2L, 2L, 2L),
.Label = c("A",
"B"), class = "factor"), DATETIME = structure(c(1553529720, 1553547300,
1553570520, 1554208980, 1554346980, 1554491520), class = c("POSIXct",
"POSIXt"), tzone = "")), row.names = c(NA, -6L), class = "data.frame")

df_ID1 <- structure(list(ID = structure(c(1L, 2L, 2L), .Label = c("A",
"B"), class = "factor"), DATETIME = structure(c(1553551980, 1554249600,
1554352500), class = c("POSIXct", "POSIXt"), tzone = ""), TIMEDIFF =
structure(c(1553530380,
1554228000, 1554330900), class = c("POSIXct", "POSIXt"), tzone = ""),
EV = c(1, 1, 1)), row.names = c(NA, -3L), class = "data.frame")


text:
Q: How to select all div from body and not from the header? I use this javascript code in order to select all DIVs and change their color. I don't want to change color of the DIV in the header. Purpose of this task is to learn HTML5, DOM, Javascript and getElementsByTagName function:
<!DOCTYPE html>

    <meta charset="utf-8"/>
    <title>test</title>

divv in header

bla

bla

bla

div in div

bla

A: Where is your problem? You just did it right to select the div in head:
    var h = document.head;
    var dh = h.getElementsByTagName('div');
    // or short:
    var dh = document.head.getElementsByTagName('div');

So why don't you use the same for the body element:
    var db = document.body.getElementsByTagName('div');

The getElementsByTagName() method can be applied on any dom element.

A: You may find it best to access the required elements using a CSS selector and appropriate style rule. Here's an example:

here is a div
<button onclick="applyRule('div','background-color: red')">Change div background colour</button>


text:
Q: How do I make WHERE IN not a string? I have a subquery where my IN expression is coming from a column in the main table.  MySQL is seeing this column as a string.  How do I fix?
So for instance, my query is being interpreted as:
SELECT song.title,
    (SELECT group_concat(username) FROM users WHERE user_id IN ('4,9')) as editors
FROM songs song WHERE ...

The '4,9' is coming from my songs table column called editors_list which is a CSV of user_ids.
So MySQL is only doing a match on the user_id of 4.  How can I make MySQL look at songs.editors_list as 4,9 so that the query looks like:
SELECT song.title,
    (SELECT group_concat(username) FROM users WHERE user_id IN (4,9)) as editors
FROM songs song WHERE ...

and therefore it matches on user_id = 4 and user_id = 9
My current query looks like:
SELECT song.title,
    (SELECT group_concat(username) FROM users WHERE user_id IN (song.editors_list)) as editors
FROM songs song WHERE ...

A: MySQL has a built-in function that allows you to search a value inside a csv format called FIND_IN_SET().
SELECT a.title,
       group_concat(b.username)
FROM   songs a
       INNER JOIN b
          ON FIND_IN_SET(b.user_id, a.editors_list) > 0
WHERE ...
GROUP  BY a.title

*

*MySQL FIND_IN_SET


text:
Q: ADAL.NET ID-Token from logged in user I have an webapplication which uses the Microsoft Graph API to get data from Office365 services. For the login i took the code from Microsofts sample project, which uses ADAL.NET Library for authentification.
When i make an http request it checks if the a request was authentificated. The problem is, when a new session was started no authetification request was performed, although the user is logged in. I get the error message Error Failed to acquire token silently as no token was found in the cache. Call method AcquireToken.
After research i found out that i have to call the Method AcquireTokenSilentlyAsync(), which verifies if an acceptable token is in the cache. I have implemented this method but it always throws an exception. After debugging i saw that there is no ID-Token when a logged in user makes an request. How can i get this ID-Token?
public static AuthProvider Instance { get; } = new AuthProvider();

        // Get an access token. First tries to get the token from the token cache.
        public async Task<string> GetUserAccessTokenAsync()
        {
            string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            HttpContextBase httpContextBase = HttpContext.Current.GetOwinContext().Environment["System.Web.HttpContextBase"] as HttpContextBase;

            SessionTokenCache tokenCache = new SessionTokenCache(signedInUserID, httpContextBase);
            var cachedItems = tokenCache.ReadItems(); // see what's in the cache

            AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.Authority, tokenCache);
            ClientCredential clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);

            string userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
            UserIdentifier userId = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);

            try
            {
                AuthenticationResult result = await authContext.AcquireTokenSilentAsync(SettingsHelper.GraphResourceId, clientCredential, userId);
                return result.AccessToken;
            }
            // Unable to retrieve the access token silently.
            catch (AdalException ex)
            {
                HttpContext.Current.Request.GetOwinContext().Authentication.Challenge(
                    new AuthenticationProperties() { RedirectUri = "/" },
                    OpenIdConnectAuthenticationDefaults.AuthenticationType);

                throw new Exception("Error" + $" {ex.Message}");
            }
        }

    public class SessionTokenCache : TokenCache
    {
        private HttpContextBase context;
        private static readonly object FileLock = new object();
        private readonly string CacheId = string.Empty;
        public string UserObjectId = string.Empty;

        public SessionTokenCache(string userId, HttpContextBase context)
        {
            this.context = context;
            this.UserObjectId = userId;
            this.CacheId = UserObjectId + "_TokenCache";

            AfterAccess = AfterAccessNotification;
            BeforeAccess = BeforeAccessNotification;
            Load();
        }

        public void Load()
        {
            lock (FileLock)
            {
                Deserialize((byte[])context.Session[CacheId]);
            }
        }

        public void Persist()
        {
            lock (FileLock)
            {
                // Reflect changes in the persistent store.
                var bytes = Serialize();
                var x = System.Text.Encoding.UTF8.GetString(bytes);
                context.Session[CacheId] = Serialize();

                // After the write operation takes place, restore the HasStateChanged bit to false.
                HasStateChanged = false;
            }
        }

A: Please go through the  sample  which helps in how to use MSAL.NET (Microsoft Authentication Library) to obtain an access token and will fix your issue.

Note:- MSAL is recommended since ADAL is going to be depreciated


text:
Q: Using generics with Morphia & MongoDB Short Description:
I'm having trouble with reading a document from mongo DB into a java class with a generic property. The error says java.lang.Double cannot be cast to com.mongodb.DBObject
Long Description:
I have a java class / mongoDb-Collection called RandomDataCollection which has properties of type MyGenericProperty<T>
@Getter @Setter @NoArgsConstructor @Entity("randomDataCollection")
public class RandomDataCollection {

    @Id
    private ObjectId id = new ObjectId();

    private String name;

    @Embedded
    private MyGenericProperty<Float> temperatureMumbai;

}

MyGenericProperty<T> looks like this
@Getter @Setter @NoArgsConstructor
public class MyGenericProperty<T> {

    private T value;

    private String unit;

}

Writing to the DB works as expected...
MyGenericProperty<Float> temperatureMumbai = new MyGenericProperty<Float>();
temperatureMumbai.setValue(32.8f);
temperatureMumbai.setUnit("°C");

RandomDataCollection randomData = new RandomDataCollection();
randomData.setName("RandomData0711");
randomData.setTemperatureMumbai(temperatureMumbai);

Datastore datastore = getDatastore();
datastore.save(randomData);

...but when I try to read from the DB...
randomData = datastore.find(RandomDataCollection.class).filter("name =", "RandomData0711").get();

...I get the following exception:
Caused by: java.lang.ClassCastException: java.lang.Double cannot be cast to com.mongodb.DBObject

I did find some discussions about generics and morphia but to be honest I didn't know how to apply those to my issue.
I'm running Morphia 1.5.8

A: There is almost certainly a better way to do this but this worked for me.
DBCursor cursor = datastore.find(RandomDataCollection.class).filter("name =", name).fetch().getCursor();
List<RandomDataCollection> list = new ArrayList<>();
while (cursor.hasNext()) {
    DBObject theObj = cursor.next();
    RandomDataCollection rec = new RandomDataCollection();
    rec.setId((ObjectId)theObj.get("_id"));
    MyGenericProperty<Float> temperatureMumbai = new MyGenericProperty<Float>();
    BasicDBObject x = (BasicDBObject)theObj.get("temperatureMumbai");
    temperatureMumbai.setValue(x.getFloat("value"));
    temperatureMumbai.setUnit(x.getString("unit"));
    rec.setTemperatureMumbai(temperatureMumbai);
    list.add(rec);
}


text:
Q: ES - Sub buckets based on values in bucket property rather than document values I am new to ElasticSearch and I am trying to bucket objects coming from a search by hierarchical categories.
I apologize in advance for the length of the question but I wanted to give ample samples and information to make the need as clear as possible.
What I am Trying to Achieve
The problem is that categories form a hierarchy but are represented as a flat array of objects, each with a depth. I would like to generate an aggregation that would bucket by category and category depth.
Here is a simplified mapping for the document that contains only the minimum data:
{
  "mappings": {
    "_doc": {
      "properties": {
        "categoriesList": {
          "properties": {
            "depth": {
              "type": "long"
            },
            "title": {
              "type": "text",
              "fields": {
                "keyword": {
                  "type": "keyword",
                  "ignore_above": 256
                }
              }
            }
          }
        }
      }
    }
  }
}

Here is a simplified sample document:
{
  "_index": "x",
  "_type": "_doc",
  "_id": "wY0w5GYBOIOl7fi31c_b",
  "_score": 22.72073,
  "_source": {
    "categoriesList": [
      {
        "title": "category_lvl_2_2",
        "depth": 2
      },
      {
        "title": "category_lvl_2",
        "depth": 2,
      },
      {
        "title": "category_lvl_1",
        "depth": 1
      }
    ]
  }
}

Now, what I am trying to achieve is to get hierarchical buckets of categories based on their depth i.e. I want to have a bucket that contains all titles of categories of depth 1 across all hits, then another bucket (or sub-bucket with the titles of just the categories of depth 2 across all hits, and so on.
Something like:
"aggregations": {
    "depth": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": 1,
          "doc_count": 47,
          "name": {
            "doc_count_error_upper_bound": 0,
            "sum_other_doc_count": 0,
            "buckets": [
              {
                "key": "category_lvl_1",
                "doc_count": 47,
                "depth_1": {
                  "doc_count": 47
                }
              }
            ]
          }
        },
        {
          "key": 2,
          "doc_count": 47,
          "name": {
            "doc_count_error_upper_bound": 0,
            "sum_other_doc_count": 0,
            "buckets": [
              {
                "key": "category_lvl_2_1",
                "doc_count": 47
              },
              {
                "key": "category_lvl_2_2",
                "doc_count": 33
              }
            ]
          }
        }
      ]
    }
  }

What I have tried
At first I tried to simply create nested aggregations as follows:
  "aggs": {
    "depth": {
      "terms": {
        "field": "categoriesList.depth"
      },
      "aggs": {
        "name": {
          "terms": {
            "field": "categoriesList.title.keyword"
          },
        }
      }
    }
  }

This, of course, did not give what I wanted. It basically gave me buckets whose keys were by depth but that contained all titles of all categories no matter what their depth was; the contents were the same. Something like the following:
  "aggregations": {
    "depth": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": 1,
          "doc_count": 47,
          "name": {
            "doc_count_error_upper_bound": 0,
            "sum_other_doc_count": 0,
            "buckets": [
              {
                "key": "category_lvl_1",
                "doc_count": 47
              },
              {
                "key": "category_lvl_2_1",
                "doc_count": 33
              },
              {
                "key": "category_lvl_2_2",
                "doc_count": 15
              }
            ]
          }
        },
        {
          "key": 2,
          "doc_count": 47,
          "name": {
            "doc_count_error_upper_bound": 0,
            "sum_other_doc_count": 0,
            "buckets": [
              {
                "key": "category_lvl_1",
                "doc_count": 47
              },
              {
                "key": "category_lvl_2_1",
                "doc_count": 33
              },
              {
                "key": "category_lvl_2_2",
                "doc_count": 15
              }
            ]
          }
        }
      ]
    }
  }

Then I tried to see if a filtered aggregation would work by trying to filter one sub-bucket by value of depth 1:
  "aggs": {
    "depth": {
      "terms": {
        "field": "categoriesList.depth"
      },
      "aggs": {
        "name": {
          "terms": {
            "field": "categoriesList.title.keyword"
          },
          "aggs": {
            "depth_1": {
              "filter": {
                "term": {
                  "categoriesList.depth": 1
                }
              }
            }
          }
        }
      }
    }
  }

This gave the same results as the simple aggregation query above but with an extra nesting level that served no purpose.
The question
With my current understanding of ES, what I am seeing makes sense: it goes over each document from the search and then creates buckets based on category depth but since each document has at least one category with each depth, the entire categories list is added to the bucket.
Is what I am trying to do possible with ES? I get the feeling that this will not work because I am basically trying to bucket and filter the properties used by the initial bucketing query rather than working on the document properties.
I could also bucket myself directly in code since we are getting the categories results but I wanted to know if it was possible to get this done on ES' side which would save me from modifying quite a bit of existing code we have.
Thanks!

A: Based on sramalingam24's comment I did the following to get it working:
Create an index with a mapping specifying nested types
I changed the mapping to tell ES that the categoriesList property was a nested object. To do so I created a new index with the following mapping:
{
  "mappings": {
    "_doc": {
      "properties": {
        "categoriesList": {
          "type": "nested",
          "properties": {
            "depth": {
              "type": "long"
            },
            "title": {
              "type": "text",
              "fields": {
                "keyword": {
                  "type": "keyword",
                  "ignore_above": 256
                }
              }
            }
          }
        }
      }
    }
  }
}

Reindex into the new index
Then I reindex from the old index to the new one.
{
  "source": {
    "index": "old_index"
  },
  "dest": {
    "index": "index_with_nested_mapping"
  }
}

Use a nested aggregation
Then I used a nested aggregation similar to this:
{
  "aggs": {
    "categories": {
      "nested": {
        "path": "categoriesList"
      },
      "aggs": {
        "depth": {
          "terms": {
            "field": "categoriesList.depth"
          },
          "aggs": {
            "sub-categories": {
              "terms": {
                "field": "categoriesList.title.keyword"
              }
            }
          }
        }
      }
    }
  }
}

Which gave me the results I desired:
{
  "aggregations": {
    "categories": {
      "doc_count": 96,
      "depth": {
        "doc_count_error_upper_bound": 0,
        "sum_other_doc_count": 0,
        "buckets": [
          {
            "key": 2,
            "doc_count": 49,
            "sub-categories": {
              "doc_count_error_upper_bound": 0,
              "sum_other_doc_count": 0,
              "buckets": [
                {
                  "key": "category_lvl_2_1",
                  "doc_count": 33
                },
                {
                  "key": "category_lvl_2_2",
                  "doc_count": 15
                }
              ]
            }
          },
          {
            "key": 1,
            "doc_count": 47,
            "sub-categories": {
              "doc_count_error_upper_bound": 0,
              "sum_other_doc_count": 0,
              "buckets": [
                {
                  "key": "category_lvl_1",
                  "doc_count": 47
                }
              ]
            }
          }
        ]
      }
    }
  }
}


text:
Q: How to create a dynamic function name using Elixir macro? I want to create a function names dynamically. I wrote this macro
defmacro generate_dynamic(name) do
  quote do
    def add_(unquote(name)) do
    end
  end
end

And I used it like this:
defmodule AnotherModule do
  generate_dynamic :animal
end

Now, I only get AnotherModule.add_ function defined, whereas I expect AnotherModule.add_animal function.

A: I did this same sort of thing in a gist to try and mimic Ruby's attr_accessor:
defmodule MacroExp do
  defmacro attr_accessor(atom) do
    getter = String.to_atom("get_#{atom}")
    setter = String.to_atom("set_#{atom}")
    quote do
      def unquote(getter)(data) do
        data |> Map.from_struct |> Map.get(unquote(atom))
      end
      def unquote(setter)(data, value) do
        data |> Map.put(unquote(atom), value)
      end
    end
  end

  defmacro attr_reader(atom) do
    getter = String.to_atom("get_#{atom}")
    quote do
      def unquote(getter)(data) do
        data |> Map.from_struct |> Map.get(unquote(atom))
      end
    end
  end
end

defmodule Calculation do
  import MacroExp
  defstruct first: nil, second: nil, operator: :plus

  attr_accessor :first   # defines set_first/2 and get_first/1
  attr_accessor :second  # defines set_second/2 and get_second/1
  attr_reader :operator  # defines set_operator/2 and get_operator/1

  def result(%Calculation{first: first, second: second, operator: :plus}) do
    first + second
  end
end

https://gist.github.com/rcdilorenzo/77d7a29737de39f0cd84

A: To achieve this, you can prepend :add_ to the name before unquoting. Also, the parentheses after the method name in this case are required to prevent ambiguities. This should do the trick:
defmacro generate_dynamic(name) do
  quote do
    def unquote(:"add_#{name}")() do
      # ...
    end
  end
end

A: Sometimes, as a useful shortcut, you can achieve the same result inline, without writing a macro using an unquote fragment.
defmodule Hello do
  [:alice, :bob] |> Enum.each fn name ->
    def unquote(:"hello_#{name}")() do
      IO.inspect("Hello #{unquote(name)}")
    end
  end
end

Hello.hello_bob    # => "Hello bob"
Hello.hello_alice  # => "Hello alice"


text:
Q: Using localStorage for switching CSS style sheets with persistence I am having an issue wherein I am trying to use the localStorage method to store user preferences when switching between two separate style sheets, one blue and one dark.
I just can't get it to function, and I seem to be unable to call the storage function let alone set it.
Here is the javascript and html code.
<head>
<title>Welcome Page</title>
<link id= "pagestyle" rel="stylesheet" type="text/css" href="blue.css" title= "blue"/>
  <link id= "pagestyle" rel="stylesheet" type="text/css" href="../blue.css" title= "blue" />

<link href='http://fonts.googleapis.com/css?family=Ubuntu' rel='stylesheet' type='text/css'>

<script type= "text/javascript">
    function swapstylesheet(sheet) {
        document.getElementById('pagestyle').setAttribute('href',sheet);
    }

    function storebackground(swapstylesheet) {
        localStorage.setItem(swapstylesheet);
    }

    function loadbackground(args) {

        document.getElementById("pagestyle").innerHTML = localStorage.swapstylesheet;
        //code
    }
</script>
<div id ="cssbutton">
    <button id= "blueb"  value = "bluev" class ="css1" onclick = "swapstylesheet('blue.css')">Blue</button>
    <button id= "darkb" value = "darkv" class ="css2" onclick = "swapstylesheet('dark.css')">Dark</button>

Anyone can tell me what I am doing wrong?

A: You didn't show where you're calling loadbackground from but your localStorage code needs to be like below:
 function storebackground(swapstylesheet) {
    localStorage.setItem('sheetKey', swapstylesheet); //you need to give a key and value
 }

 function loadbackground(args) {
    document.getElementById("pagestyle").innerHTML = localStorage.getItem('sheetKey'); //get value by key
    //or document.getElementById('pagestyle').setAttribute('href', localStorage.getItem('sheetKey'));
}

A: Don't switch stylesheets.  Create 1 stylesheet and give the body a class.  This would be done better via less or sass.
body.blue { background-color: #006; }
body.dark { background-color: #000; }
body.blue a { color: #fff; }
body.dark a { color: #600; }

Then make all your specific changes as sub styles.  Store the class in a cookie, or storage and when you load the page check if it exists and add the class to the body.


text:
Q: PHP 5.4 warning: Illegal string offset 'field' I am not understand why this code gives warning for php 5.4? How can i solve this problem?
function load(){
    for ($i = 0, $n = sizeof($messages); $i < $n; $i++){
        $this->add($messages[$i]['field'], $messages[$i]['type']);
    }
}

function add($field, $type){
    $this->messages[] = array('field' => $field, 'type' => $type);
}

A: Try this
function load(){
            for ($i = 0, $n = sizeof($messages); $i < $n; $i++){
                if(isset($messages[$i]['field']) && isset($messages[$i] ['field'])){
                $this->add($messages[$i]['field'], $messages[$i]['type']);
                }
               }
           }

function add($field, $type){
        $this->messages[] = array('field' => $field, 'type' => $type);
        }


text:
Q: What's an alternative to "Take the leap"? In the context of making or executing upon a big decision: What is a simple phrase that is similar to "Take the leap" or "Go for it"?

A: You take the bull by the horns, when you make a challenging or difficult decision. Metaphorically, this is not something that can be done halfway.

take the bull by the horns Fig. to confront a problem head-on and deal
   with it openly.
It's time to take the bull by the horns and get this job done.

McGraw-Hill Dictionary of merican Idioms and Phrasal Verbs. © 2002

In addition, the advertising slogan for Nike always come to mind in response to a situation where there's indecision or doubt:  Just do it!

A: carpe diem
It is a catchy little Latin phrase that means "seize the day."
http://www.dictionary.com/browse/carpe-diem


text:
Q: Is there a standard pattern for updating android views? I'm currently building an android application with quite a few different connected activities. In each activity I've got a private updateView() method to update all the textViews and stuff on that screen. This gets called in the onResume() method so that each time the activity comes to the front it's views will be updated.
Is this the right way to do things or is there a more standard pattern for keeping your views in sync with the data?

A: I think that you are doing this correctly. onResume would be the perfect time to update your views, I assume you are only updating if there is actually new data to be displayed?
If retrieving the data during the updateView method takes a long time then you should do it in an AsyncTask to avoid clogging the UI Thread which will make your app hang.
In fact any data retrieval like getting data from the web or reading from your apps database should be done in an AsyncTask. This is because even if your data retrieval seems to take milliseconds on your device it may conceivably take longer on another, less powerful device.


text:
Q: Probability of product of two exponential variable If there are two independent exponential variables X and Y.
$Pr(X < a)$ and $Pr(X < b)$ then what will be the probability $Pr(X*Y<c)$?

A: Well, for strictly positive values $a,b$: $$\mathsf P(X<a) ~=~\int\limits_{\{x~:~0\leqslant x<a\}} f_X(x)\operatorname d x~=~F_X(a)\\\mathsf P(Y<b) ~=~\int\limits_{\{y~:~0\leqslant y<b\}} f_Y(y)\operatorname d y ~=~F_Y(b)$$
And since we have independence
$$\mathsf P(XY<c) ~{= \mathop{\iint\qquad\qquad}\limits_{\{(x,y)~:~0\leqslant x~,~0\leqslant y<c/x\}} f_X(x)f_Y(y)\operatorname d (x,y)}$$
Where $f_X(\bullet),f_Y(\bullet)$ are the probability density functions of your independent exponential random variables (also $F_X(\bullet), F_Y(\bullet)$ are the cummulative distribution functions).
The rest is substitution and integrating over the indicated interval.

A: If $X$ and $Y$ have rate parameters $\mu$ and $\lambda$, so their pdf's are $f_X(x) = \mu e^{-\mu x}$ and $f_Y(y) = \lambda e^{-\lambda y}$ for $x,y \ge 0$, then for $c > 0$,
$$ Pr(X Y < c) = \int_0^\infty dx \int_0^{c/x} dy\; \mu \lambda e^{-\mu x - \lambda y} = 1-2\,\sqrt { {c\mu\lambda}}{{ K}_{1}\left(2\,\sqrt {
c\mu\lambda}\right)}
$$
where $K_1$ is a modified Bessel function of the second kind.


text:
Q: Use \r, \n in OGNL expression in Camel I'm using XML based Java Spring DSL for Camel routes and need to do a very simple replace in a string. Normally it works ok with an OGNL expression. But if i use special characters like \r or \n - it fails to be executed as java expression.
Example which doesn't work:
<setBody>
    <simple>${body.replace("\n","\r\n")}</simple>
</setBody>

Any ideas how to pass these chars to the java in a correct way ?
Camel version is 2.12, just in case.

A: I have currently implemented this type of logic in a sample program I made earlier like below:
from("source location")
    .setBody(body().regexReplaceAll("\r", ""))
    .to("a cool place");


text:
Q: Why is "Cat" not working in my C-shell that I built? When I type Cat hello.txt for example, it just reads Cat and starts almost an inner loop and everything I type is just repeated. single commands such as "ls" work fine. I think it has to do with there being a space. What am I doing wrong?
Thanks
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#define MAX_LENGTH 1024
#define DELIMS " \t\r\n"
int main(int argc, char *argv[])
{
    char line[MAX_LENGTH];
    int loop = 1;
    int pid;
    int status;
    char *cmd;

    while (1)
    {
        status = 0;

        printf("Ben$ ");
        // printf("%d\n",pid );
        if (!fgets(line, MAX_LENGTH, stdin))
        {
            loop = 0;
            break;
        }
        pid = fork();

        if (pid == 0)
        {

            if ((cmd = strtok(line, DELIMS)))
            {
                // Clear errors
                errno = 0;

                if (strcmp(cmd, "cd") == 0)
                {
                    char *arg = strtok(0, DELIMS);

                    if (!arg)
                        fprintf(stderr, "cd missing argument.\n");
                    else
                        chdir(arg);

                }
                else if (strcmp(cmd, "exit") == 0)
                {
                    _Exit(3);
                    printf("should have exited\n");

                }
                else
                {
                    char *name[] = {
                        "/bin/bash",
                        "-c",
                        line, NULL
                    };
                    execvp(name[0], name);

                }

                if (errno)
                    perror("Command failed");
            }
        }
        else
        {
            // printf("%d\n",pid );
            waitpid(pid, &status, 0);

            if (status != 0)
            {
                break;
            }

        }

    }

    return 0;
}

A: You call strtok, which "breaks up" a string by replacing the first of the delimiter characters with a '\0'.  So, if line has this before the strtok call:
{ 'c', 'a', 't', ' ', 'h', 'e', 'l', 'l', 'o',
  '.', 't', 'x', 't', '\n', '\0', <junk...> }

then it has this in it afterward:
{ 'c', 'a', 't', '\0', 'h', 'e', 'l', 'l', 'o',
  '.', 't', 'x', 't', '\n', '\0', <junk...> }

Thus, you invoke "/bin/bash" with "-c", "cat", NULL.
Aside: the variable loop is not tested; in a shell, cd and exit commands must be implemented in the parent, not after a fork call; and as @shanet noted, you could just execvp the command directly (for non-pipeline, no redirection) commands, though you will have to split up the arguments first.  (Real shells need to do their own file and pipe handling as well, but obviously that's something for later. :-) )


text:
Q: Creating an alias in linux to remove mutiple files So I'm new to Linux and I'm looking for a push in the right direction with this.
I have to create a couple of new aliases in a new text file, (which I did, using pico) expect for one that has been giving me trouble.
What I have to do is, create an alias with the name "rm" that will prompt once before removing more than three files, or when removing recursively.
Any advice is much appreciated.

A: alias rm='rm -I'

Assuming that your rm is relatively current. This isn't really a programming question, though.
Edit: It's a question about reading man-pages (or failing to do so).


text:
Q: How to check whether Suhosin is installed? I'm not familiar with Suhosin (never used it) but if possible I need to check using PHP whether it is installed. This is for part of an installer that I'm writing. Thanks.

A: simply write a php file in your document root like  <?php  phpinfo(); ?>
it will print all the information related to php installation just find for the "suhosin" block in it is installed on your server you can find the block with all the values set for it.

A: extension_loaded('suhosin');

PHP docs for extension_loaded.
If the extension doesn't load, it may still be available through dl:
if (!extension_loaded('suhosin')) {
    if (!dl('suhosin.so')) {
        // Extension not loaded.
        return false;
    }
}

// Extension loaded.
return true;

A: To detect the Suhosin Extension use extension_loaded() no matter if it is dynamically loaded or statically compiled:
extension_loaded('suhosin');

To detect the Suhosin-Patch, check for the constant presence:
constant("SUHOSIN_PATCH");

A: You can test if a configuration open is set for Suhosin:
$isSuhosinInstalled = ini_get('suhosin.session.max_id_length') !== '';


text:
Q: Change or Add ROW label $counters = @(
"\Processor(_Total)% Processor Time" ,"\Memory\Available MBytes"
,"\Paging File(_Total)% Usage" ,"\LogicalDisk(*)\Avg. Disk Bytes/Read"
,"\LogicalDisk()\Avg. Disk Bytes/Write" ,"\LogicalDisk(*)\Avg. Disk sec/Read"
,"\LogicalDisk()\Avg. Disk sec/Write" ,"\LogicalDisk(*)\Disk Read Bytes/sec"
,"\LogicalDisk()\Disk Write Bytes/sec" ,"\LogicalDisk(*)\Disk Reads/sec"
,"\LogicalDisk()\Disk Writes/sec"
)
(Get-Counter $counters).countersamples
`Im new to powershell and found this script to get server performance. When you execute this command, you will get a column called "Path". How would you rename this or add new row for betters understanding.
Example labels:
Read Latency = "\LogicalDisk()\Disk Reads/sec"
Write Latency = "\LogicalDisk()\Disk Writes/sec"
I have tried foreach but they will be executed one at a time and will not be accurate data. They need to be executed at once to capture the performance of the server at that exact time for all performance counters. Our environment are still running on PS 5.1 (including windows 2016/2019).


text:
Q: PHP anonymous recursive callback call I am having the following class :
class MyClass
{
    public $groups = array(
        'callback' => '',
        'name'     => ''
    );

    public function group($callback)
    {
        $this->groups['callback'] = $callback;
        return $this;
    }

    public function name($name)
    {
        $this->groups['name'] .= $name . '/';
    }

    public function execute()
    {
        // this callback should keep calling it self till no more callbacks in
        $this->groups['callback']($this);
    }
}

This is what i am trying to achieve.
$myclass = new MyClass;

$myclass->group(function($m){ // main group

    $m->group(function($a){ // sub group

        $a->group(function($b){  // 2nd sub group

            echo 'sub 2';

        })->name('sub-2');

        echo 'sub 1';

    })->name('sub-group');

    echo 'group 1';

})->name('group-1');

$myclass->execute();

But can't seem to get the sub groups to be called recursively can only get the first level executed which is group 1;


text:
Q: List comprehension using index values How do I turn the below for loop into a list comprehension?
I have a list of lists. Each sublist has a number in index 4 position, and I would like to find a way to add them up. The for loop works, but I'd like a one-line solution with list comprehension.
frequencies = []

for row in table:
    frequencies.append(int(row[4]))
sum(frequencies)

Here's my attempt:
frequencies = [sum(i) for i, x in enumerate(table) if x == 4]

However, the result is an empty object.
In[52]: total
Out[52]: []

A: Do it like this -
frequencies = sum([int(row[4]) for row in table])

The approach you're using is a little different from what you want to achieve.


text:
Q: Any idea how I can change this jQuery into ES6? I have this block of code
$( ".asset-type-select" ).change(function() {
  var selectedEventType = this.options[this.selectedIndex].value;
  if (selectedEventType == "all") {
    $('.asset-type div').removeClass('hidden');
  } else {
    $('.asset-type div').addClass('hidden');
    $('.asset-type div[data-eventtype="' + selectedEventType + '"]').removeClass('hidden');
  }
});

and it needs to be vanilla JS/ES6 as jQuery no longer exists on the system... Any ideas how I can revert it
I've got it this far, but it's not working :/
const assetChoose = document.getElementById('asset-type-select');
const filterBy = document.querySelectorAll('.asset-type div');
assetChoose.addEventListener('change', () => {
  const selectedAssetType = assetChoose.options[assetChoose.selectedIndex].value;
  if (selectedAssetType === 'all') {
    for (let i = 0; i < filterBy.length; i++) { // eslint-disable-line no-plusplus
      filterBy[i].classList.remove('hidden');
    }
  } else {
    for (let j = 0; j < filterBy.length; j++) { // eslint-disable-line no-plusplus
      filterBy[j].classList.add('hidden');
    }
    const hiddenDiv = document.querySelectorAll(`.asset-type div[data-assettype="${selectedAssetType}"]`);
    for (let k = 0; k < hiddenDiv.length; k++) { // eslint-disable-line no-plusplus
      hiddenDiv[k].classList.remove('hidden');
    }
  }
});

<select id="asset-type-select">
  <option value="all" selected="selected">All</option>
  <option value="Science">Science</option>
  ...
</select>

    ...

...

Frankly, I think this could be better, but I'm at a loss... I'd like to get rid of the i++ type references as well.
The code seems to run but doesn't throw any errors, but also doesn't do what it's intended to do either...
Any ideas would be greatly appreciated.

A: this code works for me
<select id="asset-type-select">
 <option value="all" selected="selected">All</option>
 <option value="Science">Science</option>
 ...
</select>

...

...


text:
Q: Changing Figure Size in Sympy.mpmath.plot I hope this question isn't too elementary. I've searched extensively for a solution but haven't discovered one yet.
I've recently begun using Jupyter Notebook with Sympy to take notes and do my homework in my Calculus II class (and what a HUGE BENEFIT this has been!).
However, my sole problem with it is that I'm unable to figure out how to configure the size (i.e. the dimensions in pixels) of the plot figure.
It's easy enough to do using matplotlib directly (matplotlib.pyplot.figure() specifically), but I'm using the Sympy.mpmath.plotmodule because Sympy works much better for the symbolic manipulation we're doing in this course. I know Sympy has its own plotting module, but the one in mpmath seems easier to use so far (with the exception of this one issue, of course).
However, I've looked through the mpmath documentation and have googled the problem repeatedly, without a solution.
How can you change the size of the image that results from plotting a function using the mpmath API?

A: You may try changing the size of sympy's plots via pyplot's rcParams:
import sympy
import matplotlib.pyplot as plt
%matplotlib inline

plt.rcParams['figure.figsize'] = 10, 3
sympy.mpmath.plot([cos, sin], [-4, 4])


text:
Q: Changing multiple images with JQuery So here is the JQuery I am using
jQuery(document).ready(function($) {
    $('.ltwitch').each(function () {
        var tnick = $(this).data('tnick');
        var span = $(this).next();
        $.getJSON("https://api.twitch.tv/kraken/streams/"+tnick+".json?callback=?", function(c) {
            if (c.stream == null) {
                span.html("Offline");
            } else {
                span.html("Online");
            }
        });
    });
});

And the HTML that was with it when I found it
IFStudios (...)

RoosterTeeth (...)
Now what I want to do, I have HTML that looks like this

Basically when a channel becomes live I want to switch the img src from the image I have it set to, to the same image with -online on the end. So I can have multiple pictures on the website, but I can have the images change dependent on who is live and who isn't.
So if I have

When her channel goes live, it will turn to

Or if it was
 <img src="img/portfolio/carrot.png"

it would turn to
 <img src="img/portfolio/carrot-online.png"

Any ideas?

A: Try the below code
jQuery(document).ready(function($) {
    $('.ltwitch').each(function () {
        var tnick = $(this).data('tnick');
        var span = $(this).next();
        $.getJSON("https://api.twitch.tv/kraken/streams/"+tnick+".json?callback=?", function(c) {
            var img = $(img-selector);
            var source = img.attr('src');
            if (c.stream != null) {
                // Online
                if(source.indexOf('.png') != -1){
                    source = source.replace(".png", "-online.png");
                    img.attr('src',source);
                }
            }
            else{
                // Offline
                source.replace("-online", "");
                img.attr('src',source);
            }
        });
    });
});

Note: You have to pass the correct image selector to $(img-selector). Also call the same function again for refreshing


text:
Q: Apache mod_sed - "OutputSed not allowed here" in htaccess I'm trying to use mod_sed to replace strings in HTML, using .htaccess.
According to the mod_sed docs, this should be possible as the module supports use in .htaccess.
However, I can't see any examples online that actually do this (instead of using the module inside <Location> tags), and the following .htaccess contents triggers 500 OutputSed not allowed here in the server log:
FilterDeclare APPBASEHREF
FilterProvider APPBASEHREF Sed "%{Content_Type} = 'text/html'"
FilterChain APPBASEHREF
OutputSed "s/<base data-app-base-href href=\"/<base href=\"%{ENV:BASE}/ni"
SetOutputFilter OutputSed;DEFLATE

I'd put my experience with Apache server config at "low", so I'd appreciate it if anyone could point out any potential errors.
Is mod_sed docs just incorrect, or do I need to explicitly enable mod_sed to work in .htaccess, or is something wrong with permissions somewhere?
For reference, I'm on Apache v2.4.29 and AllowOverride All is set in the virtual host file.


text:
Q: drop down list in django shows object for foreign key field I am using models to auto generate a form in Django. Here is my code
class Dependent(models.Model):
    primarystudentid = models.ForeignKey('Students', models.DO_NOTHING, db_column='PrimaryStudentID')  # Field name made lowercase.
    dependentname = models.CharField(db_column='DependentName', max_length=100)  # Field name made lowercase.
    relation = models.CharField(db_column='Relation', max_length=50)  # Field name made lowercase.
    def __str__(self):
        return "{0}".format(self.primarystudentid)

primarystudentid is an auto generated field in Students table. I have tried unicode and str. But i am still getting the value of primarystudentid in dropdown as Students object. I tried a lot of things from stack overflow and other sites but it doesn't seem to be working.
Python version Python 2.7.13
Django version 1.9.13
Any help is appreciated!

A: You need to update the str or unicode method of your Student table (not the Dependent table), and return name or whatever field you want to show in the dropdown.
Example:
class Student(models.Model):
    name = models.CharField(max_length=50)

def __str__(self):
    return u'{0}'.format(self.name)

P.S: Please update the name of field dependentname to just name, because it is quite obvious that if this is in the Dependent model then it's the name of dependent.

A: you need to reference the field in the other table.
dep = Dependent.objects.first()
dep.primarystudentid.name # This would be the name

in your str example
def __str__(self):
    return "{0}".format(self.primarystudentid.name)

just worth noting that this can easily cause a lot of extra queries to be generated.


text:
Q: JQuery .on("click") event not triggering I am currently working on a "split-screen" web application. It uses selenium to retrieve the html of a webpage then sends and displays it in iframes using srcdoc. I want, when someone presses a link in the first screen, for the second screen to display a simple "Loading" while an ajax request is sent to the backend to retrieve the html of the url (as it might take a couple of seconds to load) then display the retrieved html in the second screen.
To do so, I "inject" a JQuery event code into the src code of the first screen in the backend (shown below) right before the end body tag (as the retrieved source is a string, that is easy to do). The second screen has id="oframe".
For some reason, the JQuery event wont trigger. Any ideas why?

Note that the event works if I only have
parent.document.getElementById("oframe").srcdoc="
or
$.ajax({
            url: "/newOrigin",
            data: {"link":link},
            type: "POST",
            success: function(response) {
                 parent.document.getElementById("oframe").srcdoc=response.site;},
            error: function(error) {console.log(error);}
        });

inside the if statement.Together they stop the event, I know that because preventDefault() is not working (link opens in a new tab).

Example  tag:
cookies

A: You cannot have a line break in the middle of JavaScript string.
So, put this:
parent.document.getElementById("oframe").srcdoc="

Loading
";

all on one line:
parent.document.getElementById("oframe").srcdoc="p>Loading
";


text:
Q: CLLocationCoordinate2DMake behaviour ok im trying to deal with something strange and i don't know if its just me
im trying to use
 CLLocationCoordinate2D newCoord = CLLocationCoordinate2DMake(54.607313, -1.292585);

if i write it like this it works fine, but if i try to use
CLLocationCoordinate2D newCoord = CLLocationCoordinate2DMake(lat, lng);

(lat and lng values passed from previous vc) i does not work. i can log out the numbers and they are the same.
society[1703:307] 1.052294
society[1703:307] 1.052294
am i doing something silly?

A: ok , yes i was doing something stupid, and just to point it out remember when working with coords the "-" is a very important symbol
:O


text:
Q: How can you find whether an environment variable exists at compile time? I don't particularly know if this is a good thing or not but I used to work somewhere where everyone had an environment variable like YOUR_NAME on their computer. Then if you had a bit of debug code that was only of interest to yourself you could wrap it in #if defined( YOUR_NAME ) and it wouldn't even be compiled for someone else unless they changed it to #if defined( YOUR_NAME ) || defined( THEIR_NAME ).
I've just tried to do this myself and it doesn't seem to work, restarted Visual Studio and then the computer but it still doesn't seem to be picked up. Was there more to this hack than I understood or does it require a specific version/option selected in Visual Studio?

A: Building on what IanH set, from withing Visual Studio,

*

*right click the project  name in the Project Explorer panel.

*Choose Property Page

*Open Configuration Properties, C/C++, Preprocessor (that is the VS2008 location but it should be similar in vs2005)

*For the Preprocessor Definitions, there should be WIN32;_DEBUG and prehaps others.  At the end, add ;YOUR_NAME="$(YOUR_NAME)"

*Note that it get very upset is there is a space in the evar YOUR_NAME,

A: Rather scary concept, but if you really want to do so you could specify a preprocesor definition in Visual Studio project settings like this: YOUR_NAME=$(USERNAME) since windows machines have a %USERNAME% environment variable defined. If you are interested in using this from command line (or within a Makefile for that matter) you could specify /DYOUR_NAME=%USER_NAME% as an argument for cl.exe.
PS: Even though what you described is possible, you might want to reconsider this practice. If you would want certain functionality to be enabled only in certain scenarios, consider using some other switches that enable/disable certain features, e.g: registry values, configuration files and any other flag you would find reasonable. This would at least maintain the possibility for the same binaries to be tested by all of your colleagues. This in fact is a rather common practice, used sometimes in environments with continuous integration in place, so that you could integrate early and still not make others wait for you to finish or fix the feature. This conditional switch is of course removed as soon as the feature is even remotely seems to be ready to play well with the rest of your product.

A: Edit: I have't tried my answer, because I'm currently working under Eclipse/Linux and thus can't test it, but I think it should work. (The corresponding Linux / Eclipse variant works fine).

You have to pass the environment variable in the compiler invocation (or build script / Makefile) as a /D %YOUR_NAME% switch.
To avoid problems when %YOUR_NAME% is not defined, you could add another String in front of it, e.g.
/D NAME_%YOUR_NAME%

Then you can use
#if defined(NAME_identitycrisisuk)

or whatever your username is.

A: You can't. C Preprocessor definitions have absolutely nothing to do with environment variables. You would have to have each user having their own project files, and each user would need to add an additional define directive to the project file itself, which would be passed to cl.exe as a /D switch.

A: I just did a quick test and apparently VC++ 2005 doesn't automatically convert environment variables to preprocessor symbols (they are two completely different things).
So you would need to change some setting so that each user gets his symbol defined.


text:
Q: Could I use an external ssd connected to router via usb 3 and to computer va SMB as my plex server? I have an external SSD attached via USB 3 to my router, an ASUS RT-AC series.
I don't have any of the special file sharing services offered by 'Asuswrt' on at all, no Aicloud or anything, just the local file share through SMB.
It connects fine to my Mac Mini mid 2011 (upgraded) and I can play media off of it nicely.
Question is, does anybody use SMB specifically with macOS for their Plex Server?
Or anyone think of a reason I shouldn't?
Thanks in advance.

A: There is no reason this cannot or will not work, just be aware that all the time Plex Server is running you must have the library available or Plex will simply empty its library and re-add it when the share comes back.
By the looks of it Plex prefers to have the media locally, but most operating systems allow you to "map" SMB shares into your local system which will fill that requirement.
Plex even has a guide Mounting Network Resources which describes the process of mounting the share and setting it to appear when your machine logs in.
After that it is as simple as adding a new library in Plex and pointing it at the location of your files. The files will then be indexed and shared.


text:
Q: New XCode install not showing simulators Brand new XCode 13.3 install on MBP M1. Developers tools are installed as well.
When I click on Xcode->Preferences-Components I get the screen below...

Clicking on "Check and Install now" button spins for about 2 seconds and then stops.  Nothing happens.  Any ideas?
This area is new to me. I am trying to set up Appium for mobile testing and I need the simulators to access from.


text:
Q: Breakpoints working in lldb but not VS Code I have the following setup in my launch.json file to debug native code compiled from c++ using clang. I am able to use lldb on the command line and debug it, including setting breakpoints. But when I try setting a breakpoint using Visual Studio Code, I get the error message:
Unable to open 'foo.cc': no provider for .///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////tests/foo/foo.cc.
{
        "name": "(lldb) test",
        "type": "cppdbg",
        "request": "launch",
        "program": "./prog-test",
        "args": [],
        "stopAtEntry": false,
        "cwd": "${workspaceFolder}",
        "externalConsole": false,
        "MIMode": "lldb"
}

On the lldb prompt, I simply run breakpoint set -f foo.cc -n 18 and it works.
I am guessing this is something about the path to the file in VS Code. But changing the working directory around did not help. It is currently set to the directory from which lldb on the commandline works.
Any ideas would be appreciated!


text:
Q: Keep an image centered regardless of screen size? Here's a fiddle I created. I want the decorative ornament to always stay in the middle of the screen. I can't figure out how to do it. I tried wrapping it up in a div but that didn't work either.
HTML

CSS
.border-top {
background: url("http://i.imgur.com/Txoi4sd.png") no-repeat;
clear: both;
display: block;
height: 47px;
margin-bottom: 50px;
width: 100%;
}

A: what about  http://jsfiddle.net/wkkrnqqx/1/
.border-top {
    background: url("http://i.imgur.com/Txoi4sd.png") no-repeat;
    display: block;
    height: 47px;
    margin-bottom: 50px;
    width: 100%;
    background-position:50% 0;
}

A:

.border-top {
    background: url("http://i.imgur.com/Txoi4sd.png") center center no-repeat;
    clear: both;
    display: block;
    height: 47px;
    margin-bottom: 50px;
    width: 100%;
}

This will probably do the trick.
Reference: http://www.w3.org/TR/css3-background/#the-background


text:
Q: Candlestick chart add_trace(mode="markers") gives wrong output I'm currently building a financial dashboard with dash and plotly. I added the following candlestick chart to my dashboard:
    candlestick_chart = go.Figure(data=[go.Candlestick(x=financial_data["Date"],
                                     open=financial_data['Open'],
                                     high=financial_data['High'],
                                     low=financial_data['Low'],
                                     close=financial_data['Close'])])

Which returns the expected result:

I would like to be able to highlight specific candlesticks (e.g. with a marker)
I tried to achieve this with the add_trace function and the following code:
    candlestick_chart.add_trace(
    go.Scatter(
        x=["2020-07-01"],
        y=["350"],
        mode="markers",
        marker=dict(symbol="6")

    )
)

But this ruins the chart.

Why does that happen? How can I fix this?
EDIT: ADDED DATASOURCE
I got the data from https://finance.yahoo.com/quote/SPY/history?p=SPY with Time period set to max.
I parsed the data the following way:
    start = "2000-01-01"
end = "2021-01-01"

# Get a pandas dataframe
datapath = ('D:\\Programmieren\\trading_bot\\etf_data\\SPY.csv')

financial_data = pd.read_csv(datapath,
                             parse_dates=True,
                             index_col=0)

financial_data= financial_data.loc[start:end]
# Process data
financial_data = financial_data["2020-06-01":"2021-01-01"]

financial_data.reset_index(inplace=True)

EDIT2: SYSTEM AND VERSIONS
My packages have the following versions:
print(pd.__version__) # 1.2.3
print(plotly.__version__) # 4.14.3

And I am working with:

*

*Windows 10 Home (64-Bit)

*Python 3.9

*Python 3.8 doesn't work either

A: This could be regarded as a version issue, but the core problem is that you've defined your y-value as a list of strings with ["350"] instead of a number like [350] in:
go.Scatter(
        x=["2020-07-01"],
        y=["350"],
        mode="markers",
        marker=dict(symbol="6")

    )
)

Different versions of plotly seem to handle this differently. Simply remove the quotation marks to let Plotly interpret the value as a number instead to produce this:

Complete code with sample data
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import pandas as pd

# data
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')
df=df.tail(10)

# set up figure with values not high and not low
# include candlestick with rangeselector
fig = go.Figure(go.Candlestick(x=df['Date'],
                open=df['AAPL.Open'], high=df['AAPL.High'],
                low=df['AAPL.Low'], close=df['AAPL.Close']))

fig.add_trace(
    go.Scatter(
        x=["2017-02-10"],
        y=[135],
        mode="markers+text",
        marker=dict(symbol='triangle-down-open', size = 12),
#         text = 'important',
#         textposition = 'middle right'

    )
)

fig.show()

A: When I run your code I get the following error:
ValueError:
Invalid value of type 'builtins.str' received for the 'symbol' property of scatter.marker
    Received value: '6'

The 'symbol' property is an enumeration that may be specified as:
  - One of the following enumeration values:
        [0, 'circle', 100, 'circle-open', 200, 'circle-dot', 300,
        'circle-open-dot', 1, 'square', 101, 'square-open', 201,
        'square-dot', 301, 'square-open-dot', 2, 'diamond', 102,
        'diamond-open', 202, 'diamond-dot', 302,
        'diamond-open-dot', 3, 'cross', 103, 'cross-open', 203,
        'cross-dot', 303, 'cross-open-dot', 4, 'x', 104, 'x-open',
        204, 'x-dot', 304, 'x-open-dot', 5, 'triangle-up', 105,
        'triangle-up-open', 205, 'triangle-up-dot', 305,
        'triangle-up-open-dot', 6, 'triangle-down', 106,
        'triangle-down-open', 206, 'triangle-down-dot', 306,
        'triangle-down-open-dot', 7, 'triangle-left', 107,
        'triangle-left-open', 207, 'triangle-left-dot', 307,
        'triangle-left-open-dot', 8, 'triangle-right', 108,
        'triangle-right-open', 208, 'triangle-right-dot', 308,
        'triangle-right-open-dot', 9, 'triangle-ne', 109,
        'triangle-ne-open', 209, 'triangle-ne-dot', 309,
        'triangle-ne-open-dot', 10, 'triangle-se', 110,
        'triangle-se-open', 210, 'triangle-se-dot', 310,
        'triangle-se-open-dot', 11, 'triangle-sw', 111,
        'triangle-sw-open', 211, 'triangle-sw-dot', 311,
        'triangle-sw-open-dot', 12, 'triangle-nw', 112,
        'triangle-nw-open', 212, 'triangle-nw-dot', 312,
        'triangle-nw-open-dot', 13, 'pentagon', 113,
        'pentagon-open', 213, 'pentagon-dot', 313,
        'pentagon-open-dot', 14, 'hexagon', 114, 'hexagon-open',
        214, 'hexagon-dot', 314, 'hexagon-open-dot', 15,
        'hexagon2', 115, 'hexagon2-open', 215, 'hexagon2-dot',
        315, 'hexagon2-open-dot', 16, 'octagon', 116,
        'octagon-open', 216, 'octagon-dot', 316,
        'octagon-open-dot', 17, 'star', 117, 'star-open', 217,
        'star-dot', 317, 'star-open-dot', 18, 'hexagram', 118,
        'hexagram-open', 218, 'hexagram-dot', 318,
        'hexagram-open-dot', 19, 'star-triangle-up', 119,
        'star-triangle-up-open', 219, 'star-triangle-up-dot', 319,
        'star-triangle-up-open-dot', 20, 'star-triangle-down',
        120, 'star-triangle-down-open', 220,
        'star-triangle-down-dot', 320,
        'star-triangle-down-open-dot', 21, 'star-square', 121,
        'star-square-open', 221, 'star-square-dot', 321,
        'star-square-open-dot', 22, 'star-diamond', 122,
        'star-diamond-open', 222, 'star-diamond-dot', 322,
        'star-diamond-open-dot', 23, 'diamond-tall', 123,
        'diamond-tall-open', 223, 'diamond-tall-dot', 323,
        'diamond-tall-open-dot', 24, 'diamond-wide', 124,
        'diamond-wide-open', 224, 'diamond-wide-dot', 324,
        'diamond-wide-open-dot', 25, 'hourglass', 125,
        'hourglass-open', 26, 'bowtie', 126, 'bowtie-open', 27,
        'circle-cross', 127, 'circle-cross-open', 28, 'circle-x',
        128, 'circle-x-open', 29, 'square-cross', 129,
        'square-cross-open', 30, 'square-x', 130, 'square-x-open',
        31, 'diamond-cross', 131, 'diamond-cross-open', 32,
        'diamond-x', 132, 'diamond-x-open', 33, 'cross-thin', 133,
        'cross-thin-open', 34, 'x-thin', 134, 'x-thin-open', 35,
        'asterisk', 135, 'asterisk-open', 36, 'hash', 136,
        'hash-open', 236, 'hash-dot', 336, 'hash-open-dot', 37,
        'y-up', 137, 'y-up-open', 38, 'y-down', 138,
        'y-down-open', 39, 'y-left', 139, 'y-left-open', 40,
        'y-right', 140, 'y-right-open', 41, 'line-ew', 141,
        'line-ew-open', 42, 'line-ns', 142, 'line-ns-open', 43,
        'line-ne', 143, 'line-ne-open', 44, 'line-nw', 144,
        'line-nw-open']
  - A tuple, list, or one-dimensional numpy array of the above

To fix this, I simply just gave the marker value one of the values that it instructed for example I did marker=dict(symbol='triangle-down-open') which returned a graph like this:

The code for the graphs is:
candlestick_chart = go.Figure(data=[go.Candlestick(x=financial_data["Date"],
                                 open=financial_data['Open'],
                                 high=financial_data['High'],
                                 low=financial_data['Low'],
                                 close=financial_data['Close'])])

candlestick_chart.add_trace(
    go.Scatter(
        x=["2020-07-01"],
        y=["350"],
        mode="markers",
        marker=dict(symbol='triangle-down-open')

    )
)

candlestick_chart.show()


text:
Q: How do I use iTunes LP with different song files? I have an iTunes LP that I want to be able to use with alternate versions of the song files (higher/lower bitrate), but the iTunes LP isn't able to play the new versions of the files. What's missing?

A: After some poking around and searching more, I found the answer, and it lies in ordinarily invisible data and metadata.
The upshot is that iTunes LP primarily references files based on their XID. In order to assign the correct XIDs to the new files in iTunes, do the following (on a Mac):

*

*Right-click (control-click) the .itlp file in Finder, and Show Package Contents

*Open the manifest.xml file in a text editor (TextEdit is fine)

*Open a Terminal window and enter the command defaults write com.apple.iTunes booklet-authoring-mode 1

*Quit and relaunch iTunes

*Find the <library_item> tag in the XML file for the first song, and copy its xid attribute (the part between the quotation marks)

*Right-click (control-click) the first song in iTunes, and Get Info

*Because of step 3, the Grouping field will have changed to XID. Paste the XID copied in step 5 into this field

*Repeat steps 5 and 7 for each track (if they're listed sequentially in iTunes, you can use the "Next" button in the Get Info window to accomplish this more quickly

*Once you've assigned the XIDs for all tracks, run the iTunes LP file and everything should work

*Quit iTunes

*Open the Terminal window from before and enter the command defaults write com.apple.iTunes booklet-authoring-mode 0

*Quit Terminal

*Reopen iTunes, and you're all set and back to normal

(These instructions were gathered from Apple documentation here and here)