问:
Rails 3 runner not detecting JSON gem?
I'm trying to create Ruby script to run with my Rails 3 environment.

However, whenever I run this rubyscript with Rails Runner, I get this error:

```<code>require 'rubygems'
require 'json'

@payload = {
"message" => "helloworld",
"station" => {"id"=>12345}
}.to_json

puts @payload
</code>```

ERROR:

```<code>/usr/lib/ruby/gems/1.8/gems/activesupport-3.0.0.beta4/lib/active_support/dependencies.rb:212:in `require': no such file to load -- json (LoadError)
 from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.0.beta4/lib/active_support/dependencies.rb:212:in `require'
 from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.0.beta4/lib/active_support/dependencies.rb:198:in `load_dependency'
 from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.0.beta4/lib/active_support/dependencies.rb:554:in `new_constants_in'
 from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.0.beta4/lib/active_support/dependencies.rb:198:in `load_dependency'
 from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.0.beta4/lib/active_support/dependencies.rb:212:in `require'
 from createflags.rb:2
 from /usr/lib/ruby/gems/1.8/gems/railties-3.0.0.beta4/lib/rails/commands.rb:39:in `eval'
 from /usr/lib/ruby/gems/1.8/gems/railties-3.0.0.beta4/lib/rails/commands/runner.rb:47
 from /usr/lib/ruby/gems/1.8/gems/railties-3.0.0.beta4/lib/rails/commands.rb:39:in `require'
 from /usr/lib/ruby/gems/1.8/gems/railties-3.0.0.beta4/lib/rails/commands.rb:39
 from script/rails:6:in `require'
 from script/rails:6
</code>```

Can someone please tell me what I can do to fix this?

答:
I'm not totally familiar with the internals of Bundler, but it may be that it doesn't allow requireing other gems not in the Gemfile. Maybe adding gem 'json' would take care of this.

Of course, ActiveSupport has its own JSON module, so there should be no need to pull in another gem.

Title: Rails 3 runner not detecting JSON gem?

Body:
I'm trying to create Ruby script to run with my Rails 3 environment.

However, whenever I run this rubyscript with Rails Runner, I get this error:

require 'rubygems'
require 'json'

@payload = {
"message" => "helloworld",
"station" => {"id"=>12345}
}.to_json

puts @payload

ERROR:

/usr/lib/ruby/gems/1.8/gems/activesupport-3.0.0.beta4/lib/active_support/dependencies.rb:212:in `require': no such file to load -- json (LoadError)
 from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.0.beta4/lib/active_support/dependencies.rb:212:in `require'
 from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.0.beta4/lib/active_support/dependencies.rb:198:in `load_dependency'
 from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.0.beta4/lib/active_support/dependencies.rb:554:in `new_constants_in'
 from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.0.beta4/lib/active_support/dependencies.rb:198:in `load_dependency'
 from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.0.beta4/lib/active_support/dependencies.rb:212:in `require'
 from createflags.rb:2
 from /usr/lib/ruby/gems/1.8/gems/railties-3.0.0.beta4/lib/rails/commands.rb:39:in `eval'
 from /usr/lib/ruby/gems/1.8/gems/railties-3.0.0.beta4/lib/rails/commands/runner.rb:47
 from /usr/lib/ruby/gems/1.8/gems/railties-3.0.0.beta4/lib/rails/commands.rb:39:in `require'
 from /usr/lib/ruby/gems/1.8/gems/railties-3.0.0.beta4/lib/rails/commands.rb:39
 from script/rails:6:in `require'
 from script/rails:6

Can someone please tell me what I can do to fix this?


来源: stackexchange

问:
Numpy: find indicies conditioned on values in two different arrays (coming from R)
I have a volume represented by a 3D ndarray, X, with values between, say, 0 and 255, and I have another 3D ndarray, Y, that is an arbitrary mask of the first array, with values of either 0 or 1.

I want to find the indicies of a random sample of 50 voxels that is both greater than zero in X, the 'image', and equal to 1 in Y, the 'mask'.

My experience is with R, where the following would work:

```<code>idx <- sample(which(X>0 & Y==1), 50)
</code>```

Maybe the advantage in R is that I can index 3D arrays linearly, because just using a single index in numpy gives me a 2D matrix, for example.

I guess it probably involves numpy.random.choice, but it doesn't seem like I can use that conditionally, let alone conditioned on two different arrays. Is there another approach I should be using instead?

答:
Here's one way -

```<code>N = 50 # number of samples needed (50 for your actual case)

# Get mask based on conditionals
mask = (X>0) & (Y==1)

# Get corresponding linear indices (easier to random sample in next step)
idx = np.flatnonzero(mask)

# Get random sample
rand_idx = np.random.choice(idx, N)

# Format into three columnar output (each col for each dim/axis)
out = np.c_[np.unravel_index(rand_idx, X.shape)]
</code>```

If you need random sample without replacement, use np.random.choice() with optional arg replace=False.

Sample run -

```<code>In [34]: np.random.seed(0)
    ...: X = np.random.randint(0,4,(2,3,4))
    ...: Y = np.random.randint(0,2,(2,3,4))

In [35]: N = 5 # number of samples needed (50 for your actual case)
    ...: mask = (X>0) & (Y==1)
    ...: idx = np.flatnonzero(mask)
    ...: rand_idx = np.random.choice(idx, N)
    ...: out = np.c_[np.unravel_index(rand_idx, X.shape)]

In [37]: mask
Out[37]:
array([[[False,  True,  True, False],
        [ True, False,  True, False],
        [ True, False,  True,  True]],

       [[False,  True,  True, False],
        [False, False, False,  True],
        [ True,  True,  True,  True]]], dtype=bool)

In [38]: out
Out[38]:
array([[1, 0, 1],
       [0, 0, 1],
       [0, 0, 2],
       [1, 1, 3],
       [1, 1, 3]])
</code>```

Correlate the output out against the places of True values in mask for a quick verification.

If you don't want to flatten for getting the linear indices and directly get the indices per dim/axis, we can do it like so -

```<code>i0,i1,i2 = np.where(mask)
rand_idx = np.random.choice(len(i0), N)
out = np.c_[i0,i1,i2][rand_idx]
</code>```

For performance, index first and then concatenate with np.c_ at the last step -

```<code>out = np.c_[i0[rand_idx], i1[rand_idx], i2[rand_idx]]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a volume represented by a 3D ndarray, X, with values between, say, 0 and 255, and I have another 3D ndarray, Y, that is an arbitrary mask of the first array, with values of either 0 or 1.

I want to find the indicies of a random sample of 50 voxels that is both greater than zero in X, the 'image', and equal to 1 in Y, the 'mask'.

My experience is with R, where the following would work:

idx <- sample(which(X>0 & Y==1), 50)

Maybe the advantage in R is that I can index 3D arrays linearly, because just using a single index in numpy gives me a 2D matrix, for example.

I guess it probably involves numpy.random.choice, but it doesn't seem like I can use that conditionally, let alone conditioned on two different arrays. Is there another approach I should be using instead?

Body:
Here's one way -

N = 50 # number of samples needed (50 for your actual case)

# Get mask based on conditionals
mask = (X>0) & (Y==1)

# Get corresponding linear indices (easier to random sample in next step)
idx = np.flatnonzero(mask)

# Get random sample
rand_idx = np.random.choice(idx, N)

# Format into three columnar output (each col for each dim/axis)
out = np.c_[np.unravel_index(rand_idx, X.shape)]

If you need random sample without replacement, use np.random.choice() with optional arg replace=False.

Sample run -

In [34]: np.random.seed(0)
    ...: X = np.random.randint(0,4,(2,3,4))
    ...: Y = np.random.randint(0,2,(2,3,4))

In [35]: N = 5 # number of samples needed (50 for your actual case)
    ...: mask = (X>0) & (Y==1)
    ...: idx = np.flatnonzero(mask)
    ...: rand_idx = np.random.choice(idx, N)
    ...: out = np.c_[np.unravel_index(rand_idx, X.shape)]

In [37]: mask
Out[37]:
array([[[False,  True,  True, False],
        [ True, False,  True, False],
        [ True, False,  True,  True]],

       [[False,  True,  True, False],
        [False, False, False,  True],
        [ True,  True,  True,  True]]], dtype=bool)

In [38]: out
Out[38]:
array([[1, 0, 1],
       [0, 0, 1],
       [0, 0, 2],
       [1, 1, 3],
       [1, 1, 3]])

Correlate the output out against the places of True values in mask for a quick verification.

If you don't want to flatten for getting the linear indices and directly get the indices per dim/axis, we can do it like so -

i0,i1,i2 = np.where(mask)
rand_idx = np.random.choice(len(i0), N)
out = np.c_[i0,i1,i2][rand_idx]

For performance, index first and then concatenate with np.c_ at the last step -

out = np.c_[i0[rand_idx], i1[rand_idx], i2[rand_idx]]


问:
Laravel not registering a new command
I am  using laravel 5.5 and trying to create a new command. This has worked well in 5.4 but now it won't register at all.

First I create the command:

```<code>php artisan make:command heloworl
</code>```

And I get something like this:

```<code><?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class heloworl extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'Hello:World';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        echo "hello world";
    }
}
</code>```

Now I try php artisan hello:world and it says that the  command does not exist at all.

I also tried just php artisan to get a list of commands and it is not there.

Any ideas?

答:
You need to add it to app\Console\Kernel.php to the protected $commands array.

```<code>class Kernel extends ConsoleKernel
{

    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands
        = [
        //fully qualified namespace to class goes here
        ];

}
</code>```

Title: Laravel not registering a new command

Body:
I am  using laravel 5.5 and trying to create a new command. This has worked well in 5.4 but now it won't register at all.

First I create the command:

php artisan make:command heloworl

And I get something like this:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class heloworl extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'Hello:World';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        echo "hello world";
    }
}

Now I try php artisan hello:world and it says that the  command does not exist at all.

I also tried just php artisan to get a list of commands and it is not there.

Any ideas?

Body:
You need to add it to app\Console\Kernel.php to the protected $commands array.

class Kernel extends ConsoleKernel
{

    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands
        = [
        //fully qualified namespace to class goes here
        ];

}


问:
How to install the tools package that has Rdiff()
So I am trying to run this command in Rstudio to compare two files:

Rdiff("C:/Users/twoodward/Documents/supplierdirectorytest/Supplier_Revised_Flatfiles (1)/SupplierData.csv","C:/Users/twoodward/Documents/supplierdirectorytest/Supplier_Revised_Flatfiles (1)/SupplierDataedited.csv" to, useDiff = FALSE, forEx = FALSE,
      nullPointers = TRUE, Log = TRUE)

But for somereason it cant find the Rdiff() function, I know that the function exists in the "tools" package, but can't find any documentation installing it?

答:
You can explicitly call

```<code>tools::Rdiff(...)
</code>```

or first run

```<code>library(tools)
Rdiff(...)
</code>```

Body:
You can explicitly call

tools::Rdiff(...)

or first run

library(tools)
Rdiff(...)


问:
Is there any purpose to `bind()` unix domain socket client processes?
When using AF_UNIX (unix domain sockets), is there any application to calling bind() in a process that never calls listen()?

In my systems programming lecture and lab, we are instructed to callbind() on a unix domain socket client processes. Is there any documented, undocumented, or practical application to calling bind on a client-only unix domain socket  process? From my understanding bind() creates the special socket file, which is a responsibility a server process would undertake. Is this correct?

Here is an example code based off of what concepts discussed in class:

server.c

```<code>#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>

