问:
AngularFire2 Suscribe return values FAIL
I have this code in my authService

```<code>    constructor(
    private afAuth: AngularFireAuth,
    private db: AngularFireDatabase,
    private router: Router
  ) {
    this.authState = afAuth.authState;
    this.authState.subscribe((user: firebase.User) => {
        this.authState = user;
    });
    if ( this.authenticated ) {
      // this.router.navigate([`/content`]);
    }
  }

  // Returns true if user is logged in
  get authenticated(): any {
    return this.authState;
  }
</code>```

I call the get authenticated and it returns undefined:

COMPONENT

```<code>    constructor(
    private auth: AuthService
  ) {
      this.currentUser = this.auth.authenticated;
  }
showUser() {
    console.log(this.currentUser.uid);
  }
</code>```

I need help to fix it, any idea?

答:
Whats your purpose? What do you need and why?

I still don't know why you need it like this. But i think it's a problem of the lifecycle hook (you can find here the doc).

try it like this. this is your component

```<code>export class *YOUR_COMPONENT* implements OnInit {

   private authenticatedUser$: Subscription; <= import rxjs/Subscription
   private authenticatedUser: User; <= import firebase/app

   constructor(private auth: AuthService) {
     this.authenticatedUser$ = this.auth.getAuthenticatedUser().subscribe((user: User) => {
      // Here you're saving the firebase.user in your var authenticatedUser
      this.authenticatedUser = user;
   });

   ngOnInit() {
      // Check if user is logged in..
      if(this.authenticatedUser) {
        // When true, your code here..
      }
   }

   ....}
</code>```

and here your authService:

```<code>   export class authService {

     constructor(private afAuth: AngularFireAuth) { <= import angularfire2/auth/auth
       // constructor is empty
     });

     getAuthenticatedUser() {
       return this.auth.authState;
     }

   ....}
</code>```

this should work..

Body:
I have this code in my authService

    constructor(
    private afAuth: AngularFireAuth,
    private db: AngularFireDatabase,
    private router: Router
  ) {
    this.authState = afAuth.authState;
    this.authState.subscribe((user: firebase.User) => {
        this.authState = user;
    });
    if ( this.authenticated ) {
      // this.router.navigate([`/content`]);
    }
  }

  // Returns true if user is logged in
  get authenticated(): any {
    return this.authState;
  }

I call the get authenticated and it returns undefined:

COMPONENT

    constructor(
    private auth: AuthService
  ) {
      this.currentUser = this.auth.authenticated;
  }
showUser() {
    console.log(this.currentUser.uid);
  }

I need help to fix it, any idea?

Body:
Whats your purpose? What do you need and why?

I still don't know why you need it like this. But i think it's a problem of the lifecycle hook (you can find here the doc).

try it like this. this is your component

export class *YOUR_COMPONENT* implements OnInit {

   private authenticatedUser$: Subscription; <= import rxjs/Subscription
   private authenticatedUser: User; <= import firebase/app

   constructor(private auth: AuthService) {
     this.authenticatedUser$ = this.auth.getAuthenticatedUser().subscribe((user: User) => {
      // Here you're saving the firebase.user in your var authenticatedUser
      this.authenticatedUser = user;
   });

   ngOnInit() {
      // Check if user is logged in..
      if(this.authenticatedUser) {
        // When true, your code here..
      }
   }

   ....}

and here your authService:

   export class authService {

     constructor(private afAuth: AngularFireAuth) { <= import angularfire2/auth/auth
       // constructor is empty
     });

     getAuthenticatedUser() {
       return this.auth.authState;
     }

   ....}

this should work..


来源: stackexchange

问:
Persist from Kernel Listener throw EntityManager is closed
I want to persist a Log entity (ip,url,path,user,date...) everytime a URL is requested or served. I'm getting the "EntityManager is closed" error.
I'm looking for a simple solution if possible.
My code is the following:

First the YAML
    services:

```<code>kernelListener:
    class: AppBundle\EventListener\KernelListener
    arguments: [ '@my_logger']
    tags:
        - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
        - { name: kernel.event_listener, event: kernel.response, method: onKernelResponse }
        - { name: kernel.event_listener, event: kernel.terminate, method: onKernelTerminate }
        - { name: kernel.event_listener, event: kernel.controller, method: onKernelController }

my_logger:
    class:        AppBundle\Service\Logger
    arguments: ['@doctrine.orm.entity_manager', '@security.token_storage' ]
    scope: prototype
</code>```

Here it's my Logger service:

```<code> namespace AppBundle\Service;
use AppBundle\Entity\Log;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;

class Logger {

private $em, $token;
public function __construct(EntityManager $em, TokenStorage $token) {
    $this->em = $em;
    $this->token_storage = $token;
}

public function persist($r) {

    $log = new Log();
    $log->setAjax($r->isXmlHttpRequest());
    $log->setIp($r->getClientIp());
    $log->setMethod($r->getMethod());
    $log->setPath($path);
    $log->setUrl($r->getUri());

    if ($this->token_storage->getToken()) {
        $user = $this->token_storage->getToken()->getUser();
        if ($user instanceof \AppBundle\Entity\User) {
            $log->setUser($user);
        }
    }

    $this->em->persist($log);
    $this->em->flush();
}

}
</code>```

and the KernelListener.php

```<code> namespace AppBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Event\PostResponseEvent;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use AppBundle\Service\Logger;

class KernelListener {

protected $logger;

public function __construct(Logger $logger) {
    $this->logger = $logger;
}

public function onKernelRequest(GetResponseEvent $event) {

}

public function onKernelResponse(FilterResponseEvent $event) {
}

 public function onKernelController(FilterControllerEvent $event) {
    $r = $event->getRequest();
    $this->logger->persist($r);
}

public function onKernelTerminate(PostResponseEvent $event) {
}
}
</code>```

If I remove the flush() no error is thrown, but no Log in the DB logically.

