text:
Q: Find duplicates in a stringlist very fast what is the fastest way to find duplicates in a Tstringlist. I get the data I need to search for duplicates in a Stringlist. My current idea goes like this :
    var  TestStringList, DataStringList  : TstringList;

    for i := 0 to  DataStringList.Items-1 do
    begin
        if TestStringList.Indexof(DataStringList[i])< 0 < 0 then
        begin
          TestStringList.Add(DataStringList[i])
        end
        else
        begin
           memo1.ines.add('duplicate item found');
        end;

    end;
   ....

A: Just for completeness, (and because your code doesn't actually use the duplicate, but just indicates one has been found): Delphi's TStringList has the built-in ability to deal with duplicate entries, in it's Duplicates property. Setting it to dupIgnore will simply discard any duplicates you attempt to add. Note that the destination list has to be sorted, or Duplicates has no effect.
TestStringList.Sorted := True;
TestStringList.Duplicates := dupIgnore;

for i := 0 to  DataStringList.Items-1 do
   TestStringList.Add(DataStringList[i]);
Memo1.Lines.Add(Format('%d duplicates discarded',
                      [DataStringList.Count - TestStringList.Count]));

A quick test shows that the entire loop can be removed if you use Sorted and Duplicates:
TestStringList.Sorted := True;
TestStringList.Duplicates := dupIgnore;

TestStringList.AddStrings(DataStringList);
Memo1.Lines.Add(Format('%d duplicates discarded',
                      [DataStringList.Count - TestStringList.Count]));

See the TStringList.Duplicates documentation for more info.

A: I think that you are looking for duplicates. If so then you do the following:
Case 1: The string list is ordered
In this scenario, duplicates must appear at adjacent indices. In which case you simply loop from 1 to Count-1 and check whether or not the elements of index i is the same as that at index i-1.
Case 2: The string list is not ordered
In this scenario we need a double for loop. It looks like this:
for i := 0 to List.Count-1 do
  for j := i+1 to List.Count-1 do
    if List[i]=List[j] then
      // duplicate found

There are performance considerations. If the list is ordered the search is O(N). If the list is not ordered the search is O(N2). Clearly the former is preferable. Since a list can be sorted with complexity O(N log N), if performance becomes a factor then it will be advantageous to sort the list before searching for duplicates.

A: Judging by the use of IndexOf you use an unsorted list. The scaling factor of your algorithm then is n^2. That is slow. You can optimize it as David shown by limiting search area in the internal search and then the average factor would be n^2/2 - but that still scales badly.
Note: scaling factor here makes sense for limited workloads, say dozen or hundreds of strings per list. For larger sets of data asymptotic analysis O(...) measure would suit better. However finding O-measures for QuickSort and for hash-lists is a trivial task.
Option 1: Sort the list. Using quick-sort it would have scaling factor n + n*log(n) or O(n*log(n)) for large loads.

*

*Set Duplicates to accept

*Set Sorted to True

*Iterate the sorted list and check if the next string exists and is the same

*http://docwiki.embarcadero.com/Libraries/XE3/en/System.Classes.TStringList.Duplicates

*http://docwiki.embarcadero.com/Libraries/XE3/en/System.Classes.TStringList.Sorted
Option 2: use hashed list helper. In modern Delphi that would be TDictionary<String,Boolean>, in older Delphi there is a class used by TMemIniFile
You iterate your stringlist and then check if the string was already added into the helper collection.
The scaling factor would be a constant for small data chunks and O(1) for large ones - see http://docwiki.embarcadero.com/Libraries/XE2/en/System.Generics.Collections.TDictionary.ContainsKey

*

*If it was not - you add it with "false" value.

*If it was - you switch the value to "true"

For older Delphi you can use THashedStringList in a similar pattern (thanks @FreeConsulting)

*

*http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/delphivclwin32/IniFiles_THashedStringList_IndexOf.html

A: Unfortunately it is unclear what you want to do with the duplicates. Your else clause suggests you just want to know whether there is one (or more) duplicate(s). Although that could be the end goal, I assume you want more.
Extracting duplicates
The previously given answers delete or count the duplicate items. Here an answer for keeping them.
procedure ExtractDuplicates1(List1, List2: TStringList; Dupes: TStrings);
var
  Both: TStringList;
  I: Integer;
begin
  Both := TStringList.Create;
  try
    Both.Sorted := True;
    Both.Duplicates := dupAccept;
    Both.AddStrings(List1);
    Both.AddStrings(List2);
    for I := 0 to Both.Count - 2 do
      if (Both[I] = Both[I + 1]) then
        if (Dupes.Count = 0) or (Dupes[Dupes.Count - 1] <> Both[I]) then
          Dupes.Add(Both[I]);
  finally
    Both.Free;
  end;
end;

Performance
The following alternatives are tried in order to compare performance of the above routine.
procedure ExtractDuplicates2(List1, List2: TStringList; Dupes: TStrings);
var
  Both: TStringList;
  I: Integer;
begin
  Both := TStringList.Create;
  try
    Both.AddStrings(List1);
    Both.AddStrings(List2);
    Both.Sort;
    for I := 0 to Both.Count - 2 do
      if (Both[I] = Both[I + 1]) then
        if (Dupes.Count = 0) or (Dupes[Dupes.Count - 1] <> Both[I]) then
          Dupes.Add(Both[I]);
  finally
    Both.Free;
  end;
end;

procedure ExtractDuplicates3(List1, List2, Dupes: TStringList);
var
  I: Integer;
begin
  Dupes.Sorted := True;
  Dupes.Duplicates := dupAccept;
  Dupes.AddStrings(List1);
  Dupes.AddStrings(List2);
  for I := Dupes.Count - 1 downto 1 do
    if (Dupes[I] <> Dupes[I - 1]) or (I > 1) and (Dupes[I] = Dupes[I - 2]) then
      Dupes.Delete(I);
  if (Dupes.Count > 1) and (Dupes[0] <> Dupes[1]) then
    Dupes.Delete(0);
  while (Dupes.Count > 1) and (Dupes[0] = Dupes[1]) do
    Dupes.Delete(0);
end;

Although ExtractDuplicates3 marginally performs better, I prefer ExtractDuplicates1 because it reeds better and the TStrings parameter provides more usability. ExtractDuplicates2 performs noticeable worst, which demonstrates that sorting all items afterwards in a single run takes more time then continuously sorting every single item added.
Note
This answer is part of this recent answer for which I was about to ask the same question: "how to keep duplicates?". I didn't, but if anyone knows or finds a better solution, please comment, add or update this answer.

A: This is an old thread but I thought this solution may be useful.
An option is to pump the values from one stringlist to another one with the setting of TestStringList.Duplicates := dupError; and then trap the exception.
var  TestStringList, DataStringList  : TstringList;
TestStringList.Sorted := True;
TestStringList.Duplicates := dupError;

for i := 0 to  DataStringList.Items-1 do
begin
    try
      TestStringList.Add(DataStringList[i])
    except
        on E : EStringListError do begin
            memo1.Lines.Add('duplicate item found');
        end;
    end;
end;

....
Just note that the trapping of the exception also masks the following errors:
There is not enough memory to expand the list, the list tried to grow beyond its maximal capacity, a non-existent element of the list was referenced. (i.e. the list index was out of bounds).

A: function TestDuplicates(const dataStrList: TStringList): integer;
begin
  with TStringlist.create do begin
    {Duplicates:= dupIgnore;}
    for it:= 0 to DataStrList.count-1 do begin
      if IndexOf(DataStrList[it])< 0 then
        Add(DataStrList[it])
      else
        inc(result)
    end;
    Free;
  end;
end;


text:
Q: Bash Square Bracket Expansion So the official bash manual states that "For example, the regular expression '[0123456789]' matches any single digit, whereas '[^()]' matches any single character that is not an opening or closing parenthesis,", copied a link at the bottom of this question, for context.
So I tested it every which way I could think of, to try and do the "negate" part of this, but I could not get it to work:
$ cat test
a line
b line
c line
d line
$ grep [^abc] test
a line
b line
c line
d line
$ grep '[^abc]' test
a line
b line
c line
d line
$ grep '[^(abc)]' test
a line
b line
c line
d line
[$ grep [^(abc)] test
bash: syntax error near unexpected token `('

https://www.gnu.org/software/grep/manual/html_node/Character-Classes-and-Bracket-Expressions.html
I was expecting just line D to be shown

A: [^abc] matches any character which is not a, b, or c.
It matches a line because it includes  , l, i, n, and e, none of which are the excluded characters.
To ensure that no character in the string matches any in the list you would need grep '^[^abc]*$' test

A: To stick with the bash tag on the question, here's a pure Bash option that takes advantage of extglob (which is mostly enabled by default).
while IFS= read -r line; do
  [[ "$line" = *([^abc]) ]] && printf '%s\n' "$line"
done < test

redpajama_set_name: RedPajamaStackExchange


text:
Q: If a velocity vector $\vec {v(t)}$ has constant length, must its acceleration also have constant length? I'm not really sure how arbitrary acceleration is (like, if I can just choose an acceleration that makes the velocity vector erratically change directions while still keeping its length the same, or if such a thing would be called acceleration), so I've been kind of confused with this problem.
We've been learning about centripetal acceleration and circular motions in class, so that's probably related- but I don't have a clear idea how.
Can someone help me out?

A: No. The velocity has a constant length iff
$$
0 = \frac{d}{dt} \langle \vec v, \vec v \rangle
= 2  \left \langle \frac{d\vec v}{dt}, \vec v \right\rangle
$$hence iff the velocity is orthogonal to the acceleration. But the length of the acceleration is not constrained.


text:
Q: count each element inside jsonObject using java stream I have a json Structure like this
[{
                "startAt": 1617605301292,
                "endAt": 1617605317095,
                "duration": 15803,
                "selection": {
                    "selected.Speed": "0",
                    "selected.Low": "65535",
                    "selected.Fast": "7173",
                    "selected.medium": "5"
                },
                "details": {
                    "phase": [{
                        "value": "2",
                        "timestamp": 1617605301316
                    }]
                }
            },....]

I need the count of every item inside selection  object.
For Example

*

*0 occurred 4 times

*65535 occurred 2 times

*7173 occurred 3 times

*5 occurred 1 times

this is what I have done so far
Map<String, Long> counted = jObj.stream()
                        .filter(y -> ((Map<String, Object>) y.get("selection")).containsKey("selected.Speed"))
                        .map(x -> {
                            String Speed = String.valueOf(((Map<String, Object>) x.get("details"))
                                    .get("selected.Speed"));
                            return Speed;
                        }).collect(Collectors.toList()).stream()
                        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

so from this I am able to get the count of a single key but not the every key inside json Object.
Pardon if this is a very basic question, I am new to the stream.
TIA

A: Stream#mapMulti
If you're using java-16, you can already make use of Stream#mapMulti for this use case. Here is how to solve it with this. If you're not using java-16 yet, scroll further to find the traditional solution to the problem
Map<String, Long> counted = jObj.stream()
        .map(x -> (Map<String, Object>) x.get("details"))
        .filter(x -> x.containsKey("selected.Speed"))
        .map(Map::values)
        .mapMulti((Collection<Object> collection, Consumer<String> consumer) -> {
            collection.forEach(element -> consumer.accept(String.valueOf(element)));
        })
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

With this solution, you don't have the overhead of an extra Stream creation

Traditional approach
Normally this should solve it for you using Stream#flatMap, Map#values then List#stream and mapping every entry to a String
Map<String, Long> counted = jObj.stream()
                        .filter(y -> ((Map<String, Object>) y.get("details")).containsKey("selected.Speed"))
                        .flatMap(x -> ((Map<String, Object>)x.get("details"))
                                                          .values()
                                                          .stream()
                                                          .map(String::valueOf))
                        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

You can even use an extra map intermediate operation to avoid casting x.get("details") to a Map<String, Object> twice
Map<String, Long> counted = jObj.stream()
                        .map(x -> (Map<String, Object>) x.get("details"))
                        .filter(x -> x.containsKey("selected.Speed"))
                        .map(Map::values)
                        .flatMap(Collection::stream)
                        .map(String::valueOf)
                        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

Here is the full test I've written for this
List<Map<String, Object>> jObj = new ArrayList<>();
jObj.add(Map.of("details", Map.of("selected.Speed", "0", "selected.Low", "65535", "selected.Fast", "8000", "selected.medium", "5")));
jObj.add(Map.of("details", Map.of("selected.Speed", "1", "selected.Low", "32", "selected.Fast", "8000", "selected.medium", "5")));
jObj.add(Map.of("details", Map.of("selected.Speed", "2", "selected.Low", "32", "selected.Fast", "8000", "selected.medium", "5")));
jObj.add(Map.of("details", Map.of("selected.Speed", "0", "selected.Low", "65535", "selected.Fast", "8000", "selected.medium", "5")));

Map<String, Long> counted = jObj.stream()
        .map(x -> (Map<String, Object>) x.get("details"))
        .filter(x -> x.containsKey("selected.Speed"))
        .map(Map::values)
        .flatMap(Collection::stream)
        .map(String::valueOf)
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

System.out.println("counted = " + counted);

Which prints the expected result
counted = {0=2, 1=1, 2=1, 8000=4, 5=4, 65535=2, 32=2}

A: Here is how you should iterate through your JSON entries and process its fields:
jObj.stream()
    .map(x -> (Map<String, Object>) x.get("selection"))
    .filter(x -> x.containsKey("selected.Speed"))
    .flatMap(values -> values.entrySet().stream()) // flat-mapping entries to group them
    .collect(Collectors.groupingBy(Map.Entry::getKey)) // group entries by their keys: `selected.Low`, `selected.Fast`...
    .entrySet()
    .stream() // streaming through grouped entries
    .map(e -> new AbstractMap.SimpleEntry<>(
            e.getKey(),
            e.getValue().stream().map(Map.Entry::getValue).collect(Collectors.groupingBy(Function.identity(), Collectors.counting())))
    ) // grouping entries values counts
    .collect(Collectors.toList());


text:
Q: Using Filter Function to Find Values Equal to False and Setting to True In my Angular app I have a function that drills down to an array, and then uses a filter function to pull out values in a new array where "completed" is "false".
This is working as expected. And the way our data is, there is always one object in the array that has the property for "completed" set to "false", so I can target [0] to get to that. So, from there all I need to do is set it to "true". However, for whatever reason, how to accomplish this last step is eluding me.
This is my whole function, and what I've tried thus far:
private completeLastWorkflowStatus() {
    let currentService = this.checkDiscipline();
    for (let service of this.client.services) {
        if (service.service === currentService) {
            let targetWorkflow = service.workflow;
            let inCompleteWorkflow = targetWorkflow.filter(workflow => workflow.completed === false);
            console.log(inCompleteWorkflow);
            if (inCompleteWorkflow[0].completed === false) {
                inCompleteWorkflow[0].completed === true;
                console.log(inCompleteWorkflow[0].completed);
            }
        }
    }
}

For the last console.log listed above, I still get "false" as the value. What am I missing here? How can I set the value of "completed" to "true" for this one object in the array?

A: inCompleteWorkflow[0].completed === true; is not assignment. Do inCompleteWorkflow[0].completed = true;


text:
Q: Connect to mysql in a docker container from the host In a nutshell
I want to run mysql in a docker container and connect to it from my host. So far, the best I have achieved is:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

More details
I'm using the following Dockerfile:
FROM ubuntu:14.04.3
RUN apt-get update && apt-get install -y mysql-server

# Ensure we won't bind to localhost only
RUN grep -v bind-address /etc/mysql/my.cnf > temp.txt \
  && mv temp.txt /etc/mysql/my.cnf

# It doesn't seem needed since I'll use -p, but it can't hurt
EXPOSE 3306

CMD /etc/init.d/mysql start && tail -F /var/log/mysql.log

In the directory where there is this file, I can succesfully build the image and run it with:
> docker build -t my-image .
> docker run -d -p 12345:3306 my-image

When I attach to the image, it seems to work just fine:
# from the host
> docker exec -it <my_image_name> bash

#inside of the container now
$ mysql -u root
Welcome to the MySQL monitor.  Commands end with ; or \g.
[...]

However I don't have that much success from the host:
> mysql -P 12345 -uroot
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

Even more details

*

*I've seen that there's a question which looks like mine. However, it isn't the same (and it doesn't have any answers anyway)

*I've seen that there are images dedicated to mysql, but I didn't have more success with them

*My grep -v may feel weird. Admittedly, there may be cleaner way to do it. But when I attach my image, I can observe it actually worked as expected (ie: removed the bind-address). And I can see in the container /var/log/mysql/error.log:

Server hostname (bind-address): '0.0.0.0'; port: 3306
- '0.0.0.0' resolves to '0.0.0.0';
Server socket created on IP: '0.0.0.0'.

A: In your terminal run: docker exec -it container_name /bin/bash
Then: mysql

A: You should inspect the IP address assigned to the running container, and ther connect to that host:
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' <container name or id>
than you can connect with:
mysql -h <IP provided by inspect command> -P <port> -u <user> -p <db name>
https://mariadb.com/kb/en/installing-and-using-mariadb-via-docker/#connecting-to-mariadb-from-outside-the-container

A: I recommend checking out docker-compose.  Here's how that would work:
Create a file named, docker-compose.yml that looks like this:
version: '2'

services:

  mysql:
    image: mariadb:10.1.19
    ports:
      - 8083:3306
    volumes:
      - ./mysql:/var/lib/mysql
    environment:
      MYSQL_ROOT_PASSWORD: wp

Next, run:

$ docker-compose up

Notes:

*

*For latest mariadb image tag see https://hub.docker.com/_/mariadb/
Now, you can access the mysql console thusly:

$ mysql  -P 8083 --protocol=tcp -u root -p

Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 5.5.5-10.1.19-MariaDB-1~jessie mariadb.org binary distribution

Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

Notes:

*

*You can pass the -d flag to run the mysql/mariadb container in detached/background mode.

*The password is "wp" which is defined in the docker-compose.yml file.

*Same advice as maniekq but full example with docker-compose.

A: I do this by running a temporary docker container against my server so I don't have to worry about what is installed on my host.  First, I define what I need (which you should modify for your purposes):
export MYSQL_SERVER_CONTAINER=mysql-db
export MYSQL_ROOT_PASSWORD=pswd
export DB_DOCKER_NETWORK=db-net
export MYSQL_PORT=6604

I always create a new docker network which any other containers will need:
docker network create --driver bridge $DB_DOCKER_NETWORK

Start a mySQL database server:
docker run --detach --name=$MYSQL_SERVER_CONTAINER --net=$DB_DOCKER_NETWORK --env="MYSQL_ROOT_PASSWORD=$MYSQL_ROOT_PASSWORD" -p ${MYSQL_PORT}:3306 mysql

Capture IP address of the new server container
export DBIP="$(docker inspect ${MYSQL_SERVER_CONTAINER} | grep -i 'ipaddress' | grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])')"

Open a command line interface to the server:
docker run -it -v ${HOST_DATA}:/data --net=$DB_DOCKER_NETWORK --link ${MYSQL_SERVER_CONTAINER}:mysql --rm mysql sh -c "exec mysql -h${DBIP} -uroot -p"

This last container will remove itself when you exit the mySQL interface, while the server will continue running.  You can also share a volume between the server and host to make it easier to import data or scripts. Hope this helps!

A: mysql -u root -P 4406 -h localhost --protocol=tcp -p

Remember to change the user, port and host so that it matches your configurations. The -p flag is required if your database user is configured with a password

A: *

*docker run -e MYSQL_ROOT_PASSWORD=pass --name sql-db -p 3306:3306 mysql

*docker exec -it sql-db bash

*mysql -u root -p

A: If your Docker MySQL host is running correctly you can connect to it from local machine, but you should specify host, port and protocol like this:
mysql -h localhost -P 3306 --protocol=tcp -u root

Change 3306 to port number you have forwarded from Docker container (in your case it will be 12345).
Because you are running MySQL inside Docker container, socket is not available and you need to connect through TCP. Setting "--protocol" in the mysql command will change that.

A: For conversion,you can create  ~/.my.cnf file in host:
[Mysql]
user=root
password=yourpass
host=127.0.0.1
port=3306

Then next time just run mysql for mysql client to open connection.

A: The simple method is to share the mysql unix socket to host machine. Then connect through the socket
Steps:

*

*Create shared folder for host machine eg: mkdir /host

*Run docker container with volume mount option docker run -it -v /host:/shared <mysql image>.

*Then change mysql configuration file /etc/my.cnf and change socket entry in the file to socket=/shared/mysql.sock

*Restart MySQL service service mysql restart in docker

*Finally Connect to MySQL servver from host through the socket mysql -u root --socket=/host/mysql.sock. If password use -p option

A: OK. I finally solved this problem.  Here follows my solution used in https://sqlflow.org/sqlflow.
The Complete Solution
To make the demo self-contained, I moved all necessary code to https://github.com/wangkuiyi/mysql-server-in-docker.
The Key to the Solution
I don't use the official image on DockerHub.com https://hub.docker.com/r/mysql/mysql-server.  Instead, I made my own by installing MySQL on Ubuntu 18.04.  This approach gives me the chance to start mysqld and bind it to 0.0.0.0 (all IPs).
For details, please refer to these lines in my GitHub repo.
SQLFLOW_MYSQL_HOST=${SQLFLOW_MYSQL_HOST:-0.0.0.0}

echo "Start mysqld ..."
sed -i "s/.*bind-address.*/bind-address = ${SQLFLOW_MYSQL_HOST}/" \
    /etc/mysql/mysql.conf.d/mysqld.cnf
service mysql start

To Verify My Solution

*

*Git clone the aforementioned repo.

git clone https://github.com/wangkuiyi/mysql-server-in-docker
cd mysql-server-in-docker

*Build the MySQL server Docker image

docker build -t mysql:yi .

*Start MySQL server in a container

docker run --rm -d -p 23306:3306 mysql:yi

*Install the MySQL client on the host, if not yet.  I am running Ubuntu 18.04 on the host (my workstation), so I use apt-get.

sudo apt-get install -y mysql-client

*Connect from the host to the MySQL server running in the container.

mysql --host 127.0.0.1 --port 23306 --user root -proot

Connect from Another Container on the Same Host
We can run MySQL client from even another container (on the same host).
docker run --rm -it --net=host mysql/mysql-server mysql \
   -h 127.0.0.1 -P 13306 -u root -proot

Connect from Another Host
On my iMac, I install the MySQL client using Homebrew.
brew install mysql-client
export PATH="/usr/local/opt/mysql-client/bin:$PATH"

Then, I can access the above Ubuntu host (192.168.1.22).
mysql -h 192.168.1.22 -P 13306 -u root -proot

Connect from a Container Running on Another Host
I can even run MySQL client in a container running on the iMac to connect to the MySQL server in a container on my Ubuntu workstation.
docker run --rm -it --net=host mysql/mysql-server mysql \
    -h 192.168.1.22 -P 13306 -u root -proot

A Special Case
In the case that we run MySQL client and server in separate containers running on the same host -- this could happen when we are setting up a CI, we don't need to build our own MySQL server Docker image.  Instead, we can use the --net=container:mysql_server_container_name when we run the client container.
To start the server
docker run --rm -d --name mysql mysql/mysql-server

To start the client
docker run --rm -it --net=container:mysql mysql/mysql-server mysql \
 -h 127.0.0.1 -P 3306 -u root -proot

A: If you use "127.0.0.1" instead of localhost mysql will use tcp method and you should be able to connect container with:
mysql -h 127.0.0.1 -P 3306 -u root

A: if you running docker under docker-machine?
execute to get ip:
docker-machine ip <machine>

returns the ip for the machine and try connect mysql:
mysql -h<docker-machine-ip>

A: run following command to run container
docker run --name db_name -e MYSQL_ROOT_PASSWORD=PASS--publish 8306:3306 db_name

run this command to get mysql db in host machine
mysql -h 127.0.0.1 -P 8306 -uroot  -pPASS

in your case it is
mysql -h 127.0.0.1 -P 12345 -uroot  -pPASS

A: I was able to connect mysql server 5.7 running on my host using the below command:
mysql -h 10.10.1.7 -P 3307 --protocol=tcp -u root -p

where the ip given is my host ip and 3307 is the port forwaded in mysql docker. After entering the command type the password for mysql. That is it. Now you are connected the mysql docker container from the your host machine.

A: First, see the logs Are there any errors or not.
docker ps -a
docker logs container_name

If there is any error, search for the solution of that particular error, if there are no errors you may proceed to the next step.
Remember after starting your container MySQL take a few minutes to start so run those commands after 3-4 minutes.
docker exec -it container_name bash
# ONCE YOU ARE INSIDE CONTAINER
mysql -u root -p
SHOW DATABASES;
exit

To connect from terminal or command prompt
mysql -h localhost -P 3306 --protocol=tcp -u root -p

A: I have tried the same thing, and I was facing same problem, but I have noticed one thing, whenever I was trying to run docker container with /bin/bash like as below:
docker container run -it --name test_mysql -e MYSQL_ROOT_PASSWORD=password -p 3306:3306 mysql:latest /bin/bash
After hitting the above command, my container getting start but facing the same error" ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)"
Now, I have tried instead of above command, I have used below command:
docker container run -itd --name test_mysql -e MYSQL_ROOT_PASSWORD=password -p 3306:3306 mysql:latest
docker container exec test_mysql /bin/bash
then using the command
mysql -uroot -P3306 -p
then able to connect, Hope This idea will work in your case.
Thanks
Love Arora

A: According to the photos, go to the project -> MySQL -> inspect tab in the docker desktop app and modify the information about the database .env file.
.env file example:
DB_CONNECTION=mysql
DB_HOST=0.0.0.0:3306
DB_PORT=3306
DB_DATABASE=testdb
DB_USERNAME=sail
DB_PASSWORD=password

A: In case this will help somebody:
My prefered solution
add ~/.my.cnf with contents
[client]
user=<yourusername>
password=typethepasswordhere
host=127.0.0.1
port=3306

then from the terminal run >$ mysql and you should get in your sql cmd.
The hardcore alternative
you can also connect like this
docker exec -it containername mysql

To get into the sql cmd
or
docker exec -it contaiinername bash (or sh)

to connect in the container and then run >$ mysql

A: change "localhost" to your real con ip addr
because it's to mysql_connect()


text:
Q: who to bind listviewcolumn header into a column cell in WPF I have the following problem. I want to set a trigger binding it with the path=columnHeader
 <DataTrigger Binding="{DynamicResource ResourceKey=ActualColumnHeader}" Value="1"/>

(i really dont know how to call this...)
my code is something like this:
<ListView Name="LV_Reporte" >
        <ListView.View>
            <GridView x:Name="GV_Reporte">
                <GridViewColumn Header="Order1">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <TextBlock>
                                <TextBlock.Style>
                                    <Style>
                                        <Style.Triggers>
                                            <DataTrigger Binding="{DynamicResource ResourceKey=ActualColumnHeader}" Value="1">

                                            </DataTrigger>
                                        </Style.Triggers>
                                    </Style>
                                </TextBlock.Style>
                            </TextBlock>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>

but the problem is that i really don't know the header of the column, they will be created dynamically, that's why I want to get the header without knowing it.
I hope someone can help me.
Thanks.

A: You might be able to use the StringFormat markup
  <GridViewColumn Header="Order1" DisplayMemberBinding="{Binding Property1, StringFormat=Order1 {0}}"/>


text:
Q: Numpy: How to convert colour matrices into a flattened vector I am trying to segment a colour image using the Mean Shift algorithm using sklearn. I have the following code:
import cv2
import numpy as np
from sklearn.cluster import MeanShift, estimate_bandwidth
from sklearn.datasets.samples_generator import make_blobs
import matplotlib.pyplot as plt
from itertools import cycle
from PIL import Image

image = Image.open('sample_images/fruit_half.png').convert('RGB')
image = np.array(image)

red = image[:,:,2]
green = image[:,:,1]
blue = image[:,:,0]

I have read the image and converted it into a numpy array. I have then extracted each colour channel (R,G,B) so that I can use each as a variable for classification.
I want to convert the colour matrices above into a flattened vector, since I want to use it as a variable for classification. E.g. if the original image was 100x100 then the flattened colour sample matrix would be 10000 x 3.
I don't want to convert each matrix into its own vector; I want to all three colour matrices to be made into one flattened vector.
However, I am not sure what methods I can use to do this. Any insights are appreciated.

A: You can reshape the array to get the desired effect:
img = NP.zeros((100, 100, 3), dtype='int')
img[:,:,0] = NP.arange(0, 10000).reshape(100, 100)
img[:,:,1] = 1
img[:,:,2] = 2

Flatten the image so each colour is a column (ie. 10000 x 3):
img.reshape(-1, 3)

Output:
array([[    0, 22222, 33333],
       [    1, 22222, 33333],
       [    2, 22222, 33333],
       ...,
       [ 9997, 22222, 33333],
       [ 9998, 22222, 33333],
       [ 9999, 22222, 33333]])

To convert to a 3 x 10000 array you can use:
img.transpose(2, 0, 1).reshape(3, -1)

Output:
array([[    0,     1,     2, ...,  9997,  9998,  9999],
       [22222, 22222, 22222, ..., 22222, 22222, 22222],
       [33333, 33333, 33333, ..., 33333, 33333, 33333]])


text:
Q: Scala: how do I access a `Numeric` type's arithmetic operations? class Foo[T](t: T)(implicit int: Numeric[T]) {
  val negated = -t
  val doubled = t + t
  val squared = t * t
  // ...
}

I get red squigglies on all three lines here. What gives?

A: You have an instance of Numeric[T] for some T, and this is where all the goodies are. So you simply need to access your desired methods (e.g. plus):
class Foo[T](t: T)(implicit int: Numeric[T]) {

  val sum = int.plus(t, t)

}

If you use a context bound (the "T : Numeric" syntactic sugar), then:
class Foo[T : Numeric](t: T) {

  val sum = implicitly[Numeric[T]].plus(t, t)

}

If you want to use the shortcut operators such as +, you can simply import the members of your implicit instance:
class Foo[T](t: T)(implicit int: Numeric[T]) {

  import int._
  val sum = t + t

}

A: You need to add an import for the implicit conversion for those functions:
class Foo[T](t: T)(implicit num: Numeric[T]){
  import num._
  val negated = -t
  val doubled = t + t
  val squared = t * t
}

Because in reality they are defined like this (scala source code)
class Ops(lhs: T) {
  def +(rhs: T) = plus(lhs, rhs)
  def *(rhs: T) = times(lhs, rhs)
  // etc
}

You could also ditch the implicit conversion and do this instead:
class Foo[T](t: T)(implicit num: Numeric[T]){
  val negated = num.negate(t)
  val doubled = num.plus(t, t)
  val squared = num.times(t, t)
}


text:
Q: Pickle. EOFError: Ran out of input. Can I recover any information from a corrupt pickle file? Similar questions have been asked numerous times here, but this is slightly different. I have a pickle file that got somehow corrupted. I assume the program crashed during saving. Either way, the file is not empty, and judging by its size has all/most of the information in it. Trying to load is with pickle gets me a standard EOFError: Ran out of input error.
I understand that the file is corrupted and understand how most likely it happened. My question is if there is a way to somehow recover any of it?

A: Maybe try this code. First you will have to pad your file (with zeros) to be at least the original size, can be more (or maybe you can change some code to make this not necessary).
I modified the function _Unpickler.load() to not terminate at exceptions and to return its stack if the unpickling fails. The stack seems to be a list with the names and values of the attributes, so using setattr() you can assign them to a created object.
My example creates an object to pickle if read=False and unpickles the potentially corrupted file if read=True.
import pickle

read = False # run once with False, then corrupt file and change to True

class AClass:
    def __init__(unpickler, a, b, c):
        unpickler.a = a
        unpickler.b = b
        unpickler.c = c

def load(unpickler):
    """Read a pickled object representation from the open file.

    Return the reconstituted object hierarchy specified in the file.
    """
    # Check whether Unpickler was initialized correctly. This is
    # only needed to mimic the behavior of _pickle.Unpickler.dump().
    if not hasattr(unpickler, "_file_read"):
        raise pickle.UnpicklingError("Unpickler.__init__() was not called by "
                              "%s.__init__()" % (unpickler.__class__.__name__,))
    unpickler._unframer = pickle._Unframer(unpickler._file_read, unpickler._file_readline)
    unpickler.read = unpickler._unframer.read
    unpickler.readline = unpickler._unframer.readline
    unpickler.metastack = []
    unpickler.stack = []
    unpickler.append = unpickler.stack.append
    unpickler.proto = 0
    read = unpickler.read
    dispatch = unpickler.dispatch
    try:
        while True:
            key = read(1)
            if not key:
                return unpickler.stack
                #raise EOFError
            assert isinstance(key, pickle.bytes_types)
            try:
                dispatch[key[0]](unpickler)
            except KeyError as e:
                print("KeyError")
                #dispatch[NONE[0]](unpickler)
            except ValueError as e:
                print("ValueError")
    except pickle._Stop as stopinst:
        print("Stop raised")
        print(stopinst.value)
        return stopinst.value

if not read:
    # create an object and save it
    obj = AClass(1,2,3)

    with open("obj.pkl", 'wb') as outFile:
        pickle.dump(obj, outFile, pickle.HIGHEST_PROTOCOL)
else:
    # open the object
     with (open("obj.pkl", "rb")) as inFile:
        try:
            unpickler = pickle._Unpickler(inFile)
            obj = load(unpickler)
        except Exception as e:
            print(e)

# a list will be returned, if the unpickling fails
if isinstance(obj, list):
    l = obj
    print(l)
    i = 0
    obj = AClass(0,0,0)

    while i < len(l)-1:
        setattr(obj, l[i], l[i+1])
        i += 2

print(obj.a, obj.b, obj.c)


text:
Q: Azure Service Fabric - Configure service instance parameters using Powershell Is it possible to inject parameters at run time into a Guest Executable via the Settings.xml file or another means? I have a GuestExecutable which I need to pass some configuration to it - a URL at service creation time.
I need two instances of the service running with different parameters, the service instance information has to differ in terms of a custom parameter I need to pass through . Is this possible using Powershell or, do I need to version the config and create a new version?
Thanks in advance

A: Have you tried the following command: New-ServiceFabricApplication ?
When you create your application manifest file, the parameters will contain replaceable parameters that you set when you register a new application.
An ApplicationManifest.xml example like this:
<?xml version="1.0" encoding="utf-8"?>
<ApplicationManifest ApplicationTypeName="MyAppTypeName" ApplicationTypeVersion="1.0.0" xmlns=...>
  <Parameters>
    <Parameter Name="Web1_InstanceCount" Value="-1" />
    <Parameter Name="ENVIRONMENT_NAME" Value="DEV" />
    <Parameter Name="FEPlacementConstraints" Value="NodeTypeName==FrontEnd" />
  </Parameters>
  <ServiceManifestImport>
    <ServiceManifestRef ServiceManifestName="MyServicePkg" ServiceManifestVersion="1.0.0" />
    <ConfigOverrides />
    <EnvironmentOverrides />
  </ServiceManifestImport>
  <DefaultServices>
    <Service Name="Web1">
      <StatelessService ServiceTypeName="MyServiceType" InstanceCount="[Web1_InstanceCount]">
        <SingletonPartition />
        <PlacementConstraints>[FEPlacementConstraints]</PlacementConstraints>
      </StatelessService>
    </Service>
  </DefaultServices>
</ApplicationManifest>

You would change the settings file using config overrides like this:
<ConfigOverrides>
  <ConfigOverride Name="Config">
    <Settings>
      <Section Name="MyConfigSection">
        <Parameter Name="MySetting" Value="[ENVIRONMENT_NAME]"/>
      </Section>
    </Settings>
  </ConfigOverride>
</ConfigOverrides>

Or you could set environment variables on your service like this:
<EnvironmentOverrides CodePackageRef="Code">
  <EnvironmentVariable Name="ASPNETCORE_ENVIRONMENT" Value="[ENVIRONMENT_NAME]" />
</EnvironmentOverrides>

In my opinion the environment overrides would work better on your case,
  because most guest executable are not flexible on how you can configure them but generally they accept environment variables.

Then you:

*

*Upload your application with: Copy-ServiceFabricApplicationPackage

*Register your application with Register-ServiceFabricApplicationType

*And then you register each new app with the settings you need:

.
New-ServiceFabricApplication -ApplicationName fabric:/myapp/todolist-dev -ApplicationTypeName "MyAppTypeName" -ApplicationTypeVersion "1.0.0" -ApplicationParameter @{Web1_InstanceCount='-1'; ENVIRONMENT_NAME='DEV'}

New-ServiceFabricApplication -ApplicationName fabric:/myapp/todolist-uat -ApplicationTypeName "MyAppTypeName" -ApplicationTypeVersion "1.0.0" -ApplicationParameter @{Web1_InstanceCount='-1'; ENVIRONMENT_NAME='UAT'}

The only down side of this approach is that you would end up with two applications, but don't think would be a problem for you, they will be managed mostly the same way as you would do with a single application.
if you strictly need to run both together on same application, you could do some workarounds:

*

*Using multiple Config packages(don't think would work well with guest executables, but works well with reliable services

*Using the startup script, where you would add the logic to pass the parameter to your startup exe, something like the following:
In your ServiceManifest.xml:
  <CodePackage Name="Code" Version="1.0.0">
    <EntryPoint>
      <ExeHost>
        <Program>start.bat</Program>
        <WorkingFolder>CodePackage</WorkingFolder>
      </ExeHost>
    </EntryPoint>
  </CodePackage>

On the same folder (code) of your .exe, you create the start.bat file with following contents:
myApp.exe %EnvironmentVariableNameSetBySF%


text:
Q: Displaying a DIV larger than its parent DIV I have 2 DIVs  that I want to display on the same row (one on the left, the other on the right).
The left div:
.leftdiv {
    position: relative;
    display: inline-block;
    width : 30%;
}

The right one:
.right-div {
    float : right;
    width : 40%;
    background-color: lime;
}

The left DIV wraps 2 other DIVs: dropdown-content that is displayed after the clicking on dropdiv.
I want dropdown-content to take half (50%) of the page but even when I set its width to 100% I can not get it larger than its parent leftdiv (which must not exceed 30% of the page).
How to fix this?
JS Bin

A: You can set it 50vw (50% of viewport width).

A: Remove position:relative; from .leftdiv and set width: 50%; on .dropdown-content
I think it should work in every browser


text:
Q: Attempting to Run Eigen Benchmark with OpenBLAS Backend I'm trying to run Eigen's benchmark using OpenBLAS.  However, it doesn't appear that OpenBLAS is actually being used.
The script that I'm running is based on the example provided on the Eigen website (https://eigen.tuxfamily.org/index.php?title=How_to_run_the_benchmark_suite).
Is there anything else that needs to be done to properly use OpenBLAS?
Here is a copy of the script that I'm running.
OPENBLAS_LIBRARIES=$OPENBLASDIR/build/lib/libopenblas.so
OPENBLAS_INCLUDES=$OPENBLASDIR/build/include

export EIGEN3DIR=/root/eigen-3.3.9
export BUILDDIR=/root/eigen-tests

mkdir $BUILDDIR
cd $BUILDDIR

cmake $EIGEN3DIR -DEIGEN_BUILD_BTL=ON -DEIGEN3_INCLUDE_DIR=$EIGEN3DIR -DCMAKE_B\
UILD_TYPE=Release -DOPENBLAS_LIBRARIES=$OPENBLAS_LIBRARIES -DOPENBLAS_INCLUDES=\
$OPENBLAS_INCLUDES
cd bench/btl
make -j8
OMP_NUM_THREADS=1 ctest -V```


text:
Q: How to use generated sequence number before persisting? My scenario is very simple. I have an entityID identity field in the @Entity class and the DB (Oracle, which I'm not sure that matters):
@Id
@SequenceGenerator(name="ENTITY_SEQ_GEN", sequenceName="SEQ_GENERIC", allocationSize = 1)
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="ENTITY_SEQ_GEN")
@Column(name="ENTITY_ID")
private long entityID;

I have another field called, let's say, entityReadableID and that should be a String consisting of the stringified entityID concatenated with another String field from the entity.  E.g. if entityID is 1234, entityReadableID may be something like 1234ABC.
My problem is that, as far as I know, the value of entityID is not known before the row is created in the DB but I need to concatenate the entityReadableID using its value.  Is there a way to fetch the value of the sequence generated ID before the row is created in the DB so that I can use it to generate the other ID?  I know I can make it an insert with that field being null and then make an update once I know what entityID is but that solution seems less than elegant.
The way I am hoping Hibernate/Oracle may be able to support this is if Hibernate can somehow "reserve/issue" the next generated value for the entity being processed before the actual persistence, let me know what it is so I can manipulate with it, then at the end persist it.

A: You can get the generated Id before persisting of that entity by not using sequence directly for that entity, I mean use a separated entity for that sequence, so your entity should be something like:
@Entity
@Table(name = "ENTITY"
)
public class EntityClass implements java.io.Serializable {

    private Long entityId;
    private String entityRelatedId;

    public EntityClass() {
    }
    // you may have other constructors

    @Id
    @Column(name = "ENTITY_ID", nullable = false)
    public Long getEntityId() {
        return this.entityId;
    }

    public void setEntityId(Long entityId) {
        this.entityId = entityId;
    }

    @Column(name = "ENTITY_RELATED_ID", length = 50)
    public String getEntityRelatedId() {
        return this.entityRelatedId;
    }

    public void setEntityRelatedId(String entityRelatedId) {
        this.entityRelatedId = entityRelatedId;
    }

}

and the entity for the sequence is something like:
@Entity
@Table(name = "SEQ_GENERIC_TBL"
)
public class SeqGenericTbl implements java.io.Serializable {

    private Long id;

    public SeqGenericTbl() {
    }

    public SeqGenericTbl(Long id) {
        this.id = id;
    }

    @Id
    @SequenceGenerator(name = "ENTITY_SEQ_GEN",
            sequenceName = "SEQ_GENERIC", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ENTITY_SEQ_GEN")
    @Column(name = "ID")
    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

}

Now you can get the Id from the entity of the sequence (persist it, you can rollback that tran or delete it or empty the related table later):
    SessionFactory sf = HBUtil.getSessionFactory();
    Session s = sf.openSession();
    SeqGenericTbl sg=new SeqGenericTbl();
    s.save(sg);

    EntityClass entity1 = new EntityClass();
    entity1.setEntityId(sg.getId());
    //NOW YOU HAVE THE ID WITHOUT PERSISTING THE ENTITY
    System.out.println(entity1.getEntityId());


text:
Q: Executing Code on a local machine from an AWS lambda For a university project I have created a chatbot that calls a lambda function written in Python.
import webbrowser
import boto3
import logging
from urllib.request import Request, urlopen
import json
def handler(event,callback):

function_type = event['currentIntent']['slots']['slotOne']
print('This went to the search')
webbrowser.open('www.google.com')
response = {
    "dialogAction": {
        "type": "Close",
        "fulfillmentState": "Fulfilled",
        "message": {
          "contentType": "SSML",
          "content": "opening google now"
                },
            }
        }
    return response

I can send and receive information in this lambda fine but I am unable to have it open www.google.com using the webbrowser import. This works locally and I was wondering if there was a way to have my lambda trigger code saved locally on my machine, or have the code in my lambda be executed locally when called by my chatbot.


text:
Q: word2vec_basic not working (Tensorflow) I am new to word-embedding and Tensorflow. I am working on a project where I need to apply word2vec to health data.
I used the code for Tensorflow website (word2vec_basic.py). I modified a little this code to make it read my data instead of "text8.zip" and it runs normally until the last step:
num_steps = 100001

with tf.Session(graph=graph) as session:
# We must initialize all variables before we use them.
  tf.initialize_all_variables().run()
  print('Initialized')
  average_loss = 0
  for step in range(num_steps):
    batch_data, batch_labels = generate_batch(
      batch_size, num_skips, skip_window)
    feed_dict = {train_dataset : batch_data, train_labels : batch_labels}
    _, l = session.run([optimizer, loss], feed_dict=feed_dict)
    average_loss += l
    if step % 2000 == 0:
      if step > 0:
        average_loss = average_loss / 2000
      # The average loss is an estimate of the loss over the last 2000 batches.
      print('Average loss at step %d: %f' % (step, average_loss))
      average_loss = 0
    # note that this is expensive (~20% slowdown if computed every 500 steps)
    if step % 10000 == 0:
     sim = similarity.eval()
     for i in range(valid_size):
       valid_word = reverse_dictionary[valid_examples[i]]
       top_k = 8 # number of nearest neighbors
       nearest = (-sim[i, :]).argsort()[1:top_k+1]
       log = 'Nearest to %s:' % valid_word
       for k in range(top_k):
         close_word = reverse_dictionary[nearest[k]]
         log = '%s %s,' % (log, close_word)
       print(log)
  final_embeddings = normalized_embeddings.eval()<code>

This code is exactly the same as the example so I don't think it is wrong. the error It gave is:

KeyError                                  Traceback (most recent call last)
<ipython-input-20-fc4c5c915fc6> in <module>()
     34         for k in xrange(top_k):
     35           print(nearest[k])
---> 36           close_word = reverse_dictionary[nearest[k]]
     37           log_str = "%s %s," % (log_str, close_word)
     38         print(log_str)

KeyError: 2868

I changed the size of the input data but it still gives the same error.
I would really appreciate if someone could give me some advice on how to fix this problem.

A: If the vocabulary size is less than default maximum (50000), you should modify the number.
At the last of step 2, let's modify vocabulary_size to actual dictionary size.
data, count, dictionary, reverse_dictionary = build_dataset(words)
del words  # Hint to reduce memory.
print('Most common words (+UNK)', count[:5])
print('Sample data', data[:10], [reverse_dictionary[i] for i in data[:10]])

#add this line to modify
vocabulary_size = len(dictionary)
print('Dictionary size', len(dictionary))


text:
Q: Create a table using session variable in phpmyadmin I want to create a table with username.
So I have started this session on login page. Given below SQL query is on another page, i have session started over here also. I have kept a if statement, if submitted the query will run or else  mysqli_error().
The content on the page gets submitted and reflects in database but the table is not getting created.
 $t = "CREATE TABLE uname = '".$_SESSION['user_name']."' (
                                year DATE,
                                area_s FLOAT,
                                maxp FLOAT,
                                minp FLOAT,
                                area_e FLOAT,
                                volume FLOAT,
                                percent_change FLOAT
                                )";
                                $u = mysqli_query($dbc,$t);

A: Try "CREATE TABLE ".$_SESSION['user_name']."


text:
Q: For loops with lists? I'm starting to code in python and I came across this code snippet:
for [x, y] in L:
    for ix in range(-1, 2):
        for iy in range(-1, 2):
            cir = pylab.Circle((x + ix, y + iy), radius=sigma,  fc='r')
            pylab.gca().add_patch(cir)

at the line 1 I can not understand what is happening because I had never seen anything like it in another programming language. How this works?
for [x, y] in L:

[x, y] is a list? i dont know.

A: L must be a sequence of lists (or tuples) with two elements, which can be iterated over. So whenever for [x,y] in L: is executed, it picks each item in th sequence one by one and enters into the loop.
let the sequence be  L = [[2,3], [4,5], ['Jeff', 7]]
Now here what will happen when for [x,y] in L: will be executed is :- first list in the sequence [2,3] will be picked up and assigned as x and y respectively. And in the next iteration x and y will get the value 4 & 5 respectively. Like wise in third iteration x will be Jeff and y will be 7.
L = [[2,3], [4,5], ['Jeff', 7]]
count = 0
for [x,y] in L:
    count += 1
    print " Iteration :- %d, \t x :- %s, \t y:- %s" %(count, str(x), str(y))

A: Yes, [x, y] is a list with two elements. For your loop to work, L must be a list (or other iterable data structure) that contains a bunch of lists with two elements. Each time through the loop one of those lists is copied into [x, y], then the individual values of x and y are used in the body of the loop.
Try this and see if it makes sense:
L = [ [1, 2], [3, 4] ]

for [x, y] in L:
    print x
    print y


text:
Q: deduplication of ids in SELECT vs SELECT GROUP BY We have an issue around deduplication when our data is spread across multiple indexes, and there exists a particular id in more than one index.
When doing a straight select, we get X records back, but when we do a group by, we will get counts that add up to more than X.  We have, as stated above, tracked this back to the offending id existing in more than one index.
Sphinx is smart enough to deduplicate the records when doing the straight select, but doesn't when bucketing them for a group by.
Of course it would be better to not have the duplicates, and we'll hopefully find a way to deal with that, but for the time being, I'm wondering if there is a way to tell sphinx to do the deduplication on group by as well?


text:
Q: How can I turn off "eye candy" and make Ubuntu run as fast as possible? For example in Windows XP (and onwards), you can Right Click My PC -> Properties -> Advanced System Settings and disable a whole slew of features that turn off eye candy and make the computer runs blazing fast.

Since I'm running Ubuntu on a Virtual Machine for development purposes I really don't care if my windows have transparency or slide in and out. I just want it to run as fast as possible.
Is this possible in the latest version of Ubuntu?

A: If you want Ubuntu to run as fast as possible, I suggest you choose a lightweight Desktop Environment.
At Phoronix there is a great comparison test that shows How Desktops Impact Performance.
Some examples:

And:

Also we can conclude that Unity 2D is not always faster than 3D:

A: For starters, when you are logging in, click on the Ubuntu logo and select Ubuntu 2D.
Here are some great resources. Take careful note of the ccsm warning for 12.04 and other release-specific info. (Ccsm is the closest thing to the feature in Windows that you mentioned.)
"How can I improve overall system performance?"
How can I configure Unity?


text:
Q: why R discard decimal when as.numeric is applied? Hi to all the community,
I have the following DB:
ID Distance
M1_PRM    54,56
M1_PRM  4147,69
M1_PRM  1723,34

I use the following script to replace "," in "." in Distance as R doesn't like "," (and it works):
mysub<-function(x)(sub(",",".",x))
DB<-(apply(DB, 2,mysub))
DB<-data.frame(DB)

Then I need to convert DB$Distance as.numeric because I need to use
tapply in conjunction with sum, like:
apply(DB$Distance,ID,sum)

When I give
DB$Distance<-as.numeric(DB$Distance)

ID Distance
M1_PRM 54
M1_PRM 4147
M1_PRM 1723

It seems that R discard the decimal!!!
Someone Know what is wrong?
Thanks in advance!

A: Another approach (if you're reading this in from a file):
dat <- read.table(text = "ID Distance
 M1_PRM    54,56
 M1_PRM  4147,69
 M1_PRM  1723,34",header = TRUE,sep = "",dec = ",")
> dat
      ID Distance
1 M1_PRM    54.56
2 M1_PRM  4147.69
3 M1_PRM  1723.34

A: @joran's Answer is the way to go, if you're reading in DB with read.table or read.csv, otherwise, there's type.convert, which takes a dec option.
type.convert(as.character(DB$Distance), dec = ",")
# [1]   54.56 4147.69 1723.34

Discard the as.character, if Distance is already such.

A: R is discarding decimal because you're going in the wrong way in apply call, instead try
> DB$Distance <- as.numeric(sub(",",".",DB$Distance))
> sapply(DB, class)
       ID  Distance
 "factor" "numeric"
> DB
      ID Distance
1 M1_PRM    54.56
2 M1_PRM  4147.69
3 M1_PRM  1723.34

Then use tapply as in:
with(DB, tapply(Distance, ID, sum))

your apply(DB$Distance,ID,sum) will not work, instead use tapply(DB$Distance, DB$ID, sum) because the correct function is tapply and you have to give a numeric verctor and an index, both of them are attached in DB so R won't find ID unless you use with(.) function or DB$ID.
see ?apply and ?tapply.
I just try to give an answer to you according to your post. @joran's answer is the direct way to go if you're importing data from a file, if so, all your problem reduces to use dec = "," in the read.table call


text:
Q: Using Request.Form in ASP.NET MVC 5 I have a view that is bound to the model (EF using ASP.NET MVC 5) and there are three submit buttons to do 3 different things. I was having trouble debugging my logic based on Request.Form["button"] and found that the Request.Form.Keys[2] value contained the string that I was testing for with the 3 different buttons, so I started to use that value directly in my controller logic here:
// This gets post from 3 actions
// 1. Filter Button to filter the index to just the selected project
// 2. All Button to clear the project filter and show all
// 3. Create New button to create a lesson with the project
//    selected in the dropdown (even if not filtered)

var sRequest = Request.Form.Keys[2];

if (sRequest == "CreateNew")
{
    return RedirectToAction("Create", new { pid = lvm.ProjectFilter });
}

var lessons = db.Lessons
                .Include(l => l.Division)
                .Include(l => l.Project)
                .Include(l => l.People);

if (lvm.ProjectFilter != null && sRequest == "Filter") //user pressed the filter button
{
    lessons = lessons.Where(l => l.Project.ID == lvm.ProjectFilter);
}
else if (sRequest == "ClearFilter")
    lvm.ProjectFilter = null;

This works, but I cannot find any documentation that lets me understand what changes will break my logic.
How is the count of Keys derived based on my view structure? It appears that it is a coincidence that I have 3 submit buttons and keys count is 3, but I'm not convinced that my logic will hold up. I did try adding a string submit parameter to the controller post method, but this resulted in the view model not being properly returned and the value of submit was always null.
Here is the view markup:

    <input type="submit" value="Add New Lesson" id="CreateNew" name="CreateNew" class="btn btn-default" />

    <input type="submit" value="Filter" name="Filter" id="Filter" style="float:left" class="btn btn-default" />
    <input type="submit" value="All" name="ClearFilter" id="ClearFilter" style="float:right" class="btn btn-default" />

A: i hope everything is alright. I came across a similar situation and this post helped me.
It's works for me but I thought it was easier to do back in the days of JQuery
hahahhaha
I hope this helps.


text:
Q: Computing limit involving exponential function Could you help me to show that
$$
\lim_{x\rightarrow \infty}\frac{1-e^{-e^{-x}}}{e^{-(x+e^{-x})}}=1
$$

My attemp (incomplete)
$$
\lim_{x\rightarrow \infty}\frac{1-e^{-e^{-x}}}{e^{-(x+e^{-x})}}=\frac{1-e^{0}}{0}=\frac{0}{0}
$$
I apply L'Hopital
$$
\lim_{x\rightarrow \infty}\frac{1-e^{-e^{-x}}}{e^{-(x+e^{-x})}}=\lim_{x\rightarrow \infty}\frac{-e^{-e^{-x}}(-e^{-x})(-1)}{e^{-x-e^{-x}}(-1-e^{-x}(-1))}=\frac{0}{0}
$$
I apply again Hopital and get again $\frac{0}{0}$ ...
What am I doing wrong?

A: Alternatively:
$$\lim_{x\to\infty}\frac{1-e^{-e^{-x}}}{e^{-(x+e^{-x})}}=\lim_{x\to \infty}\frac{1-\frac{1}{e^{e^{-x}}}}{e^{-(x+e^{-x})}}=\lim_{x\to \infty}\frac{e^{e^{-x}}-1}{e^{-x}}=1.$$

A: Folllowing Matthew's hint,
$$\frac{1-e^{-t}}{t\,e^{-t}}=\frac{e^t-1}t$$
and the limit is to $t\to0^+$.

A: Note that since $e^{-x}\to 0$ by standard limits for $t\to 0 \quad \frac{e^t-1}{t}\to 1$
$$\frac{1-e^{ -e^{-x} } }{e^{-(x+e^{-x})}}=\frac{1-e^{ -e^{-x}} }{-e^{-x}}\frac{-e^{-x}}{e^{-(x+e^{-x})}}=\frac{1-e^{ -e^{-x}} }{-e^{-x}}(-e^{-x+x+e^{-x}})=\frac{e^{ -e^{-x}} -1}{-e^{-x}}(e^{e^{-x}})\\=\frac{e^{ t} -1}{t}(e^{-t})\to1\cdot 1 =1$$
Note that by your method from here
$$\lim_{x\rightarrow \infty}\frac{1-e^{-e^{-x}}}{e^{-(x+e^{-x})}}=\lim_{x\rightarrow \infty}\frac{-e^{-e^{-x}}(-e^{-x})(-1)}{e^{-x-e^{-x}}(-1-e^{-x}(-1))}=\lim_{x\rightarrow \infty}\frac{-e^{-x-e^{-x}}}{e^{-x-e^{-x}}(-1+e^{-x})}$$
we can cancel out the $e^{-x-e^{-x}}$ term and obtain
$$\lim_{x\rightarrow \infty}\frac{-\color{red}{e^{-x-e^{-x}}}}{\color{red}{e^{-x-e^{-x}}}(-1+e^{-x})}=\lim_{x\rightarrow \infty}\frac{-1}{-1+e^{-x}}=1$$


text:
Q: How to find length of a rectangular tile when viewing at some angle I have a question on angles.
I have a rectangular tile. when looking straight I can find the width of the tile, but how do I find the apparent width when I see the same rectangular tile at some angle. Below I have attached an image for more clarity. So how do I find y in the image below?

A: It depends on your projection. If you assume orthogonal projection, so that the apparent length of line segments is independent of their distance the way your images suggest, then you cannot solve this, since a rectangle of any aspect ratio might appear as a rectangle of any other aspect ratio by simply aligning it with the image plane and then rotating it around one of its axes of symmetry. So you can't deduce the original aspect ratio from the apparent one, much less the original lengths.


text:
Q: Recuperar datos borrados en SugarCRM estoy tratando de recuperar casos borrados en Sugar y hacer una traza de cual usuario los borro. No estoy seguro si los datos aún existen. He encontrado esta información, pero hasta el momento no ha sido de mucha ayuda:

*

*http://blog.innovsystems.com/sugarcrm/how-retrieve-deleted-records-sugarcrm - No logro que funcione.

*https://community.sugarcrm.com/thread/21135 - Este hilo muestra una consulta, que tampoco funciona para mi caso.

También he tratado de entender como se hace el borrado y he tratado esto, lo que retorna ciertos resultados, pero aún no lo que me interesa:
SELECT cases.id, cases.name, users.first_name, users.title, cases.date_modified
FROM cases
INNER JOIN users ON users.id = cases.modified_user_id
WHERE cases.deleted=1 ORDER BY cases.name ASC;

Veo que el sugar tiene una configuración para purgar las tablas cada mes (en mi caso).

Me gustaría saber si alguien conoce como encontrar los casos borrados, con trazabilidad de quien lo hizo o si en el caso que expongo, definitivamente los casos ya no existen, por lo que no se podrían recuperar.


text:
Q: What does ''we are all there is'' mean?
What is the meaning of this sentence?
There is both "are" and "is" in the sentence.

A: It properly means "We are all that exists".
"All there is" is idiomatic for "all that exists", basically.
"There is nothing apart from us."

A: We are the only ones on this planet. So we are the only ones that can make a difference. There is no one else. The solution is only in our hands.
The author tries to show that we must take this responsibility which no one else but us can carry.


text:
Q: Can I Semicolon Delimit Multiple Rows Into One Column? can i create a sql query that show me only one column but in these column are all the rows with semicolon.
My example:
Select Name from table1 -> Shows
[Name]
Peter
Doug
Mustafa
Emre

And now i want a query that show me that:
[Name]
Peter;Doug;Mustafa;Emre

Can u please help me!?
Greetz

A: create table #user (username varchar(25))

insert into #user (username) values ('Peter')
insert into #user (username) values ('Doug')
insert into #user (username) values ('Mustafa')
insert into #user (username) values ('Emre')

declare @tmp varchar(250)
SET @tmp = ''
select @tmp = @tmp + username + ';' from #user

select SUBSTRING(@tmp, 0, LEN(@tmp))

modify as you need but it works

A: thank you all for the help. Here is my result:
SELECT Name = STUFF((
SELECT ';' + Name
FROM Table1
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')

Greetz


text:
Q: Wordpress audio player has two different styles So, when my page loads a see an audio player that looks like:

But then, when the page finishes loading then it looks like:

I noticed this in Google Chrome, but am not sure whether it's a Google Chrome specific player or how the WordPress audio player looks by default before it loads it's styles. It's a quick thing...I see the grey one for a couple of seconds then WordPress loads and it goes away.
The reason why I'm asking is because I think it looks much better than the WordPress audio player...is there any way to use this one or does anyone know whether this is a Google Chrome specific player or WordPress specific?
I know for a fact it's not the theme or coding because I created everything from scratch, so it came from something elsewhere
All I did to get the player was copy and paste a link from an mp3 file:

Any ideas?
Thanks,
Josh

A: The UI you want is the default browser UI for an <audio> tag, specifically Google Chrome. That tag gets swapped out for a JS based audio player control once the DOM has finished loading. The dark player is the JS based audio player. The light UI you prefer is the browsers default UI.
This means, that the UI you want is only available if the user has the same OS and browser, as well as the same OS settings.
For example, here is your MP3 file in various browsers default audio player implementations on MacOS in the big 3 browsers ( safari, google chrome, firefox ):

Notice my machine is set to dark mode and 2 of the browsers adjusted the players accordingly.
My recommendation is that you keep the WP Media element script/styling, and add your own styles on top. This ensures that your player looks how you want it on all platforms.
If however you wanted to revert to the <audio> tag, you can use this:
add_action('init', 'remove_media_element', 10);
function remove_media_element() {
    wp_deregister_script('wp-mediaelement');
    wp_deregister_style('wp-mediaelement');
}

But keep in mind:

*

*This will also impact <video> tags

*Player appearance will be different on different devices

*Player functionality will differ. E.g. Safari has airplay controls, but Chrome does not, Chrome has a download menu but Safari does not

*Some plugins will stop working. A quick google for that code revealed a user asking why it broken a gallery plugin

*Browsers can and do change these UIs, what you see today may not be what you see tomorrow


text:
Q: Can SPF allow us to securely masquerade as one third party using another third party mailer? We use a paid-for bulk emailing service for our business operations and we've added that service to our own SPF record so that it may masquerade as someone from our domain for what it'll be asked to do for us:
//1.2.3.4 is replaced with our public IP
v=spf1 a mx ip4:1.2.3.4 include:bulkmailer.com ~all

Sometimes we let clients use our platform in a whitelabelled sense, themed to match their own website. They want the emails our platform sends to bear their own domain name instead of ours and classically we've recommended that they add the paid-for bulk mailing service that we use into their own SPF record, so that when we use the bulk mailer, and claim to be someone@theirdomain.com everything is all fine (I've no idea what we send for HELO/EHLO in in this situation):
v=spf1 a mx include:bulkmailer.com ~all

This concerns me though, that essentially then it's opening up the possibility that any other customer of the bulk mailer acquires the ability to pass themselves off as our client. I'm wondering whether an IP should have been included in the SPF we told our customer to apply, that would restrict things such that only we (our public IP) may masquerade as the customer?

A: If you are using a platform such as Mandrill (the system that powers MailChimp), you can verify ownership of the domain, thus preventing other Mandrill accounts from using that domain on the service.
See here for more info:
http://blog.mandrill.com/we-are-making-domain-verification-mandatory.html


text:
Q: javascript: How can I have a string that has code in it that I don't want to be executed? I am building a website that teaches people how to code a website. I am trying to add a feature where they code the exercise into a text box and I then compare that to a string to see if they got it right or not yet. I am running into an issue though when there is quotes inside the strings answer because that then ends the string thus cutting off some of the answer. How can I get around this?
All feedback is greatly appreciated!
Here is an example of a strings answer that screws it up:
var answer = "var greeting="Hello World!"; ";

The second pair of quotes end the string's declaration early. Is there a way to include all of it including the second pair of quotes in the declaration?

A: You can:

*

*Escape the quotes with \:
var answer = "var greeting=\"Hello World!\"; ";
var answer = 'var greeting=\'Hello World!\'; ';

*Use different quotes:
var answer = "var greeting='Hello World!'; ";
var answer = 'var greeting="Hello World!"; ';


text:
Q: Fast algorithm to remove odd elements from vector Given a vector of integers, I want to wrote a fast (not obvious O(n^2)) algorithm to remove all odd elements from it.
My idea is: iterate through vector till first odd element, then copy everything before it to the end of vector (call push_back method) and so on until we have looked through all original elements (except copied ones), then remove all of them, so that only the vector's tail survive.
I wrote the following code to implement it:
  void RemoveOdd(std::vector<int> *data) {

  size_t i = 0, j, start, end;
  uint l = (*data).size();
  start = 0;

  for (i = 0; i < l; ++i)
    {
      if ((*data)[i] % 2 != 0)
      {
      end = i;
      for (j = start, j < end, ++j)
        {
          (*data).push_back((*data)[j]);
        }
      start = i + 1;
      }
    }
  (*data).erase((*data).begin(), i);
  }

but it gives me lots of errors, which I can't fix. I'm very new to the programming, so expect that all of them are elementary and stupid.
Please help me with error corrections or another algorithm implementation. Any suggestions and explanations will be very appreciative. It is also better not to use algorithm library.

A: You can use the remove-erase idiom.
data.erase(std::remove_if(data.begin(), data.end(),
    [](int item) { return item % 2 != 0; }), data.end());

A: You don't really need to push_back anything (or erase elements at the front, which requires repositioning all that follows) to remove elements according to a predicate... Try to understand the "classic" inplace removal algorithm (which ultimately is how std::remove_if is generally implemented):
void RemoveOdd(std::vector<int> & data) {
    int rp = 0, wp = 0, sz = data.size();
    for(; rp<sz; ++rp) {
        if(data[rp] % 2 == 0) {
            // if the element is a keeper, write it in the "write pointer" position
            data[wp] = data[rp];
            // increment so that next good element won't overwrite this
            wp++;
        }
    }
    // shrink to include only the good elements
    data.resize(wp);
}

rp is the "read" pointer - it's the index to the current element; wp is the "write" pointer - it always points to the location where we'll write the next "good" element, which is also the "current length" of the "new" vector. Every time we have a good element we copy it in the write position and increment the write pointer. Given that wp <= rp always (as rp is incremented once at each iteration, and wp at most once per iteration), you are always overwriting either an element with itself (so no harm is done), or an element that has already been examined and either has been moved to its correct final position, or had to be discarded anyway.
This version is done with specific types (vector<int>), a specific predicate, with indexes and with "regular" (non-move) assignment, but can be easily generalized to any container with forward iterators (as its done in std::remove_if) and erase.
Even if the generic standard library algorithm works well in most cases, this is still an important algorithm to keep in mind, there are often cases where the generic library version isn't sufficient and knowing the underlying idea is useful to implement your own version.

A: Given pure algorithm implementation, you don't need to push back elements. In worst case scenario, you will do more than n^2 copy. (All odd data)
Keep two pointers: one for iterating (i), and one for placing. Iterate on all vector (i++), and if *data[I] is even, write it to *data[placed] and increment placed. At the end, reduce length to placed, all elements after are unecessary
remove_if does this for you ;)

A: void DeleteOdd(std::vector<int> & m_vec) {
    int i= 0;
    for(i= 0; i< m_vec.size(); ++i) {
        if(m_vec[i] & 0x01)
       {
             m_vec.erase(m_vec.begin()+i);
             i--;
       }
    }

    m_vec.resize(i);

}


text:
Q: Creating a database programmatically in SQL Server How can I create a database programmatically and what is the minimum information I need to do this?
Please no "SQL Server Management Object API " suggestions.

A: Create database 'Databasename'

A: From the creators:
// your connection string
string connectionString = "Server=(local)\\netsdk;uid=sa;pwd=;database=master";

// your query:
var query = GetDbCreationQuery();

var conn = new SqlConnection(connectionString);
var command = new SqlCommand(query, conn);

try
{
    conn.Open();
    command.ExecuteNonQuery();
    MessageBox.Show("Database is created successfully", "MyProgram",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
    MessageBox.Show(ex.ToString());
}
finally
{
    if ((conn.State == ConnectionState.Open))
    {
        conn.Close();
    }
}

To create in default location with default settings, just:
static string GetDbCreationQuery()
{
    // your db name
    string dbName = "MyDatabase";

    // db creation query
    string query = "CREATE DATABASE " + dbName + ";";

    return query;
}

Or, to create it in a specific location:
static string GetDbCreationQuery()
{
    // your db name
    string dbName = "MyDatabase";

    // path to your db files:
    // ensure that the directory exists and you have read write permission.
    string[] files = { Path.Combine(Application.StartupPath, dbName + ".mdf"),
                       Path.Combine(Application.StartupPath, dbName + ".ldf") };

    // db creation query:
    // note that the data file and log file have different logical names
    string query = "CREATE DATABASE " + dbName +
        " ON PRIMARY" +
        " (NAME = " + dbName + "_data," +
        " FILENAME = '" + files[0] + "'," +
        " SIZE = 3MB," +
        " MAXSIZE = 10MB," +
        " FILEGROWTH = 10%)" +

        " LOG ON" +
        " (NAME = " + dbName + "_log," +
        " FILENAME = '" + files[1] + "'," +
        " SIZE = 1MB," +
        " MAXSIZE = 5MB," +
        " FILEGROWTH = 10%)" +
        ";";

    return query;
}

Even in case the execution fails, give it another try. The db files might have got created.

A: You can either use the SQL Server Management Object API (see task "creating, altering and removing databases"):
 var srv = new Server();
 var db = new Database(srv, "mydb");
 db.Create();

Information on how to get started is here. During SQL server installation you need to install the client SDK, the SMO assemblies are in C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies
Or if you don't want the dependency on these assemblies, you can also simply run DDL statements using ADO.Net (e.g. see this question):
using (var connection = new SqlConnection(myConnectionString))
{
    connection.Open();
    var command = connection.CreateCommand();
    command.CommandText = "CREATE DATABASE mydb";
    command.ExecuteNonQuery();
}

Obviously you need a correct connection string: known sql server instance and a user with CREATE DATABASE permission.

A: You need to open a connection to the server, i.e. you need a server and instance name.
You also need the proper access rights to create a database, so you might need some user name and password depending on the authentication settings on the server.
From the server name and authentication information you can construct a connection string and open a connection.
Then you can use the CREATE DATABASE SQL command (see here on MSDN). The only needed parameter for this command is a database name.

A: You need connection information: server, possibly instance, a user having create database rights on that server/instance and the corresponding password. Then you can use SMO for creating the database. Here is a small PowerShell example that you can very easily "translate" to C#, for example:
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | Out-Null

$s = New-Object Microsoft.SqlServer.Management.Smo.Server($ServerInstance)

# Instantiate the database object and add the filegroups
$db = New-Object Microsoft.SqlServer.Management.Smo.Database($s, $DatabaseName)
$primaryFG = New-Object Microsoft.SqlServer.Management.Smo.FileGroup($db, 'PRIMARY')
$db.FileGroups.Add($primaryFG)

# Create Data file
$syslogname = $DatabaseName + '_SysData'
$dbdsysfile = New-Object Microsoft.SqlServer.Management.Smo.DataFile($primaryFG, $syslogname)
$primaryFG.Files.Add($dbdsysfile)
$dbdsysfile.FileName = $s.MasterDBPath + '\' + $syslogname + '.mdf'
$dbdsysfile.Size = [double](5.0 * 1024.0)
$dbdsysfile.GrowthType = 'KB'
$dbdsysfile.Growth = 10000.0
$dbdsysfile.IsPrimaryFile = 'True'

# Create Log file
$loglogname = $DatabaseName + '_Log'
$dblfile = New-Object Microsoft.SqlServer.Management.Smo.LogFile($db, $loglogname)
$db.LogFiles.Add($dblfile)
$dblfile.FileName = $s.MasterDBLogPath + '\' + $loglogname + '.ldf'
$dblfile.Size = [double](10.0 * 1024.0)
$dblfile.GrowthType = 'KB'
$dblfile.Growth = 10000.0

# Create database with READ_COMMITTED_SNAPSHOT isolation level.
# Other options can be set on $db object before calling Create.
$db.IsReadCommittedSnapshotOn = $true

$db.RecoveryModel = [Microsoft.SqlServer.Management.Smo.RecoveryModel]::Simple
$db.Create()

A: Assuming you have the rights to fire off a CREATE DATABASE statement you can do so as you would any other query.
I should stress that being able to do so requires quite high privileges on the server and this would be restricted to DBAs in QA and Production environments.
For that reason I would make sure that your connection uses Windows Integrated Security.  That way when the appropriate DBA runs your application the app will function as requested.
Once you have created your database you will also need to fire off the T-SQL to create logins and create users. I'm taking it as obvious that CREATE TABLE/VIEW statements will be needed.


text:
Q: Need help changing variable value to then change a displayed message I am new to Javascript, HTML, and CSS so I have been playing with a lot of new functions, objects, styles, tags, etc.
I was working on some basic math. functions and decided to try and create a life system for future reference if I ever made a game.
I want the two buttons to raise and lower the lives variable by 1 at a time. My two issues are that the variable value isn't changing onclick and the message display isn't corresponding with the lives variable, even after the value is changed. I think this is because after it runs the lifetest() function, it displays the necessary message but never checks or runs it again.

    <title>Math Page</title>

<link href="main.css" rel="stylesheet" type="text/css">

<button onclick="mathstuff()">Random number 1-10 (with math.floor </button>

<button onclick="mathstuff2()">Random number 0-1 (with math.random</button>

Please input a number 1-10

<input id="numb" type="text">
<button type="button" onclick="onetoten()">Submit</button>

<button type="button" style="position: absolute; right: 0;" onclick="lives+=" id="uplife">Click to increase life by 1</button>

LIVES

<button type="button" style="position: absolute; right: 0" onclick="lives-=" id="downlife">Click to decrease life by 1</button>

A: Yes. You are right.
You are updating the value in JavaScript but the HTML is not updated.
You have to update the HTML too and it can be done in multiple ways.

*

*Update the HTML onclick

*Repetitively check for changes and update the HTML. Use http://www.w3schools.com/jsref/met_win_setinterval.asp

*Object.observe - http://www.html5rocks.com/en/tutorials/es7/observe/

A: Your javascript is in a big mess, below I have fixed the issues in it
mathstuff = function(){
var x = Math.floor((Math.random() * 10) + 1);
document.getElementById("demo").innerHTML = x;
}
mathstuff2 = function() {
var x = Math.random();
document.getElementById("demo2").innerHTML = x;
}
onetoten = function() {
var x, text;
//get the value of input with id "numb"
x = document.getElementById("numb").value;

//if x is not a number or is less than one or greater than 10
if (isNaN(x) || x < 1 || x > 10){
    text="Not A Valid Input";
}
else {
    text="A Valid Input";
}

document.getElementById("displayonetoten").innerHTML=x+" is "+text;
}

//function gainloselife(){

var lives = 1;
//increase/decrease lives
gainlife = function(){
lives++;
    lifetest();
}

loselife = function(){
lives--;
    lifetest();
}
//lives testing
lifetest = function(){
var message;
if (isNaN(lives) || lives < 0){
//endgame();
message="You are out of lives. Better luck next time. Press Restart to try again.";
}
else {
message="You have at least a life left";
}
    document.getElementById("endingmessage").innerHTML=message;
    document.getElementById('livestext').innerHTML=lives;
}

lifetest();

and here is a working jsfiddle http://jsfiddle.net/ajaaibu/2b4s8gmf/


text:
Q: Trying to refresh page using Jquery post and ActionResult I've been trying to make the "RedirecttoAction" statement work here but it doesn't budge. Here is the method:
    [HttpPost]
    public ActionResult UpdateTech(int tech, int id)
    {
        Callout callout = db.Callouts.Find(id);
        callout.TechnicianId = tech;
        callout.TechStatus = "ASSIGNED";
        db.Entry(callout).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("CalloutAdmin/Index/");
    }

And it is called by the following JQuery, which works perfectly:
$(function () {
        $(".techdropdown").change(function () {
            var recordToUpdate = $(this).attr("id");
            var selectedTech = $(".techdropdown option:selected").val();
            window.alert(selectedTech);
            $.post("/CalloutAdmin/UpdateTech?tech=" + selectedTech + "&id=" + recordToUpdate);
        });
    });

The only thing that does not happen is the page being refreshed, which was what the redirect should do. Can anyone advise?
UPDATE
What I am trying to do is update this Callout object, without redirecting to another view. I choose a technician from a dropdownlist and it automatically sets the callout's technician value to the one I chose from the dropdown.

A: You're returning the redirect to the AJAX request, and the AJAX request is loading the page in the background. If you want to have the entire page redirect you probably want to use the success callback in jQuery
$.post("/CalloutAdmin/UpdateTech?tech=" + selectedTech + "&id=" + recordToUpdate, function() { document.location = "CalloutAdmin/Index/"; } );

If you want to have the action control the location of the redirect, you probably want to use the return a JsonResult or ContentResult from your action with the URL outputted from there have jQuery's success callback redirect the user.

A: Assuming that UpdateTech and Index both belong to CallOutAdminController then change your UpdateTech Method to look like:
[HttpPost]
public ActionResult UpdateTech(int tech, int id)
{
    Callout callout = db.Callouts.Find(id);
    callout.TechnicianId = tech;
    callout.TechStatus = "ASSIGNED";
    db.Entry(callout).State = EntityState.Modified;
    db.SaveChanges();
    return RedirectToAction("Index","CallOutAdmin");
}

Then make you jQuery function like this:
$(document).ready(function(e) {
    $(".techdropdown").change(function () {
        var recordToUpdate = $(this).attr("id");
        var selectedTech = $(".techdropdown option:selected").val();
        window.alert(selectedTech);
        window.location = "/CallOutAdmin/UpdateTech?tech=" + selectedTech + "&id=" + recordToUpdate
    });
});


text:
Q: Fish bobthefish powerline some symbols not working on Ubuntu WSL I have the following fish shell on Windows Terminal

As it can be seen most of the symbols are working for powerline but some are not working. I have already downloaded and set the font in the Windows Terminal. The font that I have set is DejaVu Sans Mono for Powerline.


text:
Q: How would I randomly choose changing variables that meet conditions? a = 3;
b = 3;
c = 3;
turnCount = 1;
function decrease(x, y) //x represents a, b, c while y subtracts 1, 2, or 3//
    //stuff I figured out//

So I'm trying to create an AI for a game, where there are 3 turns. TurnCount 1 and 2 are the computer and 3 is the player turn. On the computer turn, they will always subtract 1 from the variable with the highest value. There are 9 buttons that subtract 1, 2, or 3 from each variable. Any button that would subtract more than the value in the variable will be disabled. Now, my problem is that I want to randomize which variable is subtracted from if there is more than one variable with the highest value. My approach was this:
function theAI()
{
    highestValue = Math.max(a, b, c);
    theArray = ["", a, b, c];
    varToDecrease = theArray.indexOf(highestValue);
    decrease(varToDecrease, 1);
}

However this approach will always make a and b equal 2, therefore the buttons to subtract 3 from the variables will never be used. Can anyone please help think of a way to randomize which highestValue variable is subtracted from, so that the subtract 3 buttons are allowed to work for all three variables?

A: You can first find all the indexes of your max value, then use math random to choose an element from the array.
function theAI()
{
    highestValue = Math.max(a, b, c);
    theArray = ["", a, b, c];
    var idx = array.indexOf(element);
    while (idx != -1) {
      indices.push(idx);
      idx = array.indexOf(element, idx + 1);
    }
    varToDecrease = indices[Math.floor(indices.length * Math.random())];
    decrease(varToDecrease, 1);
}

I'm using a while loop here to search for each instance of the highest value in the array.  (It is actually close to a do-while syntax)
First I set the idx to the first location of the highest element in the array. Since I found the max element with Math.max, there is not possible that this will ever not be found.  So when something is found with indexOf, it returns the index, when something is not found, it returns -1.
So it will enter the while loop, add the current location of the highest element to the array, and then set idx to the next index of the highest element.  If there is only one found int the array, it will return -1, and the while loop will end.  However, if the idx is not -1, that means there is another max element int he array, and so the while loop will loop again.


text:
Q: How to send data from express backend to ejs front end? I am trying out a Tutorials website and in that some of my pages need to send tutorials object, video object, user object depending on which route they landed. So, is it necessary to send null object even if I don't need them on the front end? I am extracting these backend objects in script tag and assign it to window object for use in angular client.
Here are some sample codes.
// layout.ejs   common to all front end views
<script>
window.user = <%- typeof user !== 'undefined'? JSON.stringify(user) : null %>
</script>

Backend sends this type of code:
res.render('/partials/index', {
    title: 'Title'
});

But when I don't send user as null, it throws ReferenceError: user not defined. Why is it so? I am checking in the script tag if it is undefined, I am using null. Is it wrong?
If we need to explicitly send null from backend, then it seems awkward to send null everytime even though I don't need it. What is right way to do it?

A: It is because the ternary operator checks both parts (including the one with user) even it is not evaluated because the condition is false.
You either have to include this:
let user = user || null;

Or send an explicit null in the render.

A: Sorry, but I found an answer. We can set this using this. Yes it is using null as a string. That seems different.
window.user = <%- typeof user === 'undefined' ? 'null': JSON.stringify(user) %>

I hope it may help someone else.


text:
Q: Handle technical error in Jenkins Step (Jenkins pipeline) A step calls a shell script (e.g. to install an artifact on a test server) and fails for technical reasons (network does not work, database broke down, etc.). Possible reactions:

*

*Fail the whole job. Not a good idea because then one would need to repeat the previous steps for no good reason (these steps can include manual ones).

*Retry the step after e.g. a 5 minute wait. Could solve the problem sometimes, but could also lead to an infinite loop if the problem was caused by misconfiguration.

*Ask the user if to proceed or abort. Most flexible approach but needs (unexpected) use interaction.
Has Jenkins a standard solution for this?

A:
Fail the whole job. Not a good idea because then one would need to repeat the previous steps for no good reason (these steps can include manual ones).

It depends on how you rank the severity of the problem. I personally would say if you have any kind of build issues, log it, fail and send notification to whoever needs to know. But if you feel that's overkill, you might want to try something else.

Retry the step after e.g. a 5 minute wait. Could solve the problem sometimes, but could also lead to an infinite loop if the problem was caused by misconfiguration.

You can set a timeout in a Jenkinsfile to give up after, say an hour, or however long you think the job should take. This way you get to retry a few times and you're guaranteed a termination of the job if it gets stuck.

Ask the user if to proceed or abort. Most flexible approach but needs (unexpected) use interaction.

User interaction isn't a great option, especially if you you have no idea when it will happen or if your jobs are scheduled to run between 10pm-5am.
Of all the options, it sounds like the best for your may be the second;  retry a few times, and if that doesn't work then log what happens, fail, and notify someone. That should cover your sporadic technical issues. Also if retrying doesn't work, it can show that there are bigger problems to fix.


text:
Q: Clojure compile-time escape mechanism The language Forth offers a "compile-time" escape mechanism where code can be executed immediately, while the compiler is running (not at run-time). You can include print statements, for example, to debug tricky syntax or type errors).
Does Clojure have anything similar? I am getting a compile-time IllegalArgumentException in one of my function calls and would like to add a compile-time print statement to determine the argument type ((.getClass)).
Thanks.
UPDATE: Here is the complete defn that is failing compilation:
(ns my.ns.name
  (:gen-class
   :main true)
  (:use
   [clojure.contrib.str-utils2 :only (join)])
  (:import
   [java.io PrintWriter]
   [java.net URL]
   [java.util.concurrent Executors]
   [java.util.jar Manifest]
   [org.apache.commons.cli CommandLine HelpFormatter Options Option ParseException PosixParser]))

(defn set-version
  "Set the version variable to the build number."
  []
  (def version
    (-> (str "jar:" (.. my.ns.name (getProtectionDomain)
                                   (getCodeSource)
                                   (getLocation))
                    "!/META-INF/MANIFEST.MF")
      (URL.)
      (.openStream)
      (Manifest.)
      (.. getMainAttributes)
      (.getValue "Build-number"))))

This defn works:
(defn set-version
  "Set the version variable to the build number."
  []
  (println (str (.getClass my.ns.name)))
  (def version
    (-> (str "jar:" (-> my.ns.name (.getProtectionDomain)
                                   (.getCodeSource)
                                   (.getLocation))
                    "!/META-INF/MANIFEST.MF")
      (URL.)
      (.openStream)
      (Manifest.)
      (.. getMainAttributes)
      (.getValue "Build-number"))))

A: Printing the class of things during compilation is pretty restricted to special cases. You will mostly get Symbols and Seqs. Only literals have a meaningful type during compilation. You can execute arbitrary code during compilation via macros.
(defmacro debug-type
  [x]
  (println (type x))
  x)

However as I said: this will normally not be very helpful. And no: in general you cannot wrap x in an eval, eg. if x is a symbol refering to a let-local.
EDIT: Update for updated question.
(def version
  (-> (str "jar:" (-> *ns* (.getProtectionDomain)
                           (.getCodeSource)
                           (.getLocation))
                  "!/META-INF/MANIFEST.MF")
    (URL.)
    (.openStream)
    (Manifest.)
    (.getMainAttributes)
    (.getValue "Build-number")))

Try this. There is no need for a function. def inside defn should ring alarm bells.


text:
Q: Can I use emojis on a Windows PC without a touch keyboard Similar to How can I use emoji characters on a Windows 8 PC without a touch screen? but for Windows 10. I have a bog standard PC with Windows 10 installed. I tried doing the same as the suggestion for Windows 8 but that doesn't seem to work.
Most tips you find out there speak of having a screen keyboard popping up, but I don't have such an icon in the task bar that would activate the touch keyboard. Is there any other way to get to the in-built emojis?

A: *

*Right-click on your Taskbar

*Select "Show Touch Keyboard button"

*You should then see the following keyboard if you click the keyboard icon to the far right of your taskbar (left of the clock):

*You can then click the smiley face to open the emoji keyboard.

Microsoft actually recommends you keep the touch keyboard for this exact reason. But like I said in my comment, I don't use emoji and thus have no use for the keyboard, hence why I have hid it. If you use emojis often, you may want to consider keeping it on your taskbar.

A: As of the latest Windows 10 Fall Creators update 1709, you can press win+. or win+; to bring up the emoji IME panel in which you can search for the emoji you want.

A: If you right click in the black space on your taskbar, an option comes up saying Show Touch Keyboard Button. Pressing that button brings up the Touch Keyboard.


text:
Q: Symfony 3.2.1 FOSUserBundle templates as child I'm new in symfony and i'm trying to overwrite FOSUserBundle templates as child. Copying to src/Resources/FOSUserBundle/views works, but want to do this with child bundle.
I create ser/UserBundle/UserBundle.php
<?php

namespace UserBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class UserBundle extends Bundle
{
        public function getParent()
    {
        return 'FOSUserBundle';
    }

}

Then, i've made Entity:
<?php
// src/UserBundle/Entity/User.php

namespace UserBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="fos_user")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    public function __construct()
    {
        parent::__construct();
        // your own logic
    }
}

configure parameters.yml, security.yml and routing.yml.
logically works, i can /login /register etc.
Now i want to overwrite layout.html.twig so i creating src/UserBundle/Resources/views/layout.html.twig
{% extends '::base.html.twig' %}
{% block title %}Demo Application{% endblock %}

{% block body %}
    {% block fos_user_content %}{% endblock %}
    Ala ma kota
{% endblock %}

But this is not rendered :/
profiler says:
Rendering Call Graph

main 4.04ms/100%
└ @FOSUser/Security/login.html.twig 1.78ms/44%
│ └ @FOSUser/layout.html.twig 1.69ms/42%
│   └ @FOSUser/Security/login.html.twig::block(fos_user_content)
│     └ @FOSUser/Security/login_content.html.twig
└ @WebProfiler/Profiler/toolbar_js.html.twig 2.26ms/56%
  └ @WebProfiler/Profiler/base_js.html.twig

I do this according to https://www.youtube.com/watch?v=ZvLUvOaW_XY&t=512s, but this video is about symfony 2.0 and I try with Symfony 3.2. Does something changed in Symfony3 with childrening bundles?
What i'm doing wrong?


text:
Q: SQL Server foreign key, referenced tables Is there a tool or someone does have a query that can for provided table make a query that will have (left) joins on all referenced tables and subsequently all other tables that are referenced by those etc... to the n-th lvl.
Thanks

A: I think you can use sp_CascadingDataViewer (http://cascadingdataviewer.codeplex.com/) to extract the data and then cut and paste to the new database. I am sure it can be modified to output all dynamic sql in the process and that can be run in reverse order to fill the new database too.


text:
Q: Angularjs - grouping ng show How can I group ng-shows without ruining the dom tree order?
Reason: I want to decrease the amount of watchers
For example I have these ng-shows:

A

B

C

D

E

Can I somehow do something like this:

A

B

    {{ng-show-start(canEdit)}}

C

D

E

    {{ng-show-end(canEdit)}}

Using an DOM element instead of ng-show-start&end can also be an solution, but it must be able to remove its element and show the contents on true.

A: I know this question is three years old and probably irrelevant but there's the following solution in angular 1.2+

A

B

C

D

E

The -start and -end postfixes can be used with ng-show, ng-if, ng-switch, ng-repeat and your own directives if multiElement: true is set.

A: If canEdit is not going to change after the initial assignment then you can use a one time bind introduced in angular 1.3.  ng-show="::canEdit".
https://docs.angularjs.org/guide/expression
If you really want to group the
 tags then you will need to wrap them in an html element and put the ng-show on it
I don't think you need to worry about too many watchers though.  I believe (though am not certain) that angular will only assign a single watcher to canEdit as it is a single variable that is being bound in multiple locations