int main() {
    int s0, s1;
    struct sockaddr sa0 = {AF_UNIX, "a"};

    s0 = socket(AF_UNIX, SOCK_STREAM, 0);

    bind(s0, &sa0, sizeof(sa0) + sizeof("a"));
    listen(s0, 1);
    for (;;) {
        s1 = accept(s0, NULL, NULL);
        puts("connected!");
        for (;;) {
            char text[1];
            ssize_t n = read(s1, &text, sizeof(text));
            if (n < 1) {
                break;
            }
            putchar(text[0]);
        }
        close(s1);
    }
    close(s0);
    unlink("a");
    return 0;
}
</code>```

client.c

```<code>#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>

int main() {
    int s0;
    struct sockaddr sa0 = {AF_UNIX, "b"};
    struct sockaddr sa1 = {AF_UNIX, "a"};
    socklen_t sa1_len;

    s0 = socket(AF_UNIX, SOCK_STREAM, 0);
    bind(s0, &sa0, sizeof(sa0) + sizeof("b")); // What does this do??
    connect(s0, &sa1, sizeof(sa1) + sizeof("b"));
    for (;;) {
        int c = fgetc(stdin);
        if (c == EOF) {
            break;
        }
        write(s0, &c, sizeof(c));
    }
    close(s0);
    unlink("b");
    return 0;
}
</code>```

答:
The call to bind() is only required if you need to receive a connection with SOCK_STREAM type socket, but bind() behavior depends on the domain of the SOCKET. There is a manual page dedicated to this.

Useful information:

Address format

A UNIX domain socket address is represented in the following
  structure:

```<code>#define UNIX_PATH_MAX    108

struct sockaddr_un {
    sa_family_t sun_family;               /* AF_UNIX */
    char        sun_path[UNIX_PATH_MAX];  /* pathname */
};
</code>```

Three types of address are distinguished in this structure:

pathname: a UNIX domain socket can be bound to a null-terminated file system pathname using bind(2). When the address of the socket is
  returned by getsockname(2), getpeername(2), and accept(2), its length
  is offsetof(struct sockaddr_un, sun_path) + strlen(sun_path) + 1, and
  sun_path contains the null-terminated pathname.

unnamed: A stream socket that has not been bound to a pathname using bind(2) has no name. Likewise, the two sockets created by
  socketpair(2) are unnamed. When the address of an unnamed socket is
  returned by getsockname(2), getpeername(2), and accept(2), its length
  is sizeof(sa_family_t), and sun_path should not be inspected.

abstract: an abstract socket address is distinguished by the fact that sun_path[0] is a null byte ('\0'). The socket's address in this
  namespace is given by the additional bytes in sun_path that are
  covered by the specified length of the address structure. (Null bytes
  in the name have no special significance.) The name has no connection
  with file system pathnames. When the address of an abstract socket is
  returned by getsockname(2), getpeername(2), and accept(2), the
  returned addrlen is greater than sizeof(sa_family_t) (i.e., greater
  than 2), and the name of the socket is contained in the first (addrlen

sizeof(sa_family_t)) bytes of sun_path. The abstract socket namespace is a nonportable Linux extension.

Binding to a socket with a filename creates a socket in the file
  system that must be deleted by the caller when it is no longer needed
  (using unlink(2)). The usual UNIX close-behind semantics apply; the
  socket can be unlinked at any time and will be finally removed from
  the file system when the last reference to it is closed.

So:

bind() is not necessary in a client.

bind() in your context give a name to yours sockets "a" and "b"

bind(s0, &sa0, sizeof(sa0) + sizeof("b")); and similar line in yours code are undefined behavior; it gives a wrong size to bind() that exceeds the bound of &sa0. The correct code is bind(s0, &sa0, sizeof sa0);

bind() in this context (Linux, AF_UNIX) does create a special socket file; if you want to remove it, you must call unlink() or remove().

Body:
When using AF_UNIX (unix domain sockets), is there any application to calling bind() in a process that never calls listen()?

In my systems programming lecture and lab, we are instructed to callbind() on a unix domain socket client processes. Is there any documented, undocumented, or practical application to calling bind on a client-only unix domain socket  process? From my understanding bind() creates the special socket file, which is a responsibility a server process would undertake. Is this correct?

Here is an example code based off of what concepts discussed in class:

server.c

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>

int main() {
    int s0, s1;
    struct sockaddr sa0 = {AF_UNIX, "a"};

    s0 = socket(AF_UNIX, SOCK_STREAM, 0);

    bind(s0, &sa0, sizeof(sa0) + sizeof("a"));
    listen(s0, 1);
    for (;;) {
        s1 = accept(s0, NULL, NULL);
        puts("connected!");
        for (;;) {
            char text[1];
            ssize_t n = read(s1, &text, sizeof(text));
            if (n < 1) {
                break;
            }
            putchar(text[0]);
        }
        close(s1);
    }
    close(s0);
    unlink("a");
    return 0;
}

client.c

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>

int main() {
    int s0;
    struct sockaddr sa0 = {AF_UNIX, "b"};
    struct sockaddr sa1 = {AF_UNIX, "a"};
    socklen_t sa1_len;

    s0 = socket(AF_UNIX, SOCK_STREAM, 0);
    bind(s0, &sa0, sizeof(sa0) + sizeof("b")); // What does this do??
    connect(s0, &sa1, sizeof(sa1) + sizeof("b"));
    for (;;) {
        int c = fgetc(stdin);
        if (c == EOF) {
            break;
        }
        write(s0, &c, sizeof(c));
    }
    close(s0);
    unlink("b");
    return 0;
}

Body:
The call to bind() is only required if you need to receive a connection with SOCK_STREAM type socket, but bind() behavior depends on the domain of the SOCKET. There is a manual page dedicated to this.

Useful information:

Address format

A UNIX domain socket address is represented in the following
  structure:

#define UNIX_PATH_MAX    108

struct sockaddr_un {
    sa_family_t sun_family;               /* AF_UNIX */
    char        sun_path[UNIX_PATH_MAX];  /* pathname */
};

Three types of address are distinguished in this structure:

pathname: a UNIX domain socket can be bound to a null-terminated file system pathname using bind(2). When the address of the socket is
  returned by getsockname(2), getpeername(2), and accept(2), its length
  is offsetof(struct sockaddr_un, sun_path) + strlen(sun_path) + 1, and
  sun_path contains the null-terminated pathname.

unnamed: A stream socket that has not been bound to a pathname using bind(2) has no name. Likewise, the two sockets created by
  socketpair(2) are unnamed. When the address of an unnamed socket is
  returned by getsockname(2), getpeername(2), and accept(2), its length
  is sizeof(sa_family_t), and sun_path should not be inspected.

abstract: an abstract socket address is distinguished by the fact that sun_path[0] is a null byte ('\0'). The socket's address in this
  namespace is given by the additional bytes in sun_path that are
  covered by the specified length of the address structure. (Null bytes
  in the name have no special significance.) The name has no connection
  with file system pathnames. When the address of an abstract socket is
  returned by getsockname(2), getpeername(2), and accept(2), the
  returned addrlen is greater than sizeof(sa_family_t) (i.e., greater
  than 2), and the name of the socket is contained in the first (addrlen

sizeof(sa_family_t)) bytes of sun_path. The abstract socket namespace is a nonportable Linux extension.

Binding to a socket with a filename creates a socket in the file
  system that must be deleted by the caller when it is no longer needed
  (using unlink(2)). The usual UNIX close-behind semantics apply; the
  socket can be unlinked at any time and will be finally removed from
  the file system when the last reference to it is closed.

So:

bind() is not necessary in a client.

bind() in your context give a name to yours sockets "a" and "b"

bind(s0, &sa0, sizeof(sa0) + sizeof("b")); and similar line in yours code are undefined behavior; it gives a wrong size to bind() that exceeds the bound of &sa0. The correct code is bind(s0, &sa0, sizeof sa0);

bind() in this context (Linux, AF_UNIX) does create a special socket file; if you want to remove it, you must call unlink() or remove().


问:
Swift 4 alternative if let
I have this code, it checks if a file exists in the document directory, if it does it used this to set up the data for the controller, if it doesn't it uses a file supplier in the bundle, and if also that fails it set up an empty view controller.

Is there a way to conditionally set the url variable so that I can write the parse(fromFile:) method once instead of in an if else? The most intuitive way would appear to be if let url = something || let url = somethingElse then perform in the parse(fromFile: url) in the brackets, but it appears that it's not possible with swift.

```<code>if let url = try? FileManager().url(for: .documentDirectory,
                                    in: .userDomainMask,
                                    appropriateFor: nil,
                                    create: true).appendingPathComponent("database.json") {
    parse(fromFile: url)
} else if let url = Bundle.main.url(forResource: "database", withExtension: "json") {
    parse(fromFile: url)
} else {
    setUpWithNothing()
}
</code>```

答:
I would recommend to split the code into several steps:

```<code>let documentsUrl = try! FileManager.default.url(
    for: .documentDirectory,
    in: .userDomainMask,
    appropriateFor: nil,
    create: true
)
</code>```

The documents directory should always exists therefore I am not too worried about using try!. However, if you worry, you should solve that special case separately, e.g. using:

```<code> guard let documentUrl = try? ... else {
     setUpWithNothing()
     return
 }
</code>```

Then:

```<code>let fileUrl = documentUrl.appendingPathComponent("database.json")
</code>```

This call never fails, it doesn't check the existence of the file. You need to check existence explicitly:

```<code>let fileExists = FileManager.default.fileExists(atPath: fileUrl.path)