答:
Maksym was right. Thanks! In fact I used some months ago, this technique for a Service logging errors, but memory is weak specially when you are running many tasks :-(

So my working Logger is :

```<code>    public function persist($r) {
    if (!$this->em->isOpen()) {
        $this->em = $this->em->create(
                $this->em->getConnection(), $this->em->getConfiguration()
        );
    }

    $path = $r->get('_route');
    if (!$path || in_array($path, $this->paths)) {
        return null;
    }

    $log = new Log();
    $log->setAjax($r->isXmlHttpRequest());
    $log->setIp($r->getClientIp());
    $log->setMethod($r->getMethod());
    $log->setPath($path);
    $log->setUrl($r->getUri());

    if ($this->token_storage->getToken()) {
        $user = $this->token_storage->getToken()->getUser();
        if ($user instanceof \AppBundle\Entity\User) {
            $user2 = $this->em->getReference('AppBundle:User', $user->getId());
            $log->setUser($user2);
        }
    }

    $this->em->persist($log);
    $this->em->flush();
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to persist a Log entity (ip,url,path,user,date...) everytime a URL is requested or served. I'm getting the "EntityManager is closed" error.
I'm looking for a simple solution if possible.
My code is the following:

First the YAML
    services:

kernelListener:
    class: AppBundle\EventListener\KernelListener
    arguments: [ '@my_logger']
    tags:
        - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
        - { name: kernel.event_listener, event: kernel.response, method: onKernelResponse }
        - { name: kernel.event_listener, event: kernel.terminate, method: onKernelTerminate }
        - { name: kernel.event_listener, event: kernel.controller, method: onKernelController }

my_logger:
    class:        AppBundle\Service\Logger
    arguments: ['@doctrine.orm.entity_manager', '@security.token_storage' ]
    scope: prototype

Here it's my Logger service:

 namespace AppBundle\Service;
use AppBundle\Entity\Log;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;

class Logger {

private $em, $token;
public function __construct(EntityManager $em, TokenStorage $token) {
    $this->em = $em;
    $this->token_storage = $token;
}

public function persist($r) {

    $log = new Log();
    $log->setAjax($r->isXmlHttpRequest());
    $log->setIp($r->getClientIp());
    $log->setMethod($r->getMethod());
    $log->setPath($path);
    $log->setUrl($r->getUri());

    if ($this->token_storage->getToken()) {
        $user = $this->token_storage->getToken()->getUser();
        if ($user instanceof \AppBundle\Entity\User) {
            $log->setUser($user);
        }
    }

    $this->em->persist($log);
    $this->em->flush();
}

}

and the KernelListener.php

 namespace AppBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Event\PostResponseEvent;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use AppBundle\Service\Logger;

class KernelListener {

protected $logger;

public function __construct(Logger $logger) {
    $this->logger = $logger;
}

public function onKernelRequest(GetResponseEvent $event) {

}

public function onKernelResponse(FilterResponseEvent $event) {
}

 public function onKernelController(FilterControllerEvent $event) {
    $r = $event->getRequest();
    $this->logger->persist($r);
}

public function onKernelTerminate(PostResponseEvent $event) {
}
}

If I remove the flush() no error is thrown, but no Log in the DB logically.

Body:
Maksym was right. Thanks! In fact I used some months ago, this technique for a Service logging errors, but memory is weak specially when you are running many tasks :-(

So my working Logger is :

    public function persist($r) {
    if (!$this->em->isOpen()) {
        $this->em = $this->em->create(
                $this->em->getConnection(), $this->em->getConfiguration()
        );
    }

    $path = $r->get('_route');
    if (!$path || in_array($path, $this->paths)) {
        return null;
    }

    $log = new Log();
    $log->setAjax($r->isXmlHttpRequest());
    $log->setIp($r->getClientIp());
    $log->setMethod($r->getMethod());
    $log->setPath($path);
    $log->setUrl($r->getUri());

    if ($this->token_storage->getToken()) {
        $user = $this->token_storage->getToken()->getUser();
        if ($user instanceof \AppBundle\Entity\User) {
            $user2 = $this->em->getReference('AppBundle:User', $user->getId());
            $log->setUser($user2);
        }
    }

    $this->em->persist($log);
    $this->em->flush();
}


问:
Compile time safety of derived classes virtual functions?
I have this code, the question is below the code:

```<code>public class MainProgram
{
    public static void Main()
    {
        List<Animal> Animals = new List<Animal>();
        Animals.Add(new Dog());
        Animals.Add(new Poodle());
        Animals.Add(new Poodle());
        Animals.Add(new Beagle());
        Animals.Add(new Cat());

        Bark[] JustTheBarks = Dog.GetBarkList(Animals);
        foreach (Bark B in JustTheBarks)
        {
            Console.WriteLine(B.ToString());
        }
    }
}

abstract class Animal
{
    public abstract Noise GetNoise();
}

class Dog : Animal
{
    public override Noise GetNoise()
    {
        return new Bark("bark");
    }

    public static Bark[] GetBarkList(List<Animal> List)
    {
        return List
            .OfType<Dog>()
            .Select(r => r.GetNoise())
            .Cast<Bark>()
            .ToArray();
    }
}

class Beagle : Dog
{
    public override Noise GetNoise()
    {
        return new Woof("woof", 7);
    }
}

class Poodle : Dog
{
    public override Noise GetNoise()
    {
        return new Purr();
    }
}

class Cat : Animal
{
    public override Noise GetNoise()
    {
        throw new NotImplementedException();
    }
}

class Noise
{
}

class Bark : Noise
{
    protected string Text;
    public Bark(string Text)
    {
        this.Text = Text;
    }

    public override string ToString()
    {
        return $"{Text}";
    }
}

class Woof : Bark
{
    protected int Pitch;

    public Woof(string Text, int Pitch) : base(Text)
    {
        this.Pitch = Pitch;
    }
    public override string ToString()
    {
        return $"{Text}->{Pitch}";
    }
}

class Purr : Noise { }
</code>```

}

In plain text, Animals and Noises, each animal returns its own type of noise, the noises correspond to the animal class, although sometimes an animal might return different Noises based on some variable (but for a dog only some form of Bark).

This code crashes of course. The Poodle returns a Purr(), and it "should" return something of type Bark.  I have the abstract function GetNoise() which just returns a Noise. What I want/need is to write

```<code>class Dog
{
    public override Bark GetNoise();
}
</code>```

But this is not allowed, the return type must be the same. I don't want to write a second layer of GetBark() functions in every Dog class, etc.

What I want is to re-write this such that there is no casting, and everything that is derived from Dog is forced to return a Bark in its GetNoise() function such that I can safely write:

```<code>Bark B = Dog.GetNoise();
</code>```

答:
The answer of Scott Chamberlain is entirely reasonable; I would add two things to it.

First, the feature you want is called "virtual method covariance". It is supported by C++, but not by C#. It has been a fairly frequently requested feature since the early days of C#, but has never been implemented because, well, frankly, it's not a great feature:

Though type-safe in simple scenarios, it introduces new kinds of brittle base class failure in more complex, versioned scenarios

The CLR does not support it natively, so the compiler would have to generate helper methods, which are not particularly efficient

You can emulate the feature by implementing the helper methods yourself

If you want it, go advocate for it on the Roslyn github forum. You won't be the only one.

Second, you might consider in addition to Scott's solution to implement

```<code>public new virtual Bark GetNoise() => GetBark();
</code>```

As you note, you may not fill an existing virtual method slot with any method that does not exactly match the signature and return type. But you certainly may introduce a new virtual slot with a different return type.

Body:
I have this code, the question is below the code:

public class MainProgram
{
    public static void Main()
    {
        List<Animal> Animals = new List<Animal>();
        Animals.Add(new Dog());
        Animals.Add(new Poodle());
        Animals.Add(new Poodle());
        Animals.Add(new Beagle());
        Animals.Add(new Cat());

        Bark[] JustTheBarks = Dog.GetBarkList(Animals);
        foreach (Bark B in JustTheBarks)
        {
            Console.WriteLine(B.ToString());
        }
    }
}

abstract class Animal
{
    public abstract Noise GetNoise();
}

class Dog : Animal
{
    public override Noise GetNoise()
    {
        return new Bark("bark");
    }

    public static Bark[] GetBarkList(List<Animal> List)
    {
        return List
            .OfType<Dog>()
            .Select(r => r.GetNoise())
            .Cast<Bark>()
            .ToArray();
    }
}

class Beagle : Dog
{
    public override Noise GetNoise()
    {
        return new Woof("woof", 7);
    }
}

class Poodle : Dog
{
    public override Noise GetNoise()
    {
        return new Purr();
    }
}

class Cat : Animal
{
    public override Noise GetNoise()
    {
        throw new NotImplementedException();
    }
}

class Noise
{
}

class Bark : Noise
{
    protected string Text;
    public Bark(string Text)
    {
        this.Text = Text;
    }

    public override string ToString()
    {
        return $"{Text}";
    }
}

class Woof : Bark
{
    protected int Pitch;

    public Woof(string Text, int Pitch) : base(Text)
    {
        this.Pitch = Pitch;
    }
    public override string ToString()
    {
        return $"{Text}->{Pitch}";
    }
}

class Purr : Noise { }

}

In plain text, Animals and Noises, each animal returns its own type of noise, the noises correspond to the animal class, although sometimes an animal might return different Noises based on some variable (but for a dog only some form of Bark).

This code crashes of course. The Poodle returns a Purr(), and it "should" return something of type Bark.  I have the abstract function GetNoise() which just returns a Noise. What I want/need is to write

class Dog
{
    public override Bark GetNoise();
}

But this is not allowed, the return type must be the same. I don't want to write a second layer of GetBark() functions in every Dog class, etc.

What I want is to re-write this such that there is no casting, and everything that is derived from Dog is forced to return a Bark in its GetNoise() function such that I can safely write:

Bark B = Dog.GetNoise();

Body:
The answer of Scott Chamberlain is entirely reasonable; I would add two things to it.

First, the feature you want is called "virtual method covariance". It is supported by C++, but not by C#. It has been a fairly frequently requested feature since the early days of C#, but has never been implemented because, well, frankly, it's not a great feature:

Though type-safe in simple scenarios, it introduces new kinds of brittle base class failure in more complex, versioned scenarios

The CLR does not support it natively, so the compiler would have to generate helper methods, which are not particularly efficient

You can emulate the feature by implementing the helper methods yourself

If you want it, go advocate for it on the Roslyn github forum. You won't be the only one.

Second, you might consider in addition to Scott's solution to implement

public new virtual Bark GetNoise() => GetBark();

As you note, you may not fill an existing virtual method slot with any method that does not exactly match the signature and return type. But you certainly may introduce a new virtual slot with a different return type.


问:
Setup SSL with vapor
I have a config like this

```<code>{
    "default": {
        "port": "443",
        "host": "example.com",
        "securityLayer": "tls",
        "tls": {
            "certificates": "files",
            "certificateFile": "/etc/letsencrypt/live/example.com/fullchain.pem",
            "privateKeyFile": "/etc/letsencrypt/live/example.com/privkey.pem"
        }
    }
}
</code>```

On drop startup it prints out this console message:

```<code>No TLS signature supplied, defaulting to selfSigned.
</code>```

Judging by the code that produces that error message it expects signature field in the config that would be either selfSigned, signedFile or signedDirectory

I have this files from let's encrypt:

cert.pem

chain.pem

fullchain.pem

privkey.pem

What do I do to resolve that error message?

答:
This should fix problem

```<code>{
    "default": {
        "port": "443",
        "host": "example.com",
        "securityLayer": "tls",
        "tls": {
            "signature": "signedFile",
            "certificates": "files",
            "certificateFile": "/etc/letsencrypt/live/example.com/fullchain.pem",
            "privateKeyFile": "/etc/letsencrypt/live/example.com/privkey.pem"
        }
    }
}
</code>```

Vapor don't recommend to use SSL cert directly in Vapor.

You should consider use ngix or apache as SSL-proxy: https://docs.vapor.codes/2.0/deploy/nginx/

Title: Setup SSL with vapor

Body:
I have a config like this

{
    "default": {
        "port": "443",
        "host": "example.com",
        "securityLayer": "tls",
        "tls": {
            "certificates": "files",
            "certificateFile": "/etc/letsencrypt/live/example.com/fullchain.pem",
            "privateKeyFile": "/etc/letsencrypt/live/example.com/privkey.pem"
        }
    }
}

On drop startup it prints out this console message:

No TLS signature supplied, defaulting to selfSigned.

Judging by the code that produces that error message it expects signature field in the config that would be either selfSigned, signedFile or signedDirectory

I have this files from let's encrypt:

cert.pem

chain.pem

fullchain.pem

privkey.pem

What do I do to resolve that error message?

Body:
This should fix problem

{
    "default": {
        "port": "443",
        "host": "example.com",
        "securityLayer": "tls",
        "tls": {
            "signature": "signedFile",
            "certificates": "files",
            "certificateFile": "/etc/letsencrypt/live/example.com/fullchain.pem",
            "privateKeyFile": "/etc/letsencrypt/live/example.com/privkey.pem"
        }
    }
}

Vapor don't recommend to use SSL cert directly in Vapor.

You should consider use ngix or apache as SSL-proxy: https://docs.vapor.codes/2.0/deploy/nginx/


问:
Changing font of UIImagePickerController labels
My goal is to control the font of all the text in UIImagePickerController.

I had previously used an UILabel extension and the appearance proxy to control font for all UILabels.

```<code>extension UILabel {

    var defaultFontName : String {
        get { return self.font.fontName }
        set { self.font = UIFont(name: newValue, size: self.font.pointSize) }
}
</code>```

I set the default font in the AppDelegate.

```<code>UILabel.appearance().defaultFontName = kDefaultFontName
</code>```

Previously, this extended to the UIImagePickerController that I created programmatically in my project with all the cell and image labels adopting the default font. After updating Xcode 9 and Swift 4 this is not working.

I've tried adjusting the appearance proxy specifically for UILabels contained within the UIImagePickerControllerClass and giving the default font a specific point size with no success.

Why does this no longer work?

How do I access the font in the UIImagePickerController?

答: You should not use such tricks to change system behavior. Because even if you make this hacky tricks work, it could certainly be broken in iOS 12. So now, it does not work, because of .appearence. System controllers, like image picker are created separately and does not use appearence to create them self’s. Since ios11. But in ios10 there were something like warning about that in docs</p>

Body:
My goal is to control the font of all the text in UIImagePickerController.

I had previously used an UILabel extension and the appearance proxy to control font for all UILabels.

extension UILabel {

    var defaultFontName : String {
        get { return self.font.fontName }
        set { self.font = UIFont(name: newValue, size: self.font.pointSize) }
}

I set the default font in the AppDelegate.

UILabel.appearance().defaultFontName = kDefaultFontName

Previously, this extended to the UIImagePickerController that I created programmatically in my project with all the cell and image labels adopting the default font. After updating Xcode 9 and Swift 4 this is not working.

I've tried adjusting the appearance proxy specifically for UILabels contained within the UIImagePickerControllerClass and giving the default font a specific point size with no success.

Why does this no longer work?

How do I access the font in the UIImagePickerController?


问:
JSON default Ruby library
I have a bit of JSON code I'm using to make a Ruby app work. It checks out on most linters and validators (I haven't tried one where it doesn't work.)

The thing is, though, the Ruby library for it doesn't work. I continue trying it, with different ways and tries, but it just won't load right. It gives me an unexpected token error. I'm just very confused, because it works on the other validators I've tried. Is the gem broken, or am I doing something wrong?

Edit: The code being used is the JSON.parse method, after a to_json method from a file.read method. The content is being read straight from a file.

Content:

```<code>{
"black":{ "id":10, "title":"Black Room",
"desc":"You're in a large, black room filled with cobwebs.",
"around":[20, 30], "items":[], "npcs":[] },

"grey":{ "id":20, "title":"Grey Room",
"desc":"You're in a fine, grey room filled with nothing all.",
"around":[10, 20], "items":[], "npcs":[] },

"white":{ "id":30, "title":"White Room",
"desc":"You're in a small, white room filled with sunlight.",
"around":[10, 30], "items":[], "npcs":[] },

"null":{ "id":0, "title":"Null Room",
"desc":"You shouldn't be in here... please leave.",
"around":[10, 20, 30], "items":[], "npcs":[] }
}
</code>```

答: I figured out the problem. Turns out, there were no code issues, but the problem lied within the file encoding itself. I had it encoded in UTF-8, like most of my other files, and the default on my text editor. I converted the file to ASCII and it worked fine. Thanks for the help, though.</p>

Title: JSON default Ruby library

Body:
I have a bit of JSON code I'm using to make a Ruby app work. It checks out on most linters and validators (I haven't tried one where it doesn't work.)

The thing is, though, the Ruby library for it doesn't work. I continue trying it, with different ways and tries, but it just won't load right. It gives me an unexpected token error. I'm just very confused, because it works on the other validators I've tried. Is the gem broken, or am I doing something wrong?

Edit: The code being used is the JSON.parse method, after a to_json method from a file.read method. The content is being read straight from a file.

Content:

{
"black":{ "id":10, "title":"Black Room",
"desc":"You're in a large, black room filled with cobwebs.",
"around":[20, 30], "items":[], "npcs":[] },

"grey":{ "id":20, "title":"Grey Room",
"desc":"You're in a fine, grey room filled with nothing all.",
"around":[10, 20], "items":[], "npcs":[] },

"white":{ "id":30, "title":"White Room",
"desc":"You're in a small, white room filled with sunlight.",
"around":[10, 30], "items":[], "npcs":[] },

"null":{ "id":0, "title":"Null Room",
"desc":"You shouldn't be in here... please leave.",
"around":[10, 20, 30], "items":[], "npcs":[] }
}


问:
Evaluation of Regression Neural Network
Hej,

I am trying to write a small program to solve a Regression problem. My dataset is hereby 4 random x (x1,x2,x3 and x4) and 1 y value. One of the rows looks like this:

```<code>0.634585    0.552366    0.873447    0.196890    8.75
</code>```

I know want to predict the y-value as close as possible so after the training I would like to evaluate how good my model is by showing the loss. Unfortunately I always receive

```<code>Training cost= nan
</code>```

The most important lines of could would be:

```<code>X_data = tf.placeholder(shape=[None, 4], dtype=tf.float32)
y_target = tf.placeholder(shape=[None, 1], dtype=tf.float32)

# Input neurons : 4
# Hidden neurons : 2 x 8
# Output neurons : 3
hidden_layer_nodes = 8

w1 = tf.Variable(tf.random_normal(shape=[4,hidden_layer_nodes])) # Inputs -> Hidden Layer1
b1 = tf.Variable(tf.random_normal(shape=[hidden_layer_nodes]))   # First Bias
w2 = tf.Variable(tf.random_normal(shape=[hidden_layer_nodes,1])) # Hidden layer2 -> Outputs
b2 = tf.Variable(tf.random_normal(shape=[1]))   # Third Bias

hidden_output = tf.nn.relu(tf.add(tf.matmul(X_data, w1), b1))
final_output = tf.nn.relu(tf.add(tf.matmul(hidden_output, w2), b2))

loss = tf.reduce_mean(-tf.reduce_sum(y_target * tf.log(final_output), axis=0))

optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
train = optimizer.minimize(loss)

init = tf.global_variables_initializer()

steps = 10000

with tf.Session() as sess:

    sess.run(init)

    for i in range(steps):

        sess.run(train,feed_dict={X_data:X_train,y_target:y_train})

        # PRINT OUT A MESSAGE EVERY 100 STEPS
        if i%500 == 0:

            print('Currently on step {}'.format(i))

    training_cost = sess.run(loss, feed_dict={X_data:X_test,y_target:y_test})
    print("Training cost=", training_cost)
</code>```

Maybe someone knows where my mistake is or even better, how to constantly show the error during my training :) I know how this is done with the tf.estimator, but not without. If you need the dataset, let me know.

Cheers!

答:
This is because the Relu activation function causes the exploding gradient. Therefore, you need to reduce the learning rate accordingly. Moreover, you can try a different activation function also (for this you may have to normalize your dataset first)

Here, (In simple multi-layer FFNN only ReLU activation function doesn't converge) is a similar problem as your case. Follow the answer and you will understand.

Hope this helps.

Title: Evaluation of Regression Neural Network

Body:
Hej,

I am trying to write a small program to solve a Regression problem. My dataset is hereby 4 random x (x1,x2,x3 and x4) and 1 y value. One of the rows looks like this:

0.634585    0.552366    0.873447    0.196890    8.75

I know want to predict the y-value as close as possible so after the training I would like to evaluate how good my model is by showing the loss. Unfortunately I always receive

Training cost= nan

The most important lines of could would be:

X_data = tf.placeholder(shape=[None, 4], dtype=tf.float32)
y_target = tf.placeholder(shape=[None, 1], dtype=tf.float32)

# Input neurons : 4
# Hidden neurons : 2 x 8
# Output neurons : 3
hidden_layer_nodes = 8

w1 = tf.Variable(tf.random_normal(shape=[4,hidden_layer_nodes])) # Inputs -> Hidden Layer1
b1 = tf.Variable(tf.random_normal(shape=[hidden_layer_nodes]))   # First Bias
w2 = tf.Variable(tf.random_normal(shape=[hidden_layer_nodes,1])) # Hidden layer2 -> Outputs
b2 = tf.Variable(tf.random_normal(shape=[1]))   # Third Bias

hidden_output = tf.nn.relu(tf.add(tf.matmul(X_data, w1), b1))
final_output = tf.nn.relu(tf.add(tf.matmul(hidden_output, w2), b2))

loss = tf.reduce_mean(-tf.reduce_sum(y_target * tf.log(final_output), axis=0))

optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001)
train = optimizer.minimize(loss)

init = tf.global_variables_initializer()

steps = 10000

with tf.Session() as sess:

    sess.run(init)

    for i in range(steps):

        sess.run(train,feed_dict={X_data:X_train,y_target:y_train})

        # PRINT OUT A MESSAGE EVERY 100 STEPS
        if i%500 == 0:

            print('Currently on step {}'.format(i))

    training_cost = sess.run(loss, feed_dict={X_data:X_test,y_target:y_test})
    print("Training cost=", training_cost)

Maybe someone knows where my mistake is or even better, how to constantly show the error during my training :) I know how this is done with the tf.estimator, but not without. If you need the dataset, let me know.

Cheers!


问:
Saving relation JPA with Spring boot
I'm doing a registration and I have the fields

Nome:

Data de Nascimento:

Inscrição Estadual:

Nome Responsável:

CPF Responsável:

Cep:

Bloco:

Número:

when i saving, I can not write data from the PessoasEnderecos class, the other data is recording normal. I'm getting all the data on the screen so much that I debugged the browser to see ..

It shows no error. Does anyone know what I'm missing ??

my class Pacientes

```<code>@Entity
@Table(name = "pacientes", schema = "sau")
public class Pacientes implements Serializable  {

    private static final long serialVersionUID = 5776384003601026304L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "idPaciente")
    private Long idPaciente;

    @JoinColumn(name="idPessoa")
    @ManyToOne(cascade = CascadeType.ALL)
    private Pessoas pessoa;

    @Column(name = "nomeResponsavel")
    private String nomeResponsavel;

    @Column(name = "cpfResponsavel")
    private String cpfResponsavel;

    public Pacientes() {
    }
    //gets and sets
    }
</code>```

my class Pessoas

```<code>@Entity
@Table(name = "pessoas", schema="glb")
public class Pessoas implements Serializable {

    private static final long serialVersionUID = -4042023941980758267L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    private Long idPessoa;

    @Temporal(TemporalType.DATE)
    private Date dataNascimento;

    private String inscricaoEstadual;

    private String inscricaoMunicipal;

    private String nome;

    public Pessoas() {
    }
  //gets and sets

}

@Entity
@Table(name = "pessoas_enderecos" ,schema="glb")
public class PessoasEnderecos implements Serializable  {

    private static final long serialVersionUID = -2560542418318988673L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long idPessoaEndereco;

    private String bloco;

    private String cep;

    private String numero;

    @JoinColumn(name="idPessoa")
    @ManyToOne(optional = false, cascade = CascadeType.ALL)
    private Pessoas pessoa;

    public PessoasEnderecos() {
    }

//gets and sets

}
</code>```

my methods

class Controller

```<code>@RequestMapping(method = RequestMethod.POST, value = "/pacientes")
    public Pacientes cadastrarPacientes(@RequestBody Pacientes pac) {
        return pacientesService.cadastrar(pac);
    }
</code>```

class service

```<code>public Pacientes cadastrar(Pacientes pacientes){
        return pacRepository.save(pacientes);
    }
</code>```

class repository

```<code>public interface PacientesRepository extends JpaRepository<Pacientes, Integer> {

}
</code>```

答:
You should also add the linkage @OneToMany in Pacientes:

```<code>public class Pacientes implements Serializable {
...
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "pessoa")
    @PrimaryKeyJoinColumn
    private List<PessoasEnderecos> pessoasEnderecos = new ArrayList<>();
</code>```

Update:

```<code>and your JSON should be something like this:

{
  "nomeResponsavel": "abc",
  "pessoasEnderecos": [
    {
      "bloco": "sdds",
      "cep": "sdasdsad",
      "numero": "sdasdsa"
    }
  ]
}
</code>```

Title: Saving relation JPA with Spring boot

Body:
I'm doing a registration and I have the fields

Nome:

Data de Nascimento:

Inscrição Estadual:

Nome Responsável:

CPF Responsável:

Cep:

Bloco:

Número:

when i saving, I can not write data from the PessoasEnderecos class, the other data is recording normal. I'm getting all the data on the screen so much that I debugged the browser to see ..

It shows no error. Does anyone know what I'm missing ??

my class Pacientes

@Entity
@Table(name = "pacientes", schema = "sau")
public class Pacientes implements Serializable  {

    private static final long serialVersionUID = 5776384003601026304L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "idPaciente")
    private Long idPaciente;

    @JoinColumn(name="idPessoa")
    @ManyToOne(cascade = CascadeType.ALL)
    private Pessoas pessoa;

    @Column(name = "nomeResponsavel")
    private String nomeResponsavel;

    @Column(name = "cpfResponsavel")
    private String cpfResponsavel;

    public Pacientes() {
    }
    //gets and sets
    }

my class Pessoas

@Entity
@Table(name = "pessoas", schema="glb")
public class Pessoas implements Serializable {

    private static final long serialVersionUID = -4042023941980758267L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    private Long idPessoa;

    @Temporal(TemporalType.DATE)
    private Date dataNascimento;

    private String inscricaoEstadual;

    private String inscricaoMunicipal;

    private String nome;

    public Pessoas() {
    }
  //gets and sets

}

@Entity
@Table(name = "pessoas_enderecos" ,schema="glb")
public class PessoasEnderecos implements Serializable  {

    private static final long serialVersionUID = -2560542418318988673L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long idPessoaEndereco;

    private String bloco;

    private String cep;

    private String numero;

    @JoinColumn(name="idPessoa")
    @ManyToOne(optional = false, cascade = CascadeType.ALL)
    private Pessoas pessoa;

    public PessoasEnderecos() {
    }

//gets and sets

}

my methods

class Controller

@RequestMapping(method = RequestMethod.POST, value = "/pacientes")
    public Pacientes cadastrarPacientes(@RequestBody Pacientes pac) {
        return pacientesService.cadastrar(pac);
    }

class service

public Pacientes cadastrar(Pacientes pacientes){
        return pacRepository.save(pacientes);
    }

class repository

public interface PacientesRepository extends JpaRepository<Pacientes, Integer> {

}

Body:
You should also add the linkage @OneToMany in Pacientes:

public class Pacientes implements Serializable {
...
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "pessoa")
    @PrimaryKeyJoinColumn
    private List<PessoasEnderecos> pessoasEnderecos = new ArrayList<>();

Update:

and your JSON should be something like this:

{
  "nomeResponsavel": "abc",
  "pessoasEnderecos": [
    {
      "bloco": "sdds",
      "cep": "sdasdsad",
      "numero": "sdasdsa"
    }
  ]
}


问:
Command Line File Diff & Merge via Anaconda's Spyder
Does the Spyder IDE provide for file diff & merge configuration via the command line?  I haven't seen anything relevant in their documentation nor have I found a plugin that might provide this functionality.  No relevant options seem to be available by default:

```<code>~$ which spyder
//anaconda/envs/test_env/bin/spyder

~$ spyder --help
Usage: spyder [options] files

Options:
  -h, --help            show this help message and exit
  --new-instance        Run a new instance of Spyder, even if the single
                        instance mode has been turned on (default)
  --defaults            Reset configuration settings to defaults
  --reset               Remove all configuration files!
  --optimize            Optimize Spyder bytecode (this may require
                        administrative privileges)
  -w WORKING_DIRECTORY, --workdir=WORKING_DIRECTORY
                        Default working directory
  --show-console        Do not hide parent console window (Windows)
  --multithread         Internal console is executed in another thread
                        (separate from main application thread)
  --profile             Profile mode (internal test, not related with Python
                        profiling)
  --window-title=WINDOW_TITLE
                        String to show in the main window title
  -p OPEN_PROJECT, --project=OPEN_PROJECT
                        Path that contains an Spyder project
</code>```

Thanks for your feedback.

答:
(Spyder maintainer here)

Does the Spyder IDE provide for file diff & merge configuration via the command line?

No, it doesn't. There are other IDEs that provide it, e.g. VSCode and Atom, but in its graphical interface not through its command line options.

Body:
Does the Spyder IDE provide for file diff & merge configuration via the command line?  I haven't seen anything relevant in their documentation nor have I found a plugin that might provide this functionality.  No relevant options seem to be available by default:

~$ which spyder
//anaconda/envs/test_env/bin/spyder

~$ spyder --help
Usage: spyder [options] files

Options:
  -h, --help            show this help message and exit
  --new-instance        Run a new instance of Spyder, even if the single
                        instance mode has been turned on (default)
  --defaults            Reset configuration settings to defaults
  --reset               Remove all configuration files!
  --optimize            Optimize Spyder bytecode (this may require
                        administrative privileges)
  -w WORKING_DIRECTORY, --workdir=WORKING_DIRECTORY
                        Default working directory
  --show-console        Do not hide parent console window (Windows)
  --multithread         Internal console is executed in another thread
                        (separate from main application thread)
  --profile             Profile mode (internal test, not related with Python
                        profiling)
  --window-title=WINDOW_TITLE
                        String to show in the main window title
  -p OPEN_PROJECT, --project=OPEN_PROJECT
                        Path that contains an Spyder project

Thanks for your feedback.


问:
Dreamweaver replace with regular expression
I'm having a problem with a simple Find and Replace in Dreamweaver using a regex.

This is what's in my find box:

```<code><div id="title">([^ö]*)</div>
</code>```

This is what's in my replace box

```<code><div id="title">
    <div class="center">
       $1
       <span>hello there</span>
    </div>
</div>
</code>```

If I run the find and replace above on this:

```<code><div id="title"><h1>Page title</h1></div>
<div class="content">
   more content
</div>
</code>```

I can't get to this result:

```<code><div id="title">
    <div class="center">
        <h1>Page title</h1>
        <span>hello there</span>
    </div>
</div>
<div class="content">
   more content
</div>
</code>```

Because the content of de find box does not define that I only want the content between
 and the first
...

Any ideas?

答:
Matching markup languages with regexes is tricky to say the least.

In your case (assuming that the
 tags you're searching and replacing won't contain any nested
 tags), you could get by with using

```<code><div id="title">([\s\S]*?)</div>
</code>```

as your search regex.

[\s\S] matches any character,
including linebreaks (that's more
explicit than [^ö], I'd say).

*
matches zero or more of those

?
makes the star "lazy", meaning that
it will match as few characters as
possible - thereby ensuring that the
match will stop at the next
.

ContentLicense: CC BY-SA 2.5

Body:
I'm having a problem with a simple Find and Replace in Dreamweaver using a regex.

This is what's in my find box:

([^ö]*)

This is what's in my replace box

       $1
       hello there

If I run the find and replace above on this:

Page title

   more content

I can't get to this result:

Page title

        hello there

   more content

Because the content of de find box does not define that I only want the content between
 and the first
...

Any ideas?

Body:
Matching markup languages with regexes is tricky to say the least.

In your case (assuming that the <div> tags you're searching and replacing won't contain any nested <div> tags), you could get by with using

<div id="title">([\s\S]*?)</div>

as your search regex.

[\s\S] matches any character,
including linebreaks (that's more
explicit than [^ö], I'd say).

*
matches zero or more of those

?
makes the star "lazy", meaning that
it will match as few characters as
possible - thereby ensuring that the
match will stop at the next </div>.


问:
vapor can not load html and leaf
I use vapor load a html or leaf,it gives me error message '500'.The server log show me

```<code>[Data File Error: unable to load file at path /Users/apple/Desktop/QSSwiftServer/Resources/Views/welcome.leaf]
 [Identifier: Core.DataFileError.load]

[Possible Causes: file doesn't exist, missing read permissions at specified path, data read is corrupted, system issue]

[Suggested Fixes: ensure that file permissions are correct for specified paths]

[Documentation Links: https://developer.apple.com/reference/foundation/filemanager]
</code>```

Here is my code:

```<code>get { req in
        return try self.view.make("welcome.leaf", ["message": "Hello world!"])
    }
</code>```

How can I solve this problem？

答:
You should put your file into {Project Dir}/Resources/Views/

In your case welcome.leaf should be in /Users/apple/Desktop/QSSwiftServer/Resources/Views/

Title: vapor can not load html and leaf

Body:
I use vapor load a html or leaf,it gives me error message '500'.The server log show me

[Data File Error: unable to load file at path /Users/apple/Desktop/QSSwiftServer/Resources/Views/welcome.leaf]
 [Identifier: Core.DataFileError.load]

[Possible Causes: file doesn't exist, missing read permissions at specified path, data read is corrupted, system issue]

[Suggested Fixes: ensure that file permissions are correct for specified paths]

[Documentation Links: https://developer.apple.com/reference/foundation/filemanager]

Here is my code:

get { req in
        return try self.view.make("welcome.leaf", ["message": "Hello world!"])
    }

How can I solve this problem？


问:
Elasticsearch - how to bulk insert index + add index to alias?
I have a script that creates indices which are generated periodically using the _bulk API. For example, it would create the following:

```<code>/foo_2017-06-01/bar/abcd
/foo_2017-05-31/bar/efgh
....
</code>```

But I want an alias to, basically, index all of these indices - and newer ones. For example I want:

```<code>/foo --> [/foo_2017-06-01, /foo_2017-05-31, ...]
</code>```

Is this possible? Or what can I do to achieve the same thing?

答:
You can use Templates to do this:
https://www.elastic.co/guide/en/elasticsearch/reference/5.4/indices-templates.html

Templates allow you to apply settings to newly created indexes automatically. For example, the following template will apply to all indexes with the 'foo_' prefix and add it to the foo alias.

```<code>PUT _template/template_1
{
    "template" : "foo_*",
    "settings" : {
        "number_of_shards" : 1
    },
    "aliases" : {,
        "foo" : {}
    }
}
</code>```

Body:
I have a script that creates indices which are generated periodically using the _bulk API. For example, it would create the following:

/foo_2017-06-01/bar/abcd
/foo_2017-05-31/bar/efgh
....

But I want an alias to, basically, index all of these indices - and newer ones. For example I want:

/foo --> [/foo_2017-06-01, /foo_2017-05-31, ...]

Is this possible? Or what can I do to achieve the same thing?

Body:
You can use Templates to do this:
https://www.elastic.co/guide/en/elasticsearch/reference/5.4/indices-templates.html

Templates allow you to apply settings to newly created indexes automatically. For example, the following template will apply to all indexes with the 'foo_' prefix and add it to the foo alias.

PUT _template/template_1
{
    "template" : "foo_*",
    "settings" : {
        "number_of_shards" : 1
    },
    "aliases" : {,
        "foo" : {}
    }
}


问:
webRequest API: How to get the requestId of a new request?
The chrome.webRequest API has the concept of a request ID (source: Chrome webRequest documention):

Request IDs

Each request is identified by a request ID. This ID is unique within a browser session and the context of an extension. It remains constant during the the life cycle of a request and can be used to match events for the same request. Note that several HTTP requests are mapped to one web request in case of HTTP redirection or HTTP authentication.

You can use it to correlate the requests even across redirects. But how do you initially get hold off the id when start a new request with fetch or XMLHttpRequest?

So far, I have not found anything better than to use the URL of the request as a way to make the initial link between the new request and the requestId. However, if there are overlapping requests to the same resource, this is not reliable.

Questions:

If you make a new request (either with fetch or XMLHttpRequest), how do you reliably get access to the requestId?

Does the fetch API or XMLHttpRequest API allow access to the requestId?

What I want to do is to use the functionality provided by the webRequest API to modify a single request, but I want to make sure that I do not accidentally modify other pending requests.

答:
To the best of my knowledge, there is no direct support in the fetch or XHMLHttpRequest API. Also I'm not aware of completely reliable way to get hold of the requestId.

What I ended up doing was installing a onBeforeRequest listener, storing the requestId, and then immediately removing the listener again. For instance, it could look like this:

```<code>function makeSomeRequest(url) {

  let listener;
  const removeListener = () => {
    if (listener) {
      chrome.webRequest.onBeforeRequest.removeListener(listener);
      listener = null;
    }
  };

  let requestId;
  listener = (details) => {
    if (!requestId && urlMatches(details.url, url)) {
      requestId = details.requestId;
      removeListener();
    }
  };
  chrome.webRequest.onBeforeRequest.addListener(listener, { urls: ['<all_urls>'] });

  // install other listeners, which can then use the stored "requestId"
  // ...

  // finally, start the actual request, for instance
  const promise = fetch(url).then(doSomething);

  // and make sure to always clean up the listener
  promise.then(removeListener, removeLister);
}
</code>```

It is not perfect, and matching the URL is a detail that I left open. You could simply compare whether the details.url is identical to url:

```<code>function urlMatches(url1, url2) {
  return url1 === url2;
}
</code>```

Note that it is not guaranteed that you see the identical URL, for instance, if make a request against http://some.domain.test, you will see http://some.domain.test/ in your listener (see my other question about the details). Or http:// could have been replaced by https:// (here I'm not sure, but it could be because of other extensions like HTTPS Everywhere).

That is why the code above should only be seen as a sketch of the idea. It seems to work good enough in practice, as long as you do not start multiple requests to the identical URL. Still, I would be interested in learning about a better way to approach the problem.

Body:
To the best of my knowledge, there is no direct support in the fetch or XHMLHttpRequest API. Also I'm not aware of completely reliable way to get hold of the requestId.

What I ended up doing was installing a onBeforeRequest listener, storing the requestId, and then immediately removing the listener again. For instance, it could look like this:

function makeSomeRequest(url) {

  let listener;
  const removeListener = () => {
    if (listener) {
      chrome.webRequest.onBeforeRequest.removeListener(listener);
      listener = null;
    }
  };

  let requestId;
  listener = (details) => {
    if (!requestId && urlMatches(details.url, url)) {
      requestId = details.requestId;
      removeListener();
    }
  };
  chrome.webRequest.onBeforeRequest.addListener(listener, { urls: ['<all_urls>'] });

  // install other listeners, which can then use the stored "requestId"
  // ...

  // finally, start the actual request, for instance
  const promise = fetch(url).then(doSomething);

  // and make sure to always clean up the listener
  promise.then(removeListener, removeLister);
}

It is not perfect, and matching the URL is a detail that I left open. You could simply compare whether the details.url is identical to url:

function urlMatches(url1, url2) {
  return url1 === url2;
}

Note that it is not guaranteed that you see the identical URL, for instance, if make a request against http://some.domain.test, you will see http://some.domain.test/ in your listener (see my other question about the details). Or http:// could have been replaced by https:// (here I'm not sure, but it could be because of other extensions like HTTPS Everywhere).

That is why the code above should only be seen as a sketch of the idea. It seems to work good enough in practice, as long as you do not start multiple requests to the identical URL. Still, I would be interested in learning about a better way to approach the problem.


问:
How to delete libraries in ModelSim/QuestaSim?
I’ve done many projects on this software and I want to delete a big ammount of libraries that are useless and now are giving me errors to simulate my new projects I think the best option is to delete old files(libraries).</p>

答:
You can either:

delete the matching directories on disk and edit the modelsim.ini file(s) by hand, or

use vdel.exe.

Usage of vdel:

```<code>PS> .\vdel.exe -h
Usage: vdel -help
       vdel [-lib <path>] [-modelsimini <ini_filepath>] [-verbose] { -all | <primary> [<secondary>] | -allsystemc |  [-dpiobj [<platform>|<compiler>| <platform_compiler> |all] ]  [-obj [<platform>|<compiler>|<platform_compiler>|all] ]}
</code>```

Body:
You can either:

delete the matching directories on disk and edit the modelsim.ini file(s) by hand, or

use vdel.exe.

Usage of vdel:

PS> .\vdel.exe -h
Usage: vdel -help
       vdel [-lib <path>] [-modelsimini <ini_filepath>] [-verbose] { -all | <primary> [<secondary>] | -allsystemc |  [-dpiobj [<platform>|<compiler>| <platform_compiler> |all] ]  [-obj [<platform>|<compiler>|<platform_compiler>|all] ]}


问:
Inputting as a Char Array
I am trying to get input as a character array and manipulate it. For example this is what I have. But I just started arrays and I am confused getting confused on how I should be storing the char array.

```<code>   void getMessage(char message[CHARACTERS])
   {
        int i = 0;
        cout << "Enter message: ";
        for (i = 0; i < CHARACTERS; i++)
        {
            cin >> message[i];
            if (message[i] == NULL)
                break;
        }
            cout << "The message you entered was:" << endl << message[i] << endl;
   }
</code>```

Characters is equal to the constant 100 since I do not know the size of the array, it is based off of user input. When I try to get the array to output it doesn't.

答:
You're making a confusion here:

```<code>if (message[i] == NULL)
</code>```

In C++, NULL is defined as a macro and expanded to zero, so what you're actually testing is

```<code>if (message[i] == 0)
</code>```

This is hardly possible if you're inputting from a terminal or a text file (You're surely not reading a binary file in this way!). Change it to either of below depending on your needs, then it should work.

```<code>// Input a line
if (message[i] == '\n') {
    message[i] = '\0'; // strip the newline
    break;
}
</code>```

```<code>// Input until something goes wrong
if (cin.fail()) {
    message[i] = '\0';
    break;
}
</code>```

```<code>// Or combine them:
if (message[i] == '\n' || cin.fail()) {
    message[i] = '\0';
    break;
}
</code>```

It's also a good manner to remember to terminate the string, in case you read all the buffer and cout would output everything before a zero character, being a potential access violation:

```<code>for (...) {...}
message[CHARACTERS - 1] = '\0'.
</code>```

Moreover, your output statement is also wrong:

```<code>cout << "The message you entered was:" << endl << message[i] << endl;
</code>```

You're only outputting one character by message[i]. If you want to output the entire message, strip the array indexing operator:

```<code>... << message << ....
</code>```

so that you're using the ostream& operator <<(const char*) overload to output a string.

Title: Inputting as a Char Array

Body:
I am trying to get input as a character array and manipulate it. For example this is what I have. But I just started arrays and I am confused getting confused on how I should be storing the char array.

   void getMessage(char message[CHARACTERS])
   {
        int i = 0;
        cout << "Enter message: ";
        for (i = 0; i < CHARACTERS; i++)
        {
            cin >> message[i];
            if (message[i] == NULL)
                break;
        }
            cout << "The message you entered was:" << endl << message[i] << endl;
   }

Characters is equal to the constant 100 since I do not know the size of the array, it is based off of user input. When I try to get the array to output it doesn't.

Body:
You're making a confusion here:

if (message[i] == NULL)

In C++, NULL is defined as a macro and expanded to zero, so what you're actually testing is

if (message[i] == 0)

This is hardly possible if you're inputting from a terminal or a text file (You're surely not reading a binary file in this way!). Change it to either of below depending on your needs, then it should work.

// Input a line
if (message[i] == '\n') {
    message[i] = '\0'; // strip the newline
    break;
}

// Input until something goes wrong
if (cin.fail()) {
    message[i] = '\0';
    break;
}

// Or combine them:
if (message[i] == '\n' || cin.fail()) {
    message[i] = '\0';
    break;
}

It's also a good manner to remember to terminate the string, in case you read all the buffer and cout would output everything before a zero character, being a potential access violation:

for (...) {...}
message[CHARACTERS - 1] = '\0'.

Moreover, your output statement is also wrong:

cout << "The message you entered was:" << endl << message[i] << endl;

You're only outputting one character by message[i]. If you want to output the entire message, strip the array indexing operator:

... << message << ....

so that you're using the ostream& operator <<(const char*) overload to output a string.


问:
Casting List of object and Get the Result
I'm Trying to cast a list to an object like:

```<code>public static List<Object> lstproductname = new List<Object>();

var partialResult = db.Company.OrderBy(x => x.id).Take(1);
            var finalResult = (from j in db.productListDbSet
                               join comp in partialResult
                               on j.mstr_company_id equals comp.id
                               select new { j.id, j.name }).OrderBy(x => x.name).ToList();

            lstproductname = finalResult.Cast<object>().ToList();
</code>```

Trying to use foreach as a result but no luck..

```<code>            foreach (var d in lstproductname.ToList())
            {
                string s =   d.ToString();
            }
</code>```

lstproductname has a content like { id = 1, name = "Product1" }

I need to get the id value and the name value but unfortunately can't get it..

I tried something from foreach like

```<code>foreach (var d in lstproductname.ToList())
            {
                string id =   d.id.ToString();
                string name = d.name.ToString();
            }
</code>```

This one is not working..

```<code> string id =   d.id.ToString();
 string name = d.name.ToString();
</code>```

Any idea how to get this is Highly Appreciated.

答:
This is the solution:

Create a new class

```<code>public class FinalProduct
{
    public int id { get; set; }
    public string name { get; set; }
}
</code>```

LINQ

```<code>        public static List<FinalProduct> lstproductname = new
        List<FinalProduct>();

        var partialResult = db.Company.OrderBy(x => x.id).Take(1);
        var finalResult = (from j in db.productListDbSet
                           join comp in partialResult
                           on j.mstr_company_id equals comp.id
                           select new FinalProduct {id= j.id,name= j.name }).OrderBy(x => x.name).ToList();

        lstproductname = finalResult.Cast<FinalProduct>().ToList();
        foreach (var d in lstproductname.ToList())
        {
            String id = d.id.ToString();
            String name = d.name.ToString();
        }
</code>```

Solution idea from @Stephen Muecke Thanks..

Body:
I'm Trying to cast a list to an object like:

public static List<Object> lstproductname = new List<Object>();

var partialResult = db.Company.OrderBy(x => x.id).Take(1);
            var finalResult = (from j in db.productListDbSet
                               join comp in partialResult
                               on j.mstr_company_id equals comp.id
                               select new { j.id, j.name }).OrderBy(x => x.name).ToList();

            lstproductname = finalResult.Cast<object>().ToList();

Trying to use foreach as a result but no luck..

            foreach (var d in lstproductname.ToList())
            {
                string s =   d.ToString();
            }

lstproductname has a content like { id = 1, name = "Product1" }

I need to get the id value and the name value but unfortunately can't get it..

I tried something from foreach like

foreach (var d in lstproductname.ToList())
            {
                string id =   d.id.ToString();
                string name = d.name.ToString();
            }

This one is not working..

 string id =   d.id.ToString();
 string name = d.name.ToString();

Any idea how to get this is Highly Appreciated.

Body:
This is the solution:

Create a new class

public class FinalProduct
{
    public int id { get; set; }
    public string name { get; set; }
}

LINQ

        public static List<FinalProduct> lstproductname = new
        List<FinalProduct>();

        var partialResult = db.Company.OrderBy(x => x.id).Take(1);
        var finalResult = (from j in db.productListDbSet
                           join comp in partialResult
                           on j.mstr_company_id equals comp.id
                           select new FinalProduct {id= j.id,name= j.name }).OrderBy(x => x.name).ToList();

        lstproductname = finalResult.Cast<FinalProduct>().ToList();
        foreach (var d in lstproductname.ToList())
        {
            String id = d.id.ToString();
            String name = d.name.ToString();
        }

Solution idea from @Stephen Muecke Thanks..


问:
How to define variable names dynamically in Perl 6?

I have a name which I'd like to give to a variable, in another string variable:
my $name = '$a'; or simply my $name = 'a'; How to make the variable and to use it? I mean something like this (but it doesn't work):

my $name = '$a';
my {$name} = 1; # Doesn't work
say $a; # should be 1
```

A more general case. I have a list of variable names, say my @names = '$aa' ... '$cc'; How to declare and use the variable, whose name will be e.g. @names[2]?

答:
Lexical scopes are immutable, but the way you would do it is ::($name) or MY::($name).

my $a; # required or it will generate an error

my $name = '$a';

::($name) = 1;
say $a;          # 1

MY::($name) = 2;
say $a;          # 2

sub foo ($name,$value) { CALLER::MY::($name) = $value }
foo($name,3);
say $a;          # 3
```

Body:
I have a name which I'd like to give to a variable, in another string variable:
my $name = '$a'; or simply my $name = 'a'; How to make the variable and to use it? I mean something like this (but it doesn't work):

my $name = '$a';
my {$name} = 1; # Doesn't work
say $a; # should be 1

A more general case. I have a list of variable names, say my @names = '$aa' ... '$cc'; How to declare and use the variable, whose name will be e.g. @names[2]?


问:
scroll at the left when first open excel-macro
I have a macro and it perfectly run. however, the result is always shown at the right (latest column).

I tried to add the macro:

```<code>select.range("A1")
</code>```

or

```<code>Application.Goto Reference:="R1C1"
</code>```

and it still is not working.

Is there anyone know how to make the scroll bar at the left (column A) when first open?

答:
I solved this issue.
I add this line "ActiveWindow.LargeScroll ToRight:=-1"

thank you

Body:
I have a macro and it perfectly run. however, the result is always shown at the right (latest column).

I tried to add the macro:

select.range("A1")

or

Application.Goto Reference:="R1C1"

and it still is not working.

Is there anyone know how to make the scroll bar at the left (column A) when first open?


问:
Getting specific row from a list fails
This is the API output:

```<code>{
    "resultLength":133710,
    "resultList" : [
            {
            "date" :  1510872659568,
            "requestParameters" : [
              "datesAsStringsFormat=dd-MMM-yyyy",
              "datesAsStrings=true",
              "outputFormat=xlsx",
              "requestId=14e7aa1f-680f-49d0-8e76-cfd797b9b6b6"
            ],
            "score" :  1,
            "totalRequestTime" :  1261,
            "userId" :  167895
            },
            {
            "date" :  1510872659679,
            "requestParameters" : [
              "datesAsStringsFormat=dd-MMM-yyyy",
              "datesAsStrings=true",
              "outputFormat=xlsx",
              "requestId=14e7aa1f-680f-49d0-8e76-cfd797b9be78"
            ],
            "score" :  1,
            "totalRequestTime" :  1255,
            "userId" :  452669
            }
    ]
}
</code>```

I am trying to extract the requestId for each userId, however for some reason I am not able to. This is what I tried:

```<code>req = requests.get(url=url, auth=(user,password))
out = req.json()
results = out['resultList']

solr_df = pd.DataFrame()
for record in results:
    requestId = pd.DataFrame(record['requestParameters'][3],columns=['requestId'])
    df = pd.DataFrame(requestId)
    df['userId'] = record['userId']
    solr_df = solr_df.append(df)
</code>```

However it throws a ValueError: DataFrame constructor not properly called!
Can you assist with rectifying the error?

If it too hard to only extract the requestId row for each requestParameter, perhaps you can assist instead removing all rows that aren't requestId related after the for statement runs?

Edit:

When I run it for record['requestParameters'], it runs succesfully but it extracts all rows of requestParameters per userId.

I just tried slicing as such: portfolioId = pd.DataFrame(record['requestParameters'][-1:0]) and it did return results (unlike a single index call), however it was for both outputFormat and requestId rows.
I then tried portfolioId = pd.DataFrame(record['requestParameters'][1:2]) and it returned results for both requestId and datesAsStrings.

It looks like requestParameters rows are not indexed consistently (not sure why it is possible), is there still a way to get a specific row from a list?

Thank you

答:
According to docs: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html</p>

```<code>req = requests.get(url=url, auth=(user,password))
out = req.json()
results = out['resultList']

df = pd.DataFrame()
for record in results:
    requestId = pd.DataFrame({"requestId": record['requestParameters'][3]})
    df = pd.DataFrame(requestId)
    df['userId'] = record['userId']
    df = df.append(df)
</code>```

Title: Getting specific row from a list fails

Body:
This is the API output:

{
    "resultLength":133710,
    "resultList" : [
            {
            "date" :  1510872659568,
            "requestParameters" : [
              "datesAsStringsFormat=dd-MMM-yyyy",
              "datesAsStrings=true",
              "outputFormat=xlsx",
              "requestId=14e7aa1f-680f-49d0-8e76-cfd797b9b6b6"
            ],
            "score" :  1,
            "totalRequestTime" :  1261,
            "userId" :  167895
            },
            {
            "date" :  1510872659679,
            "requestParameters" : [
              "datesAsStringsFormat=dd-MMM-yyyy",
              "datesAsStrings=true",
              "outputFormat=xlsx",
              "requestId=14e7aa1f-680f-49d0-8e76-cfd797b9be78"
            ],
            "score" :  1,
            "totalRequestTime" :  1255,
            "userId" :  452669
            }
    ]
}

I am trying to extract the requestId for each userId, however for some reason I am not able to. This is what I tried:

req = requests.get(url=url, auth=(user,password))
out = req.json()
results = out['resultList']

solr_df = pd.DataFrame()
for record in results:
    requestId = pd.DataFrame(record['requestParameters'][3],columns=['requestId'])
    df = pd.DataFrame(requestId)
    df['userId'] = record['userId']
    solr_df = solr_df.append(df)

However it throws a ValueError: DataFrame constructor not properly called!
Can you assist with rectifying the error?

If it too hard to only extract the requestId row for each requestParameter, perhaps you can assist instead removing all rows that aren't requestId related after the for statement runs?

Edit:

When I run it for record['requestParameters'], it runs succesfully but it extracts all rows of requestParameters per userId.

I just tried slicing as such: portfolioId = pd.DataFrame(record['requestParameters'][-1:0]) and it did return results (unlike a single index call), however it was for both outputFormat and requestId rows.
I then tried portfolioId = pd.DataFrame(record['requestParameters'][1:2]) and it returned results for both requestId and datesAsStrings.

It looks like requestParameters rows are not indexed consistently (not sure why it is possible), is there still a way to get a specific row from a list?

Thank you

Body:
According to docs: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html

req = requests.get(url=url, auth=(user,password))
out = req.json()
results = out['resultList']

df = pd.DataFrame()
for record in results:
    requestId = pd.DataFrame({"requestId": record['requestParameters'][3]})
    df = pd.DataFrame(requestId)
    df['userId'] = record['userId']
    df = df.append(df)


问:
Break from loop after given a number
I am having issue to have my "break loop" to work, it doesn't throw any error so I can't even see what's happening. It is the option 3 when I tell the script to start blinking my LED. Originally I was looking into some ways if there is a way to run your loop and go back to your MainMenu while the loop is still running, But that wasn't the options, so I wanted to try something similar to use "for number in range(10):"

```<code>def loop():
    while True:
        os.system('clear')
        print
        print ('1. ON')
        print ('2. OFF')
        print ('3. Blink')
        print
        choice = int(raw_input('1-[ON], 2-[OFF]: '))
        if choice == 1:
            print
            print ('Turning ON')
            GPIO.output(LedPin, GPIO.LOW)  # Led ON
        elif choice == 2:
            print
            print ('Turning OFF')
            GPIO.output(LedPin, GPIO.HIGH)  # Led OFF
        elif choice == 3:
            number = 0
            for number in range(10):
               number = number + 1
               if number == 5:
                  break
                  GPIO.output(LedPin, GPIO.LOW + str(number))  # Led ON
                  time.sleep(0.05)
                  GPIO.output(LedPin, GPIO.HIGH + str(number))  # Led OFF
                  time.sleep(0.05)
               #print ('Number is ' + str(number))
</code>```

this example works fine:

```<code>    number = 0

for number in range(10):
   number = number + 1

   if number == 5:
      break    # break here

   print('Number is ' + str(number))

print('Out of loop')
</code>```

Output:

```<code>Number is 1
Number is 2
Number is 3
Number is 4
Out of loop
</code>```

答:
I dont know if this will help at all, but maybe try using quit or a while loop instead like:

when number == 5:

quit (This will make your program stop)

However, even if you use break, it doesn't make sense to write code after it, so maybe comment your code that goes after it out and see if it works.

Title: Break from loop after given a number

Body:
I am having issue to have my "break loop" to work, it doesn't throw any error so I can't even see what's happening. It is the option 3 when I tell the script to start blinking my LED. Originally I was looking into some ways if there is a way to run your loop and go back to your MainMenu while the loop is still running, But that wasn't the options, so I wanted to try something similar to use "for number in range(10):"

def loop():
    while True:
        os.system('clear')
        print
        print ('1. ON')
        print ('2. OFF')
        print ('3. Blink')
        print
        choice = int(raw_input('1-[ON], 2-[OFF]: '))
        if choice == 1:
            print
            print ('Turning ON')
            GPIO.output(LedPin, GPIO.LOW)  # Led ON
        elif choice == 2:
            print
            print ('Turning OFF')
            GPIO.output(LedPin, GPIO.HIGH)  # Led OFF
        elif choice == 3:
            number = 0
            for number in range(10):
               number = number + 1
               if number == 5:
                  break
                  GPIO.output(LedPin, GPIO.LOW + str(number))  # Led ON
                  time.sleep(0.05)
                  GPIO.output(LedPin, GPIO.HIGH + str(number))  # Led OFF
                  time.sleep(0.05)
               #print ('Number is ' + str(number))

this example works fine:

    number = 0

for number in range(10):
   number = number + 1

   if number == 5:
      break    # break here

   print('Number is ' + str(number))

print('Out of loop')

Output:

Number is 1
Number is 2
Number is 3
Number is 4
Out of loop


问:
What is the maximum depth of the java call stack?
How deep do I need to go into the call stack before I get a StackOverflowError? Is the answer platform dependent?</p>

答:
It depends on the amount of virtual memory allocated to the stack.

http://www.odi.ch/weblog/posting.php?posting=411

You can tune this with the -Xss VM parameter or with the Thread(ThreadGroup, Runnable, String, long) constructor.


问:
Swift 4 - Cannot assign value of type 'NSDate' to type 'Date?' ONLY on Physical Device
I've seen the other questions related to this error, but I've not seen anyone mention what I'm currently experiencing. Note that before converting to Swift 4, I had no problems with this code.

Below is the offending code:

```<code>let verseNotification = NSManagedObject(entity: entity, insertInto: self.managedObjectContext) as! VerseNotification
verseNotification.date_scheduled = NSDate(timeIntervalSinceNow: finalTimeToScheduleSinceNow)
</code>```

Note that the attribute date_scheduled is of type Date:

```<code>@NSManaged public var date_scheduled: Date?
</code>```

When I build my app to deploy in DEBUG on my physical iPhone (an iPhone 7), I get the following error (after converting from Swift 3 to Swift 4):

```<code>Cannot assign value of type 'NSDate' to type 'Date?' - Insert 'as Date'
</code>```

Doing as it says fixes the problem... So, now my code is this:

```<code>verseNotification.date_scheduled = NSDate(timeIntervalSinceNow: finalTimeToScheduleSinceNow) as Date
</code>```

...Until I switch the target to the simulator. When I switch the target to be the Simulator iPhone 7 device, I now get the following error:

```<code>'NSDate' is not implicitly convertible to 'Date'; did you mean to use 'as' to explicitly convert?
</code>```

The confounding thing about this error is, as you can see above, I AM explicitly converting to type Date. Ironically, the only way I can get rid of this error for the Simulator iPhone 7 is to remove the as Date that I added in the first step.

What is going on? What am I missing?

I'm concerned about building a release version to "Generic Device," not knowing why I'm getting the conflicting errors.

UPDATE
I've discovered something new and quite interesting.

When I build to deploy to my physical iPhone 7 device, the generated Core Data definition of my data model object creates the date_scheduled attribute as Date.

However, when I build to deploy on the Simulator iPhone 7, the generated Core Date definition of my data model object creates the date_scheduled attribute as NSDate.

Is this new in Swift 4 or Xcode 9? Is there a new setting that I'm missing after the conversion from Swift 3 to Swift 4?

答: It’s Xcode bug. Please, report or open radar on that to be fixed in future releases</p>

Body:
I've seen the other questions related to this error, but I've not seen anyone mention what I'm currently experiencing. Note that before converting to Swift 4, I had no problems with this code.

Below is the offending code:

let verseNotification = NSManagedObject(entity: entity, insertInto: self.managedObjectContext) as! VerseNotification
verseNotification.date_scheduled = NSDate(timeIntervalSinceNow: finalTimeToScheduleSinceNow)

Note that the attribute date_scheduled is of type Date:

@NSManaged public var date_scheduled: Date?

When I build my app to deploy in DEBUG on my physical iPhone (an iPhone 7), I get the following error (after converting from Swift 3 to Swift 4):

Cannot assign value of type 'NSDate' to type 'Date?' - Insert 'as Date'

Doing as it says fixes the problem... So, now my code is this:

verseNotification.date_scheduled = NSDate(timeIntervalSinceNow: finalTimeToScheduleSinceNow) as Date

...Until I switch the target to the simulator. When I switch the target to be the Simulator iPhone 7 device, I now get the following error:

'NSDate' is not implicitly convertible to 'Date'; did you mean to use 'as' to explicitly convert?

The confounding thing about this error is, as you can see above, I AM explicitly converting to type Date. Ironically, the only way I can get rid of this error for the Simulator iPhone 7 is to remove the as Date that I added in the first step.

What is going on? What am I missing?

I'm concerned about building a release version to "Generic Device," not knowing why I'm getting the conflicting errors.

UPDATE
I've discovered something new and quite interesting.

When I build to deploy to my physical iPhone 7 device, the generated Core Data definition of my data model object creates the date_scheduled attribute as Date.

However, when I build to deploy on the Simulator iPhone 7, the generated Core Date definition of my data model object creates the date_scheduled attribute as NSDate.

Is this new in Swift 4 or Xcode 9? Is there a new setting that I'm missing after the conversion from Swift 3 to Swift 4?


答:
To extract the id, you can try this:

```<code>req = requests.get(url=url, auth=(user,password))
out = req.json()
results = out['resultList']
ids = [i["requestParameters"][-1] for i in results["resultList"]]
</code>```

Output:

```<code>['requestId=14e7aa1f-680f-49d0-8e76-cfd797b9b6b6', 'requestId=14e7aa1f-680f-49d0-8e76-cfd797b9be78']
</code>```

Or, if you just want the numerical value:

```<code>import re
req = requests.get(url=url, auth=(user,password))
out = req.json()
results = out['resultList']
final_val = [re.findall('(?<=requestId\=)[\w-]+', i["requestParameters"][-1])[0] for i in results["resultList"]]
</code>```

Output:

```<code>['14e7aa1f-680f-49d0-8e76-cfd797b9b6b6', '14e7aa1f-680f-49d0-8e76-cfd797b9be78']
</code>```

Title: Getting specific row from a list fails

Body:
To extract the id, you can try this:

req = requests.get(url=url, auth=(user,password))
out = req.json()
results = out['resultList']
ids = [i["requestParameters"][-1] for i in results["resultList"]]

Output:

['requestId=14e7aa1f-680f-49d0-8e76-cfd797b9b6b6', 'requestId=14e7aa1f-680f-49d0-8e76-cfd797b9be78']

Or, if you just want the numerical value:

import re
req = requests.get(url=url, auth=(user,password))
out = req.json()
results = out['resultList']
final_val = [re.findall('(?<=requestId\=)[\w-]+', i["requestParameters"][-1])[0] for i in results["resultList"]]

Output:

['14e7aa1f-680f-49d0-8e76-cfd797b9b6b6', '14e7aa1f-680f-49d0-8e76-cfd797b9be78']


问:
Defining shared variables in a package - go
I have a package with multiple go files in it, I am looking for best practices to follow when using these variables

```<code>var print string

type someStruct struct {
  //some vars
}
</code>```

Consider package files has following go files in it

file1.go has a string variable print

file2.go has a struct someStruct

file3.go needs a string variable print

file4.go needs a struct someStruct

should I access/use the variable from file1.go in file3.go or create a new string variable i.e., file3print

same way should I access/use the someStruct from file2.go in file4.go
or create a new struct i.e., file3SomeStruct

答:
Do not create file-specific types, nor variables, a la file3SomeStruct, just for the sake of avoiding sharing of those identifiers between files, a practice like this seems to me very unreasonable and would most definitely be considered bad practice.

Sharing of identifiers between files is absolutely ok and you can find countless examples of this practice in the standard library.

Just take a look through the net/http package source files.

If you want, you can think of packages as representing a single-concept, e.g. HTTP, and the package's files representing its sub-concepts, like an HTTP server, HTTP client, or HTTP request. But for the HTTP to be useful its sub-concepts need to be able to interact. (This is not a required standard, some packages may be better off with a different design.)

Body:
I have a package with multiple go files in it, I am looking for best practices to follow when using these variables

var print string

type someStruct struct {
  //some vars
}

Consider package files has following go files in it

file1.go has a string variable print

file2.go has a struct someStruct

file3.go needs a string variable print

file4.go needs a struct someStruct

should I access/use the variable from file1.go in file3.go or create a new string variable i.e., file3print

same way should I access/use the someStruct from file2.go in file4.go
or create a new struct i.e., file3SomeStruct


问:
Are classmethods thread safe?
I am working on a class which operates in a multithreaded environment, and looks something like this (with excess noise removed):

```<code>class B:

    @classmethod
    def apply(cls, item):
        cls.do_thing(item)

    @classmethod
    def do_thing(cls, item)
        'do something to item'

    def run(self):
        pool = multiprocessing.Pool()
        for list_of_items in self.data_groups:
            pool.map(list_of_items, self.apply)
</code>```

My concern is that two threads might call apply or do_thing at the same time, or that a subclass might try to do something stupid with cls in one of these functions.  I could use staticmethod instead of classmethod, but calling do_thing would become a lot more complicated, especially if a subclass reimplements one of these but not the other.  So my question is this:  Is the above class thread-safe, or is there a potential problem with using classmethods like that?

答:
Both other answers are technically correct in that the safety of do_thing() depends on what happens inside the function.

But the more precise answer is that the call itself is safe. In other words if apply()and do_thing()are a pure functions, then your code is safe. Any unsafe-ness would be due to them not being pure functions (e.g. relying on or affecting a shared variable during execution)

As shx2 mentioned, classmethods are only "in" a class visually, for grouping. They have no inherent attachment to any instance of the class. Therefore this code is roughly equivalent in functioning:

```<code>def apply(item):
    do_thing(item)

def do_thing(item)
    'do something to item'

class B:
    def run(self):
        pool = multiprocessing.Pool()
        for list_of_items in self.data_groups:
            pool.map(list_of_items, apply)
</code>```

A further note on concurrency given the other answers:

threading.Lock is easy to understand, but should be your last resort. In naive implementations it is often slower than completely linear processing. Your code will usually be faster if you can use things like threading.Event, queue.Queue, or multiprocessing.Pipe to transfer information instead.

asyncio is the new hotness in python3. It's a bit more difficult to get right but is generally the fastest method.

If you want a great walkthrough modern concurrency techniques in python check out core developer Raymond Hettinger's Keynote on Concurrency. The whole thing is great, but the downside of lockis highlighted starting at t=57:59.

Title: Are classmethods thread safe?

Body:
I am working on a class which operates in a multithreaded environment, and looks something like this (with excess noise removed):

class B:

    @classmethod
    def apply(cls, item):
        cls.do_thing(item)

    @classmethod
    def do_thing(cls, item)
        'do something to item'

    def run(self):
        pool = multiprocessing.Pool()
        for list_of_items in self.data_groups:
            pool.map(list_of_items, self.apply)

My concern is that two threads might call apply or do_thing at the same time, or that a subclass might try to do something stupid with cls in one of these functions.  I could use staticmethod instead of classmethod, but calling do_thing would become a lot more complicated, especially if a subclass reimplements one of these but not the other.  So my question is this:  Is the above class thread-safe, or is there a potential problem with using classmethods like that?

Body:
Both other answers are technically correct in that the safety of do_thing() depends on what happens inside the function.

But the more precise answer is that the call itself is safe. In other words if apply()and do_thing()are a pure functions, then your code is safe. Any unsafe-ness would be due to them not being pure functions (e.g. relying on or affecting a shared variable during execution)

As shx2 mentioned, classmethods are only "in" a class visually, for grouping. They have no inherent attachment to any instance of the class. Therefore this code is roughly equivalent in functioning:

def apply(item):
    do_thing(item)

def do_thing(item)
    'do something to item'

class B:
    def run(self):
        pool = multiprocessing.Pool()
        for list_of_items in self.data_groups:
            pool.map(list_of_items, apply)

A further note on concurrency given the other answers:

threading.Lock is easy to understand, but should be your last resort. In naive implementations it is often slower than completely linear processing. Your code will usually be faster if you can use things like threading.Event, queue.Queue, or multiprocessing.Pipe to transfer information instead.

asyncio is the new hotness in python3. It's a bit more difficult to get right but is generally the fastest method.

If you want a great walkthrough modern concurrency techniques in python check out core developer Raymond Hettinger's Keynote on Concurrency. The whole thing is great, but the downside of lockis highlighted starting at t=57:59.


问:
return same object after destructuring in function params
Let's say I have an Object

var bar = {hi: 1, there: 2};

I would like to, at the end of the function, return the same object that was passed while at the same time doing a destructuring assignment in the function param.

It might look like this:

```<code>function foo({hi, there}){
    //logic with variables "hi" and "there"
    return ...arguments;
}
</code>```

and have the return value be the same as bar;
for obvious reasons the spread operator doesn't work in this context, but I'm wondering if there is a simple way to do this or something similar.

答:
Name and destructure separately:</p>

```<code>function foo(obj) {
    let {hi, there} = obj;
    // logic with variables "hi" and "there"
    return obj;
}
</code>```

Body:
Let's say I have an Object

var bar = {hi: 1, there: 2};

I would like to, at the end of the function, return the same object that was passed while at the same time doing a destructuring assignment in the function param.

It might look like this:

function foo({hi, there}){
    //logic with variables "hi" and "there"
    return ...arguments;
}

and have the return value be the same as bar;
for obvious reasons the spread operator doesn't work in this context, but I'm wondering if there is a simple way to do this or something similar.

Body:
Name and destructure separately:

function foo(obj) {
    let {hi, there} = obj;
    // logic with variables "hi" and "there"
    return obj;
}


问:
Finding Median in Sql Server
I want to get the median of unitRate from [dbo].[ReplaceCost_DirectCost_Details] view in Microsoft Sql Server Management Studio. I already got Min,Max and avg of it.But do not know about median. I tried following code, but did not get median .Thanks in advacen for your help.

 select
        JobName as JobName
       ,Client as Client
       ,AssetClass as AssetClass
       ,AssetType as AssetType
       ,AssetSubType as AssetSubType
       ,Component as Component
       ,ComponentType as ComponentType
       ,ComponentSubType as ComponentSubType
       ,UnitRate AS UnitRate
       ,Max(UnitRate) over (partition by JobName,Client,AssetClass,AssetType,AssetSubType,Component,ComponentType,ComponentSubType) as [MaxFinalUnitRate]
       ,Min(UnitRate) over (partition by JobName,Client,AssetClass,AssetType,AssetSubType,Component,ComponentType,ComponentSubType)  as [MinFinalUnitRate]
       ,AVG(UnitRate) over (partition by JobName,Client,AssetClass,AssetType,AssetSubType,Component,ComponentType,ComponentSubType) as [MeanFinalUnitRate]
       ,AVG (UnitRate)  over (partition by JobName,Client,AssetClass,AssetType,AssetSubType,Component,ComponentType,ComponentSubType)as Median
       from
        (
         Select top (10)
        JobName as JobName
       ,Client as Client
       ,AssetClass as AssetClass
       ,AssetType as AssetType
       ,AssetSubType as AssetSubType
       ,Component as Component
       ,ComponentType as ComponentType
       ,ComponentSubType as ComponentSubType
       ,UnitRate AS UnitRate
       ,ROW_NUMBER () over (partition by JobName,Client,AssetClass,AssetType,AssetSubType,Component,ComponentType,ComponentSubType order by UnitRate) as [RowNum]
       ,COUNT(*) OVER (PARTITION BY JobName,Client,AssetClass,AssetType,AssetSubType,Component,ComponentType,ComponentSubType ) AS RowCnt

     from [dbo].[ReplaceCost_DirectCost_Details] rdd
     where  client = 'APV_Ballina_Shire_Council_Old'  and  UnitRate is not Null and UnitRate <> 0
       ) x
       WHERE   RowNum IN ((RowCnt + 1) / 2, (RowCnt + 2) / 2)
```

答:
EDIT

SQL Fiddle

```<code>CREATE TABLE Table1
    ([somevalue] int)
;

INSERT INTO Table1
    ([somevalue])
VALUES
    (141),
    (325),
    (325),
    (353),
    (3166),
    (325),
    (207),
    (141),
    (3166),
    (161)
;
</code>```

Query 1:

```<code>with cte as (
  select *
  , row_number() over(order by somevalue) as RowNum
  , count(*) over() as RowCnt
  from table1
  )
select
*
from CTE
WHERE   RowNum IN ((RowCnt + 1) / 2, (RowCnt + 2) / 2)

| somevalue | RowNum | RowCnt |
|-----------|--------|--------|
|       325 |      5 |     10 |
|       325 |      6 |     10 |
</code>```

Please consider the following small example. There are 7 rows of data, the median is the "midpoint" of those, so the where clause uses a row number compared to row count, and returns just that midpoint valuse. That value (67) repesents the median of that small sample.

SQL Fiddle

MS SQL Server 2014 Schema Setup:

```<code>CREATE TABLE Table1
    ([somevalue] int)
;

INSERT INTO Table1
    ([somevalue])
VALUES
    (2),
    (45),
    (67),
    (89),
    (4567),
    (6),
    (1290)
;
</code>```

Query 1:

```<code>with cte as (
  select *
  , row_number() over(order by somevalue) as RowNum
  , count(*) over() as RowCnt
  from table1
  )
select
*
from CTE
WHERE   RowNum IN ((RowCnt + 1) / 2, (RowCnt + 2) / 2)
</code>```

Results:

```<code>| somevalue | RowNum | RowCnt |
|-----------|--------|--------|
|        67 |      4 |      7 |
</code>```

Title: Finding Median in Sql Server

Body:
EDIT

SQL Fiddle

CREATE TABLE Table1
    ([somevalue] int)
;

INSERT INTO Table1
    ([somevalue])
VALUES
    (141),
    (325),
    (325),
    (353),
    (3166),
    (325),
    (207),
    (141),
    (3166),
    (161)
;

Query 1:

with cte as (
  select *
  , row_number() over(order by somevalue) as RowNum
  , count(*) over() as RowCnt
  from table1
  )
select
*
from CTE
WHERE   RowNum IN ((RowCnt + 1) / 2, (RowCnt + 2) / 2)

| somevalue | RowNum | RowCnt |
|-----------|--------|--------|
|       325 |      5 |     10 |
|       325 |      6 |     10 |

Please consider the following small example. There are 7 rows of data, the median is the "midpoint" of those, so the where clause uses a row number compared to row count, and returns just that midpoint valuse. That value (67) repesents the median of that small sample.

SQL Fiddle

MS SQL Server 2014 Schema Setup:

CREATE TABLE Table1
    ([somevalue] int)
;

INSERT INTO Table1
    ([somevalue])
VALUES
    (2),
    (45),
    (67),
    (89),
    (4567),
    (6),
    (1290)
;

Query 1:

with cte as (
  select *
  , row_number() over(order by somevalue) as RowNum
  , count(*) over() as RowCnt
  from table1
  )
select
*
from CTE
WHERE   RowNum IN ((RowCnt + 1) / 2, (RowCnt + 2) / 2)

Results:

| somevalue | RowNum | RowCnt |
|-----------|--------|--------|
|        67 |      4 |      7 |


问:
data frame (matrix) performance: memory layout
I am a newbie to R. Assume the memory layout is the same for data frame and matrix.

In the following matrix

a=matrix(1:10000000,1000000,10)

it has 1M rows and 10 columns. Is the memory for row or for column sequential physically? Or is the physical memory first store [1,1],[2,1],[3,1],,[1M,1],[2,1]  or [1,2],[1,2],..[1,10],[2,1]...?

Suppose the matrix with 10M element is of size 100M, and the L2 cache is 4M, then L2 cache can't store all these 10M element. If we process the data sequentially, we will have less L2 cache missing ratio. For our case, we need to process row by row and read several columns at the same time, such as column A, B, C, and then create some result. If the layout of the memory is first store 10 items in 1st row,  then store 10 items in the 2nd row, then the performance might be better.

If there any way to control the memory layout?

答:
Matrices are stored column-wise:

```<code>> m=matrix(1:12,nrow=3)
> m
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12
</code>```

Data frames are just pretty lists, and lists are stored as vectors of elements. I'm not even sure that list elements are guaranteed to be contiguous in memory.

Read up on writing R extensions for more info on how memory is handled. As far as I know there's no way to control the memory layout. Don't worry about it until it becomes a problem.

Body:
Matrices are stored column-wise:

> m=matrix(1:12,nrow=3)
> m
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12

Data frames are just pretty lists, and lists are stored as vectors of elements. I'm not even sure that list elements are guaranteed to be contiguous in memory.

Read up on writing R extensions for more info on how memory is handled. As far as I know there's no way to control the memory layout. Don't worry about it until it becomes a problem.


问:
Delete all rows in sheet 1 with same value in column as in sheet 2
I'd like to achieve the example i provided below, deleting all rows in sheet1 that are similar to sheet2.

Sheet1

```<code>   Name             ID
-------------------------
 1. Name11         Value1
 2. Name22         Value2
 3. Name33         Value3
 4. Name44         Value4
 5. Name55         Value5
    ...            ...
</code>```

Sheet2

```<code>   Name             ID
-------------------------
 1. Name13         Value3
 2. Name52         Value5
    ...            ...
</code>```

Sheet1 After deleting the row

```<code>   Name             ID
-------------------------
 1. Name11         Value1
 2. Name22         Value2
 3. Name44         Value4
    ...
</code>```

答:
Try something like this:</p>

```<code>function myFunction() {
  var ss=SpreadsheetApp.getActive();
  var sh1=ss.getSheetByName('Sheet1');
  var sh2=ss.getSheetByName('Sheet2');
  var rg1=sh1.getDataRange();
  var rg2=sh2.getDataRange();
  var v1A=rg1.getValues();
  var v2A=rg2.getValues();
  for(var i=v1A.length-1;i>0;i--)
  {
    var row1=v1A[i];
    for(var j=1;j<v2A.length;j++)
    {
      row2=v2A[j];
      if(row1.join()==row2.join())
      {
        sh1.deleteRow(i+1);
        break;
      }
    }
  }
}
</code>```

Body:
I'd like to achieve the example i provided below, deleting all rows in sheet1 that are similar to sheet2.

Sheet1

   Name             ID
-------------------------
 1. Name11         Value1
 2. Name22         Value2
 3. Name33         Value3
 4. Name44         Value4
 5. Name55         Value5
    ...            ...

Sheet2

   Name             ID
-------------------------
 1. Name13         Value3
 2. Name52         Value5
    ...            ...

Sheet1 After deleting the row

   Name             ID
-------------------------
 1. Name11         Value1
 2. Name22         Value2
 3. Name44         Value4
    ...

Body:
Try something like this:

function myFunction() {
  var ss=SpreadsheetApp.getActive();
  var sh1=ss.getSheetByName('Sheet1');
  var sh2=ss.getSheetByName('Sheet2');
  var rg1=sh1.getDataRange();
  var rg2=sh2.getDataRange();
  var v1A=rg1.getValues();
  var v2A=rg2.getValues();
  for(var i=v1A.length-1;i>0;i--)
  {
    var row1=v1A[i];
    for(var j=1;j<v2A.length;j++)
    {
      row2=v2A[j];
      if(row1.join()==row2.join())
      {
        sh1.deleteRow(i+1);
        break;
      }
    }
  }
}


问:
TinyMCE local image upload with multiple inline editors
First of all, I am a beginner in tinymce and furthermore not an english native, so sorry for any mistakes ;)

I intend to upload local images (Base64) from multiple inline tinymce(v.4) editors on my site by pressing a button and running the function the tinymce website provides:

tinymce.activeEditor.uploadImages(function(success) {
  $.post('ajax/post.php', tinymce.activeEditor.getContent()).done(function() {
    console.log("Uploaded images and posted content as an ajax request.");
  });
});```

So far it works wery well, but I still have a small problem: It only uploads images from the "active editor" (as stated in the code). If I add an image to an editor, than focus to another on the page and then run the function, it only uploads from the currently active editor, but not my previously added image.

How do I achieve that it uploads from ALL editors on the page?

Thanks in advance!

答:
TinyMCE already has a way to handle inserting local images and getting them to your server:

https://www.tinymce.com/docs/advanced/handle-async-image-uploads/

If you configure this on each editor when you init() the editor these things will get done properly across all editor instances.

Body:
First of all, I am a beginner in tinymce and furthermore not an english native, so sorry for any mistakes ;)

I intend to upload local images (Base64) from multiple inline tinymce(v.4) editors on my site by pressing a button and running the function the tinymce website provides:

tinymce.activeEditor.uploadImages(function(success) {
  $.post('ajax/post.php', tinymce.activeEditor.getContent()).done(function() {
    console.log("Uploaded images and posted content as an ajax request.");
  });
});

So far it works wery well, but I still have a small problem: It only uploads images from the "active editor" (as stated in the code). If I add an image to an editor, than focus to another on the page and then run the function, it only uploads from the currently active editor, but not my previously added image.

How do I achieve that it uploads from ALL editors on the page?

Thanks in advance!