问:
Git clone fail while commit working fine in gitlab
I am getting the below error while trying to commit in gitlab. Is there any prior environmental setup I need to do before the commit?</p>

```<code>/opt/gitlab/embedded/lib/ruby/2.3.0/psych.rb:474:in `initialize': Permission denied @ rb_sysopen - /opt/gitlab/embedded/service/gitlab-shell/config.yml (Errno::EACCES)
        from /opt/gitlab/embedded/lib/ruby/2.3.0/psych.rb:474:in `open'
        from /opt/gitlab/embedded/lib/ruby/2.3.0/psych.rb:474:in `load_file'
        from /opt/gitlab/embedded/service/gitlab-shell/lib/gitlab_config.rb:7:in `initialize'
        from /opt/gitlab/embedded/service/gitlab-shell/lib/gitlab_logger.rb:13:in `new'
        from /opt/gitlab/embedded/service/gitlab-shell/lib/gitlab_logger.rb:13:in `<top (required)>'
        from /opt/gitlab/embedded/service/gitlab-shell/lib/gitlab_net.rb:6:in `require_relative'
        from /opt/gitlab/embedded/service/gitlab-shell/lib/gitlab_net.rb:6:in `<top (required)>'
        from /opt/gitlab/embedded/service/gitlab-shell/lib/gitlab_shell.rb:4:in `require_relative'
        from /opt/gitlab/embedded/service/gitlab-shell/lib/gitlab_shell.rb:4:in `<top (required)>'
        from /opt/gitlab/embedded/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
        from /opt/gitlab/embedded/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
        from /opt/gitlab/embedded/service/gitlab-shell/bin/gitlab-shell:22:in `<main>'
fatal: The remote end hung up unexpectedly
</code>```

答:
The error mentions that permission is denied to the GitLab Shell config file. Make sure the file /opt/gitlab/embedded/service/gitlab-shell/config.yml is owned by git so GitLab Shell can read the configuration during push.

It's curious that this file has a permission problem to begin with, though. If you changed any configuration in /etc/gitlab/gitlab.rb then be sure to run sudo gitlab-ctl reconfigure. Also, avoid messing with anything inside /opt/gitlab.

Body:
I am getting the below error while trying to commit in gitlab. Is there any prior environmental setup I need to do before the commit?

/opt/gitlab/embedded/lib/ruby/2.3.0/psych.rb:474:in `initialize': Permission denied @ rb_sysopen - /opt/gitlab/embedded/service/gitlab-shell/config.yml (Errno::EACCES)
        from /opt/gitlab/embedded/lib/ruby/2.3.0/psych.rb:474:in `open'
        from /opt/gitlab/embedded/lib/ruby/2.3.0/psych.rb:474:in `load_file'
        from /opt/gitlab/embedded/service/gitlab-shell/lib/gitlab_config.rb:7:in `initialize'
        from /opt/gitlab/embedded/service/gitlab-shell/lib/gitlab_logger.rb:13:in `new'
        from /opt/gitlab/embedded/service/gitlab-shell/lib/gitlab_logger.rb:13:in `<top (required)>'
        from /opt/gitlab/embedded/service/gitlab-shell/lib/gitlab_net.rb:6:in `require_relative'
        from /opt/gitlab/embedded/service/gitlab-shell/lib/gitlab_net.rb:6:in `<top (required)>'
        from /opt/gitlab/embedded/service/gitlab-shell/lib/gitlab_shell.rb:4:in `require_relative'
        from /opt/gitlab/embedded/service/gitlab-shell/lib/gitlab_shell.rb:4:in `<top (required)>'
        from /opt/gitlab/embedded/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
        from /opt/gitlab/embedded/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
        from /opt/gitlab/embedded/service/gitlab-shell/bin/gitlab-shell:22:in `'
fatal: The remote end hung up unexpectedly


来源: stackexchange

问:
Python connect socket to process
I have a (very) simple web server I wrote in C and I want to test it. I wrote it so it takes data on stdin and sends out on stdout. How would I connect the input/output of a socket (created with socket.accept()) to the input/output of a process created with subprocess.Popen?

Sounds simple, right? Here's the killer: I'm running Windows.

Can anyone help?

Here's what I've tried:

Passing the client object itself as stdin/out to subprocess.Popen. (It never hurts to try.)

Passing socket.makefile() results as stdin/out to subprocess.Popen.

Passing the socket's file number to os.fdopen().

Also, in case the question was unclear, here's a slimmed-down version of my code:

```<code>sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', PORT))
sock.listen(5)
cli, addr = sock.accept()
p = subprocess.Popen([PROG])
#I want to connect 'p' to the 'cli' socket so whatever it sends on stdout
#goes to the client and whatever the client sends goes to its stdin.
#I've tried:
p = subprocess.Popen([PROG], stdin = cli.makefile("r"), stdout = cli.makefile("w"))
p = subprocess.Popen([PROG], stdin = cli, stdout = cli)
p = subprocess.Popen([PROG], stdin = os.fdopen(cli.fileno(), "r"), stdout = os.fdopen(cli.fileno(), "w"))
#but all of them give me either "Bad file descriptor" or "The handle is invalid".
</code>```

答:
I had the same issue and tried the same way to bind the socket, also on windows. The solution I came out with was to share the socket and bind it on the process to stdin and stdout. My solutions are completely in python but I guess that they are easily convertible.

```<code>import socket, subprocess

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', PORT))
sock.listen(5)
cli, addr = sock.accept()

process = subprocess.Popen([PROG], stdin=subprocess.PIPE)
process.stdin.write(cli.share(process.pid))
process.stdin.flush()

# you can now use `cli` as client normally
</code>```

And in the other process:

```<code>import sys, os, socket

sock = socket.fromshare(os.read(sys.stdin.fileno(), 372))
sys.stdin = sock.makefile("r")
sys.stdout = sock.makefile("w")

# stdin and stdout now write to `sock`
</code>```

The 372 is the len of a measured socket.share call. I don't know if this is constant, but it worked for me. This is possible only in windows, as the share function is only available on that OS.

ContentLicense: CC BY-SA 3.0

Title: Python connect socket to process

Body:
I have a (very) simple web server I wrote in C and I want to test it. I wrote it so it takes data on stdin and sends out on stdout. How would I connect the input/output of a socket (created with socket.accept()) to the input/output of a process created with subprocess.Popen?

Sounds simple, right? Here's the killer: I'm running Windows.

Can anyone help?

Here's what I've tried:

Passing the client object itself as stdin/out to subprocess.Popen. (It never hurts to try.)

Passing socket.makefile() results as stdin/out to subprocess.Popen.

Passing the socket's file number to os.fdopen().

Also, in case the question was unclear, here's a slimmed-down version of my code:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', PORT))
sock.listen(5)
cli, addr = sock.accept()
p = subprocess.Popen([PROG])
#I want to connect 'p' to the 'cli' socket so whatever it sends on stdout
#goes to the client and whatever the client sends goes to its stdin.
#I've tried:
p = subprocess.Popen([PROG], stdin = cli.makefile("r"), stdout = cli.makefile("w"))
p = subprocess.Popen([PROG], stdin = cli, stdout = cli)
p = subprocess.Popen([PROG], stdin = os.fdopen(cli.fileno(), "r"), stdout = os.fdopen(cli.fileno(), "w"))
#but all of them give me either "Bad file descriptor" or "The handle is invalid".

Body:
I had the same issue and tried the same way to bind the socket, also on windows. The solution I came out with was to share the socket and bind it on the process to stdin and stdout. My solutions are completely in python but I guess that they are easily convertible.

import socket, subprocess

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', PORT))
sock.listen(5)
cli, addr = sock.accept()

process = subprocess.Popen([PROG], stdin=subprocess.PIPE)
process.stdin.write(cli.share(process.pid))
process.stdin.flush()

# you can now use `cli` as client normally

And in the other process:

import sys, os, socket

sock = socket.fromshare(os.read(sys.stdin.fileno(), 372))
sys.stdin = sock.makefile("r")
sys.stdout = sock.makefile("w")

# stdin and stdout now write to `sock`

The 372 is the len of a measured socket.share call. I don't know if this is constant, but it worked for me. This is possible only in windows, as the share function is only available on that OS.


问:
Running large dataset causes timeout
I am building a Spark application that is relatively simple. Generally, the logic looks like this:

```<code>val file1 = sc.textFile("s3://file1/*")
val file2 = sc.textFile("s3://file2/*")
// map over files
val file1Map = file1.map(word => (word, "val1"))
val file2Map = file2.map(differentword => (differentword, "val2"))
val unionRdd = file1Map.union(file2Map)
val groupedUnion = unionRdd.groupByKey()
val output = groupedUnion.map(tuple => {
    // do something that requires all the values, return new object
    if(oneThingIsTrue) tuple._1 else "null"
}).filter(line => line != "null")
output.saveAsTextFile("s3://newfile/")
</code>```

The question has to do with this not working when I run it with larger datasets. I can run it without errors when the Dataset is around 700GB. When I double it to 1.6TB, the job will get halfway before timing out. Here is the Err log:

```<code>INFO MapOutputTrackerWorker: Don't have map outputs for shuffle 0, fetching them
INFO MapOutputTrackerWorker: Doing the fetch; tracker endpoint = NettyRpcEndpointRef(spark://MapOutputTracker@172.31.4.36:39743)
ERROR MapOutputTrackerWorker: Error communicating with MapOutputTracker
    org.apache.spark.rpc.RpcTimeoutException: Futures timed out after [800 seconds]. This timeout is controlled by spark.network.timeout
</code>```

I have tried increasing the network timeout to both 800 seconds and 1600 seconds but all this does is delay the error for longer. I am running the code on 10r4.2xl which have 8 cores each and 62gb RAM. I have EBS setup to have 3TB storage. I am running this code via Zeppelin in Amazon EMR.

Can anyone help me debug this? The CPU usage of the cluster will be close to 90% the whole time until it gets halfway and it drops back to 0 completely. The other interesting thing is that it looks like it fails in the second stage when it is shuffling. As you can see from the trace, it is doing the fetch and never gets it.

Here is a photo from Ganglia.

答:
I'm still not sure what caused this but I was able to get around it by coalescing the unionRdd and then grouping that result. Changing the above code to: </p>

```<code>...
// union rdd is 30k partitions, coalesce into 8k
val unionRdd = file1Map.union(file2Map)
val col = unionRdd.coalesce(8000)
val groupedUnion = col.groupByKey()
...
</code>```

<p>It might not be efficient, but it works. </p>

Title: Running large dataset causes timeout

Body:
I am building a Spark application that is relatively simple. Generally, the logic looks like this:

val file1 = sc.textFile("s3://file1/*")
val file2 = sc.textFile("s3://file2/*")
// map over files
val file1Map = file1.map(word => (word, "val1"))
val file2Map = file2.map(differentword => (differentword, "val2"))
val unionRdd = file1Map.union(file2Map)
val groupedUnion = unionRdd.groupByKey()
val output = groupedUnion.map(tuple => {
    // do something that requires all the values, return new object
    if(oneThingIsTrue) tuple._1 else "null"
}).filter(line => line != "null")
output.saveAsTextFile("s3://newfile/")

The question has to do with this not working when I run it with larger datasets. I can run it without errors when the Dataset is around 700GB. When I double it to 1.6TB, the job will get halfway before timing out. Here is the Err log:

INFO MapOutputTrackerWorker: Don't have map outputs for shuffle 0, fetching them
INFO MapOutputTrackerWorker: Doing the fetch; tracker endpoint = NettyRpcEndpointRef(spark://MapOutputTracker@172.31.4.36:39743)
ERROR MapOutputTrackerWorker: Error communicating with MapOutputTracker
    org.apache.spark.rpc.RpcTimeoutException: Futures timed out after [800 seconds]. This timeout is controlled by spark.network.timeout

I have tried increasing the network timeout to both 800 seconds and 1600 seconds but all this does is delay the error for longer. I am running the code on 10r4.2xl which have 8 cores each and 62gb RAM. I have EBS setup to have 3TB storage. I am running this code via Zeppelin in Amazon EMR.

Can anyone help me debug this? The CPU usage of the cluster will be close to 90% the whole time until it gets halfway and it drops back to 0 completely. The other interesting thing is that it looks like it fails in the second stage when it is shuffling. As you can see from the trace, it is doing the fetch and never gets it.

Here is a photo from Ganglia.

Body:
I'm still not sure what caused this but I was able to get around it by coalescing the unionRdd and then grouping that result. Changing the above code to:

...
// union rdd is 30k partitions, coalesce into 8k
val unionRdd = file1Map.union(file2Map)
val col = unionRdd.coalesce(8000)
val groupedUnion = col.groupByKey()
...

It might not be efficient, but it works.


问:
Notice: Undefined index: query in
I'm doing a webpage for a university task but I'm having problems with this code.

```<code>if ($_POST["id_temporada"]>0 and $_POST["query"]=="") {
    $consulta="select * from obras where id_temporada=".$_POST["id_temporada"];
}
</code>```

also with this one

```<code>if ($_POST["id_temporada"]>0 and $_POST["query"]<>"") {
    $consulta="select * from obras where temporada=".$_POST["id_temporada"]." and nombre
    like '%".$_POST["query"]."%'";
}
</code>```

In both cases, I have the notice I posted on the title. What should i do?

答:
You have to check if the index exists with isset($variable) before accessing that index. </p>

<p>$_POST["query"]=="" should be (!isset($_POST["query"])||$_POST["query"]=="")</p>

Title: Notice: Undefined index: query in

Body:
I'm doing a webpage for a university task but I'm having problems with this code.

if ($_POST["id_temporada"]>0 and $_POST["query"]=="") {
    $consulta="select * from obras where id_temporada=".$_POST["id_temporada"];
}

also with this one

if ($_POST["id_temporada"]>0 and $_POST["query"]<>"") {
    $consulta="select * from obras where temporada=".$_POST["id_temporada"]." and nombre
    like '%".$_POST["query"]."%'";
}

In both cases, I have the notice I posted on the title. What should i do?

Body:
You have to check if the index exists with isset($variable) before accessing that index.

$_POST["query"]=="" should be (!isset($_POST["query"])||$_POST["query"]=="")


问:
Navigating to Commonly/Recently Used Dirs, in Terminal (Unix/OS X)
Would it be possible to save certain locations that I've used recently/commonly (like /folder/folder/folder/) so that I don't have to manually navigate through each dir between my current and destination dir?

Sort of like alt-tab, but for paths.  I'm on OS X, but perhaps this can be done using basic Unix skills?

Thanks!

答:
If you set up your shell to save commands history, using Ctrl+R hotkey may save you some time, which performs search of previously executed commands as you type. Another good thing to know is that most shells provide you with file/directory name completion if you press Tab key once/twice, which is also of great help.

EDIT: you can also make some symbolic links inside single (e.g. home) directory to quickly access directories. Use ln -s <path to target file/directory> <path to link> command. Target paths could either be relative or absolute.

ContentLicense: CC BY-SA 2.5


问:
Generate random tokens (unique id's) for users in a table in SQL server
I want to create a table in sql server and fill it up with data (people's info). The goal is to get every person a unique ID in the first row which has to start with fixed alphabets GM followed by A-Z or 2-9 numeric , initial of First name, Initial of Last name and A-Z or 2-9.

答:
Note: With the logic you are requesting i don't think you can produce Unique value without check that the table doesn't contains the generated value, the only way is to use NEWID() function that generate a GUID, else i think that there is always a duplication risk

I don't know if this is the best way to do that, but i can say that it gives the expected output. You can create this function and use it to generate the identifier:

```<code>ALTER FUNCTION dbo.CreateIdentifier
(
    -- Add the parameters for the function here
    @Firstname varchar(255),
    @Lastname varchar(255),
    @random1 decimal(18,10) ,
    @random2 decimal(18,10)
)
RETURNS varchar(10)
AS
BEGIN
    -- Declare the return variable here
    DECLARE @S VARCHAR(10)
    DECLARE @S1 VARCHAR(1)
    DECLARE @S2 VARCHAR(1)
    DECLARE @len INT
    DECLARE @Random1Fixed INT
    DECLARE @Random2Fixed INT

    declare @alphabet varchar(36) = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ23456789'

    SET @alphabet = REPLACE(@alphabet,LEFT(@Lastname,1),'')
    SET @alphabet = REPLACE(@alphabet,LEFT(@Firstname,1),'')

    SELECT @len = len(@alphabet)
    SET @Random1Fixed = ROUND(((@len - 1 -1) * @random1 + 1), 0)
    SET @Random2Fixed = ROUND(((@len - 1 -1) * @random2 + 1), 0)

    SET @S1 = substring(@alphabet, convert(int, @Random1Fixed ), 1)
    SET @S2 = substring(@alphabet, convert(int, @Random2Fixed), 1)

    SET @S = 'GM' + @S1 + LEFT(@Firstname,1) + LEFT(@Lastname,1) + @S2
    RETURN @S

END
</code>```

And you can use it as the following

```<code>SELECT dbo.CreateIdentifier('John','Wills',RAND(),RAND())
</code>```

I am passing RAND() as parameter because it cannot be used within a function

Body:
Note: With the logic you are requesting i don't think you can produce Unique value without check that the table doesn't contains the generated value, the only way is to use NEWID() function that generate a GUID, else i think that there is always a duplication risk

I don't know if this is the best way to do that, but i can say that it gives the expected output. You can create this function and use it to generate the identifier:

ALTER FUNCTION dbo.CreateIdentifier
(
    -- Add the parameters for the function here
    @Firstname varchar(255),
    @Lastname varchar(255),
    @random1 decimal(18,10) ,
    @random2 decimal(18,10)
)
RETURNS varchar(10)
AS
BEGIN
    -- Declare the return variable here
    DECLARE @S VARCHAR(10)
    DECLARE @S1 VARCHAR(1)
    DECLARE @S2 VARCHAR(1)
    DECLARE @len INT
    DECLARE @Random1Fixed INT
    DECLARE @Random2Fixed INT

    declare @alphabet varchar(36) = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ23456789'

    SET @alphabet = REPLACE(@alphabet,LEFT(@Lastname,1),'')
    SET @alphabet = REPLACE(@alphabet,LEFT(@Firstname,1),'')

    SELECT @len = len(@alphabet)
    SET @Random1Fixed = ROUND(((@len - 1 -1) * @random1 + 1), 0)
    SET @Random2Fixed = ROUND(((@len - 1 -1) * @random2 + 1), 0)

    SET @S1 = substring(@alphabet, convert(int, @Random1Fixed ), 1)
    SET @S2 = substring(@alphabet, convert(int, @Random2Fixed), 1)

    SET @S = 'GM' + @S1 + LEFT(@Firstname,1) + LEFT(@Lastname,1) + @S2
    RETURN @S

END

And you can use it as the following

SELECT dbo.CreateIdentifier('John','Wills',RAND(),RAND())

I am passing RAND() as parameter because it cannot be used within a function


问:
Pandas to_csv - Not save index values repeatedly?
Pandas 0.20.3 - Excuse the poor title. I don't know the best way to describe it.

DataFrame:

```<code>In [363]: df
Out[363]:
           IP   Jroid   ST
0   127.0.0.3  Joid12  stq
1   127.0.0.2  Jroid2  stt
2   127.0.0.1  Jroid1  sth
3   127.0.0.1  Jroid1  stl
4   127.0.0.1  Jroid3  stj
5   127.0.0.1  Jroid2   ll
6   127.0.0.2  Jroid1  stq
7   127.0.0.1  Jroid3  stt
8   127.0.0.1  Jroid1  sth
9   127.0.0.2  Jroid1  stl
10  127.0.0.3  Jroid1  stq
11  127.0.0.3  Jroid3  stt
</code>```

DataFrame grouped perfectly for my needs:

```<code>In [365]: df.groupby(['IP','Jroid','ST']).ST.agg('count')
Out[365]:
IP         Jroid   ST
127.0.0.1  Jroid1  sth    2
                   stl    1
           Jroid2  ll     1
           Jroid3  stj    1
                   stt    1
127.0.0.2  Jroid1  stl    1
                   stq    1
           Jroid2  stt    1
127.0.0.3  Joid12  stq    1
           Jroid1  stq    1
           Jroid3  stt    1
Name: ST, dtype: int64
</code>```

Now

```<code>df.groupby(['IP','Jroid','ST']).ST.agg('count').to_csv('/tmp/hi.csv')
</code>```

renders as such:

```<code>127.0.0.1,Jroid1,sth,2
127.0.0.1,Jroid1,stl,1
127.0.0.1,Jroid2,ll,1
127.0.0.1,Jroid3,stj,1
127.0.0.1,Jroid3,stt,1
127.0.0.2,Jroid1,stl,1
127.0.0.2,Jroid1,stq,1
127.0.0.2,Jroid2,stt,1
127.0.0.3,Joid12,stq,1
127.0.0.3,Jroid1,stq,1
127.0.0.3,Jroid3,stt,1
</code>```

How can I can have "to_csv" save the exact way it is represented by "df.groupby(['IP','Jroid','ST']).ST.agg('count')"?
Is it possible?

Creating a new df doesn't seem to help:

```<code>print_df = df.groupby(['IP','Jroid','ST']).ST.agg('count')
print_df.to_csv('/tmp/hi.csv')
</code>```

Does the same thing though.

答:
As DeepSpace stated it won't be a valid CSV format

You can do it within .xlsx

```<code>df.to_excel('df.xlsx', engine='xlsxwriter')
</code>```

Body:
Pandas 0.20.3 - Excuse the poor title. I don't know the best way to describe it.

DataFrame:

In [363]: df
Out[363]:
           IP   Jroid   ST
0   127.0.0.3  Joid12  stq
1   127.0.0.2  Jroid2  stt
2   127.0.0.1  Jroid1  sth
3   127.0.0.1  Jroid1  stl
4   127.0.0.1  Jroid3  stj
5   127.0.0.1  Jroid2   ll
6   127.0.0.2  Jroid1  stq
7   127.0.0.1  Jroid3  stt
8   127.0.0.1  Jroid1  sth
9   127.0.0.2  Jroid1  stl
10  127.0.0.3  Jroid1  stq
11  127.0.0.3  Jroid3  stt

DataFrame grouped perfectly for my needs:

In [365]: df.groupby(['IP','Jroid','ST']).ST.agg('count')
Out[365]:
IP         Jroid   ST
127.0.0.1  Jroid1  sth    2
                   stl    1
           Jroid2  ll     1
           Jroid3  stj    1
                   stt    1
127.0.0.2  Jroid1  stl    1
                   stq    1
           Jroid2  stt    1
127.0.0.3  Joid12  stq    1
           Jroid1  stq    1
           Jroid3  stt    1
Name: ST, dtype: int64

Now

df.groupby(['IP','Jroid','ST']).ST.agg('count').to_csv('/tmp/hi.csv')

renders as such:

127.0.0.1,Jroid1,sth,2
127.0.0.1,Jroid1,stl,1
127.0.0.1,Jroid2,ll,1
127.0.0.1,Jroid3,stj,1
127.0.0.1,Jroid3,stt,1
127.0.0.2,Jroid1,stl,1
127.0.0.2,Jroid1,stq,1
127.0.0.2,Jroid2,stt,1
127.0.0.3,Joid12,stq,1
127.0.0.3,Jroid1,stq,1
127.0.0.3,Jroid3,stt,1

How can I can have "to_csv" save the exact way it is represented by "df.groupby(['IP','Jroid','ST']).ST.agg('count')"?
Is it possible?

Creating a new df doesn't seem to help:

print_df = df.groupby(['IP','Jroid','ST']).ST.agg('count')
print_df.to_csv('/tmp/hi.csv')

Does the same thing though.

Body:
As DeepSpace stated it won't be a valid CSV format

You can do it within .xlsx

df.to_excel('df.xlsx', engine='xlsxwriter')


问:
Pari/Gp directing output
Is there an easy convenient way to direct output in Pari/GP to file? My aim is to get the full decimal expansion of 2^400000-1 either on screen or in a text file?

```<code>(23:37) gp > 2^400000-1
%947 = 996014342993......(4438 digits)......609762267975[+++]
</code>```

GP terminal output gives this, which is not the goal. Basic output re-direction does not work either. Any ideas? Thanks.

```<code>(23:38) gp > 2^400000-1 > output.txt
</code>```

There is a manual online, it does not say much about the output, except for the variable TeXstyle. I am unsure how to work with this though.

答: Quick and easy is to just do print(2^400000-1) and then you can cut+paste. Otherwise write(filename, 2^400000-1) if you want in a file.

Title: Pari/Gp directing output

Body:
Is there an easy convenient way to direct output in Pari/GP to file? My aim is to get the full decimal expansion of 2^400000-1 either on screen or in a text file?

(23:37) gp > 2^400000-1
%947 = 996014342993......(4438 digits)......609762267975[+++]

GP terminal output gives this, which is not the goal. Basic output re-direction does not work either. Any ideas? Thanks.

(23:38) gp > 2^400000-1 > output.txt

There is a manual online, it does not say much about the output, except for the variable TeXstyle. I am unsure how to work with this though.


问:
How to generate ActiveRecord query for
I have a question about ActiveRecord queries:
What's the best way to write AR for a query like so:

```<code>SELECT .* FROM `professionals`
LEFT OUTER JOIN `networks`
  ON `networks`.`userable_id` = `professionals`.`id`
  AND `networks`.`userable_type` = 'Professional'
WHERE (`networks`.`insurer_id` IS NULL OR (`networks`.`insurer_id` != 1))
</code>```

The most trouble I'm having is with this part within the query:

```<code>WHERE (`networks`.`insurer_id` IS NULL OR (`networks`.`insurer_id` != 1))
</code>```

I am able to generate that above query with this:

```<code>professionals.left_joins(:networks)
  .where(networks: { insurer_id: nil })
  .or(
  professionals.left_joins(:networks)
    .where.not(networks: { insurer_id: @insurer&.id }))
</code>```

Which is quite insanely smelly because it looks as if I'm repeating part of the query within the first query. Is there a way for me to write it better?

I've been having quite a lot of trouble when using WHERE NOT and chaining OR queries in Rails. So when they eventually all exist at the same time, I'm really out of luck.

EDIT>>>>>>>
Not having the NULL condition seems to ignore the other items of the LEFT JOIN...

```<code>[4] pry(main)> Professional.left_joins(:networks).where.not(networks: {insurer_id: 1}).count
   (0.4ms)  SELECT COUNT(*) FROM `professionals` LEFT OUTER JOIN `networks` ON `networks`.`userable_id` = `professionals`.`id` AND `networks`.`userable_type` = 'Professional' WHERE (`networks`.`insurer_id` != 1)
=> 0
</code>```

答:
The best thing you can do is refactor your SQL before switching it to AR:

```<code>SELECT .* FROM `professionals`
LEFT OUTER JOIN `networks`
  ON `networks`.`userable_id` = `professionals`.`id`
  AND `networks`.`userable_type` = 'Professional'
WHERE (`networks`.`insurer_id` IS NULL OR (`networks`.`insurer_id` != 1))
</code>```

If an insurer ID is NOT 1, then is NULL a valid value? I would say so. you should be able to replace

```<code>(`networks`.`insurer_id` IS NULL OR (`networks`.`insurer_id` != 1))
</code>```

with

```<code>`networks`.`insurer_id` != 1
</code>```

Which leaves us with

```<code>SELECT .* FROM `professionals`
LEFT OUTER JOIN `networks`
  ON `networks`.`userable_id` = `professionals`.`id`
  AND `networks`.`userable_type` = 'Professional'
WHERE `networks`.`insurer_id` != 1
</code>```

which should be a TON easier to query using AR.

Title: How to generate ActiveRecord query for

Body:
I have a question about ActiveRecord queries:
What's the best way to write AR for a query like so:

SELECT .* FROM `professionals`
LEFT OUTER JOIN `networks`
  ON `networks`.`userable_id` = `professionals`.`id`
  AND `networks`.`userable_type` = 'Professional'
WHERE (`networks`.`insurer_id` IS NULL OR (`networks`.`insurer_id` != 1))

The most trouble I'm having is with this part within the query:

WHERE (`networks`.`insurer_id` IS NULL OR (`networks`.`insurer_id` != 1))

I am able to generate that above query with this:

professionals.left_joins(:networks)
  .where(networks: { insurer_id: nil })
  .or(
  professionals.left_joins(:networks)
    .where.not(networks: { insurer_id: @insurer&.id }))

Which is quite insanely smelly because it looks as if I'm repeating part of the query within the first query. Is there a way for me to write it better?

I've been having quite a lot of trouble when using WHERE NOT and chaining OR queries in Rails. So when they eventually all exist at the same time, I'm really out of luck.

EDIT>>>>>>>
Not having the NULL condition seems to ignore the other items of the LEFT JOIN...

[4] pry(main)> Professional.left_joins(:networks).where.not(networks: {insurer_id: 1}).count
   (0.4ms)  SELECT COUNT(*) FROM `professionals` LEFT OUTER JOIN `networks` ON `networks`.`userable_id` = `professionals`.`id` AND `networks`.`userable_type` = 'Professional' WHERE (`networks`.`insurer_id` != 1)
=> 0

Body:
The best thing you can do is refactor your SQL before switching it to AR:

SELECT .* FROM `professionals`
LEFT OUTER JOIN `networks`
  ON `networks`.`userable_id` = `professionals`.`id`
  AND `networks`.`userable_type` = 'Professional'
WHERE (`networks`.`insurer_id` IS NULL OR (`networks`.`insurer_id` != 1))

If an insurer ID is NOT 1, then is NULL a valid value? I would say so. you should be able to replace

(`networks`.`insurer_id` IS NULL OR (`networks`.`insurer_id` != 1))

with

`networks`.`insurer_id` != 1

Which leaves us with

SELECT .* FROM `professionals`
LEFT OUTER JOIN `networks`
  ON `networks`.`userable_id` = `professionals`.`id`
  AND `networks`.`userable_type` = 'Professional'
WHERE `networks`.`insurer_id` != 1

which should be a TON easier to query using AR.


问:
Neo4j cypher - filter out child nodes
Imagine the following graph:

The goal is to query for all connecting nodes between two entities ("Main" and "Other" in this case), but filter out mutual descendants. In other words, I would like the result set to only contain a and b, but not c, because C is a descendant of B, which is already included in the result set.

答:
This query collects all the direct descendants of the 2 entities, and then filters out the ones that have a direct descendant as a parent:</p>

```<code>MATCH (:Node {name : "Main"})-[:child]->(child:Node)<-[:child]-(:Node {name : "Other"})
WITH COLLECT(child) AS children
UNWIND children AS c
MATCH (c)<-[:child]-(parent:Node)
WITH c, children, COLLECT(parent) AS parents
WHERE NONE(p IN parents WHERE p IN children)
RETURN c;
</code>```

Title: Neo4j cypher - filter out child nodes

Body:
This query collects all the direct descendants of the 2 entities, and then filters out the ones that have a direct descendant as a parent:

MATCH (:Node {name : "Main"})-[:child]->(child:Node)<-[:child]-(:Node {name : "Other"})
WITH COLLECT(child) AS children
UNWIND children AS c
MATCH (c)<-[:child]-(parent:Node)
WITH c, children, COLLECT(parent) AS parents
WHERE NONE(p IN parents WHERE p IN children)
RETURN c;


问:
Regular expression to extract contents between two specific words using python(or nltk)
I'm trying to build a class and take each poem as an object, which has attributes of the title (followed by "POEM:"), author and content.
I extracted title and author and put in a list.
However, I don't know how to extract the content, and put into a list.

I have a txt file which includes many poems.
Sample poems are:

```<code>POEM: lala AUTHOR: la
aaaaaaaaaaaaaa,
aaaaaaaaa,
akaaaaaaaa

POEM: alal AUTHOR: al
llllllllllll,
llllll.

llllllll,
lllllllllll

POEM: lal AUTHOR:as
sssssssss,
sssssss,
sssssss
</code>```

This is what I did

```<code>import re
f=open('Poems.txt', 'r')
data=f.read().replace('\n','')
re.findall(r"^POEM:.*?(?=POEM)",data)
</code>```

I want to get all the poems as separate strings in a list, but I can only get the first poem.

```<code>'POEM: lala AUTHOR: la, aaaaaaaaaaaaaa, aaaaaaaaa, akaaaaaaaa'
</code>```

答:
Code

See regex in use here

```<code>\s*(?=POEM:)
</code>```

Note: The regex above is simply catching whitespace and asserting the position matches (with positive lookahead). See explanation for more details.

Usage

See code in use here

The basics

```<code>import re

s = "Your string here"
r = r"\s*(?=POEM:)"

print re.split(r, s)
</code>```

In practice (with your sample string)

```<code>import re

s = """POEM: lala AUTHOR: la
aaaaaaaaaaaaaa,
aaaaaaaaa,
akaaaaaaaa

POEM: alal AUTHOR: al
llllllllllll,
llllll.

llllllll,
lllllllllll

POEM: lal AUTHOR:as
sssssssss,
sssssss,
sssssss"""

r = r"\s*(?=POEM:)"

print re.split(r, s)
</code>```

Results

```<code>[
    'POEM: lala AUTHOR: la\naaaaaaaaaaaaaa,\naaaaaaaaa,\nakaaaaaaaa',
    'POEM: alal AUTHOR: al\nllllllllllll,\nllllll.\n\nllllllll,\nlllllllllll',
    'POEM: lal AUTHOR:as\nsssssssss,\nsssssss,\nsssssss'
]
</code>```

Explanation

\s* Match any number of whitespace characters

(?=POEM:) Positive lookahead ensuring what follows matches POEM: literally

Body:
I'm trying to build a class and take each poem as an object, which has attributes of the title (followed by "POEM:"), author and content.
I extracted title and author and put in a list.
However, I don't know how to extract the content, and put into a list.

I have a txt file which includes many poems.
Sample poems are:

POEM: lala AUTHOR: la
aaaaaaaaaaaaaa,
aaaaaaaaa,
akaaaaaaaa

POEM: alal AUTHOR: al
llllllllllll,
llllll.

llllllll,
lllllllllll

POEM: lal AUTHOR:as
sssssssss,
sssssss,
sssssss

This is what I did

import re
f=open('Poems.txt', 'r')
data=f.read().replace('\n','')
re.findall(r"^POEM:.*?(?=POEM)",data)

I want to get all the poems as separate strings in a list, but I can only get the first poem.

'POEM: lala AUTHOR: la, aaaaaaaaaaaaaa, aaaaaaaaa, akaaaaaaaa'

Body:
Code

See regex in use here

\s*(?=POEM:)

Note: The regex above is simply catching whitespace and asserting the position matches (with positive lookahead). See explanation for more details.

Usage

See code in use here

The basics

import re

s = "Your string here"
r = r"\s*(?=POEM:)"

print re.split(r, s)

In practice (with your sample string)

import re

s = """POEM: lala AUTHOR: la
aaaaaaaaaaaaaa,
aaaaaaaaa,
akaaaaaaaa

POEM: alal AUTHOR: al
llllllllllll,
llllll.

llllllll,
lllllllllll

POEM: lal AUTHOR:as
sssssssss,
sssssss,
sssssss"""

r = r"\s*(?=POEM:)"

print re.split(r, s)

Results

[
    'POEM: lala AUTHOR: la\naaaaaaaaaaaaaa,\naaaaaaaaa,\nakaaaaaaaa',
    'POEM: alal AUTHOR: al\nllllllllllll,\nllllll.\n\nllllllll,\nlllllllllll',
    'POEM: lal AUTHOR:as\nsssssssss,\nsssssss,\nsssssss'
]

Explanation

\s* Match any number of whitespace characters

(?=POEM:) Positive lookahead ensuring what follows matches POEM: literally


问:
How can I use the C modf function in php?
There does not appear to be one?</p>

答:
Here's the answer

```
function modf($x, &$ipart)
{
 $ipart = (int) $x;
 return $x - $ipart;
}
```

Thanks

Body: There does not appear to be one?

Body:
Here's the answer

function modf($x, &$ipart)
{
 $ipart = (int) $x;
 return $x - $ipart;
}

Thanks


问:
Batch file to start download and track it
How do I create a batch file that downloads from https://www.sample.com/downloads/filename.exe and tracks it (echo %percent% complete . . .)?</p>

答:
Here is an example :

@echo off
Mode 110,12
Title Download with BITS Transfer
set "URL=http://devbuilds.kaspersky-labs.com/devbuilds/KVRT/latest/full/KVRT.exe"
for %%a in ("%URL%") do set "SaveAsFile=%%~nxa"
powershell "Import-Module BitsTransfer; Start-BitsTransfer '%URL%' '%SaveAsFile%'"
Start "" "%SaveAsFile%"
```


问:
model hasMany Relation with where condition?
I can get all articles for each category with this code:

```<code>$category->article
</code>```

Now I want to get all articles with some condition (in articles table)

I try this

```<code>$category->article->wherePublish(1)->
                    whereFeature('top')->latest()->
                    take(9)->get();
</code>```

but I get this error:

Method wherePublish does not exist.

答:
$category->article executes the query and you get a collection. Collections do not have wherePublish and similar magic methods, that's why you're getting the error.

If you want to filter articles, use this syntax:

```<code>Article::where('category_id', $category->id)
    ->wherePublish(1)
    ->whereFeature('top')
    ->latest()
    ->take(9)
    ->get();
</code>```

This will work for hasOne and hasMany relationships. For belongsToMany use whereHas() method instead of where().

Alternatively, you could define a separate relationship like:

```<code>public function filteredArticles()
{
    return $this->hasMany(Article::class, 'article_id')
        ->wherePublish(1)
        ->whereFeature('top')
        ->latest()
        ->take(9);
}
</code>```

And use it:

```<code>$category->filteredArticles
</code>```

Body:
I can get all articles for each category with this code:

$category->article

Now I want to get all articles with some condition (in articles table)

I try this

$category->article->wherePublish(1)->
                    whereFeature('top')->latest()->
                    take(9)->get();

but I get this error:

Method wherePublish does not exist.

Body:
$category->article executes the query and you get a collection. Collections do not have wherePublish and similar magic methods, that's why you're getting the error.

If you want to filter articles, use this syntax:

Article::where('category_id', $category->id)
    ->wherePublish(1)
    ->whereFeature('top')
    ->latest()
    ->take(9)
    ->get();

This will work for hasOne and hasMany relationships. For belongsToMany use whereHas() method instead of where().

Alternatively, you could define a separate relationship like:

public function filteredArticles()
{
    return $this->hasMany(Article::class, 'article_id')
        ->wherePublish(1)
        ->whereFeature('top')
        ->latest()
        ->take(9);
}

And use it:

$category->filteredArticles


问:
JavaScript: Compare dates in an array and sum the "price" for each month/year
I have a json file with multiple transactions with a date and a price attribute. Now I want to compare the dates and if they are in the same month and year I want to sum up the prices.

JSON:

```<code>transactions: [
{
  date: "2017-11-17",
  price: "28",
},
{
  ...
}
</code>```

JavaScript:

```<code>request.onload = function() {
  for(const transaction of request.response.transactions) {
    let year = new Date(transaction.date).getFullYear();
    let month = new Date(transaction.date).getMonth();

    console.log(year + ' ' + month);  // output: 2017-11 ...
  }
};
</code>```

I tried to loop over the json object but I struggle to find a solution to compare the dates.

答:
Another solution is reduce:

var transactions = [
  {date: "2017-11-17",price: "28"},
  {date: "2017-12-17",price: "22"},
  {date: "2017-12-17",price: "20"}
];

var result = transactions.reduce(function(acc, obj) {
  var key = obj.date.substr(0,7);
  acc[key] = (acc[key] || 0) + +obj.price;
  return acc;
}, Object.create(null));

console.log(result);```

Body:
I have a json file with multiple transactions with a date and a price attribute. Now I want to compare the dates and if they are in the same month and year I want to sum up the prices.

JSON:

transactions: [
{
  date: "2017-11-17",
  price: "28",
},
{
  ...
}

JavaScript:

request.onload = function() {
  for(const transaction of request.response.transactions) {
    let year = new Date(transaction.date).getFullYear();
    let month = new Date(transaction.date).getMonth();

    console.log(year + ' ' + month);  // output: 2017-11 ...
  }
};

I tried to loop over the json object but I struggle to find a solution to compare the dates.


问:
webpack not copying images
I trying to import local package, that already bundled in webpack. When I build an app everything looks good, except webpack not copying images, fonts, etc. from that internal package. Any ideas what's going wrong?

When I try to reference my custom library, that is already bundled:

```<code>- dist
-- asdfjlsjdflasdjflsdaf.ttf
-- sdjflsjdfasjdflsjdfsd.eot
-- mylibrary.js
</code>```

only mylibrary.js is copied. So parent app looks like:

```<code>- dist
-- mylibrary.js
-- parentapp.js
- packages
-- mylibrary
--- src...
--- dist...
</code>```

Problem could be solved:

by increasing the loader limit and everything that converted to
base64 and included in mylibrary.js is available in my parent app

copy plugin, which copy fonts from mylibrary, but this solution looks ugly, since everyone who using mylibrary should care about copying fonts, images, etc.

答:
The best way to understand is to see how webpack takes care of images, fonts etc.

Here is a module that uses bootstrap and has the required concepts in action.

The index.html uses bootstrap styles and one glyph as well. The glyph (and bootstrap in all) uses one image from bootstrap binaries.

After you build the module, you can compare the paths of the image in original bootstrap binary (i.e. node_modules/bootstrap/dist/css/bootstrap.css) and the bundled output file (i.e. dist/bundle.js). You can search for glyphicons-halflings-regular.svg in those files.

The webpack simply

Copies images/fonts to your configured (in loader config) output folders

Updates those resource paths in the bundled output files (i.e. js, css etc)

(1) above need to be configured by you via a loader for ex. (2) will be automatically taken care by webpack provided the module.rules in webpack config are working properly for the images/fonts.

Hope that makes things a bit clear.

Title: webpack not copying images

Body:
I trying to import local package, that already bundled in webpack. When I build an app everything looks good, except webpack not copying images, fonts, etc. from that internal package. Any ideas what's going wrong?

When I try to reference my custom library, that is already bundled:

- dist
-- asdfjlsjdflasdjflsdaf.ttf
-- sdjflsjdfasjdflsjdfsd.eot
-- mylibrary.js

only mylibrary.js is copied. So parent app looks like:

- dist
-- mylibrary.js
-- parentapp.js
- packages
-- mylibrary
--- src...
--- dist...

Problem could be solved:

by increasing the loader limit and everything that converted to
base64 and included in mylibrary.js is available in my parent app

copy plugin, which copy fonts from mylibrary, but this solution looks ugly, since everyone who using mylibrary should care about copying fonts, images, etc.


答:
So I am going to make some assumptions here and hopefully your set up is like so

```<code>class Professional
  has_many :networks, as: :userable
end

class Network
   belongs_to :userable, polymorphic: true
end
</code>```

Then the following should work appropriately (using Arel)

```<code>net = Network.arel_table

Professional.left_joins(:networks)
  .where(net[:insured_id].not_eq(@insured.id)
    .or(net[:insured_id].eq(nil)))
</code>```

This will generate the SQL you posted assuming @insured.id returns 1

Title: How to generate ActiveRecord query for

Body:
So I am going to make some assumptions here and hopefully your set up is like so

class Professional
  has_many :networks, as: :userable
end

class Network
   belongs_to :userable, polymorphic: true
end

Then the following should work appropriately (using Arel)

net = Network.arel_table

Professional.left_joins(:networks)
  .where(net[:insured_id].not_eq(@insured.id)
    .or(net[:insured_id].eq(nil)))

This will generate the SQL you posted assuming @insured.id returns 1


问:
Serving Assets on 'static' subdomain
How can I configure rails to serve assets on different subdomain? I basically want view/assets helpers to use subdomain for all static files, such as;

instead of example.com/application.css -> static.example.com/application.css

instead of example.com/application.js -> static.example.com/application.js

instead of example.com/logo.jpg -> static.example.com/logo.jpg

答:
You can also try the rack-cors gem for Cross-Origin Resource Sharing. https://github.com/cyu/rack-cors

I've used this gem in a Rails 4 app when my font-awesome icons wouldn't render once I started using subdomains. This wiki put me on the right path: https://github.com/bokmann/font-awesome-rails/wiki/CORS-Cross-Domain-Support

Besides modifying my Gemfile, I also put the following code into config/application.rb toward the top according to this guide: https://github.com/cyu/rack-cors/blob/master/examples/rails4/config/application.rb

```<code>config.middleware.insert_before 0, "Rack::Cors", :debug => true, :logger => (-> { Rails.logger }) do
  allow do
    origins '*'

    resource '/cors',
      :headers => :any,
      :methods => [:post],
      :max_age => 0

    resource '*',
      :headers => :any,
      :methods => [:get, :post, :delete, :put, :patch, :options, :head],
      :max_age => 0
  end
end
</code>```

Title: Serving Assets on 'static' subdomain

Body:
You can also try the rack-cors gem for Cross-Origin Resource Sharing. https://github.com/cyu/rack-cors

I've used this gem in a Rails 4 app when my font-awesome icons wouldn't render once I started using subdomains. This wiki put me on the right path: https://github.com/bokmann/font-awesome-rails/wiki/CORS-Cross-Domain-Support

Besides modifying my Gemfile, I also put the following code into config/application.rb toward the top according to this guide: https://github.com/cyu/rack-cors/blob/master/examples/rails4/config/application.rb

config.middleware.insert_before 0, "Rack::Cors", :debug => true, :logger => (-> { Rails.logger }) do
  allow do
    origins '*'

    resource '/cors',
      :headers => :any,
      :methods => [:post],
      :max_age => 0

    resource '*',
      :headers => :any,
      :methods => [:get, :post, :delete, :put, :patch, :options, :head],
      :max_age => 0
  end
end


问:
Jekyll - command not found
I am trying to get Jekyll running but I have no experience with Ruby.

As far as I can tell the installation of Jekyll has succeeded.

However:

```<code>$ jekyll
</code>```

Gives an error:

```<code>-bash: jekyll: command not found
</code>```

This is the gem env result:

```<code>  - RUBYGEMS VERSION: 1.3.4
  - RUBY VERSION: 1.8.7 (2010-01-10 patchlevel 249) [universal-darwin10.0]
  - INSTALLATION DIRECTORY: /Volumes/HDD/DADU/gems
  - RUBY EXECUTABLE: /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby
  - EXECUTABLE DIRECTORY: /Volumes/HDD/DADU/gems/bin
  - RUBYGEMS PLATFORMS:
    - ruby
    - universal-darwin-10
  - GEM PATHS:
     - /Volumes/HDD/DADU/gems
     - /Volumes/HDD/DADU/.gem/ruby/1.8
     - /Library/Ruby/Gems/1.8
     - /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :benchmark => false
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - http://gems.rubyforge.org/
</code>```

And I found the following paths leading to "something" Jekyll:

~.gem/ruby/1.8/gems/jekyll-0.11.0/lib/jekyll.rb

~.gem/ruby/1.8/gems/bin/jekyll (exec file)

答:
In my case I had to run bundle install --force

Then bundle exec jekyll serve works, but jekyll serve still doesn't. It seems I'll have to go with the former from now on…

Title: Jekyll - command not found

Body:
I am trying to get Jekyll running but I have no experience with Ruby.

As far as I can tell the installation of Jekyll has succeeded.

However:

$ jekyll

Gives an error:

-bash: jekyll: command not found

This is the gem env result:

  - RUBYGEMS VERSION: 1.3.4
  - RUBY VERSION: 1.8.7 (2010-01-10 patchlevel 249) [universal-darwin10.0]
  - INSTALLATION DIRECTORY: /Volumes/HDD/DADU/gems
  - RUBY EXECUTABLE: /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby
  - EXECUTABLE DIRECTORY: /Volumes/HDD/DADU/gems/bin
  - RUBYGEMS PLATFORMS:
    - ruby
    - universal-darwin-10
  - GEM PATHS:
     - /Volumes/HDD/DADU/gems
     - /Volumes/HDD/DADU/.gem/ruby/1.8
     - /Library/Ruby/Gems/1.8
     - /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :benchmark => false
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - http://gems.rubyforge.org/

And I found the following paths leading to "something" Jekyll:

~.gem/ruby/1.8/gems/jekyll-0.11.0/lib/jekyll.rb

~.gem/ruby/1.8/gems/bin/jekyll (exec file)


问:
Insert data into MySQL Databse with PHP/AJAX, execute success option AFTER it's inserted (Callback)
I've been trying to make a simple site, and I can't quite wrap my head around some of the things said here, some of which are also unrelated to my situation.

The site has a form with 3 input boxes, a button, and a list. The info is submitted through a separate PHP file to a MySQL database, once the submit button is clicked. I'm supposed to make the list (it's inside a div) update once the info is successfully sent and updated in the database. So far I've made it work with async:false but I'm not supposed to, because of society.

Without this (bad) option, the list doesn't load after submitting the info, because (I assume) the method is executed past it, since it doesn't wait for it to finish.

What do I exactly have to do in "success:" to make it work? (Or, I've read something about .done() within the $.ajax clause, but I'm not sure how to make it work.)

What's the callback supposed to be like? I've never done it before and I can get really disoriented with the results here because each case is slightly different.

function save() {
    var name = document.getElementById('name');
    var email = document.getElementById('email');
    var telephone = document.getElementById('telephone');

    $.ajax({
        url: "save.php",
        method: "POST",
        data: { name: name.value, email: email.value, telephone: telephone.value },
        success: $("List").load(" List")
    });
}```

Thank you in advanced and if I need include further info don't hesitate to ask.

答:
I will show you piece of solution that I use in my project. I cannot say it is optimal or best practices, but it works for me and can work for you:

PHP:

```<code>     function doLoadMails(){
       //initialize empty variable
       $mails;

      $conn = new mysqli($_POST['ip'], $_POST['login'], $_POST['pass'], $_POST['db']);
         // Check connection
         if ($conn->connect_error) {
         die("");
             }
          //some select, insert, whatever
         $sql = "SELECT ... ... ... ";
          $result = $conn->query($sql);

           if ($result->num_rows > 0) {
               // output data of each row, j is counter for rows
                $j =0;
              while($row_a = $result->fetch_assoc()) {

             //for each row, fill array
            $mails[$j][0] = $row_a["name"] ;
            $mails[$j][1] = $row_a["mail"] ;
            $mails[$j][2] = $row_a["language"] ;

                $j++;

                }
          }

        //if $mails has results (we added something into it)
          if(isset($mails)){
          echo json_encode($mails);/return json*/   }
          else{
//some error message you can handle in JS
echo"[null]";}

    }
</code>```

and then in JS

```<code>function doLoadMails() {

    $.ajax({
        data: { /*pass parameters*/ },
        type: "post",
        url: "dataFunnel.php",
        success: function(data) { /*data is a dummy variable for everything your PHP echoes/returns*/
            console.log(data); //you can check what you get

            if (data != "[null]") { /*some error handling ..., in my case if it matches what I have declared as error state in PHP - !(isset($mails))*/ }
        }
    });
</code>```

Keep in mind, that you can echo/return directly the result of your SQL request and put it into JS in some more raw format, and handle further processing here.

In your solution, you will probably need to echo the return code of the INSERT request.

Body:
I've been trying to make a simple site, and I can't quite wrap my head around some of the things said here, some of which are also unrelated to my situation.

The site has a form with 3 input boxes, a button, and a list. The info is submitted through a separate PHP file to a MySQL database, once the submit button is clicked. I'm supposed to make the list (it's inside a div) update once the info is successfully sent and updated in the database. So far I've made it work with async:false but I'm not supposed to, because of society.

Without this (bad) option, the list doesn't load after submitting the info, because (I assume) the method is executed past it, since it doesn't wait for it to finish.

What do I exactly have to do in "success:" to make it work? (Or, I've read something about .done() within the $.ajax clause, but I'm not sure how to make it work.)

What's the callback supposed to be like? I've never done it before and I can get really disoriented with the results here because each case is slightly different.

function save() {
    var name = document.getElementById('name');
    var email = document.getElementById('email');
    var telephone = document.getElementById('telephone');

    $.ajax({
        url: "save.php",
        method: "POST",
        data: { name: name.value, email: email.value, telephone: telephone.value },
        success: $("List").load(" List")
    });
}

Thank you in advanced and if I need include further info don't hesitate to ask.

Body:
I will show you piece of solution that I use in my project. I cannot say it is optimal or best practices, but it works for me and can work for you:

PHP:

     function doLoadMails(){
       //initialize empty variable
       $mails;

      $conn = new mysqli($_POST['ip'], $_POST['login'], $_POST['pass'], $_POST['db']);
         // Check connection
         if ($conn->connect_error) {
         die("");
             }
          //some select, insert, whatever
         $sql = "SELECT ... ... ... ";
          $result = $conn->query($sql);

           if ($result->num_rows > 0) {
               // output data of each row, j is counter for rows
                $j =0;
              while($row_a = $result->fetch_assoc()) {

             //for each row, fill array
            $mails[$j][0] = $row_a["name"] ;
            $mails[$j][1] = $row_a["mail"] ;
            $mails[$j][2] = $row_a["language"] ;

                $j++;

                }
          }

        //if $mails has results (we added something into it)
          if(isset($mails)){
          echo json_encode($mails);/return json*/   }
          else{
//some error message you can handle in JS
echo"[null]";}

    }

and then in JS

function doLoadMails() {

    $.ajax({
        data: { /*pass parameters*/ },
        type: "post",
        url: "dataFunnel.php",
        success: function(data) { /*data is a dummy variable for everything your PHP echoes/returns*/
            console.log(data); //you can check what you get

            if (data != "[null]") { /*some error handling ..., in my case if it matches what I have declared as error state in PHP - !(isset($mails))*/ }
        }
    });

Keep in mind, that you can echo/return directly the result of your SQL request and put it into JS in some more raw format, and handle further processing here.

In your solution, you will probably need to echo the return code of the INSERT request.


问:
Is there no way to parallelize calls to an executable in Windows
I've got a list of files for each of which I'm calling sox. Because it takes a while I thought I'd speed the process up by parallelizing it, each call to sox is independent of each other so I thought it'd be a simple thing.

But it seems you cannot call the same executable from a different process, as that leads to an The process cannot access the file because it is being used by another process. error.

I'm guessing that is the cause because there's no other file I'm using across different processes. And yet I'm quite surprised by this, why would RO access not be possible? And does that really mean there's absolutely no way for me to speed my program up?

答: Found the error. I had at the end of my sox command 2> $nul to suppress the output. That was of course causing issues. :D


问:
Using PHP Object values in AJAX
I am working on a pet-project. I have a php class. in the HTML, I make instances of that object. So the same page can contain many instances. now, I have to make ajax calls. the ajax call is based on the instances of the object. the data sent in ajax calls is can contain names of database tables and such. I was wondering how safe that is. any thoughts?</p>

答: It is better to call a function, which knows the fields of the DB to query and takes passed values as parameters.</p>

Title: Using PHP Object values in AJAX


问:
Automatically triggering Travis on push to a different repository?
Is there a way to trigger Travis CI build for repository X each time there's a push to repository Y? Specifically, I want my builds to start each time there's a push to http://github.com/tensorflow/tensorflow</p>

答:
Good question! Here are some solutions that I could think of:

If you have admin privileges on the repo (or know someone who does), you could create a webhook that subscribes to the push event and when triggered, start a build on Travis CI using the Travis API.

This would entail:

Creating a new GitHub webhook over on http://github.com/tensorflow/tensorflow/settings/hooks/new. While of course, customizing the settings as you see fit, but with the information I have, I recommend using the application/json content type and only have GitHub trigger the webhook with the push event.

Write a small web app expecting the HTTP POST payloads from GitHub and start builds using Travis CI's API. This web app can be written in any language but it must be deployed to somewhere that is always awake and listening (to prevent missing builds).

Here's my example of that.

```<code>post "/push-webhook" do
  uri = URI.parse("https://api.travis-ci.org/repo/your-org/your-repo/requests")

  request = Net::HTTP::Get.new(uri.request_uri)
  request["Content-Type"] = "application/json"
  request["Accept"] = "application/json"
  request["Travis-API-Version"] = "3"
  request["Authorization"] = "token your-token"

  body = { "request" => { "branch" => "master" } }
  request.body = body.to_json

  response = http.request(request)
end
</code>```

And voila! Once this web app is deployed, and your GitHub webhook is configured properly, you should see builds to run on Travis CI with every new push on http://github.com/tensorflow/tensorflow.

Helpful documentation

https://docs.travis-ci.com/user/triggering-builds/

https://developer.github.com/webhooks/

https://developer.github.com/webhooks/configuring/

However, if you do not have admin privileges on the repo, you could create a mirror of repository that is in your control and then follow the instructions above (with a few differences). From the little research I did, it's not possible (or at least not easy) to create a mirror of a repository all on GitHub without admin access of the original/official repository.

With that said, I found a workaround that should work.

Import tensorflow/tensorflow to GitLab and use the Mirror Repository feature so it mirrors http://github.com/tensorflow/tensorflow as your GitLab repo's upstream.

From there, follow the instructions above as normal except use GitLab's webhook API instead of GitHub's to send push events to trigger our web app to start builds on Travis CI.

Helpful documentation

https://about.gitlab.com/2016/12/01/how-to-keep-your-fork-up-to-date-with-its-origin/

https://docs.gitlab.com/ce/user/project/integrations/webhooks.html

I hope this information was helpful. Please let me know if you have any other questions and I'd be happy to help in any way I can. :)

Body:
Good question! Here are some solutions that I could think of:

If you have admin privileges on the repo (or know someone who does), you could create a webhook that subscribes to the push event and when triggered, start a build on Travis CI using the Travis API.

This would entail:

Creating a new GitHub webhook over on http://github.com/tensorflow/tensorflow/settings/hooks/new. While of course, customizing the settings as you see fit, but with the information I have, I recommend using the application/json content type and only have GitHub trigger the webhook with the push event.

Write a small web app expecting the HTTP POST payloads from GitHub and start builds using Travis CI's API. This web app can be written in any language but it must be deployed to somewhere that is always awake and listening (to prevent missing builds).

Here's my example of that.

post "/push-webhook" do
  uri = URI.parse("https://api.travis-ci.org/repo/your-org/your-repo/requests")

  request = Net::HTTP::Get.new(uri.request_uri)
  request["Content-Type"] = "application/json"
  request["Accept"] = "application/json"
  request["Travis-API-Version"] = "3"
  request["Authorization"] = "token your-token"

  body = { "request" => { "branch" => "master" } }
  request.body = body.to_json

  response = http.request(request)
end

And voila! Once this web app is deployed, and your GitHub webhook is configured properly, you should see builds to run on Travis CI with every new push on http://github.com/tensorflow/tensorflow.

Helpful documentation

https://docs.travis-ci.com/user/triggering-builds/

https://developer.github.com/webhooks/

https://developer.github.com/webhooks/configuring/

However, if you do not have admin privileges on the repo, you could create a mirror of repository that is in your control and then follow the instructions above (with a few differences). From the little research I did, it's not possible (or at least not easy) to create a mirror of a repository all on GitHub without admin access of the original/official repository.

With that said, I found a workaround that should work.

Import tensorflow/tensorflow to GitLab and use the Mirror Repository feature so it mirrors http://github.com/tensorflow/tensorflow as your GitLab repo's upstream.

From there, follow the instructions above as normal except use GitLab's webhook API instead of GitHub's to send push events to trigger our web app to start builds on Travis CI.

Helpful documentation

https://about.gitlab.com/2016/12/01/how-to-keep-your-fork-up-to-date-with-its-origin/

https://docs.gitlab.com/ce/user/project/integrations/webhooks.html

I hope this information was helpful. Please let me know if you have any other questions and I'd be happy to help in any way I can. :)


问:
Get Current date in SQLBase
I have an SQLBase and I am trying to get the current date of the system to be equal to the date of a column (create_date).

The MySQL Code will be:

```<code>Select * From Date D
Where D.Create_date=CURDATE();
</code>```

Can someone suggest me a way to take the current date in a SQLBase?

The date format should only contain the date(yyyy-MM-dd) and not the timestamp.

答:
This should get you the results you want:</p>

```<code>DECLARE @Temp TABLE (
Col1 NVARCHAR(1)
,Date  date
)

INSERT INTO @Temp
VALUES
('a','2017-12-08')
,('b','2017-12-08')

SELECT *
FROM @Temp
WHERE Date = CONVERT(date, getdate())
</code>```

Title: Get Current date in SQLBase

Body:
I have an SQLBase and I am trying to get the current date of the system to be equal to the date of a column (create_date).

The MySQL Code will be:

Select * From Date D
Where D.Create_date=CURDATE();

Can someone suggest me a way to take the current date in a SQLBase?

The date format should only contain the date(yyyy-MM-dd) and not the timestamp.

Body:
This should get you the results you want:

DECLARE @Temp TABLE (
Col1 NVARCHAR(1)
,Date  date
)

INSERT INTO @Temp
VALUES
('a','2017-12-08')
,('b','2017-12-08')

SELECT *
FROM @Temp
WHERE Date = CONVERT(date, getdate())


问:
Django ajax file upload form - file not uploading
I have a file upload form in html with which I'm trying to upload a file(and file size to display) via ajax call. I'm using django. Whenever I try to do anything nothing happens. Here's the upload form:

```<code><form class="uploadForm" method="post" enctype="multipart/form-data">
  {% csrf_token %}
  <input type="file" id="uploadFile">
  <input type="submit" class="button" id="uploadButton" value="Upload">
</form>
</code>```

Here's my Jquery + Ajax:

```<code>$('.uploadForm').on('submit', function(event){
  event.preventDefault();
  var fileSize = ($('#uploadFile')[0].files[0].size/1024);
  var fileName = $('#uploadFile')[0].files[0].name;
  var realSize = sizeConverter(fileSize);
  var fileData = new FormData($('#uploadFile')[0]);
  var csrfToken = '{{ csrf_token }}';
  $.ajax({
    url: '{% url 'project:uploadFile' %}',
    type: 'post',
    data: {
      'fileData': fileData,
      'fileSize': realSize,
      csrfmiddlewaretoken: '{{ csrf_token }}'
     },
    cache: false,
    processData: false,
    contentType: false,
    success: function(data){
      alert(data);
    }
  });
});
</code>```

Here are views.py:

```<code>class uploadFile(TemplateView):
template_name = "project/uploadFile.html"

def post(self, request):
    fileSize = request.POST.get('fileSize')
    fileData = request.FILES['fileData']
    return JsonResponse(fileSize, safe=False)
</code>```

Now, with this setup when I submit the form nothing happens. I don't get any errors in the console, nothing.
When I remove 'fileData' from data and cache: false, processData: false, contentType: false, inside Ajax this works(text only though).
I tried changing new FormData($('#uploadFile')[0]); to new FormData($('#uploadFile').get(0)); but that did not help. I am guessing the issue here is with the fileData variable but what could be wrong with it? I appreciate your help.

Thanks

答:
Based on the documentation on FormData(), the correct approach would be in the sense of:

```<code>var formData = new FormData();
formData.append('fileSize', sizeConverter($('#uploadFile')[0].files[0].size/1024));
formData.append('file', $('#uploadFile')[0].files[0]);
formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');
$.ajax({
    url: "{% url 'project:uploadFile' %}",
    type: 'post',
    data: formData,
    cache: false,
    processData: false,
    contentType: false,
    success: function(data){
      alert(data);
    }
});
</code>```

The issue is probably here $('#uploadFile')[0]. It should be $('#uploadFile')[0].files[0]. Also, url syntax has an error with quotes.

Body:
I have a file upload form in html with which I'm trying to upload a file(and file size to display) via ajax call. I'm using django. Whenever I try to do anything nothing happens. Here's the upload form:

<form class="uploadForm" method="post" enctype="multipart/form-data">
  {% csrf_token %}
  <input type="file" id="uploadFile">
  <input type="submit" class="button" id="uploadButton" value="Upload">
</form>

Here's my Jquery + Ajax:

$('.uploadForm').on('submit', function(event){
  event.preventDefault();
  var fileSize = ($('#uploadFile')[0].files[0].size/1024);
  var fileName = $('#uploadFile')[0].files[0].name;
  var realSize = sizeConverter(fileSize);
  var fileData = new FormData($('#uploadFile')[0]);
  var csrfToken = '{{ csrf_token }}';
  $.ajax({
    url: '{% url 'project:uploadFile' %}',
    type: 'post',
    data: {
      'fileData': fileData,
      'fileSize': realSize,
      csrfmiddlewaretoken: '{{ csrf_token }}'
     },
    cache: false,
    processData: false,
    contentType: false,
    success: function(data){
      alert(data);
    }
  });
});

Here are views.py:

class uploadFile(TemplateView):
template_name = "project/uploadFile.html"

def post(self, request):
    fileSize = request.POST.get('fileSize')
    fileData = request.FILES['fileData']
    return JsonResponse(fileSize, safe=False)

Now, with this setup when I submit the form nothing happens. I don't get any errors in the console, nothing.
When I remove 'fileData' from data and cache: false, processData: false, contentType: false, inside Ajax this works(text only though).
I tried changing new FormData($('#uploadFile')[0]); to new FormData($('#uploadFile').get(0)); but that did not help. I am guessing the issue here is with the fileData variable but what could be wrong with it? I appreciate your help.

Thanks

Body:
Based on the documentation on FormData(), the correct approach would be in the sense of:

var formData = new FormData();
formData.append('fileSize', sizeConverter($('#uploadFile')[0].files[0].size/1024));
formData.append('file', $('#uploadFile')[0].files[0]);
formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');
$.ajax({
    url: "{% url 'project:uploadFile' %}",
    type: 'post',
    data: formData,
    cache: false,
    processData: false,
    contentType: false,
    success: function(data){
      alert(data);
    }
});

The issue is probably here $('#uploadFile')[0]. It should be $('#uploadFile')[0].files[0]. Also, url syntax has an error with quotes.


问:
UiTextView localized with xib strings file
I use base internationalization in xCode to manage multiple languages in my app.

In a xib file I've got this object :

```<code>Xrj-9E-2VK it's an UITextView
</code>```

In the corresponding strings file :

```<code>"Xrj-9E-2VK.text" = "text translated in french"
</code>```

But my text is still in English.

Any Suggestion ?

答:
If you want to use the existing MainStoryboard.strings file you can programmatically assign the text of your textview using localizedStringForKey:value:table: like this

[[NSBundle mainBundle] localizedStringForKey:@"abc-12-3ba.text" value:@"" table:@"MainStoryboard"]

Body:
I use base internationalization in xCode to manage multiple languages in my app.

In a xib file I've got this object :

Xrj-9E-2VK it's an UITextView

In the corresponding strings file :

"Xrj-9E-2VK.text" = "text translated in french"

But my text is still in English.

Any Suggestion ?


问:
Deleting CloudKit Records Swift 4
I am having issues deleting CloudKit records. This is my first time dealing with the API and apparently there are two ways to do this.

Saving records is straight forward and ostensibly so is deleting them, except this doesn't do it:

```<code>func deleteRecords() {

    let recordID = record.recordID
    publicDatabase.delete(withRecordID: recordID) { (recordID, error) in
        guard let recordID = recordID else {
        print(error!.localizedDescription)
            return
    }
        print("Record \(recordID) was successfully deleted")
    }
}
</code>```

I understand using a ckModifyRecordsOperation is another way to do this but this is a batch operation. I only need to delete one record at a time. Here's my code for that:

```<code> func batchDelete() {
    let recordIDsToDelete = [CKRecordID]()
    let operation = CKModifyRecordsOperation(recordsToSave: nil, recordIDsToDelete: recordIDsToDelete)
    operation.modifyRecordsCompletionBlock = { savedRecords, deletedRecordIDs, error in
        // handle errors here
    }
    publicDatabase.add(operation)
    print("Batch \(recordIDsToDelete) record was successfully deleted")
}
</code>```

Neither of these separately or together are working for me.

答:
You are correct, there are two ways. The first way you describe is referred to by Apple as a "convenience" function. If you're just deleting a single record, it's probably the quickest option to implement. However, each convenience operation conducts its own trip to the database. If you loop through thousands of records and delete them individually with the convenience function, you're going to use a lot of your cloudKit quota making a series of individual calls.

The second option, the operation, let's you batch the deletes and send them in one operation. Generally, this will be a more efficient use of your cloudkit quotas. But, according to Apple docs, there's no technical difference between the two; the the convenience function is just a wrapper to the operation.

Now, to your specific problem, the operation has two separate completion blocks: perRecordCompletionBlock and modifyRecordsCompletionBlock. As the names imply, the first block is called after each and every record is processed in the operation and that's where errors are surfaced. Make sure you implement perRecordCompletionBlock and check for errors there (and then you'll have to decide if your error handling steps belong in the perRecordCompletionBlock or the modifyRecordsCompletionBlock).

Finally, if the operation (or convenience function) is running and you confirm that the completion blocks fire without errors but the record still doesn't delete, this typically indicates you passed nil rather than a valid record to the deletion.

Title: Deleting CloudKit Records Swift 4

Body:
I am having issues deleting CloudKit records. This is my first time dealing with the API and apparently there are two ways to do this.

Saving records is straight forward and ostensibly so is deleting them, except this doesn't do it:

func deleteRecords() {

    let recordID = record.recordID
    publicDatabase.delete(withRecordID: recordID) { (recordID, error) in
        guard let recordID = recordID else {
        print(error!.localizedDescription)
            return
    }
        print("Record \(recordID) was successfully deleted")
    }
}

I understand using a ckModifyRecordsOperation is another way to do this but this is a batch operation. I only need to delete one record at a time. Here's my code for that:

 func batchDelete() {
    let recordIDsToDelete = [CKRecordID]()
    let operation = CKModifyRecordsOperation(recordsToSave: nil, recordIDsToDelete: recordIDsToDelete)
    operation.modifyRecordsCompletionBlock = { savedRecords, deletedRecordIDs, error in
        // handle errors here
    }
    publicDatabase.add(operation)
    print("Batch \(recordIDsToDelete) record was successfully deleted")
}

Neither of these separately or together are working for me.


问:
Scala & Spark: Cast multiple columns at once
Since the VectorAssembler is crashing, if a passed column has any other type than NumericType or BooleanType and I'm dealing with a lot of TimestampType columns, I want to know:

Is there a easy way, to cast multiple columns at once?

Based on this answer I already have a convenient way to cast a single column:

```<code>def castColumnTo(df: DataFrame,
    columnName: String,
    targetType: DataType ) : DataFrame = {
      df.withColumn( columnName, df(columnName).cast(targetType) )
}
</code>```

I thought about calling castColumnTo recursively, but I strongly doubt that that's the (performant) way to go.

答:
I am translating scala program for python. I found smart answer to your problem.
The column are named V1 - V28, Time, Amount, Class.
(I am not Scala pro)
The solution looks like this.

```<code>// cast all the column to Double type.
val df = raw.select(((1 to 28).map(i => "V" + i) ++ Array("Time", "Amount", "Class")).map(s => col(s).cast("Double")): _*)
</code>```

The link: https://github.com/intel-analytics/analytics-zoo/blob/master/apps/fraudDetection/Fraud%20Detction.ipynb

Body:
Since the VectorAssembler is crashing, if a passed column has any other type than NumericType or BooleanType and I'm dealing with a lot of TimestampType columns, I want to know:

Is there a easy way, to cast multiple columns at once?

Based on this answer I already have a convenient way to cast a single column:

def castColumnTo(df: DataFrame,
    columnName: String,
    targetType: DataType ) : DataFrame = {
      df.withColumn( columnName, df(columnName).cast(targetType) )
}

I thought about calling castColumnTo recursively, but I strongly doubt that that's the (performant) way to go.

Body:
I am translating scala program for python. I found smart answer to your problem.
The column are named V1 - V28, Time, Amount, Class.
(I am not Scala pro)
The solution looks like this.

// cast all the column to Double type.
val df = raw.select(((1 to 28).map(i => "V" + i) ++ Array("Time", "Amount", "Class")).map(s => col(s).cast("Double")): _*)

The link: https://github.com/intel-analytics/analytics-zoo/blob/master/apps/fraudDetection/Fraud%20Detction.ipynb


问:
How to delay the .keyup() handler until the user stops typing?
I’ve got a search field. Right now it searches for every keyup. So if someone types “Windows”, it will make a search with AJAX for every keyup: “W”, “Wi”, “Win”, “Wind”, “Windo”, “Window”, “Windows”.

I want to have a delay, so it only searches when the user stops typing for 200 ms.

There is no option for this in the keyup function, and I have tried setTimeout, but it didn’t work.

How can I do that?

答:
Building upon CMS's answer here's new delay method which preserves 'this' in its usage:

```<code>var delay = (function(){
  var timer = 0;
  return function(callback, ms, that){
    clearTimeout (timer);
    timer = setTimeout(callback.bind(that), ms);
  };
})();
</code>```

Usage:

```<code>$('input').keyup(function() {
    delay(function(){
      alert('Time elapsed!');
    }, 1000, this);
});
</code>```

Body:
Building upon CMS's answer here's new delay method which preserves 'this' in its usage:

var delay = (function(){
  var timer = 0;
  return function(callback, ms, that){
    clearTimeout (timer);
    timer = setTimeout(callback.bind(that), ms);
  };
})();

Usage:

$('input').keyup(function() {
    delay(function(){
      alert('Time elapsed!');
    }, 1000, this);
});


问:
Is there any good add-ins in Visual C#2008?
My visual assist x didn't work after I installed visual c# 2008.
Is there any good add-ins like VAX? </p>

答: It really depends on what you want to do with the add-ins.  My personal favorite is ViEmu which makes Visual Studio respect the Vim keybindings.  It takes some getting used to, but once you have it down, the Vim way of doing things is extremely efficient.</p>

OwnerDisplayName: Jinx

LastEditorDisplayName: Jinx

OwnerDisplayName: Steve Rowe


问:
React Router negate path
I'm using the nested routing functionality of react-router-dom v4 and there is one use case that I haven't found a solution for.

I have two Routes at the root component.

One for almost the entirety of the site and the other for the account section.

I was hoping to be able to do something like...

<Route path="/^(account)" ... />

... or something similar, but I so far have been unable to get that working. Is there a mechanism for this?

EDIT Based on Comment:

The BrowserRouter component has two defined Routes.

```<code>/*
 * Would serve as the root route for all pages that aren't under account.
 * i.e.
 * /
 * /about
 * /some-section
 */
<Route path="/^(account)" component={SiteLayout} />

/*
 * The other would respond on...
 * /account
 * /account/forgot
 * etc.
 */
<Route path="/account" component={Account} />
</code>```

Hopefully that demonstrates what I'm looking for a bit more clearly.

答:
Surely you could just use a catch all for all other routes?</p>

```<code><Router>
    <Switch>
      <Route path="/account" component={Account} />
      <Route component={NotAccount} />
    </Switch>
</Router>
</code>```

Title: React Router negate path

Body:
I'm using the nested routing functionality of react-router-dom v4 and there is one use case that I haven't found a solution for.

I have two Routes at the root component.

One for almost the entirety of the site and the other for the account section.

I was hoping to be able to do something like...

<Route path="/^(account)" ... />

... or something similar, but I so far have been unable to get that working. Is there a mechanism for this?

EDIT Based on Comment:

The BrowserRouter component has two defined Routes.

/*
 * Would serve as the root route for all pages that aren't under account.
 * i.e.
 * /
 * /about
 * /some-section
 */
<Route path="/^(account)" component={SiteLayout} />

/*
 * The other would respond on...
 * /account
 * /account/forgot
 * etc.
 */
<Route path="/account" component={Account} />

Hopefully that demonstrates what I'm looking for a bit more clearly.

Body:
Surely you could just use a catch all for all other routes?

<Router>
    <Switch>
      <Route path="/account" component={Account} />
      <Route component={NotAccount} />
    </Switch>
</Router>


问:
Trying to change the x-position-variable, but only the value changes, not the position of the ctx
I'm trying to make a click and drag functionality, so that when I click and hold, I will be able to move a "brick". But when I try to change the x-position to e.clientX inside my mousemove eventListener, only the value of the variable changes, and the brick doesn't change position. Even if i simply change the x-position to a number, nothing but the value changes. I tried console.log the var, and as I said, the value changes.

var brick1 = { //my brick variables
 x: 0,
 y: 0,
 width: brickWidth,
 height: brickHeight,
 img: "media/brick.png",
 clicked: false
 };

var myBrick1 = new object(brick1.img, brick1.x, brick1.y, brick1.width, brick1.height); //my actual brick object

document.addEventListener("mousemove", mouseMoveHandler, false);
function mouseMoveHandler(e){
  var mouseX = e.clientX - (canvas.offsetLeft+10);
  var mouseY = e.clientY - (canvas.offsetTop+10);

  if(brick1.clicked){
    brick1.x = 120; //The value changes, but not the position
    brick1.x = mouseX - (brick1.width/2);
    console.log(brick1.clicked);
    console.log(brick1.x);
  }
}

 ```

Can someone tell me why this is happening? And hopefully how to fix it?
Let me know if you need more samples from my code to see the issue.

答:
You are expecting a pass by value to work as a pass by reference in your constructor.

```<code>var myBrick1 = new object(brick1.img, brick1.x, brick1.y, brick1.width, brick1.height); //my actual brick object
</code>```

Here you use a new object to construct from the values of brick1 and assign to the new object. I assumed your constructor looks something like

```<code>function object(img, x, y, w, h) {
  this.img = img;  /* object so reference assignment */
  this.x = x;      /* number so value assignment */
  this.y = y;      /* number so value assignment */
  this.w = w;      /* number so value assignment */
  this.h = h;      /* number so value assignment */
  /* some methods ect... */
}
</code>```

when you then change the value of brick1

```<code>if(brick1.clicked){
  brick1.x = 120; //The value changes, but not the position
  brick1.x = mouseX - (brick1.width/2);
  console.log(brick1.clicked);
  console.log(brick1.x);
}
</code>```

This only changes the brick1 values of properties x and y. Since they were passed to the objects as values not references.

You can change your code to

```<code>myBrick1.x = 120;
</code>```

It is a good thing this doesn't assign by reference or all your bricks would have the same x, y coordinates.  Full altered statement:

```<code>if(brick1.clicked) {
  myBrick1.x = 120; //The value changes, but not the position
  myBrick1.x = mouseX - (myBrick1.width/2);
  console.log(brick1.clicked);
  console.log(brick1.x);
}
</code>```

Body:
I'm trying to make a click and drag functionality, so that when I click and hold, I will be able to move a "brick". But when I try to change the x-position to e.clientX inside my mousemove eventListener, only the value of the variable changes, and the brick doesn't change position. Even if i simply change the x-position to a number, nothing but the value changes. I tried console.log the var, and as I said, the value changes.

var brick1 = { //my brick variables
 x: 0,
 y: 0,
 width: brickWidth,
 height: brickHeight,
 img: "media/brick.png",
 clicked: false
 };

var myBrick1 = new object(brick1.img, brick1.x, brick1.y, brick1.width, brick1.height); //my actual brick object

document.addEventListener("mousemove", mouseMoveHandler, false);
function mouseMoveHandler(e){
  var mouseX = e.clientX - (canvas.offsetLeft+10);
  var mouseY = e.clientY - (canvas.offsetTop+10);

  if(brick1.clicked){
    brick1.x = 120; //The value changes, but not the position
    brick1.x = mouseX - (brick1.width/2);
    console.log(brick1.clicked);
    console.log(brick1.x);
  }
}

Can someone tell me why this is happening? And hopefully how to fix it?
Let me know if you need more samples from my code to see the issue.

Body:
You are expecting a pass by value to work as a pass by reference in your constructor.

var myBrick1 = new object(brick1.img, brick1.x, brick1.y, brick1.width, brick1.height); //my actual brick object

Here you use a new object to construct from the values of brick1 and assign to the new object. I assumed your constructor looks something like

function object(img, x, y, w, h) {
  this.img = img;  /* object so reference assignment */
  this.x = x;      /* number so value assignment */
  this.y = y;      /* number so value assignment */
  this.w = w;      /* number so value assignment */
  this.h = h;      /* number so value assignment */
  /* some methods ect... */
}

when you then change the value of brick1

if(brick1.clicked){
  brick1.x = 120; //The value changes, but not the position
  brick1.x = mouseX - (brick1.width/2);
  console.log(brick1.clicked);
  console.log(brick1.x);
}

This only changes the brick1 values of properties x and y. Since they were passed to the objects as values not references.

You can change your code to

myBrick1.x = 120;

It is a good thing this doesn't assign by reference or all your bricks would have the same x, y coordinates.  Full altered statement:

if(brick1.clicked) {
  myBrick1.x = 120; //The value changes, but not the position
  myBrick1.x = mouseX - (myBrick1.width/2);
  console.log(brick1.clicked);
  console.log(brick1.x);
}


问:
XNA mouse picking issues
I am pulling my hair out over this mouse picking thing. I do not know if the problem lies in my Ray calculation or my BoundingSpheres, anyway here's the code for my ray calculations:

```<code>public Ray CalculateRay(InputManager input)
{
    Vector3 nearSource = new Vector3(input.CurrentMousePosition, 0f);
    Vector3 farSource = new Vector3(input.CurrentMousePosition, 1f);

    Vector3 nearPoint = Engine.Device.Viewport.Unproject(nearSource, _projectionMatrix,
    _viewMatrix, Matrix.Identity);

    Vector3 farPoint = Engine.Device.Viewport.Unproject(farSource,
    _projectionMatrix, _viewMatrix, Matrix.Identity);

    Vector3 direction = farPoint - nearPoint;
    direction.Normalize();

    return new Ray(nearPoint, direction);
}
</code>```

and for the intersection check:

```<code>public bool RayIntersectsModel()
{
    foreach (ModelMesh mesh in _model.Meshes)
    {
        BoundingSphere sphere = mesh.BoundingSphere;

        sphere.Center = _position;

        Ray ray = Engine.Camera.CalculateRay(Engine.Input);

        if (sphere.Intersects(ray) != null)
        {
           return true;
        }
    }
    return false;
}
</code>```

It's not like it isn't working at all but it seems to be very inaccurate... or something. The models are just spheres, very simple. Any help or insight would be greatly appreciated!
Thanks!

答: Well, when I was transforming my bounding sphere I was first applying the world matrix then the bone transforms. This seems to put the bounding sphere in the wrong place. Switching it to first applying the bone transforms THEN the world matrix did it.</p>

Title: XNA mouse picking issues

Body:
I am pulling my hair out over this mouse picking thing. I do not know if the problem lies in my Ray calculation or my BoundingSpheres, anyway here's the code for my ray calculations:

public Ray CalculateRay(InputManager input)
{
    Vector3 nearSource = new Vector3(input.CurrentMousePosition, 0f);
    Vector3 farSource = new Vector3(input.CurrentMousePosition, 1f);

    Vector3 nearPoint = Engine.Device.Viewport.Unproject(nearSource, _projectionMatrix,
    _viewMatrix, Matrix.Identity);

    Vector3 farPoint = Engine.Device.Viewport.Unproject(farSource,
    _projectionMatrix, _viewMatrix, Matrix.Identity);

    Vector3 direction = farPoint - nearPoint;
    direction.Normalize();

    return new Ray(nearPoint, direction);
}

and for the intersection check:

public bool RayIntersectsModel()
{
    foreach (ModelMesh mesh in _model.Meshes)
    {
        BoundingSphere sphere = mesh.BoundingSphere;

        sphere.Center = _position;

        Ray ray = Engine.Camera.CalculateRay(Engine.Input);

        if (sphere.Intersects(ray) != null)
        {
           return true;
        }
    }
    return false;
}

It's not like it isn't working at all but it seems to be very inaccurate... or something. The models are just spheres, very simple. Any help or insight would be greatly appreciated!
Thanks!


问:
Push footer to bottom when page is not full
I'm developing a mobile web app. This is the main structure from top to bottom: header div, menu div, content div, footer div. The header, menu and footer are constant and pages are loaded into the content div using ajax.

Some of the pages have lots of content and they fill out the page so scroll is needed. Some of the pages have only one or two lines of content so they leave a big empty part (Not necessarily different pages - one page for example shows a list of orders, you can have no orders and you can have hundreds...).

This is what i want to achieve: If the page is not full with content, the footer will be in the bottom of the page. If the page is full and scroll is needed, the footer will be immediately after the content (so you scroll down the page and in the end you reach the footer).

The sticky footer solutions are not good for me because i don't want the footer to stick to the bottom always, only when the page is not full of content.

Is there anyway to achieve that? Thanks.

答:
This solution worked for me. I think this is perfect if you have more than only a #header and #footer. It just push the content down with a padding-bottom if body is smaller than the viewport.</p>

```<code>function autoHeight() {
    var bodyHeight = $("body").height();
    var vwptHeight = $(window).height();
    var gap = vwptHeight - bodyHeight;
    if (vwptHeight > bodyHeight) {
        $("#content").css( "padding-bottom" , gap );
    } else {
        $("#content").css( "padding-bottom" , "0" );
    }
}
$(document).ready(function() {
    autoHeight();
});
$(window).resize(function() {
    autoHeight();
});
</code>```

Body:
This solution worked for me. I think this is perfect if you have more than only a #header and #footer. It just push the content down with a padding-bottom if body is smaller than the viewport.

function autoHeight() {
    var bodyHeight = $("body").height();
    var vwptHeight = $(window).height();
    var gap = vwptHeight - bodyHeight;
    if (vwptHeight > bodyHeight) {
        $("#content").css( "padding-bottom" , gap );
    } else {
        $("#content").css( "padding-bottom" , "0" );
    }
}
$(document).ready(function() {
    autoHeight();
});
$(window).resize(function() {
    autoHeight();
});


问:
Lead function in Hive
I am trying to retrieve the next "name1" after a specific "name2". For example, next "name1" after "complete2" in "name2" is "init3". This is the query I use, but it returns null.</p>

```<code>    date_time                    name1        name2
    2017-11-23 00:09:46          init1        complete1
    2017-11-23 00:09:48          init2        complete2
    2017-11-23 00:09:50          init3        complete3

   select date_time,name1,name2,
   lead(name1,1) over (order by date_time) as next_word
   from tab1
   where date_time between "2017-11-23 00:00:00" and "2017-11-23 23:59:59"
   and name2 like "%complete2%";
</code>```

答:
Here is the solution

```<code>SELECT *
  FROM (SELECT date_time,name1,name2,
               LEAD(name1,1) over (ORDER BY date_time) AS next_word
          FROM tab1
         WHERE date_time between "2017-11-23 00:00:00" and "2017-11-23 23:59:59" ) v
 WHERE name2 LIKE "%complete2%";
</code>```

Output

```<code>2017-11-23 00:09:48 init2   complete2   init3
</code>```

Hive evaluates the WHERE conditions before applying the LEAD. In your query that would have limited the LEAD to be applied in one record for which there was no LEAD.

You can use a subquery like I have done above or use a CTE/ WITH Clause.

Hope this helps!

Title: Lead function in Hive

Body:
I am trying to retrieve the next "name1" after a specific "name2". For example, next "name1" after "complete2" in "name2" is "init3". This is the query I use, but it returns null.

    date_time                    name1        name2
    2017-11-23 00:09:46          init1        complete1
    2017-11-23 00:09:48          init2        complete2
    2017-11-23 00:09:50          init3        complete3

   select date_time,name1,name2,
   lead(name1,1) over (order by date_time) as next_word
   from tab1
   where date_time between "2017-11-23 00:00:00" and "2017-11-23 23:59:59"
   and name2 like "%complete2%";

Body:
Here is the solution

SELECT *
  FROM (SELECT date_time,name1,name2,
               LEAD(name1,1) over (ORDER BY date_time) AS next_word
          FROM tab1
         WHERE date_time between "2017-11-23 00:00:00" and "2017-11-23 23:59:59" ) v
 WHERE name2 LIKE "%complete2%";

Output

2017-11-23 00:09:48 init2   complete2   init3

Hive evaluates the WHERE conditions before applying the LEAD. In your query that would have limited the LEAD to be applied in one record for which there was no LEAD.

You can use a subquery like I have done above or use a CTE/ WITH Clause.

Hope this helps!


问:
Cannot connect to EC2 - ssh: connect to host port 22: Connection refused
I am currently overseas and I am trying to connect to my EC2 instance through ssh but I am getting the error ssh: connect to host ec2-34-207-64-42.compute-1.amazonaws.com port 22: Connection refused

I turned on my vpn to New York but still nothing changes. What reasons could there be for not being able to connect to this instance?

The instance is still running and serving the website but I am not able to connect through ssh. Is this a problem with the wifi where I am staying or with the instance itself?

答:
In AWS, navigate to Services > EC2.

Under Resources, select Running Instances.

Highlight your instance and click Connect.

In Terminal, cd into the directory containing your key and copy the command in step 3 under "To access your instance."

In Terminal, run: ssh -vvv -i [MyEC2Key].pem ec2-user@xx.xx.xx.xx(xx.xx.xx.xx = your EC2 Public IP) OR run the command in the example under step 4.


问:
How can I get the list of flavor dimensions in build.gradle?
In my build.gradle, I have

```<code>android {
    flavorDimensions "first", "second"
    productFlavors {
        a {
            dimension "first"
        }
...
}
</code>```

How can I get the list of flavorDimensions in the same order that gradle will use when creating the combinations of flavors?

答: It's available as an ArrayList from android.flavorDimensionList.

Body:
In my build.gradle, I have

android {
    flavorDimensions "first", "second"
    productFlavors {
        a {
            dimension "first"
        }
...
}

How can I get the list of flavorDimensions in the same order that gradle will use when creating the combinations of flavors?


问:
Emulating static constructors for templated classes

I would like to have a templated class with a static data member, and initialize it by emulating a "static constructor." For a non-templated class, this has already been answered (see static constructors in C++? I need to initialize private static objects and What is a static constructor?). However, none of the answers seem to work for a templated class.

The following is an example that tries to adapt the "static constructor" idiom from the previous answers to a templated class. (Note that the example is simply initializing an int and could be written without such constructors; however, I require a general solution.)

```<code>#include <iostream>

struct Foo
{
    static int x;
    static struct init
    {
        init()
        {
            std::cout << "Initializing Foo..." << std::endl;
            x = 1;
        }
    } initializer;
};
int Foo::x;
Foo::init Foo::initializer;

template<int N>
struct Bar
{
    static int x;
    static struct init
    {
        init()
        {
            std::cout << "Initializing Bar..." << std::endl;
            x = N;
        }
    } initializer;
};

template<int N>
int Bar<N>::x;
template<int N>
typename Bar<N>::init Bar<N>::initializer;

int main()
{
    std::cout << Foo::x << std::endl;
    std::cout << Bar<1>::x << std::endl;
    return 0;
}
</code>```

This outputs:

```<code>Initializing Foo...
1
0
</code>```

But I expected it to output:

```<code>Initializing Foo...
Initializing Bar...
1
1
</code>```

Is this an example of the "static initialization order fiasco?"

答:
I have found a clean solution that works for any data type. Since the assignment operation inside a template is evaluated when the compiler comes across a specific Bar<N>::x to instantiate, we can write:

```<code>template<int N>
int Bar<N>::x = init<N>();
</code>```

where init() is a function templated on N that returns an int. Additionally, init() will only be called once for each value of N that the compiler instantiates.

As a more useful example, here I initialize a static std::array according to some arbitrary function:

```<code>#include <iostream>
#include <array>

template<int N>
struct Foo
{
    static std::array<double,N> x;
};

template<int N>
std::array<double,N> init()
{
    std::array<double,N> y;
    for (int i=0; i<N; ++i) {
        y[i] = (double)(i*i+i)/N;
    }
    return y;
}

template<int N>
std::array<double,N> Foo<N>::x = init<N>();

int main()
{
    const int N = 10;
    for (int i=0; i<N; ++i) {
        std::cout << Foo<N>::x[i] << std::endl;
    }
    return 0;
}
</code>```

Body:
I would like to have a templated class with a static data member, and initialize it by emulating a "static constructor." For a non-templated class, this has already been answered (see static constructors in C++? I need to initialize private static objects and What is a static constructor?). However, none of the answers seem to work for a templated class.

The following is an example that tries to adapt the "static constructor" idiom from the previous answers to a templated class. (Note that the example is simply initializing an int and could be written without such constructors; however, I require a general solution.)

#include <iostream>

struct Foo
{
    static int x;
    static struct init
    {
        init()
        {
            std::cout << "Initializing Foo..." << std::endl;
            x = 1;
        }
    } initializer;
};
int Foo::x;
Foo::init Foo::initializer;

template<int N>
struct Bar
{
    static int x;
    static struct init
    {
        init()
        {
            std::cout << "Initializing Bar..." << std::endl;
            x = N;
        }
    } initializer;
};

template<int N>
int Bar<N>::x;
template<int N>
typename Bar<N>::init Bar<N>::initializer;

int main()
{
    std::cout << Foo::x << std::endl;
    std::cout << Bar<1>::x << std::endl;
    return 0;
}

This outputs:

Initializing Foo...
1
0

But I expected it to output:

Initializing Foo...
Initializing Bar...
1
1

Is this an example of the "static initialization order fiasco?"

Body:
I have found a clean solution that works for any data type. Since the assignment operation inside a template is evaluated when the compiler comes across a specific Bar<N>::x to instantiate, we can write:

template<int N>
int Bar<N>::x = init<N>();

where init() is a function templated on N that returns an int. Additionally, init() will only be called once for each value of N that the compiler instantiates.

As a more useful example, here I initialize a static std::array according to some arbitrary function:

#include <iostream>
#include <array>

template<int N>
struct Foo
{
    static std::array<double,N> x;
};

template<int N>
std::array<double,N> init()
{
    std::array<double,N> y;
    for (int i=0; i<N; ++i) {
        y[i] = (double)(i*i+i)/N;
    }
    return y;
}

template<int N>
std::array<double,N> Foo<N>::x = init<N>();

int main()
{
    const int N = 10;
    for (int i=0; i<N; ++i) {
        std::cout << Foo<N>::x[i] << std::endl;
    }
    return 0;
}