let defaultUrl = Bundle.main.url(forResource: "database", withExtension: "json")
let databaseUrl = fileExists ? fileUrl : defaultUrl!
</code>```

Again, you shouldn't worry about the existence of the file in your bundle, if you know it's there and simply call:

```<code>parse(fromFile: databaseUrl)
</code>```

However, if you want to be extra careful, just remove the ! and use:

```<code>if let databaseUrl = fileExists ? fileUrl : defaultUrl {
    parse(fromFile: databaseUrl)
} else {
    setUpWithNothing()
}
</code>```

Title: Swift 4 alternative if let

Body:
I have this code, it checks if a file exists in the document directory, if it does it used this to set up the data for the controller, if it doesn't it uses a file supplier in the bundle, and if also that fails it set up an empty view controller.

Is there a way to conditionally set the url variable so that I can write the parse(fromFile:) method once instead of in an if else? The most intuitive way would appear to be if let url = something || let url = somethingElse then perform in the parse(fromFile: url) in the brackets, but it appears that it's not possible with swift.

if let url = try? FileManager().url(for: .documentDirectory,
                                    in: .userDomainMask,
                                    appropriateFor: nil,
                                    create: true).appendingPathComponent("database.json") {
    parse(fromFile: url)
} else if let url = Bundle.main.url(forResource: "database", withExtension: "json") {
    parse(fromFile: url)
} else {
    setUpWithNothing()
}

Body:
I would recommend to split the code into several steps:

let documentsUrl = try! FileManager.default.url(
    for: .documentDirectory,
    in: .userDomainMask,
    appropriateFor: nil,
    create: true
)

The documents directory should always exists therefore I am not too worried about using try!. However, if you worry, you should solve that special case separately, e.g. using:

 guard let documentUrl = try? ... else {
     setUpWithNothing()
     return
 }

Then:

let fileUrl = documentUrl.appendingPathComponent("database.json")

This call never fails, it doesn't check the existence of the file. You need to check existence explicitly:

let fileExists = FileManager.default.fileExists(atPath: fileUrl.path)

let defaultUrl = Bundle.main.url(forResource: "database", withExtension: "json")
let databaseUrl = fileExists ? fileUrl : defaultUrl!

Again, you shouldn't worry about the existence of the file in your bundle, if you know it's there and simply call:

parse(fromFile: databaseUrl)

However, if you want to be extra careful, just remove the ! and use:

if let databaseUrl = fileExists ? fileUrl : defaultUrl {
    parse(fromFile: databaseUrl)
} else {
    setUpWithNothing()
}


问:
Join all nested arrays of a collection in one array in mongodb c#
I have documents with this structure:

```<code>    {
        "_id" : ObjectId("5a26f1764cacd91bf4624a76"),
        "CompetitorIds" : [
            "3a11f1764cacd91bf4624b84",
            "2a26f1764cacd91bf4624a55"
        ],
        "BusinessId" : "5a1bfcac2b8fb6096885cbb8"
    }
</code>```

And I want to get an unique array with all competitorIds, for example, if I have these documents:

```<code>    {
        "_id" : ObjectId("5a26f1764cacd91bf4624a76"),
        "CompetitorIds" : [
            "111111111111111111111111",
            "222222222222222222222222"
        ],
        "BusinessId" : "5a1bfcac2b8fb6096885cbb8"
    }
    {
        "_id" : ObjectId("7a26f1764cacd91bf4112a88"),
        "CompetitorIds" : [
            "333333333333333333333333",
            "444444444444444444444444"
        ],
        "BusinessId" : "5a1bfcac2b8fb6096885cbb8"
    }
</code>```

I want an array like:

```<code>["111111111111111111111111","222222222222222222222222","333333333333333333333333","444444444444444444444444"]
</code>```

Now, I'm doing like this, using MongoDB.Driver to C#:

```<code>public class Product
{
    public ObjectId Id { get; set; }
    public string[] CompetitorIds { get; set; }
    public string BusinessId { get; set; }
}

public List<string> GetAllCompetitors(string businessId)
{
    var builder = Builders<Product>.Filter;
    var filter = builder.Eq(p => p.BusinessId, businessId) & builder.Where(p => p.CompetitorIds.Length > 0);
    var collection = _collection.Find(filter);
    var productIdsAlreadyBound = collection.ToList().SelectMany(x => x.CompetitorIds).ToList();
}
</code>```

But I want to know if there is a better way to do that. Any suggestions?

答:
EDIT: While the below works @Veeram's solution in the comment up there is way more elegant.

Here is how you can do that:

First, you define a type that represents your document structure after the (required) $unwind stage. This type just makes the C# client nicer to deal with so you can write typed code instead of fiddling with strings.

```<code>public class ProductAfterUnwind
{
    public string CompetitorIds { get; set; }
}
</code>```

And then you can do this:

```<code>var productIdsAlreadyBound = _collection
    .Aggregate()
    .Match(p => p.BusinessId == "5a1bfcac2b8fb6096885cbb8")
    .Unwind<Product, ProductAfterUnwind>(p => p.CompetitorIds)
    .Group(p => string.Empty, grouping => new
    {
        CompetitorIds = grouping.Select(p => p.CompetitorIds).Distinct()
    })
    .FirstOrDefault();
</code>```

Body:
I have documents with this structure:

    {
        "_id" : ObjectId("5a26f1764cacd91bf4624a76"),
        "CompetitorIds" : [
            "3a11f1764cacd91bf4624b84",
            "2a26f1764cacd91bf4624a55"
        ],
        "BusinessId" : "5a1bfcac2b8fb6096885cbb8"
    }

And I want to get an unique array with all competitorIds, for example, if I have these documents:

    {
        "_id" : ObjectId("5a26f1764cacd91bf4624a76"),
        "CompetitorIds" : [
            "111111111111111111111111",
            "222222222222222222222222"
        ],
        "BusinessId" : "5a1bfcac2b8fb6096885cbb8"
    }
    {
        "_id" : ObjectId("7a26f1764cacd91bf4112a88"),
        "CompetitorIds" : [
            "333333333333333333333333",
            "444444444444444444444444"
        ],
        "BusinessId" : "5a1bfcac2b8fb6096885cbb8"
    }

I want an array like:

["111111111111111111111111","222222222222222222222222","333333333333333333333333","444444444444444444444444"]

Now, I'm doing like this, using MongoDB.Driver to C#:

public class Product
{
    public ObjectId Id { get; set; }
    public string[] CompetitorIds { get; set; }
    public string BusinessId { get; set; }
}

public List<string> GetAllCompetitors(string businessId)
{
    var builder = Builders<Product>.Filter;
    var filter = builder.Eq(p => p.BusinessId, businessId) & builder.Where(p => p.CompetitorIds.Length > 0);
    var collection = _collection.Find(filter);
    var productIdsAlreadyBound = collection.ToList().SelectMany(x => x.CompetitorIds).ToList();
}

But I want to know if there is a better way to do that. Any suggestions?

Body:
EDIT: While the below works @Veeram's solution in the comment up there is way more elegant.

Here is how you can do that:

First, you define a type that represents your document structure after the (required) $unwind stage. This type just makes the C# client nicer to deal with so you can write typed code instead of fiddling with strings.

public class ProductAfterUnwind
{
    public string CompetitorIds { get; set; }
}

And then you can do this:

var productIdsAlreadyBound = _collection
    .Aggregate()
    .Match(p => p.BusinessId == "5a1bfcac2b8fb6096885cbb8")
    .Unwind<Product, ProductAfterUnwind>(p => p.CompetitorIds)
    .Group(p => string.Empty, grouping => new
    {
        CompetitorIds = grouping.Select(p => p.CompetitorIds).Distinct()
    })
    .FirstOrDefault();


问:
Reading JSON String using JSON/Gson
I have the JSON String of the below format which I get as a http request in Java. I need to get the name and values of the below JSON string, but I am not able to get the correct solution.

Can any one tell me how to parse this? Also, let me know if we will be able to format this string because there is no property names from the 3 element.

The string format is

```<code>{

 'appname':'application',
 'Version':'0.1.0',
 'UUID':'300V',
 'WWXY':'310W',
 'ABCD':'270B',
 'YUDE':'280T'

}
</code>```

edit#1 formatted the question.

答:
In JavaScript, you can do something like

```<code> var v = eval("("+data_from_server+")");
 var aName = v.appname;
</code>```

For example this script will alert appname.

```<code>    <script>
        var serverdata = "{'appname':'application', 'Version':'0.1.0', 'UUID':'300V', 'WWXY':'310W', 'ABCD':'270B', 'YUDE':'280T'}";
        var v = eval("("+serverdata+")");
        alert(v.appname);
    </script>
</code>```

Based on your comment on this answer, here is a way to parse in Java

In Java, you may want to leverage GSon. See here.

You need to define a Java class that maps the JSON object one-to-one. Then ask GSon to create a Java object using the JSON String. Here is the example.

Your Java class that maps JSON should look like this

```<code>    public  class MyData{
        public String appname;
        public String Version;
        public String UUID;
        public String WWXY;
        public String ABCD;
        public String YUDE;
        public MyData(){}
    }
</code>```

And you parse in Java like this.

```<code>    String jsons = "{'appname':'application', 'Version':'0.1.0', 'UUID':'300V', 'WWXY':'310W', 'ABCD':'270B', 'YUDE':'280T'}";
    Gson gson = new Gson();
    MyData obj = gson.fromJson(jsons, MyData.class);
    System.out.println("ada "+ obj.appname);
</code>```

ContentLicense: CC BY-SA 2.5

Title: Reading JSON String using JSON/Gson

Body:
I have the JSON String of the below format which I get as a http request in Java. I need to get the name and values of the below JSON string, but I am not able to get the correct solution.

Can any one tell me how to parse this? Also, let me know if we will be able to format this string because there is no property names from the 3 element.

The string format is

{

 'appname':'application',
 'Version':'0.1.0',
 'UUID':'300V',
 'WWXY':'310W',
 'ABCD':'270B',
 'YUDE':'280T'

}

edit#1 formatted the question.

Body:
In JavaScript, you can do something like

 var v = eval("("+data_from_server+")");
 var aName = v.appname;

For example this script will alert appname.

    <script>
        var serverdata = "{'appname':'application', 'Version':'0.1.0', 'UUID':'300V', 'WWXY':'310W', 'ABCD':'270B', 'YUDE':'280T'}";
        var v = eval("("+serverdata+")");
        alert(v.appname);
    </script>

Based on your comment on this answer, here is a way to parse in Java

In Java, you may want to leverage GSon. See here.

You need to define a Java class that maps the JSON object one-to-one. Then ask GSon to create a Java object using the JSON String. Here is the example.

Your Java class that maps JSON should look like this

    public  class MyData{
        public String appname;
        public String Version;
        public String UUID;
        public String WWXY;
        public String ABCD;
        public String YUDE;
        public MyData(){}
    }

And you parse in Java like this.

    String jsons = "{'appname':'application', 'Version':'0.1.0', 'UUID':'300V', 'WWXY':'310W', 'ABCD':'270B', 'YUDE':'280T'}";
    Gson gson = new Gson();
    MyData obj = gson.fromJson(jsons, MyData.class);
    System.out.println("ada "+ obj.appname);


问:
How to get a random value from a random WebElement from a List of WebElements
I am trying to save in a string the value from a random attribute
After that,I want to click on it so I can save the title of the page and compare the two strings
My code is right here:

```<code>public void clickOnRandomProduct(List <WebElement> elements){

        Random r = new Random();
        int randomValue = r.nextInt(elements.size());
        String valoareField=elements.get(randomValue).getAttribute("alt");
        System.out.println(valoareField);
        elements.get(randomValue).click();

    }
</code>```

I receive "null" from my string and I don't know why

答:
I don't know why I didn't spot this earlier.

Change your function declaration:

```<code>public void clickOnRandomProduct(List<WebELement> elements) {
</code>```

And of course, change the code where you are declaring/setting that list.

Body:
I am trying to save in a string the value from a random attribute
After that,I want to click on it so I can save the title of the page and compare the two strings
My code is right here:

public void clickOnRandomProduct(List <WebElement> elements){

        Random r = new Random();
        int randomValue = r.nextInt(elements.size());
        String valoareField=elements.get(randomValue).getAttribute("alt");
        System.out.println(valoareField);
        elements.get(randomValue).click();

    }

I receive "null" from my string and I don't know why

Body:
I don't know why I didn't spot this earlier.

Change your function declaration:

public void clickOnRandomProduct(List<WebELement> elements) {

And of course, change the code where you are declaring/setting that list.


问:
Insert into a MySQL table or update if exists
I want to add a row to a database table, but if a row exists with the same unique key I want to update the row.

For example:

INSERT INTO table_name (ID, NAME, AGE) VALUES(1, "A", 19);
```

Let’s say the unique key is ID, and in my Database, there is a row with ID = 1. In that case, I want to update that row with these values. Normally this gives an error.

If I use INSERT IGNORE it will ignore the error, but it still won’t update.

答:
Any of these solution will work regarding your question:

```<code>INSERT IGNORE INTO table (id, name, age) VALUES (1, "A", 19);
</code>```

or

```<code>INSERT INTO TABLE (id, name, age) VALUES(1, "A", 19)
    ON DUPLICATE KEY UPDATE NAME = "A", AGE = 19;
</code>```

or

```<code>REPLACE INTO table (id, name, age) VALUES(1, "A", 19);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to add a row to a database table, but if a row exists with the same unique key I want to update the row.

For example:

INSERT INTO table_name (ID, NAME, AGE) VALUES(1, "A", 19);

Let’s say the unique key is ID, and in my Database, there is a row with ID = 1. In that case, I want to update that row with these values. Normally this gives an error.

If I use INSERT IGNORE it will ignore the error, but it still won’t update.

Body:
Any of these solution will work regarding your question:

INSERT IGNORE INTO table (id, name, age) VALUES (1, "A", 19);

or

INSERT INTO TABLE (id, name, age) VALUES(1, "A", 19)
    ON DUPLICATE KEY UPDATE NAME = "A", AGE = 19;

or

REPLACE INTO table (id, name, age) VALUES(1, "A", 19);


问:
Need Build IVR call flow UI with Drag-Drop element like OpenVBX (Twilio)
Need to create application for desing IVR call flow with drag-drop element UI like OpenVBX(Twilio). I have no advance level knowledge about front-end technologies like CSS and pure JavaScript. I need to this implementation with PHP based project.

Can you please help me out which kind of tool are helpful for this requirement?

答: It's better to use D3 js library for drag and drop interface and then integrate with your VOIP platform.</p>


问:
Determine if python is being run in Ubuntu Linux
I have a Python 3.2 program that runs like this:

```<code>import platform
sysname = platform.system()
sysver = platform.release()
print(sysname+" "+sysver)
</code>```

And on windows it returns:

Windows 7

But on Ubuntu and others it returns:

Linux 3.0.0-13-generic

I need something like:

Ubuntu 11.10 or Mint 12

答:
Looks like platform.dist() and platform.linux_distribution() are deprecated in Python 3.5 and will be removed in Python 3.8. The following works in Python 2/3

```<code>import platform
'ubuntu' in platform.version().lower()
</code>```

Example return value

```<code>>>> platform.version()
'#45~20.04.1-Ubuntu SMP Mon Apr 4 09:38:31 UTC 2022'
</code>```

Body:
I have a Python 3.2 program that runs like this:

import platform
sysname = platform.system()
sysver = platform.release()
print(sysname+" "+sysver)

And on windows it returns:

Windows 7

But on Ubuntu and others it returns:

Linux 3.0.0-13-generic

I need something like:

Ubuntu 11.10 or Mint 12

Body:
Looks like platform.dist() and platform.linux_distribution() are deprecated in Python 3.5 and will be removed in Python 3.8. The following works in Python 2/3

import platform
'ubuntu' in platform.version().lower()

Example return value

>>> platform.version()
'#45~20.04.1-Ubuntu SMP Mon Apr 4 09:38:31 UTC 2022'


问:
I'm trying to read a .csv file into my sas terminal but it will only display the first row of observations
enter image description hereI'm reading a .csv file into my sas terminal using infile, but for some reason it will not display anything past my first row of observations. Here is my code:</p>

```<code>data fines;
        infile '/home/scf-09/ianscott/Acct493/Project/dataset1.csv'
                firstobs = 1
                truncover DSD
        ;
        length
                Parent $15
                Year $4
                Penalty $11
                Subtraction $10
                Net $11
                Agency $20
                Primary $20
                Secondary $20
                Country $15
                Industry $20
        ;
informat Parent Year Penalty Subtraction Net Agency Primary Secondary Country Industry 10.;
        input
                Parent $
                Year
                Penalty
                Subtraction
                Net
                Agency $
                Primary $
                Secondary $
                Country $
                Industry $;
run;

proc print data=fines(obs=5);
        title 'fines data';
run;

1 Bank of America 2011 20000000 0 20000000 Justice Department C mortgage abuses Servicemembers Civil USA financial services
</code>```

答:
```<code>infile '/home/scf-09/ianscott/Acct493/Project/dataset1.csv'
            firstobs = 1
            truncover DSD
    ;
</code>```

The first thing I look at when having this kind of issue is whether the file has the same line terminator as what your OS expects.  If your SAS runs on Unix, and the file's in Excel here so it's probably on Windows, for example, then you have 0A line terminator; that's usually the opposite problem if anything, though.  If you're going the other way around - the CSV was created in Unix but you're in Windows - then it won't see any line terminators.  You might need TERMSTR option to the appropriate terminator.

I see / slashes (unix-style), so that makes me think this is very likely the issue. Try adding TERMSTR=LF to your infile.

Body:
enter image description hereI'm reading a .csv file into my sas terminal using infile, but for some reason it will not display anything past my first row of observations. Here is my code:

data fines;
        infile '/home/scf-09/ianscott/Acct493/Project/dataset1.csv'
                firstobs = 1
                truncover DSD
        ;
        length
                Parent $15
                Year $4
                Penalty $11
                Subtraction $10
                Net $11
                Agency $20
                Primary $20
                Secondary $20
                Country $15
                Industry $20
        ;
informat Parent Year Penalty Subtraction Net Agency Primary Secondary Country Industry 10.;
        input
                Parent $
                Year
                Penalty
                Subtraction
                Net
                Agency $
                Primary $
                Secondary $
                Country $
                Industry $;
run;

proc print data=fines(obs=5);
        title 'fines data';
run;

1 Bank of America 2011 20000000 0 20000000 Justice Department C mortgage abuses Servicemembers Civil USA financial services

Body:
infile '/home/scf-09/ianscott/Acct493/Project/dataset1.csv'
            firstobs = 1
            truncover DSD
    ;

The first thing I look at when having this kind of issue is whether the file has the same line terminator as what your OS expects.  If your SAS runs on Unix, and the file's in Excel here so it's probably on Windows, for example, then you have 0A line terminator; that's usually the opposite problem if anything, though.  If you're going the other way around - the CSV was created in Unix but you're in Windows - then it won't see any line terminators.  You might need TERMSTR option to the appropriate terminator.

I see / slashes (unix-style), so that makes me think this is very likely the issue. Try adding TERMSTR=LF to your infile.


问:
Adding elements to an empty ArrayList<T>
I am adding objects to an ArrayList that is initialized as null inside a for each loop, but SonarLint is giving me a "NullPointerException" could be thrown when I try to add each object. Why is this error being pointed out? </p>

```<code>public List<SatelliteData> getData()
  {
    SatelliteData satellite;
    ArrayList<SatelliteData> satelliteList = null;

    try(FileInputStream file = new FileInputStream(satelliteOutputFile))
    {
      TLEParser parsedFile = new TLEParser();
      List<TLE> tleList = parsedFile.readFile(file);

      for (TLE tle : tleList)
      {
        satellite = new SatelliteData(tle);
        satellite.collectSatelliteData();

        satelliteList.add(satellite); //A "NullPointerException" could be thrown; "satelliteList" is nullable here
      }

    }
    catch (IOException ex)
    {
      LOGGER.error("IO Exception: " +  ex);
      notifyTheObservers("IO Exception: " + ex);
    }

    return satelliteList;
  }
</code>```

答:
You shouldn't call member methods on variables that have been initialized to nothing/null.

In this case you have

```<code>ArrayList<SatelliteData> satelliteList = null;
</code>```

This variable does not have any memory allocated to it.

At this point your computer knows : Okay there exists something
  called satelliteData but it actually doesn't know where it is?

Calling add() method on it, is likely to throw a NullPointerException because this variable is a reference that is pointing to null/nothing.

To overcome this, You need to initialize the variable like this :

```<code>ArrayList<SatelliteData> satelliteList = new ArrayList<SatelliteData>();
</code>```

At this point your computer created that satteliteData and knows
  exactly where it exists hence it can happily operate upon it.

This will allocate some memory to this variable and now it has its own methods you can call.

Body:
I am adding objects to an ArrayList that is initialized as null inside a for each loop, but SonarLint is giving me a "NullPointerException" could be thrown when I try to add each object. Why is this error being pointed out?

public List<SatelliteData> getData()
  {
    SatelliteData satellite;
    ArrayList<SatelliteData> satelliteList = null;

    try(FileInputStream file = new FileInputStream(satelliteOutputFile))
    {
      TLEParser parsedFile = new TLEParser();
      List<TLE> tleList = parsedFile.readFile(file);

      for (TLE tle : tleList)
      {
        satellite = new SatelliteData(tle);
        satellite.collectSatelliteData();

        satelliteList.add(satellite); //A "NullPointerException" could be thrown; "satelliteList" is nullable here
      }

    }
    catch (IOException ex)
    {
      LOGGER.error("IO Exception: " +  ex);
      notifyTheObservers("IO Exception: " + ex);
    }

    return satelliteList;
  }

Body:
You shouldn't call member methods on variables that have been initialized to nothing/null.

In this case you have

ArrayList<SatelliteData> satelliteList = null;

This variable does not have any memory allocated to it.

At this point your computer knows : Okay there exists something
  called satelliteData but it actually doesn't know where it is?

Calling add() method on it, is likely to throw a NullPointerException because this variable is a reference that is pointing to null/nothing.

To overcome this, You need to initialize the variable like this :

ArrayList<SatelliteData> satelliteList = new ArrayList<SatelliteData>();

At this point your computer created that satteliteData and knows
  exactly where it exists hence it can happily operate upon it.

This will allocate some memory to this variable and now it has its own methods you can call.


问:
C# - Declaration of class variables
How can I create a new instance of Boeing737 and use it later in the program. For example I want to be able to create 5 Boeings, do I have to define them like

```<code>Boeing737 boeing1 =  new Boeing737(name: "Boeing737" + Console.ReadLine(),fuel: int.Parse(Console.ReadLine()) , tons: 0);

Boeing737 boeing2 =  new Boeing737(name: "Boeing737" + Console.ReadLine(),fuel: int.Parse(Console.ReadLine()) , tons: 0);
</code>```

and so on...
Or is there easier way?
Other question, to WHAT can I assign all the properties of boeing1 for example?

Here is my current code:

```<code>class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Insert the type of boeing that u are using");
        Boeing737 boeing = new Boeing737(name: "Boeing737" + Console.ReadLine(),fuel: int.Parse(Console.ReadLine()) , tons: 0);
        Console.WriteLine("{0} has {1} tons of fuel and weights {2}", boeing.Name, boeing.Fuel, boeing.Tons);
        Console.ReadKey();

    }
}

public class Planes
{
    public Planes(string name, int fuel, int tons)
    {
        Name = name;
        Fuel = fuel;
        Tons = tons;
    }
    public int Tons;
    public int Fuel;
    public string Name { private set; get; }
}
class Boeing737 : Planes
{
    public Boeing737(string name, int fuel, int tons) : base(name, fuel, tons)
    {
        Tons = 700;
    }
}
</code>```

}

答:
Use array initialization:</p>

```<code>var boeings = new []
  {
    new Boeing737("name", 123, 1000),
    new Boeing737("name", 123, 1000),
    new Boeing737("name", 123, 1000),
    new Boeing737("name", 123, 1000),
  };
</code>```

Title: C# - Declaration of class variables

Body:
How can I create a new instance of Boeing737 and use it later in the program. For example I want to be able to create 5 Boeings, do I have to define them like

Boeing737 boeing1 =  new Boeing737(name: "Boeing737" + Console.ReadLine(),fuel: int.Parse(Console.ReadLine()) , tons: 0);

Boeing737 boeing2 =  new Boeing737(name: "Boeing737" + Console.ReadLine(),fuel: int.Parse(Console.ReadLine()) , tons: 0);

and so on...
Or is there easier way?
Other question, to WHAT can I assign all the properties of boeing1 for example?

Here is my current code:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Insert the type of boeing that u are using");
        Boeing737 boeing = new Boeing737(name: "Boeing737" + Console.ReadLine(),fuel: int.Parse(Console.ReadLine()) , tons: 0);
        Console.WriteLine("{0} has {1} tons of fuel and weights {2}", boeing.Name, boeing.Fuel, boeing.Tons);
        Console.ReadKey();

    }
}

public class Planes
{
    public Planes(string name, int fuel, int tons)
    {
        Name = name;
        Fuel = fuel;
        Tons = tons;
    }
    public int Tons;
    public int Fuel;
    public string Name { private set; get; }
}
class Boeing737 : Planes
{
    public Boeing737(string name, int fuel, int tons) : base(name, fuel, tons)
    {
        Tons = 700;
    }
}

}

Body:
Use array initialization:

var boeings = new []
  {
    new Boeing737("name", 123, 1000),
    new Boeing737("name", 123, 1000),
    new Boeing737("name", 123, 1000),
    new Boeing737("name", 123, 1000),
  };


问:
How to Modify value of optionset by code C#?
Do you know if there is a solution to modify the value (not a label) of an option in optionset by code C#.

for example, I have this Option:
(Label: OldLabel, Value: OldValue)

and I want this:
(Label: OldLabel, Value: NewValue)

I tried by the following code, but is not working:

```<code>UpdateOptionValueRequest updateOptionValueRequest =
    new UpdateOptionValueRequest
    {
        OptionSetName = _globalOptionSetName,
        // Update the second option value.
        Value = newValue,
        Label = new Label("oldLabel", _languageCode)
    };

_serviceProxy.Execute(updateOptionValueRequest);

//Publish the OptionSet
PublishXmlRequest pxReq3 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) };
_serviceProxy.Execute(pxReq3);
</code>```

答:
As per @Arun Vinoth, this does not appear to be possible via code, with good reason, as it could break the data.

Let's say you have this option set of salutations:

1000 Ms.

1001 Mrs.

1002 Mr.

1003 Dr.

When storing option set values on records, CRM stores only the integer value. So in the Contact's Salutation column will be values like 1000, 1001, etc.
If you go in and change Mrs.'s value from 1001 to 2002, the records that had 1001 will still have 1001. When you got to load that Contact, it will try to find 1001, which no longer exists, and you'll get an error.

The master list of option set values gets stored in a table called StringMap that matches the integer value to its labels (which are language dependent).
Whenever CRM retrieves an option set column, it looks up the integer value in the stringmap table and returns the label for the active language.

Because of all this, the way to do what you want is to create a new value in the option set, set all records that have the old value to have the new value, then delete the old value from the option set.

What are you really trying to do here?

Body:
Do you know if there is a solution to modify the value (not a label) of an option in optionset by code C#.

for example, I have this Option:
(Label: OldLabel, Value: OldValue)

and I want this:
(Label: OldLabel, Value: NewValue)

I tried by the following code, but is not working:

UpdateOptionValueRequest updateOptionValueRequest =
    new UpdateOptionValueRequest
    {
        OptionSetName = _globalOptionSetName,
        // Update the second option value.
        Value = newValue,
        Label = new Label("oldLabel", _languageCode)
    };

_serviceProxy.Execute(updateOptionValueRequest);

//Publish the OptionSet
PublishXmlRequest pxReq3 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) };
_serviceProxy.Execute(pxReq3);


问:
How to configure Openlayers for a flat 1:1 pixel coordinate system?
I'm trying to build a map for the game Guild Wars 2, but having trouble getting openlayers to handle the coordinate system correctly and render the map completely.

Here's a fiddle of what I have: https://jsfiddle.net/ndqb8rqx/

The Guild Wars world is square and 49152 pixels on both axes. The origin ([0, 0]) of the coordinates should be the north-west. The south-east should be [49152, 49152]. The developer of the game makes the tiles for the map available as a service: https://wiki.guildwars2.com/wiki/API:Tile_service

I created a Projection based on Zoomify to try to handle this:

```<code>var gw2Projection = new ol.proj.Projection({
  code: 'ZOOMIFY',
  units: 'pixels',
  extent: [0, -49152, 49152, 0]
})
</code>```

And I also added the game tiles as a Tilelayer from an XYZ source, like this:

```<code>new ol.layer.Tile({
  source: new ol.source.XYZ({
    url: 'https://tiles.guildwars2.com/1/1/{z}/{x}/{y}.jpg',
    projection: gw2Projection
  }),
}),
</code>```

The first problem is that openlayers doesn't render the complete map. The map actually extends further south and east than the fiddle shows. The bottom right edge which is actually shown in the fiddle is really [32768, 32768], but the map extends out to [49152, 49152]. It seems that openlayers simply shrinks the coordinate system to the area of a single tile when zoomed completely out. Instead I would like the coordinates to match 1:1 with the pixels.

The other problem is that currently the y-coordinate increase in the northern direction. I would like to invert the y-axis, such that the y-coordinates increase in the southern direction.

答:
@ahocevar nudged me in the right direction. The suggestion of creating a custom tilegrid was necessary but instead of setting the zoom level, it was necessary to set the actual resolutions.

So by adding a tilegrid like this:

```<code>var tilegrid = new ol.tilegrid.TileGrid({
  extent: extent,
  resolutions: [128, 64, 32, 16, 8, 4, 2, 1]
});
</code>```

Using it in the layer source like this:

```<code>source: new ol.source.XYZ({
  tileGrid: tilegrid,
  url: 'https://tiles.guildwars2.com/1/1/{z}/{x}/{y}.jpg',
  projection: gw2Projection
}),
</code>```

And finally adding it to the view as well:

```<code>view: new ol.View({
  center: ol.extent.getCenter(extent),
  zoom: 1,
  projection: gw2Projection,
  extent:extent,
  resolutions: tilegrid.getResolutions()
})
</code>```

The entire map is now shown, and the coordinates are correct. The Y-axis is still negative though.

Here's a fiddle with the result, I also included the TileDebug layer for good measure: https://jsfiddle.net/kay99yor/1/

Body:
I'm trying to build a map for the game Guild Wars 2, but having trouble getting openlayers to handle the coordinate system correctly and render the map completely.

Here's a fiddle of what I have: https://jsfiddle.net/ndqb8rqx/

The Guild Wars world is square and 49152 pixels on both axes. The origin ([0, 0]) of the coordinates should be the north-west. The south-east should be [49152, 49152]. The developer of the game makes the tiles for the map available as a service: https://wiki.guildwars2.com/wiki/API:Tile_service

I created a Projection based on Zoomify to try to handle this:

var gw2Projection = new ol.proj.Projection({
  code: 'ZOOMIFY',
  units: 'pixels',
  extent: [0, -49152, 49152, 0]
})

And I also added the game tiles as a Tilelayer from an XYZ source, like this:

new ol.layer.Tile({
  source: new ol.source.XYZ({
    url: 'https://tiles.guildwars2.com/1/1/{z}/{x}/{y}.jpg',
    projection: gw2Projection
  }),
}),

The first problem is that openlayers doesn't render the complete map. The map actually extends further south and east than the fiddle shows. The bottom right edge which is actually shown in the fiddle is really [32768, 32768], but the map extends out to [49152, 49152]. It seems that openlayers simply shrinks the coordinate system to the area of a single tile when zoomed completely out. Instead I would like the coordinates to match 1:1 with the pixels.

The other problem is that currently the y-coordinate increase in the northern direction. I would like to invert the y-axis, such that the y-coordinates increase in the southern direction.

Body:
@ahocevar nudged me in the right direction. The suggestion of creating a custom tilegrid was necessary but instead of setting the zoom level, it was necessary to set the actual resolutions.

So by adding a tilegrid like this:

var tilegrid = new ol.tilegrid.TileGrid({
  extent: extent,
  resolutions: [128, 64, 32, 16, 8, 4, 2, 1]
});

Using it in the layer source like this:

source: new ol.source.XYZ({
  tileGrid: tilegrid,
  url: 'https://tiles.guildwars2.com/1/1/{z}/{x}/{y}.jpg',
  projection: gw2Projection
}),

And finally adding it to the view as well:

view: new ol.View({
  center: ol.extent.getCenter(extent),
  zoom: 1,
  projection: gw2Projection,
  extent:extent,
  resolutions: tilegrid.getResolutions()
})

The entire map is now shown, and the coordinates are correct. The Y-axis is still negative though.

Here's a fiddle with the result, I also included the TileDebug layer for good measure: https://jsfiddle.net/kay99yor/1/


问:
Find missing element
I saw the following question:

Given an array A of integers, find an integer k that is not present in A. Assume that the integers are 32-bit signed integers.

How to solve it?

Thank you

//// update -- This is the provided solution - but I don't think it is correct ////
Consider a very simple hash function F(x)=x mod (n+1). we can build a bit-vector of length
n+1 that is initialized to 0 and for every element in A, we set bit F(A[i]) to 1.Since there are only n elements in the array, we can find the missing element easily.

I think the above solution is wrong.

For example,
A [ 2, 100, 4 ], then both 4 and 100 will match to the same place.

答:
```<code>max (items) + 1
</code>```

springs to mind.  Of course it would fail if one of the elements was 2^31-1 and another was -(2^32).

Failing that, sort them and look for an interval.

Title: Find missing element

Body:
max (items) + 1

springs to mind.  Of course it would fail if one of the elements was 2^31-1 and another was -(2^32).

Failing that, sort them and look for an interval.


答:
I would create a list of Boeing737 and I would not take the straight input from the console.

```<code>List<Boeing737> boeingList = new List<Boeing737>();
boeingList.add(new Boeing737() { param=value...});
</code>```

Then later on you can access them by index, name, loop through them, etc.

I would also look into Linq

Title: C# - Declaration of class variables

Body:
I would create a list of Boeing737 and I would not take the straight input from the console.

List<Boeing737> boeingList = new List<Boeing737>();
boeingList.add(new Boeing737() { param=value...});

Then later on you can access them by index, name, loop through them, etc.

I would also look into Linq


问:
In Swift I would like to "join" two sequences in to a sequence of tuples
I would like to join two (or more) sequences that would then create a sequence of tuples.  Where the first tuple would contain the first element of each sequence and the second tuple would contain the second elements, etc ...   Below is an example function that takes two arrays and creates a third array of tuples. I then can use this sequence to process with map(), filter() and reduce() functions.

My example works, but is lacking in a bunch of ways.  It is for arrays not for all sequences, It stops generating tuples when the first sequence runs out of elements. I would like nils to be in the tuples for the short sequences that can no longer provide elements. It is only for two arrays, I would like it to be for any number of sequences,

Partial solutions would be helpful.  I'm a functional programming newbie so the proper name for this function would also be appreciated.  Maybe its is already in the switfz library I just know what it is called.  I chose "join" because it is roughly similar to the SQL "join" which also builds tuples (a.k.a. rows)

```<code>func join<T> (s1: Array<T>, s2: Array<T>) -> Array<(T,T)> {

var g1 = s1.generate();
var g2 = s2.generate();

var result:Array<(T,T)> = []

while let e1 = g1.next() {

    if let e2 = g2.next() {
        result.append((e1,e2))
    }
}
return result
}

class Hamming {
    class func compute(input: String, against: String) -> Int {
        return join(Array(input),Array(against)).reduce(0){ return ($1.0 != $1.1) ? $0 + 1 : $0 }
    }
}

Hamming.compute("abcde","abcdf")  // 1
</code>```

答:
Here is a Swift 4 version of drewag's answer. I packaged it up as a Swift 4 package on GitHub, along with some tests: https://github.com/danramteke/Zip2WithNilPadding

Here is the relevant code in Swift 4:

```<code>public struct Zip2WithNilPadding<T: Sequence, U: Sequence>: Sequence {
    public typealias Iterator = AnyIterator<(T.Iterator.Element?, U.Iterator.Element?)>

    public let first: T
    public let second: U

    public init(_ first: T, _ second: U) {
        self.first = first
        self.second = second
    }

    public func makeIterator() -> Iterator {
        var iterator1: T.Iterator? = first.makeIterator()
        var iterator2: U.Iterator? = second.makeIterator()

        return Iterator() {
            let element1 = iterator1?.next()
            let element2 = iterator2?.next()

            if element1 == nil && element2 == nil {
              return nil
            } else {
              return (element1, element2)
            }
        }
    }
}
</code>```

Body:
I would like to join two (or more) sequences that would then create a sequence of tuples.  Where the first tuple would contain the first element of each sequence and the second tuple would contain the second elements, etc ...   Below is an example function that takes two arrays and creates a third array of tuples. I then can use this sequence to process with map(), filter() and reduce() functions.

My example works, but is lacking in a bunch of ways.  It is for arrays not for all sequences, It stops generating tuples when the first sequence runs out of elements. I would like nils to be in the tuples for the short sequences that can no longer provide elements. It is only for two arrays, I would like it to be for any number of sequences,

Partial solutions would be helpful.  I'm a functional programming newbie so the proper name for this function would also be appreciated.  Maybe its is already in the switfz library I just know what it is called.  I chose "join" because it is roughly similar to the SQL "join" which also builds tuples (a.k.a. rows)

func join<T> (s1: Array<T>, s2: Array<T>) -> Array<(T,T)> {

var g1 = s1.generate();
var g2 = s2.generate();

var result:Array<(T,T)> = []

while let e1 = g1.next() {

    if let e2 = g2.next() {
        result.append((e1,e2))
    }
}
return result
}

class Hamming {
    class func compute(input: String, against: String) -> Int {
        return join(Array(input),Array(against)).reduce(0){ return ($1.0 != $1.1) ? $0 + 1 : $0 }
    }
}

Hamming.compute("abcde","abcdf")  // 1

Body:
Here is a Swift 4 version of drewag's answer. I packaged it up as a Swift 4 package on GitHub, along with some tests: https://github.com/danramteke/Zip2WithNilPadding

Here is the relevant code in Swift 4:

public struct Zip2WithNilPadding<T: Sequence, U: Sequence>: Sequence {
    public typealias Iterator = AnyIterator<(T.Iterator.Element?, U.Iterator.Element?)>

    public let first: T
    public let second: U

    public init(_ first: T, _ second: U) {
        self.first = first
        self.second = second
    }

    public func makeIterator() -> Iterator {
        var iterator1: T.Iterator? = first.makeIterator()
        var iterator2: U.Iterator? = second.makeIterator()

        return Iterator() {
            let element1 = iterator1?.next()
            let element2 = iterator2?.next()

            if element1 == nil && element2 == nil {
              return nil
            } else {
              return (element1, element2)
            }
        }
    }
}


问:
get all unique prefetch_related objects in Django
in models.py:

```<code>from django.db import models
...
class Product(models.Model):
   ...
   recommended = models.ManyToManyField('self', blank=True)
   ...
</code>```

if i have a queryset of Product how can i get all unique recommended objects?

example: product «A» has 3 recommended products: «B», «C» and «D», product «B» has 2 recommended products: «C» and «E», in queryset «products» we have «A» and «B» products, in this example:

```<code># get_products() returns QuerySet of «A» and «B» products
products = get_products().prefetch_related('recommended')
recommended = [item for p in products for item in p.recommended.all()]
</code>```

we will get list of [«B», «C», «D», «C», «E»], but how to get only [«B», «C», «D», «E»]?

P.S. of course we can filter objects in «for» cycle, but maybe there's more effective and fair way?
...

Update #1 (answer to Mark Galloway):

```<code>products = self.request.basket.get_products().prefetch_related(
        Prefetch('recommended', queryset=models.Product.objects.distinct()))
recommended_list = [item for p in products for item in p.recommended.all()]
</code>```

returns:

```<code>[<Product: Vestibulum ante ipsum primis in>, <Product: Vivamus quis turpis>, <Product: Pellentesque habitant>, <Product: Vivamus quis turpis>]
</code>```

where <Product: Vivamus quis turpis> repeated

P.S. does anybody knows?

答:
Assuming your model is as follows (from your description and output, I am assuming you must have symmetrical=False):

```<code>class Product(models.Model):
    recommended = models.ManyToManyField('self', blank=True, symmetrical=False, related_name='recommended_by')
</code>```

Then I think the following does what you are after:

```<code>Product.objects.filter(recommended_by__in=get_products()).distinct()
>>> <QuerySet [<Product: B>, <Product: C>, <Product: D>, <Product: E>]>
</code>```

Body:
in models.py:

from django.db import models
...
class Product(models.Model):
   ...
   recommended = models.ManyToManyField('self', blank=True)
   ...

if i have a queryset of Product how can i get all unique recommended objects?

example: product «A» has 3 recommended products: «B», «C» and «D», product «B» has 2 recommended products: «C» and «E», in queryset «products» we have «A» and «B» products, in this example:

# get_products() returns QuerySet of «A» and «B» products
products = get_products().prefetch_related('recommended')
recommended = [item for p in products for item in p.recommended.all()]

we will get list of [«B», «C», «D», «C», «E»], but how to get only [«B», «C», «D», «E»]?

P.S. of course we can filter objects in «for» cycle, but maybe there's more effective and fair way?
...

Update #1 (answer to Mark Galloway):

products = self.request.basket.get_products().prefetch_related(
        Prefetch('recommended', queryset=models.Product.objects.distinct()))
recommended_list = [item for p in products for item in p.recommended.all()]

returns:

[<Product: Vestibulum ante ipsum primis in>, <Product: Vivamus quis turpis>, <Product: Pellentesque habitant>, <Product: Vivamus quis turpis>]

where <Product: Vivamus quis turpis> repeated

P.S. does anybody knows?

Body:
Assuming your model is as follows (from your description and output, I am assuming you must have symmetrical=False):

class Product(models.Model):
    recommended = models.ManyToManyField('self', blank=True, symmetrical=False, related_name='recommended_by')

Then I think the following does what you are after:

Product.objects.filter(recommended_by__in=get_products()).distinct()
>>> <QuerySet [<Product: B>, <Product: C>, <Product: D>, <Product: E>]>


问:
Can't find the reference to a library
Trying to shadow copy file from path A to Path B but it keep throwing me error message

{"Could not load file or assembly 'AlphaVSS.x64, Version=1.4.0.0,
  Culture=neutral, PublicKeyToken=959d3993561034e3' or one of its
  dependencies. An attempt was made to load a program with an incorrect
  format."}

Code i try with it

  Public Sub copyFile(baza As String, destination As String)

        If IO.File.Exists(baza) Then

            Dim myFileInfo As FileInfo
            myFileInfo = New FileInfo(baza)

            Dim _volume As String = myFileInfo.Directory.Root.Name

            Dim _vssImplementation As IVssImplementation = VssUtils.LoadImplementation()
            Dim _backup As IVssBackupComponents = _vssImplementation.CreateVssBackupComponents()

            _backup.InitializeForBackup(Nothing)

            _backup.GatherWriterMetadata()

            _backup.SetContext(VssVolumeSnapshotAttributes.Persistent Or VssVolumeSnapshotAttributes.NoAutoRelease)
            _backup.SetBackupState(False, True, Alphaleonis.Win32.Vss.VssBackupType.Full, False)

            Dim MyGuid01 As Guid = _backup.StartSnapshotSet()
            Dim MyGuid02 As Guid = _backup.AddToSnapshotSet(_volume, Guid.Empty)

            _backup.PrepareForBackup()
            _backup.DoSnapshotSet()

            _backup.ExposeSnapshot(MyGuid02, Nothing, VssVolumeSnapshotAttributes.ExposedLocally, "L:")

            Dim sVSSFile2 As String = baza.Replace(_volume, "L:\")

            If (File.Exists(sVSSFile2)) Then
                System.IO.File.Copy(sVSSFile2, destination + "\" + System.IO.Path.GetFileName(baza), True)

                For Each prop As VssSnapshotProperties In _backup.QuerySnapshots
                    If (prop.ExposedName = "L:\") Then
                        Console.WriteLine("File found !")
                        _backup.DeleteSnapshot(prop.SnapshotId, True)
                    End If
                Next

                _backup = Nothing

                Console.WriteLine("File copied")

            Else

                Console.WriteLine("------------------------------------------")
                Console.WriteLine("File not exist: " + baza)

            End If
        End If
    End Sub
```

<p>I have the VSS nuget package and references</p>

<p><img src="https://i.stack.imgur.com/tIa3T.png" alt="enter image description here"></p>

<p>It throws error on line</p>

```Dim _vssImplementation As IVssImplementation = VssUtils.LoadImplementation()
```

答:
An attempt was made to load a program with an incorrect format

This message means you're trying to load an executable (.dll, .exe, etc.) which cannot be run by the process (or by Windows itself depending on the situation).

The most common cause for this error is trying to load 32-bit code into a 64-bit process (or vice versa). 64-bit processes can only run 64-bit code, and 32-bit processes can only run 32-bit code.

Since it is the AlphaVSS.x64 assembly that's faulting, your project is most likely compiled into a 32-bit executable. You should either remove this reference or change your project to target x64 only (note that if you do the latter you won't be able to run your application on 32-bit machines).

Title: Can't find the reference to a library

Body:
Trying to shadow copy file from path A to Path B but it keep throwing me error message

{"Could not load file or assembly 'AlphaVSS.x64, Version=1.4.0.0,
  Culture=neutral, PublicKeyToken=959d3993561034e3' or one of its
  dependencies. An attempt was made to load a program with an incorrect
  format."}

Code i try with it

  Public Sub copyFile(baza As String, destination As String)

        If IO.File.Exists(baza) Then

            Dim myFileInfo As FileInfo
            myFileInfo = New FileInfo(baza)

            Dim _volume As String = myFileInfo.Directory.Root.Name

            Dim _vssImplementation As IVssImplementation = VssUtils.LoadImplementation()
            Dim _backup As IVssBackupComponents = _vssImplementation.CreateVssBackupComponents()

            _backup.InitializeForBackup(Nothing)

            _backup.GatherWriterMetadata()

            _backup.SetContext(VssVolumeSnapshotAttributes.Persistent Or VssVolumeSnapshotAttributes.NoAutoRelease)
            _backup.SetBackupState(False, True, Alphaleonis.Win32.Vss.VssBackupType.Full, False)

            Dim MyGuid01 As Guid = _backup.StartSnapshotSet()
            Dim MyGuid02 As Guid = _backup.AddToSnapshotSet(_volume, Guid.Empty)

            _backup.PrepareForBackup()
            _backup.DoSnapshotSet()

            _backup.ExposeSnapshot(MyGuid02, Nothing, VssVolumeSnapshotAttributes.ExposedLocally, "L:")

            Dim sVSSFile2 As String = baza.Replace(_volume, "L:\")

            If (File.Exists(sVSSFile2)) Then
                System.IO.File.Copy(sVSSFile2, destination + "\" + System.IO.Path.GetFileName(baza), True)

                For Each prop As VssSnapshotProperties In _backup.QuerySnapshots
                    If (prop.ExposedName = "L:\") Then
                        Console.WriteLine("File found !")
                        _backup.DeleteSnapshot(prop.SnapshotId, True)
                    End If
                Next

                _backup = Nothing

                Console.WriteLine("File copied")

            Else

                Console.WriteLine("------------------------------------------")
                Console.WriteLine("File not exist: " + baza)

            End If
        End If
    End Sub

I have the VSS nuget package and references

It throws error on line

Dim _vssImplementation As IVssImplementation = VssUtils.LoadImplementation()


问:
jQuery – "Read More" span not reappearing after clicking "Read Less"
I'm setting up a portfolio website with project descriptions that are previewed with an excerpt and reveal the full details upon clicking "Read More." I'm pretty new to jQuery but I got it working so that you click "Read More," the paragraph shows up with a "Close" span at the end, and then you click "Close" and it disappears. The problem is "Read More" doesn't reappear after the paragraph is hidden.

https://codepen.io/anon/pen/OOegJx

```<code><div class="project-description">
    <p class="excerpt">Excerpt goes here.</p>
    <span class="read-more open">Read More</span>
    <p class="full hidden">At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos.
   <span class="read-more close">Close</span></p>
</div>

.full {
  display: block;
}

.hidden {
  display: none;
}

.open {
  display: block;
}

$(document).ready(function(){
  $('.open').click(function() {
     $(this).siblings('.full').removeClass('hidden');
     $(this).css('display', 'none');
  })

  $('.close').click(function() {
     $(this).parent('.full').addClass('hidden');
     $(this).parent('.open').css('display', 'block');
  })
});
</code>```

(My site is one-page, so I tried to write the JS in a way that won't open up all of my other project's descriptions, just the one I clicked "Read More" on. Not sure if that affects finding a solution)

答:
Something you've done that is a great thing: you have contained the stuff you'll be working with to a single element. Something that works well is to create a reference to that container el, then use that and create references to the descendant nodes. Note in the following, I don't care which nodes contain what, or are siblings to what -- they're all descendants of your .project-description. By creating the references to them within the .each() statement, you can have multiple copies of this on a page that don't crash with each other.

$(document).ready(function(){
  var containerEl = $('.project-description');

  containerEl.each(function(){
    var openEl = $(this).find('.open');
    var closeEl = $(this).find('.close');
    var fullEl = $(this).find('.full');

    openEl.click(function() {
       fullEl.removeClass('hidden');
       $(this).css('display', 'none');
    })

    closeEl.click(function() {
       fullEl.addClass('hidden');
       openEl.css('display', 'inline-block');
    })

  })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.full {
  display: block;
}

.hidden {
  display: none;
}

.open {
  display: inline-block;
}

.read-more {
  background-color: #ccc;
}</code>```

Excerpt goes here.

    Read More

At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos.
   Close

Second goes here.

    Read More

Proin eget tortor risus. Pellentesque in ipsum id orci porta dapibus. Nulla quis lorem ut libero malesuada feugiat. Quisque velit nisi, pretium ut lacinia in, elementum id enim. Curabitur arcu erat, accumsan id imperdiet et, porttitor at sem.
   Close

And another goes here.

    Read More

Pellentesque in ipsum id orci porta dapibus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque velit nisi, pretium ut lacinia in, elementum id enim. Mauris blandit aliquet elit, eget tincidunt nibh pulvinar a. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui.
   Close

```

Body:
I'm setting up a portfolio website with project descriptions that are previewed with an excerpt and reveal the full details upon clicking "Read More." I'm pretty new to jQuery but I got it working so that you click "Read More," the paragraph shows up with a "Close" span at the end, and then you click "Close" and it disappears. The problem is "Read More" doesn't reappear after the paragraph is hidden.

https://codepen.io/anon/pen/OOegJx

Excerpt goes here.

    Read More

At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos.
   Close

.full {
  display: block;
}

.hidden {
  display: none;
}

.open {
  display: block;
}

$(document).ready(function(){
  $('.open').click(function() {
     $(this).siblings('.full').removeClass('hidden');
     $(this).css('display', 'none');
  })

  $('.close').click(function() {
     $(this).parent('.full').addClass('hidden');
     $(this).parent('.open').css('display', 'block');
  })
});

(My site is one-page, so I tried to write the JS in a way that won't open up all of my other project's descriptions, just the one I clicked "Read More" on. Not sure if that affects finding a solution)

Body:
Something you've done that is a great thing: you have contained the stuff you'll be working with to a single element. Something that works well is to create a reference to that container el, then use that and create references to the descendant nodes. Note in the following, I don't care which nodes contain what, or are siblings to what -- they're all descendants of your .project-description. By creating the references to them within the .each() statement, you can have multiple copies of this on a page that don't crash with each other.

$(document).ready(function(){
  var containerEl = $('.project-description');

  containerEl.each(function(){
    var openEl = $(this).find('.open');
    var closeEl = $(this).find('.close');
    var fullEl = $(this).find('.full');

    openEl.click(function() {
       fullEl.removeClass('hidden');
       $(this).css('display', 'none');
    })

    closeEl.click(function() {
       fullEl.addClass('hidden');
       openEl.css('display', 'inline-block');
    })

  })
});

.full {
  display: block;
}

.hidden {
  display: none;
}

.open {
  display: inline-block;
}

.read-more {
  background-color: #ccc;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="project-description">
    <p class="excerpt">Excerpt goes here.</p>
    <span class="read-more open">Read More</span>
    <p class="full hidden">At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos.
   <span class="read-more close">Close</span></p>
</div>
<div class="project-description">
    <p class="excerpt">Second goes here.</p>
    <span class="read-more open">Read More</span>
    <p class="full hidden">Proin eget tortor risus. Pellentesque in ipsum id orci porta dapibus. Nulla quis lorem ut libero malesuada feugiat. Quisque velit nisi, pretium ut lacinia in, elementum id enim. Curabitur arcu erat, accumsan id imperdiet et, porttitor at sem.
   <span class="read-more close">Close</span></p>
</div>
<div class="project-description">
    <p class="excerpt">And another goes here.</p>
    <span class="read-more open">Read More</span>
    <p class="full hidden">Pellentesque in ipsum id orci porta dapibus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque velit nisi, pretium ut lacinia in, elementum id enim. Mauris blandit aliquet elit, eget tincidunt nibh pulvinar a. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui.
   <span class="read-more close">Close</span></p>
</div>


问:
What is the Rubiest way to check strictly for false value (and exclude nil)?
What is the Rubiest way check that a value is false and not nil (which is a falsy value)?

example using a fictional method false?:

```<code>a = false
a.false? # should return true
a = nil
a.false? # should return false
</code>```

答:
I concur with @spickermann's comment to your question that the most Ruby way would be to not distinguish between nil and false.

The most OO way would be to allow an object to decide for itself whether it is false or not, just the way you are doing in your question: by responding to a false? message.

```<code>class TrueClass
  def true?
    true
  end
end

class FalseClass
  def false?
    true
  end
end

class Object
  def true?
    false
  end

  def false?
    false
  end
end
</code>```

If you want to be a nice Ruby citizen, you encapsulate these monkeypatches in a mixin, so that they show up in the ancestors chain:

```<code>module StrictlyTrue
  def true?
    true
  end
end

class TrueClass
  include StrictlyTrue
end

module StrictlyFalse
  def false?
    true
  end
end

class FalseClass
  include StrictlyFalse
end

module NeitherFalseNorTrue
  def true?
    false
  end

  def false?
    false
  end
end

class Object
  include NeitherFalseNorTrue
end
</code>```

And if you want to be totally nice, you can wrap this in a Refinement:

```<code>module StrictlyTrue
  def true?
    true
  end
end

module StrictlyFalse
  def false?
    true
  end
end

module NeitherFalseNorTrue
  def true?
    false
  end

  def false?
    false
  end
end

module StrictBooleans
  refine TrueClass do
    include StrictlyTrue
  end

  refine FalseClass do
    include StrictlyFalse
  end

  refine Object do
    include NeitherFalseNorTrue
  end
end
</code>```

Body:
What is the Rubiest way check that a value is false and not nil (which is a falsy value)?

example using a fictional method false?:

a = false
a.false? # should return true
a = nil
a.false? # should return false

Body:
I concur with @spickermann's comment to your question that the most Ruby way would be to not distinguish between nil and false.

The most OO way would be to allow an object to decide for itself whether it is false or not, just the way you are doing in your question: by responding to a false? message.

class TrueClass
  def true?
    true
  end
end

class FalseClass
  def false?
    true
  end
end

class Object
  def true?
    false
  end

  def false?
    false
  end
end

If you want to be a nice Ruby citizen, you encapsulate these monkeypatches in a mixin, so that they show up in the ancestors chain:

module StrictlyTrue
  def true?
    true
  end
end

class TrueClass
  include StrictlyTrue
end

module StrictlyFalse
  def false?
    true
  end
end

class FalseClass
  include StrictlyFalse
end

module NeitherFalseNorTrue
  def true?
    false
  end

  def false?
    false
  end
end

class Object
  include NeitherFalseNorTrue
end

And if you want to be totally nice, you can wrap this in a Refinement:

module StrictlyTrue
  def true?
    true
  end
end

module StrictlyFalse
  def false?
    true
  end
end

module NeitherFalseNorTrue
  def true?
    false
  end

  def false?
    false
  end
end

module StrictBooleans
  refine TrueClass do
    include StrictlyTrue
  end

  refine FalseClass do
    include StrictlyFalse
  end

  refine Object do
    include NeitherFalseNorTrue
  end
end


问:
Select values that meet different conditions on different rows?
This is a very basic query I can't figure out....

Let's say I have a two column table like this:

```<code>userid  |  roleid
--------|--------
   1    |    1
   1    |    2
   1    |    3
   2    |    1
</code>```

I want to get all distinct userids that have roleids 1, 2 AND 3.  Using the above example, the only result I want returned is userid 1.  How do I do this?

答:
Assuming userid, roleid are contained in a unique index (meaning there cannot be 2 records where userid = x and roleid = 1</p>

```<code>select count(*), userid from t
where roleid in (1,2,3)
group by userid
having count(*) = 3
</code>```

OwnerDisplayName: John

Body:
This is a very basic query I can't figure out....

Let's say I have a two column table like this:

userid  |  roleid
--------|--------
   1    |    1
   1    |    2
   1    |    3
   2    |    1

I want to get all distinct userids that have roleids 1, 2 AND 3.  Using the above example, the only result I want returned is userid 1.  How do I do this?

LastEditorDisplayName: John

Body:
Assuming userid, roleid are contained in a unique index (meaning there cannot be 2 records where userid = x and roleid = 1

select count(*), userid from t
where roleid in (1,2,3)
group by userid
having count(*) = 3


问:
Query temp table in stored proc whilst debugging in SQL 2008 Management Studio
I have a really large stored procedure which calls other stored procedures and applies the results into temp tables.

I am debugging in SQL 2008 Management Studio and can use the watch window to query local parameters but how can I query a temp table on whilst debugging?

If its not possible is there an alternative approach? I have read about using table variables instead, would it be possible to query these? If so how would I do this?

答:
Use global temporary tables, i.e. with double hash.

```<code>insert into ##temp select ...
</code>```

While debugging, you can pause the SP at some point, and in another query window, the ## table is available for querying.

```<code>select * from ##temp
</code>```

Single hash tables (#tmp) is session specific and is only visible from the session.

Body:
Use global temporary tables, i.e. with double hash.

insert into ##temp select ...

While debugging, you can pause the SP at some point, and in another query window, the ## table is available for querying.

select * from ##temp

Single hash tables (#tmp) is session specific and is only visible from the session.


问:
how can I quickly convert in python an xlsx file into a csv file?
I have a 140MB Excel file I need to analyze using pandas. The problem is that if I open this file as xlsx it takes python 5 minutes simply to read it. I tried to manually save this file as csv and then it takes Python about a second to open and read it! There are different 2012-2014 solutions that why Python 3 don't really work on my end.

Can somebody suggest how to convert very quickly file 'C:\master_file.xlsx' to 'C:\master_file.csv'?

答:
Fastest way that pops to mind:

pandas.read_excel

pandas.DataFrame.to_csv

As an added benefit, you'll be able to do cleanup of the data before saving it to csv.

```<code>import pandas as pd
df = pd.read_excel('C:\master_file.xlsx', header=0) #, sheetname='<your sheet>'
df.to_csv('C:\master_file.csv', index=False, quotechar="'")
</code>```

At some point, dealing with lots of data will take lots of time.  Just a fact of life.  Good to look for options if it's a problem, though.

Body:
Fastest way that pops to mind:

pandas.read_excel

pandas.DataFrame.to_csv

As an added benefit, you'll be able to do cleanup of the data before saving it to csv.

import pandas as pd
df = pd.read_excel('C:\master_file.xlsx', header=0) #, sheetname='<your sheet>'
df.to_csv('C:\master_file.csv', index=False, quotechar="'")

At some point, dealing with lots of data will take lots of time.  Just a fact of life.  Good to look for options if it's a problem, though.


问:
Ruby rails add field to form with JavaScript
I am using ruby on rails and JavaScript. I want to create a form in which one field can have more than one "object". In my example an employee can add multiple formations.

Just to let you know, I don't know much in JavaScript and I am not an expert in Web languages. So please explain to me what are my problems in the following code.

This is the code in my employe _form.html.erb

```<code><div id="formationSet" class="form-group row">
</div>
<a href="javascript:" id="addNewFormation">Add Formations</a>
</code>```

this is my code in employeFormation.js

```<code>$(document).ready(function(){
    $('#addNewFormation').click(function(){
        $('div#formationSet').append('<div class ="FormationsForm"><input type="text" class="input-large" placeholder="Caption">'+
            '<button class="removeNewFormation" type="button">remove</button>    </div>');
    });

    $("div#formationSet").on('click', '.removeNewFormation', function(){
        $(this).closest('.FormationsForm').remove();
    });
});
</code>```

and this is my code in application.js

```<code>//= require employeFormation
</code>```

what I actually want is that when I click on addFormation its add a field below the other and I can remove it and is added to my object when I create the new employee

Thanks you for your answer.

Edit: corrected some typo in the code (thanks to KKK). But its still not working

答:
Above ruby 4.0 aparently $(document).ready dont get notify as before. So I had to change it like this: </p>

```<code>var ready = function() {
    $('#addNewFormation').click(function(){
        $('div#formationSet').append('<div class ="FormationsForm"> <%=     f.label :email %> \n <%= f.text_field :email %>' +

        '<button class="removeNewFormation" type="button">remove</button></div>');
    });

    $("div#formationSet").on('click', '.removeNewFormation', function(){
        $(this).closest('.FormationsForm').remove();
    });
};

$(document).ready(ready);
$(document).on('page:change', ready);
</code>```

Body:
I am using ruby on rails and JavaScript. I want to create a form in which one field can have more than one "object". In my example an employee can add multiple formations.

Just to let you know, I don't know much in JavaScript and I am not an expert in Web languages. So please explain to me what are my problems in the following code.

This is the code in my employe _form.html.erb

Add Formations

this is my code in employeFormation.js

$(document).ready(function(){
    $('#addNewFormation').click(function(){
        $('div#formationSet').append('
<input type="text" class="input-large" placeholder="Caption">'+
            '<button class="removeNewFormation" type="button">remove</button>
');
    });

    $("div#formationSet").on('click', '.removeNewFormation', function(){
        $(this).closest('.FormationsForm').remove();
    });
});

and this is my code in application.js

//= require employeFormation

what I actually want is that when I click on addFormation its add a field below the other and I can remove it and is added to my object when I create the new employee

Thanks you for your answer.

Edit: corrected some typo in the code (thanks to KKK). But its still not working

Body:
Above ruby 4.0 aparently $(document).ready dont get notify as before. So I had to change it like this:

var ready = function() {
    $('#addNewFormation').click(function(){
        $('div#formationSet').append('<div class ="FormationsForm"> <%=     f.label :email %> \n <%= f.text_field :email %>' +

        '<button class="removeNewFormation" type="button">remove</button></div>');
    });

    $("div#formationSet").on('click', '.removeNewFormation', function(){
        $(this).closest('.FormationsForm').remove();
    });
};

$(document).ready(ready);
$(document).on('page:change', ready);


答:
Read the documentation. There are requirements when using the package

Visual C++ 2017 Redistributables must be installed on the machine running any application using AlphaVSS

Note that your application must be built using "Prefer 32-bit" unchecked if the Platform Target is set to Any CPU. Also note that your application must be built for 64-bit to work on a 64-bit system (or Any CPU with Prefer 32-bit off), and in 32-bit to work on a 32-bit system.

I initially had the same error as you, until I unchecked "Prefer 32-bit", then that line of code worked.

Title: Can't find the reference to a library


问:
How can I start a background job in Powershell that outlives it's parent?
Consider the following code:

```<code>start-job -scriptblock { sleep 10; cmd /c set > c:\env.txt; }
exit
</code>```

The background job is killed when the parent exits, so the call to cmd.exe never occurs. I would like to write some similar code, such that the parent exits immediately, and the child continues to run in the background.

I would like to keep everything in one script if possible.

答:
If you use Start-Process, you create a new child process that has your powershell session as its parent process. If you kill the powershell parent process that starts this, the new process will be orphaned and keep running. It will, however, not survive if you kill the parent's process tree

```<code>Start-Process -FilePath notepad.exe
</code>```

Powershell cannot start a new independent process outside of its process tree for you. However, this can be done in Windows using CreateProcess and this functionality is exposed through WMI. Luckily, you can call that from powershell:

```<code>Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList notepad.exe
</code>```

This way, the new process will also keep running if the process tree is killed, because the new process does not have your powershell session as a parent, but the WMI host process.

Body:
Consider the following code:

start-job -scriptblock { sleep 10; cmd /c set > c:\env.txt; }
exit

The background job is killed when the parent exits, so the call to cmd.exe never occurs. I would like to write some similar code, such that the parent exits immediately, and the child continues to run in the background.

I would like to keep everything in one script if possible.

Body:
If you use Start-Process, you create a new child process that has your powershell session as its parent process. If you kill the powershell parent process that starts this, the new process will be orphaned and keep running. It will, however, not survive if you kill the parent's process tree

Start-Process -FilePath notepad.exe

Powershell cannot start a new independent process outside of its process tree for you. However, this can be done in Windows using CreateProcess and this functionality is exposed through WMI. Luckily, you can call that from powershell:

Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList notepad.exe

This way, the new process will also keep running if the process tree is killed, because the new process does not have your powershell session as a parent, but the WMI host process.