问:
C++ segmentation fault issue
If anyone is able to help and tell me why it segfaults, I would really appreciate it. Thanks!

Note: I'm not allowed to modify the main function by any means.

```<code>#include <iostream>
#include <algorithm>
#include <functional>
#include <list>
#include <cmath>

class Object {
 public:
 private:
  float d;

 public:
  Object(float n) : d(n) {}
  Object() {}

  struct PointType {
    float x2;
    float y2;
    PointType(float x1, float y1) : x2(x1), y2(y1) {}
    PointType() {}
    float x() { return x2; }
    float y() { return y2; }
    PointType center() { return *this; }
    friend std::ostream &operator<<(std::ostream &os, const PointType &p) {
      os << p;

      return os;
    }
  };

  virtual void render() const {}
  virtual ~Object() {}
};

class Point : public Object {
 private:
  PointType mpoint;

 public:
  Point(const PointType &pt, float &y1) : Object(y1), mpoint(pt) {}
  Point(const PointType &pt) : mpoint(pt) {}
  Point() {}

  Point center() const { return *this; }
  float x() { return mpoint.x2; }
  float y() { return mpoint.y2; }
  friend std::ostream &operator<<(std::ostream &os, const Point &p) {
    os << p.center();
    return os;
  }
};

class VisiblePoint : public Point {
 public:
  VisiblePoint(const Object::PointType &point) : Point(point) {}

  void render() const override {
    std::cout << "Point at " << center() << std::endl;
  }
};

// A simple pseudo-random number generator.
class PseudoRandom {
  const int A = 101;
  const int B = 919;
  const int C = 10619863;

  int _current;

 public:
  PseudoRandom() : _current(0) {}

  int operator()() {
    _current = (A * _current + B) % C;
    _current += (_current < 0) ? C : 0;
    return _current;
  }

  int operator()(int n) { return (*this)() % n; }

  float operator()(float a, float b) {
    int result = (*this)();
    return a + (b - a) * static_cast<float>(result) / float(C);
  }
};

int main() {
  std::list<Object *> objects;
  PseudoRandom random;

  for (int i = 0; i < 10; ++i) {
    switch (random(1)) {
      case 0: {
        const Object::PointType point(random(0, 1), random(0, 1));
        objects.push_back(new VisiblePoint(point));
        break;
      }
      case 1: {
      }
      case 2: {
      }
      case 3: {
      }
      case 4: {
      }
    }
  }
  std::cout << "BEGIN" << std::endl;

  std::for_each(objects.begin(), objects.end(), std::mem_fn(&Object::render));

  std::cout << "END" << std::endl;

  for (const Object *object : objects) {
    delete object;
  }
  objects.clear();
}
</code>```

答:
You have a stack overflow because of

```<code>friend std::ostream& operator<<(std::ostream& os, const Point& p)
{
   os << p.center();
   return os;
}
</code>```

calling itself without ending because Point::center() returns a Point (center just return the instance)

You have the same stack overflow problem for PointType, you can change these definition to have for instance :

```<code>friend std::ostream& operator<<(std::ostream& os, const Point& p)
{
    os << p.mpoint;
    return os;
}

friend std::ostream& operator<<(std::ostream& os, const
        PointType& p)
{
    os << "x=" << p.x2 << ", y=" << p.y2;
    return os;
}
</code>```

Compilation and execution :

```<code>pi@raspberrypi:/tmp $ g++ -g -pedantic -Wextra -Wall c.cc
pi@raspberrypi:/tmp $ ./a.out
BEGIN
Point at x=0.00882667, y=0.89158
Point at x=0.015971, y=0.613159
Point at x=0.845152, y=0.360472
Point at x=0.186335, y=0.819929
Point at x=0.108734, y=0.982257
Point at x=0.0107827, y=0.0891412
Point at x=0.337889, y=0.126905
Point at x=0.567967, y=0.364747
Point at x=0.788968, y=0.685901
Point at x=0.889105, y=0.799651
END
</code>```

Note the member d is private in Object and there is no way to access it (nor to write it), if I add

```<code>friend std::ostream& operator<<(std::ostream& os, const Object & o) {
  os << "d=" << o.d;
  return os;
}
</code>```

and modify the operator<< for Point to have :

```<code>friend std::ostream& operator<<(std::ostream& os, const Point& p)
{
    os << p.mpoint << ", ";
    os << (const Object &) p;
    return os;
}
</code>```

and initialize d in the default constructor of Object :

```<code>Object() : d(0) {}
</code>```

Compilation and execution :

```<code>pi@raspberrypi:/tmp $ g++ -g -pedantic -Wextra -Wall c.cc
pi@raspberrypi:/tmp $ ./a.out
BEGIN
Point at x=0.00882667, y=0.89158, d=0
Point at x=0.015971, y=0.613159, d=0
Point at x=0.845152, y=0.360472, d=0
Point at x=0.186335, y=0.819929, d=0
Point at x=0.108734, y=0.982257, d=0
Point at x=0.0107827, y=0.0891412, d=0
Point at x=0.337889, y=0.126905, d=0
Point at x=0.567967, y=0.364747, d=0
Point at x=0.788968, y=0.685901, d=0
Point at x=0.889105, y=0.799651, d=0
END
pi@raspberrypi:/tmp $
</code>```

Title: C++ segmentation fault issue

Body:
If anyone is able to help and tell me why it segfaults, I would really appreciate it. Thanks!

Note: I'm not allowed to modify the main function by any means.

#include <iostream>
#include <algorithm>
#include <functional>
#include <list>
#include <cmath>

class Object {
 public:
 private:
  float d;

 public:
  Object(float n) : d(n) {}
  Object() {}

  struct PointType {
    float x2;
    float y2;
    PointType(float x1, float y1) : x2(x1), y2(y1) {}
    PointType() {}
    float x() { return x2; }
    float y() { return y2; }
    PointType center() { return *this; }
    friend std::ostream &operator<<(std::ostream &os, const PointType &p) {
      os << p;

      return os;
    }
  };

  virtual void render() const {}
  virtual ~Object() {}
};

class Point : public Object {
 private:
  PointType mpoint;

 public:
  Point(const PointType &pt, float &y1) : Object(y1), mpoint(pt) {}
  Point(const PointType &pt) : mpoint(pt) {}
  Point() {}

  Point center() const { return *this; }
  float x() { return mpoint.x2; }
  float y() { return mpoint.y2; }
  friend std::ostream &operator<<(std::ostream &os, const Point &p) {
    os << p.center();
    return os;
  }
};

class VisiblePoint : public Point {
 public:
  VisiblePoint(const Object::PointType &point) : Point(point) {}

  void render() const override {
    std::cout << "Point at " << center() << std::endl;
  }
};

// A simple pseudo-random number generator.
class PseudoRandom {
  const int A = 101;
  const int B = 919;
  const int C = 10619863;

  int _current;

 public:
  PseudoRandom() : _current(0) {}

  int operator()() {
    _current = (A * _current + B) % C;
    _current += (_current < 0) ? C : 0;
    return _current;
  }

  int operator()(int n) { return (*this)() % n; }

  float operator()(float a, float b) {
    int result = (*this)();
    return a + (b - a) * static_cast<float>(result) / float(C);
  }
};

int main() {
  std::list<Object *> objects;
  PseudoRandom random;

  for (int i = 0; i < 10; ++i) {
    switch (random(1)) {
      case 0: {
        const Object::PointType point(random(0, 1), random(0, 1));
        objects.push_back(new VisiblePoint(point));
        break;
      }
      case 1: {
      }
      case 2: {
      }
      case 3: {
      }
      case 4: {
      }
    }
  }
  std::cout << "BEGIN" << std::endl;

  std::for_each(objects.begin(), objects.end(), std::mem_fn(&Object::render));

  std::cout << "END" << std::endl;

  for (const Object *object : objects) {
    delete object;
  }
  objects.clear();
}

Body:
You have a stack overflow because of

friend std::ostream& operator<<(std::ostream& os, const Point& p)
{
   os << p.center();
   return os;
}

calling itself without ending because Point::center() returns a Point (center just return the instance)

You have the same stack overflow problem for PointType, you can change these definition to have for instance :

friend std::ostream& operator<<(std::ostream& os, const Point& p)
{
    os << p.mpoint;
    return os;
}

friend std::ostream& operator<<(std::ostream& os, const
        PointType& p)
{
    os << "x=" << p.x2 << ", y=" << p.y2;
    return os;
}

Compilation and execution :

pi@raspberrypi:/tmp $ g++ -g -pedantic -Wextra -Wall c.cc
pi@raspberrypi:/tmp $ ./a.out
BEGIN
Point at x=0.00882667, y=0.89158
Point at x=0.015971, y=0.613159
Point at x=0.845152, y=0.360472
Point at x=0.186335, y=0.819929
Point at x=0.108734, y=0.982257
Point at x=0.0107827, y=0.0891412
Point at x=0.337889, y=0.126905
Point at x=0.567967, y=0.364747
Point at x=0.788968, y=0.685901
Point at x=0.889105, y=0.799651
END

Note the member d is private in Object and there is no way to access it (nor to write it), if I add

friend std::ostream& operator<<(std::ostream& os, const Object & o) {
  os << "d=" << o.d;
  return os;
}

and modify the operator<< for Point to have :

friend std::ostream& operator<<(std::ostream& os, const Point& p)
{
    os << p.mpoint << ", ";
    os << (const Object &) p;
    return os;
}

and initialize d in the default constructor of Object :

Object() : d(0) {}

Compilation and execution :

pi@raspberrypi:/tmp $ g++ -g -pedantic -Wextra -Wall c.cc
pi@raspberrypi:/tmp $ ./a.out
BEGIN
Point at x=0.00882667, y=0.89158, d=0
Point at x=0.015971, y=0.613159, d=0
Point at x=0.845152, y=0.360472, d=0
Point at x=0.186335, y=0.819929, d=0
Point at x=0.108734, y=0.982257, d=0
Point at x=0.0107827, y=0.0891412, d=0
Point at x=0.337889, y=0.126905, d=0
Point at x=0.567967, y=0.364747, d=0
Point at x=0.788968, y=0.685901, d=0
Point at x=0.889105, y=0.799651, d=0
END
pi@raspberrypi:/tmp $


来源: stackexchange

问:
Why Larecipe can't load correctly?
I installed Larecipe in the project and he can't load correctly. When i see "/docs/1.0/overview", get errors in console and layout can't be load.

Uncaught ReferenceError: CreateLarecipe is not defined

Uncaught ReferenceError: LaRecipe is not defined

I made package updates and unfortunately it did not help.

```<code>Laravel Framework 5.7.28
"binarytorch/larecipe": "^2.1",
</code>```

答:
Please try this. I think you have to recreate boostrap/cache/compiled.php file.</p>

```<code>php artisan optimize
</code>```

ContentLicense: CC BY-SA 4.0

Title: Why Larecipe can't load correctly?

Body:
I installed Larecipe in the project and he can't load correctly. When i see "/docs/1.0/overview", get errors in console and layout can't be load.

Uncaught ReferenceError: CreateLarecipe is not defined

Uncaught ReferenceError: LaRecipe is not defined

I made package updates and unfortunately it did not help.

Laravel Framework 5.7.28
"binarytorch/larecipe": "^2.1",

Body:
Please try this. I think you have to recreate boostrap/cache/compiled.php file.

php artisan optimize


问:
How to send and receive userdata in notification?
I want to send NSMutableDictionary with 4 key-values in notification and want same at receiving side.

How to do that?

答:
```<code>- (void)postNotificationName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo;
</code>```

I think you can use the userInfo argument

ContentLicense: CC BY-SA 3.0

Body:
- (void)postNotificationName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo;

I think you can use the userInfo argument


问:
I want to know if django can dynamically add html tags, just like javascrip
I want to know if django can dynamically add html tags, just like javascrip.if so, how to add html tags dynamically with django-template</p>

答: the html generated by Django can be dynamic in the sense it has the template logic applied at the server, however, once generated and delivered to the browser Django cannot change the html. Using Javascript you can modify the html at the client.</p>


问:
How use local views built with gem devise in rails app?
I am following a guide for oauth google, using gem 'devise' in rails.
All is ok, but now that I cannot change the graphics with the views,
I realised that the controller that I'm using, redirects its method to other controllers and other views that aren't in my app, but are in other path (devise gem). how can I redirect all in my app?

to explain myself this is part of the result of command rake routes:

```<code>Prefix Verb     URI Pattern                                                                              Controller#Action
                 new_user_session GET      /users/sign_in(.:format)                                                                 devise/sessions#new
                     user_session POST     /users/sign_in(.:format)                                                                 devise/sessions#create
             destroy_user_session DELETE   /users/sign_out(.:format)                                                                devise/sessions#destroy
</code>```

the controller Action is mapped on  devise/session  controller that isn't in my app but in the path

```<code> ".rvm/gems/ruby-2.6.1/gems/devise-4.6.2/app/controller..."
</code>```

so that call the views that are on the directory as

```<code>".rvm/gems/ruby-2.6.1/gems/devise-4.6.2/app/views..."
</code>```

but I want that controllers to use my views.

this is the routes.rb file:

```<code>Rails.application.routes.draw do

  devise_for :users, :controllers => { :omniauth_callbacks =>  "users/omniauth_callbacks" }
  resources :homepage, only: [:index]
  resources :schedules, only: [:index, :edit]
  resources :notes, only: [:index, :edit]
  resources :accounts, only: [:index, :edit]

  root :to => 'homepage#index'

end
</code>```

This is the only controller that I have created:

```<code>class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def google_oauth2
    @user = User.from_omniauth(request.env["omniauth.auth"])

    if @user.persisted?
      sign_in @user, :event => :authentication #this will throw if @user is not activated
      set_flash_message(:notice, :success, :kind => "Google") if is_navigational_format?
    else
      session["devise.google_data"] = request.env["omniauth.auth"]
    end
    redirect_to '/'
  end
end
</code>```

答:
Devise allows overriding views and controllers. Usually it's sufficient to override the views by adding files like app/views/devise/sessions/new.html.erb, there's a generator to copy default views to your app:

```<code>rails generate devise:views
</code>```

See devise's README for more details.

Body:
I am following a guide for oauth google, using gem 'devise' in rails.
All is ok, but now that I cannot change the graphics with the views,
I realised that the controller that I'm using, redirects its method to other controllers and other views that aren't in my app, but are in other path (devise gem). how can I redirect all in my app?

to explain myself this is part of the result of command rake routes:

Prefix Verb     URI Pattern                                                                              Controller#Action
                 new_user_session GET      /users/sign_in(.:format)                                                                 devise/sessions#new
                     user_session POST     /users/sign_in(.:format)                                                                 devise/sessions#create
             destroy_user_session DELETE   /users/sign_out(.:format)                                                                devise/sessions#destroy

the controller Action is mapped on  devise/session  controller that isn't in my app but in the path

 ".rvm/gems/ruby-2.6.1/gems/devise-4.6.2/app/controller..."

so that call the views that are on the directory as

".rvm/gems/ruby-2.6.1/gems/devise-4.6.2/app/views..."

but I want that controllers to use my views.

this is the routes.rb file:

Rails.application.routes.draw do

  devise_for :users, :controllers => { :omniauth_callbacks =>  "users/omniauth_callbacks" }
  resources :homepage, only: [:index]
  resources :schedules, only: [:index, :edit]
  resources :notes, only: [:index, :edit]
  resources :accounts, only: [:index, :edit]

  root :to => 'homepage#index'

end

This is the only controller that I have created:

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def google_oauth2
    @user = User.from_omniauth(request.env["omniauth.auth"])

    if @user.persisted?
      sign_in @user, :event => :authentication #this will throw if @user is not activated
      set_flash_message(:notice, :success, :kind => "Google") if is_navigational_format?
    else
      session["devise.google_data"] = request.env["omniauth.auth"]
    end
    redirect_to '/'
  end
end

Body:
Devise allows overriding views and controllers. Usually it's sufficient to override the views by adding files like app/views/devise/sessions/new.html.erb, there's a generator to copy default views to your app:

rails generate devise:views

See devise's README for more details.


问:
Is there a way to store both Image and string variables in one array? (Unity)
I am making a 3D game in unity where player can interact with images and notes (approximately 3-4 paragraphs).

I created the canvas, when player interacts with the notes on the ground, the menu(canvas) pops up.

I wonder, is there any way to store string variables with Image gameObjects in the same array?
Also, i'm going to use these images on the canvas, so should i create as an Image or as a Sprite ?

答:
If you want them to be UI components, you should create Image components.

I suppose you can achieve this by defining your list to be of the two objects common ancestor; Object:

```<code>var list = new List<object>();

list.Add("Hello");
list.Add(5);
list.Add(MyImage);

foreach (object obj in list)
{
    if (obj is string)
    {
        Debug.Log(obj.ToString());
    }
}
</code>```

Body:
If you want them to be UI components, you should create Image components.

I suppose you can achieve this by defining your list to be of the two objects common ancestor; Object:

var list = new List<object>();

list.Add("Hello");
list.Add(5);
list.Add(MyImage);

foreach (object obj in list)
{
    if (obj is string)
    {
        Debug.Log(obj.ToString());
    }
}


问:
How to read all files in a folder from Java?
How to read all the files in a folder through Java? It doesn't matter which API.</p>

答:
```<code>File directory = new File("/user/folder");
File[] myarray;
myarray=new File[10];
myarray=directory.listFiles();
for (int j = 0; j < myarray.length; j++)
{
       File path=myarray[j];
       FileReader fr = new FileReader(path);
       BufferedReader br = new BufferedReader(fr);
       String s = "";
       while (br.ready()) {
          s += br.readLine() + "\n";
       }
}
</code>```


问:
Set HTML img attribute to Angular binding
Inside the HTML class for my Angular component, I have an image displaying with:

```<code><div class="row" id="work">
  <div class="col-xl-3 col-lg-4 col-md-6 col-sm-12" id="">
      <img class="img-fluid" width="100%" [height]="height" src="assets/images/logo.png" alt="">
      <img class="img-fluid" width="100%" height="100" src="assets/images/logo.png" alt="">
      <img class="img-fluid" width="100%" height="100" src="assets/images/logo.png" alt="">
  </div>
</div>
</code>```

In my typescript file for the component, I have a height variable being set to "100" on init.

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  height = "500";

  constructor() { }

  ngOnInit() {
    this.height = "500";
  }
}
</code>```

On page load, the image height is equal to the default images height, it it not reading/using my height variable. Probably something silly, but not sure what.

EDIT:

"img-fluid" was the problem. It ignores the height attribute, sets height to auto, so I couldnt set it myself from Typescript.

答: The "img-fluid" tag was the problem. It ignores the height attribute, sets height to auto, so I couldnt set it myself with Typescript.</p>

Body:
Inside the HTML class for my Angular component, I have an image displaying with:

In my typescript file for the component, I have a height variable being set to "100" on init.

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  height = "500";

  constructor() { }

  ngOnInit() {
    this.height = "500";
  }
}

On page load, the image height is equal to the default images height, it it not reading/using my height variable. Probably something silly, but not sure what.

EDIT:

"img-fluid" was the problem. It ignores the height attribute, sets height to auto, so I couldnt set it myself from Typescript.


问:
Avoid jpa fetch eager with join table
I have the next classes:

A class User:

```<code>@Entity
@JsonRootName(value = "user")
@Table(name = "web_users", schema = "t_dw_comercial")
public class User {

   @Id
   private int userId;

   private String fullName;

   private String ldapId;

   private String email;

   @ManyToOne
    @JoinColumn(name= "u_type", nullable=false)
    private Role uType;

    private String deleteFlag;

    private String typeAccess;

    @OneToMany(fetch=FetchType.LAZY)
    @JoinTable(name="web_users_roles",
    joinColumns = {@JoinColumn(name="user_id")},
    inverseJoinColumns = {@JoinColumn(name="role_id")}
    )
    private List<Role> roles;

}
</code>```

A class Role:

```<code>@Entity
@JsonRootName(value = "roles")
@Table(name = "web_roles", schema = "t_dw_comercial")
public class Role {

   @Id
   private int roleId;

   private String roleName;

   @OneToMany
   @JoinTable(name="web_users_roles",
        joinColumns = {@JoinColumn(name="user_id")},
        inverseJoinColumns = {@JoinColumn(name="role_id")})
   private List<Section> sections = new ArrayList<Section>();

}
</code>```

Service:

```<code>@Service
public class UserService implements IUserService{

    @Autowired
    UserRepository repository;

    public User findUserByLdapId(String loginName) {

        return repository.findUserByLdapId(loginName);
    }
}
</code>```

Repository:

```<code>@Repository
public interface UserRepository extends CrudRepository<User, Long>{

    @Query("SELECT u FROM User u where u.ldapId= ?1")
public User findUserByLdapId(String loginName);

}
</code>```

Controller:

```<code>@Controller
@RestController
public class UserController {

    @Autowired
    private IUserService userService;

    @CrossOrigin
    @RequestMapping(value = "/dashboard", params = {"user"}, method = RequestMethod.GET,  produces = "application/json")
    public ResponseEntity<User>  getUser(@RequestParam(value = "user") String ldapId) {

        User user =  userService.findUserByLdapId(ldapId);

        if(user == null)
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);

        return new ResponseEntity<>(user, HttpStatus.OK);

    };
}
</code>```

As you can see I have a role in a user and a list of roles. The one called uType would be something like a main role, and the list, secondary roles. I know that this role will appear twice but I don't care about it at all.

I would like to have the main role fetched eager and the list of roles fetched lazy, on demand, is it possible?

So a json would looks like:

```<code>{
    "user": {
        "userId": 1,
        "fullName": "Carolina Ponce",
        "ldapId": "f8cygqn",
        "email": "carolina@blabla.com",
        "uType": {
            "roleId": 1,
            "roleName": "Admin",
            "sections": [
                {
                    "sectionId": 2,
                    "sectionName": "Admin",
                    "components": []
                },
                {
                    "sectionId": 1,
                    "sectionName": "Dashboard",
                    "components": [
                        {
                            "componentId": 2,
                            "componentName": "Provincia",
                            "jsonArray": [
                                {
                                    "ID": "6",
                                    "NAME": "BUENOS AIRES"
                                }
                            ]
                        },
                        {
                            "componentId": 1,
                            "componentName": "Rubros",
                            "jsonArray": [
                                {
                                    "ID": "1",
                                    "NAME": "Automotriz"
                                },
                                {
                                    "ID": "31",
                                    "NAME": "Universidades"
                                }
                            ]
                        }
                    ]
                }
            ]
        },
        "deleteFlag": "",
        "typeAccess": ""
    }
}
</code>```

Thanks in advance!

答:
I'm not sure if I understand your questions correctly as Jpa/Hibernate does this by default. All *ToOne relationships are eager by default, while all *ToMany are lazy by default.

From the docs of @OneToMany.

```<code>public abstract FetchType fetch

    (Optional) Whether the association should be lazily loaded or must be eagerly
    fetched. The EAGER strategy is a requirement on the persistence provider runtime
    that the associated entities must be eagerly fetched. The LAZY strategy is a
    hint to the persistence provider runtime.

Default:
    javax.persistence.FetchType.LAZY
</code>```

And from the docs of @ManyToOne

```<code>public abstract FetchType fetch

   (Optional) Whether the association should be lazily loaded or must be eagerly
   fetched. The EAGER strategy is a requirement on the persistence provider runtime
   that the associated entity must be eagerly fetched. The LAZY strategy is a hint
   to the persistence provider runtime.

Default:
   javax.persistence.FetchType.EAGER
</code>```

Title: Avoid jpa fetch eager with join table

Body:
I have the next classes:

A class User:

@Entity
@JsonRootName(value = "user")
@Table(name = "web_users", schema = "t_dw_comercial")
public class User {

   @Id
   private int userId;

   private String fullName;

   private String ldapId;

   private String email;

   @ManyToOne
    @JoinColumn(name= "u_type", nullable=false)
    private Role uType;

    private String deleteFlag;

    private String typeAccess;

    @OneToMany(fetch=FetchType.LAZY)
    @JoinTable(name="web_users_roles",
    joinColumns = {@JoinColumn(name="user_id")},
    inverseJoinColumns = {@JoinColumn(name="role_id")}
    )
    private List<Role> roles;

}

A class Role:

@Entity
@JsonRootName(value = "roles")
@Table(name = "web_roles", schema = "t_dw_comercial")
public class Role {

   @Id
   private int roleId;

   private String roleName;

   @OneToMany
   @JoinTable(name="web_users_roles",
        joinColumns = {@JoinColumn(name="user_id")},
        inverseJoinColumns = {@JoinColumn(name="role_id")})
   private List
 sections = new ArrayList
();

}

Service:

@Service
public class UserService implements IUserService{

    @Autowired
    UserRepository repository;

    public User findUserByLdapId(String loginName) {

        return repository.findUserByLdapId(loginName);
    }
}

Repository:

@Repository
public interface UserRepository extends CrudRepository<User, Long>{

    @Query("SELECT u FROM User u where u.ldapId= ?1")
public User findUserByLdapId(String loginName);

}

Controller:

@Controller
@RestController
public class UserController {

    @Autowired
    private IUserService userService;

    @CrossOrigin
    @RequestMapping(value = "/dashboard", params = {"user"}, method = RequestMethod.GET,  produces = "application/json")
    public ResponseEntity<User>  getUser(@RequestParam(value = "user") String ldapId) {

        User user =  userService.findUserByLdapId(ldapId);

        if(user == null)
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);

        return new ResponseEntity<>(user, HttpStatus.OK);

    };
}

As you can see I have a role in a user and a list of roles. The one called uType would be something like a main role, and the list, secondary roles. I know that this role will appear twice but I don't care about it at all.

I would like to have the main role fetched eager and the list of roles fetched lazy, on demand, is it possible?

So a json would looks like:

{
    "user": {
        "userId": 1,
        "fullName": "Carolina Ponce",
        "ldapId": "f8cygqn",
        "email": "carolina@blabla.com",
        "uType": {
            "roleId": 1,
            "roleName": "Admin",
            "sections": [
                {
                    "sectionId": 2,
                    "sectionName": "Admin",
                    "components": []
                },
                {
                    "sectionId": 1,
                    "sectionName": "Dashboard",
                    "components": [
                        {
                            "componentId": 2,
                            "componentName": "Provincia",
                            "jsonArray": [
                                {
                                    "ID": "6",
                                    "NAME": "BUENOS AIRES"
                                }
                            ]
                        },
                        {
                            "componentId": 1,
                            "componentName": "Rubros",
                            "jsonArray": [
                                {
                                    "ID": "1",
                                    "NAME": "Automotriz"
                                },
                                {
                                    "ID": "31",
                                    "NAME": "Universidades"
                                }
                            ]
                        }
                    ]
                }
            ]
        },
        "deleteFlag": "",
        "typeAccess": ""
    }
}

Thanks in advance!

Body:
I'm not sure if I understand your questions correctly as Jpa/Hibernate does this by default. All *ToOne relationships are eager by default, while all *ToMany are lazy by default.

From the docs of @OneToMany.

public abstract FetchType fetch

    (Optional) Whether the association should be lazily loaded or must be eagerly
    fetched. The EAGER strategy is a requirement on the persistence provider runtime
    that the associated entities must be eagerly fetched. The LAZY strategy is a
    hint to the persistence provider runtime.

Default:
    javax.persistence.FetchType.LAZY

And from the docs of @ManyToOne

public abstract FetchType fetch

   (Optional) Whether the association should be lazily loaded or must be eagerly
   fetched. The EAGER strategy is a requirement on the persistence provider runtime
   that the associated entity must be eagerly fetched. The LAZY strategy is a hint
   to the persistence provider runtime.

Default:
   javax.persistence.FetchType.EAGER


问:
class method triggered without being called
I've defined a class to handle playing audio files. I'm instantiating the class, and calling its addEventListener() method at which time, playSound() is being triggered without the element being tapped. Also, when I call getEventListeners(bgMusic.elem) - the listener is no longer attached.

```<code>class WebAudio {

    constructor(soundFile, elem) {
        this.soundFile = soundFile;
        this.elem = elem;
        this.audio = new Audio('sound/' + this.soundFile);
    }

    addListener() {
        this.elem.addEventListener('touchstart', this.playSound());
    }

    playSound() {
        if (context.state != 'suspended') {
            console.log('playing audio file');
            if (!this.audio.playing) {
                this.audio.play();
            }
        } else {
            console.log("Audio Context locked? " + context.state)
        }
    }

}

var AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new AudioContext();
function webAudioTouchUnlock(context) {
    return new Promise( (resolve, reject) => {
        //if AudioContext is suspended, and window has been interacted with
        if (context.state === 'suspended' && 'ontouchstart' in window) {
           console.log(context.state);
           var unlock = () => {
               //resume AudioContext (allow playing sound), remove event listeners
               context.resume().then(() => {
                   console.log("context resumed");
                   document.body.removeEventListener('touchstart', unlock);
                   document.body.removeEventListener('touchend', unlock);
                   resolve(true);
               }, function (reason) {
                 reject(reason);
               });
           };
           document.body.addEventListener('touchstart', unlock, false);
           document.body.addEventListener('touchend', unlock, false);
       } else {
           console.log('context not suspended? Context is ' + context.state);
           resolve(false);
       }
    });
}

webAudioTouchUnlock(context);
let bgMusic = new WebAudio('bensound-clearday.mp3', document.querySelector('#sound_button'));
bgMusic.addListener();
</code>```

答:
When you add the event listener like:

```<code> this.elem.addEventListener('touchstart', this.playSound());
</code>```

You care calling the function: this.playSound() and adding the result of that function (undefined) as the listener.

You just want to add the reference to the function:

```<code>this.elem.addEventListener('touchstart', this.playSound);
</code>```

so the listener can call it when it needs too.

Also you will probably need to use something like this to maintain the proper this:

```<code>this.elem.addEventListener('touchstart', () => this.playSound());
</code>```

or:

```<code>this.elem.addEventListener('touchstart', this.playSound.bind(this));
</code>```

Body:
I've defined a class to handle playing audio files. I'm instantiating the class, and calling its addEventListener() method at which time, playSound() is being triggered without the element being tapped. Also, when I call getEventListeners(bgMusic.elem) - the listener is no longer attached.

class WebAudio {

    constructor(soundFile, elem) {
        this.soundFile = soundFile;
        this.elem = elem;
        this.audio = new Audio('sound/' + this.soundFile);
    }

    addListener() {
        this.elem.addEventListener('touchstart', this.playSound());
    }

    playSound() {
        if (context.state != 'suspended') {
            console.log('playing audio file');
            if (!this.audio.playing) {
                this.audio.play();
            }
        } else {
            console.log("Audio Context locked? " + context.state)
        }
    }

}

var AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new AudioContext();
function webAudioTouchUnlock(context) {
    return new Promise( (resolve, reject) => {
        //if AudioContext is suspended, and window has been interacted with
        if (context.state === 'suspended' && 'ontouchstart' in window) {
           console.log(context.state);
           var unlock = () => {
               //resume AudioContext (allow playing sound), remove event listeners
               context.resume().then(() => {
                   console.log("context resumed");
                   document.body.removeEventListener('touchstart', unlock);
                   document.body.removeEventListener('touchend', unlock);
                   resolve(true);
               }, function (reason) {
                 reject(reason);
               });
           };
           document.body.addEventListener('touchstart', unlock, false);
           document.body.addEventListener('touchend', unlock, false);
       } else {
           console.log('context not suspended? Context is ' + context.state);
           resolve(false);
       }
    });
}

webAudioTouchUnlock(context);
let bgMusic = new WebAudio('bensound-clearday.mp3', document.querySelector('#sound_button'));
bgMusic.addListener();

Body:
When you add the event listener like:

 this.elem.addEventListener('touchstart', this.playSound());

You care calling the function: this.playSound() and adding the result of that function (undefined) as the listener.

You just want to add the reference to the function:

this.elem.addEventListener('touchstart', this.playSound);

so the listener can call it when it needs too.

Also you will probably need to use something like this to maintain the proper this:

this.elem.addEventListener('touchstart', () => this.playSound());

or:

this.elem.addEventListener('touchstart', this.playSound.bind(this));


问:
Grouping Joined Tables
I am trying to join the products and attributes tables and group them by product id in order to get a list of products with their attributes. So I tried the following Entity Framework query:

```<code>    var productsWithAttributes = (from product in ctx.products
                                  join attribute in ctx.attributes on product.id equals attribute.productId
                                  select new
                                     {
                                          product = product,
                                          a1 = attribute.a1,
                                          a2 = attribute.a2,
                                          a3 = attribute.a3,
                                          a4 = attribute.a4
                                  } into t
                                  group t by t.product.id into g
                                     select new
                                     {
                                         product = g.Select(p => p.product).FirstOrDefault(),
                                         attributes = g.Select(r => new Attr()
                                         {
                                             a1 = r.a1,
                                             a2 = r.a2,
                                             a3 = r.a3,
                                             a4 = r.a4
                                         }).ToList()
                                     }
                                    ).ToList();
</code>```

But this took around 70 minutes and when I looked into the SQL query it produced, I saw tens of subqueries with tens of joins.

Then I tried just to do the grouping on the sql server and did the projection into the desired structure on the application server. And this is the EF code for that:

```<code>    var productsWithAttributes = (from product in ctx.products
                                  join attribute in ctx.attributes on product.id equals attribute.productId
                                  select new
                                      {
                                          product = product,
                                          a1 = attribute.a1,
                                          a2 = attribute.a2,
                                          a3 = attribute.a3,
                                          a4 = attribute.a4
                                  } into t
                                      group t by t.product.id

                            ).ToList();
</code>```

This took around 3 minutes. But the SQL prodcued by this query still looked complex with multiple subqueries and joins. I would epect something along the lines of:

```<code>select product.*, attribute.a1, attribute.a2, attribute.a3, attribute.a4
from product
join attribute on product.id = attribute.productId
group by product.id
</code>```

Then I tried just the join without grouping:

```<code>    var productsWithAttributes = (from product in ctx.products
                                      join attribute in ctx.attributes on product.id equals attribute.productId
                                      select new
                                      {
                                          product = product,
                                          a1 = attribute.a1,
                                          a2 = attribute.a2,
                                          a3 = attribute.a3,
                                          a4 = attribute.a4,

                                      }
                                    ).ToList();
</code>```

This took 1.5 minutes and the SQL code produced by EF was as expected.

In short, adding grouping to the join creates a convoluted SQL query which takes longer but it is still acceptable in terms of performance. But adding the final projection after this grouping produces an increadibly convoluted SQL query that takes and unaccepytable amount of time.

What is the correct way of creating this query with EF?

答: If you want to create joined tables then all you have to do is create another table with both pk(Primay keys) and full join them instead of inner joining them or just joinig.</p>

Title: Grouping Joined Tables

Body:
I am trying to join the products and attributes tables and group them by product id in order to get a list of products with their attributes. So I tried the following Entity Framework query:

    var productsWithAttributes = (from product in ctx.products
                                  join attribute in ctx.attributes on product.id equals attribute.productId
                                  select new
                                     {
                                          product = product,
                                          a1 = attribute.a1,
                                          a2 = attribute.a2,
                                          a3 = attribute.a3,
                                          a4 = attribute.a4
                                  } into t
                                  group t by t.product.id into g
                                     select new
                                     {
                                         product = g.Select(p => p.product).FirstOrDefault(),
                                         attributes = g.Select(r => new Attr()
                                         {
                                             a1 = r.a1,
                                             a2 = r.a2,
                                             a3 = r.a3,
                                             a4 = r.a4
                                         }).ToList()
                                     }
                                    ).ToList();

But this took around 70 minutes and when I looked into the SQL query it produced, I saw tens of subqueries with tens of joins.

Then I tried just to do the grouping on the sql server and did the projection into the desired structure on the application server. And this is the EF code for that:

    var productsWithAttributes = (from product in ctx.products
                                  join attribute in ctx.attributes on product.id equals attribute.productId
                                  select new
                                      {
                                          product = product,
                                          a1 = attribute.a1,
                                          a2 = attribute.a2,
                                          a3 = attribute.a3,
                                          a4 = attribute.a4
                                  } into t
                                      group t by t.product.id

                            ).ToList();

This took around 3 minutes. But the SQL prodcued by this query still looked complex with multiple subqueries and joins. I would epect something along the lines of:

select product.*, attribute.a1, attribute.a2, attribute.a3, attribute.a4
from product
join attribute on product.id = attribute.productId
group by product.id

Then I tried just the join without grouping:

    var productsWithAttributes = (from product in ctx.products
                                      join attribute in ctx.attributes on product.id equals attribute.productId
                                      select new
                                      {
                                          product = product,
                                          a1 = attribute.a1,
                                          a2 = attribute.a2,
                                          a3 = attribute.a3,
                                          a4 = attribute.a4,

                                      }
                                    ).ToList();

This took 1.5 minutes and the SQL code produced by EF was as expected.

In short, adding grouping to the join creates a convoluted SQL query which takes longer but it is still acceptable in terms of performance. But adding the final projection after this grouping produces an increadibly convoluted SQL query that takes and unaccepytable amount of time.

What is the correct way of creating this query with EF?


问:
GORM - get raw DB value for domain class properties
I'm using GORM for MongoDB in my Grails 3 web-app to manage read/writes from DB.

I have the following 2 domain classes:

```<code>class Company {
  String id
}

class Team {
  String id
  Company company
}
</code>```

For teams, their company is saved on DB as String, and with GORM I can simply use team.company to get an instance of Company domain class.

However, I need to override the getter for company, and I need the raw value for company id (as stored on DB), without GORM getting in the way and performing its magic.
Is there a way to get the raw String value?

Any help is welcome! Thanks in advance

Update (May 27)

Investigating @TaiwaneseDavidCheng suggestion, I updated my code to

```<code>class Company {
  String id
}

class Team {
  String id
  Company company
  String companyId

  static mapping = {
    company       attr: "company"    // optional
    companyId     attr: "company", insertable: false, updateable: false
  }
}
</code>```

Please note that I'm using GORM for MongoDB, which (citing the manual) tries to be as compatible as possible with GORM for Hibernate, but requires a slightly different implementation.

However I found out (by trial&error) that GORM for MongoDB doesn't support a similar solution, as it seems only one property at a time can be mapped to a MongoDB document property.

In particular the last property in alphabetical order wins, e.g. companyId in my example.

I figured out a way to make the whole thing work, I'm posting my own answer below.

答:
(Follows the edit to my question above)

I defined a custom mapping, and made use of Grails transients by also defining custom getter and setter for team's company.

```<code>class Company {
  String id
}

class Team {
  String id
  Company company
  String companyId

  static mapping = {
    companyId     attr: "company"    // match against MongoDB property
  }

  static transients = [ 'company' ]  // non-persistent property

  Company getCompany() {
    return Company.get(companyId)
  }
  void setCompany(Company company) {
    companyId = company.id
  }

}
</code>```

Body:
I'm using GORM for MongoDB in my Grails 3 web-app to manage read/writes from DB.

I have the following 2 domain classes:

class Company {
  String id
}

class Team {
  String id
  Company company
}

For teams, their company is saved on DB as String, and with GORM I can simply use team.company to get an instance of Company domain class.

However, I need to override the getter for company, and I need the raw value for company id (as stored on DB), without GORM getting in the way and performing its magic.
Is there a way to get the raw String value?

Any help is welcome! Thanks in advance

Update (May 27)

Investigating @TaiwaneseDavidCheng suggestion, I updated my code to

class Company {
  String id
}

class Team {
  String id
  Company company
  String companyId

  static mapping = {
    company       attr: "company"    // optional
    companyId     attr: "company", insertable: false, updateable: false
  }
}

Please note that I'm using GORM for MongoDB, which (citing the manual) tries to be as compatible as possible with GORM for Hibernate, but requires a slightly different implementation.

However I found out (by trial&error) that GORM for MongoDB doesn't support a similar solution, as it seems only one property at a time can be mapped to a MongoDB document property.

In particular the last property in alphabetical order wins, e.g. companyId in my example.

I figured out a way to make the whole thing work, I'm posting my own answer below.

Body:
(Follows the edit to my question above)

I defined a custom mapping, and made use of Grails transients by also defining custom getter and setter for team's company.

class Company {
  String id
}

class Team {
  String id
  Company company
  String companyId

  static mapping = {
    companyId     attr: "company"    // match against MongoDB property
  }

  static transients = [ 'company' ]  // non-persistent property

  Company getCompany() {
    return Company.get(companyId)
  }
  void setCompany(Company company) {
    companyId = company.id
  }

}


问:
spring-cloud-dataflow: Stream Deployments Fail on OSX
I am unable to deploy and execute a basic http | log stream following the
getting-started stream guide:

```<code>wget https://raw.githubusercontent.com/spring-cloud/spring-cloud-dataflow/2.1.0.RELEASE/spring-cloud-dataflow-server/docker-compose.yml;
export DATAFLOW_VERSION=2.1.0.RELEASE;
export SKIPPER_VERSION=2.0.2.RELEASE;
docker-compose up;
open http://localhost:9393/dashboard/#/streams/create;
echo "Then, create a stream via text input: `http | log`"
echo "Then, deploy the stream. The deployment fails with exit code 137."
</code>```

I get the green "Successfully deployed stream definition".
The status shows as "Deploying", but it never fully deploys.
There are no ERROR messages in the logs, in the UI, or in the network requests.

Here is the console output of docker-compose up after I deploy the stream.

```<code>skipper              | 2019-05-24 22:31:53.363  INFO 1 --- [io-7577-exec-10] o.s.s.support.LifecycleObjectSupport     : started UPGRADE UPGRADE_DEPLOY_TARGET_APPS_SUCCEED UPGRADE_DEPLOY_TARGET_APPS UPGRADE_START UPGRADE_DELETE_SOURCE_APPS UPGRADE_CHECK_TARGET_APPS UPGRADE_WAIT_TARGET_APPS UPGRADE_CANCEL UPGRADE_DEPLOY_TARGET_APPS_FAILED UPGRADE_CHECK_CHOICE UPGRADE_EXIT INSTALL INSTALL_INSTALL INSTALL_EXIT ERROR DELETE DELETE_DELETE DELETE_EXIT ROLLBACK ROLLBACK_START ROLLBACK_EXIT_INSTALL ROLLBACK_EXIT ROLLBACK_EXIT_UPGRADE ROLLBACK_CHOICE INITIAL ERROR_JUNCTION  /  / uuid=f1ca31f2-ddcf-4203-88c8-de367c104151 / id=http-log-ingest-5
skipper              | 2019-05-24 22:31:53.504  INFO 1 --- [eTaskExecutor-1] o.s.c.s.s.s.StateMachineConfiguration    : Entering state ObjectState [getIds()=[INITIAL], getClass()=class org.springframework.statemachine.state.ObjectState, hashCode()=1038812346, toString()=AbstractState [id=INITIAL, pseudoState=org.springframework.statemachine.state.DefaultPseudoState@12280a0a, deferred=[], entryActions=[], exitActions=[org.springframework.cloud.skipper.server.statemachine.ResetVariablesAction@6fd12c5], stateActions=[], regions=[], submachine=null]]
skipper              | 2019-05-24 22:31:53.540  INFO 1 --- [eTaskExecutor-3] o.s.c.s.s.s.StateMachineConfiguration    : Entering state StateMachineState [getIds()=[INSTALL], toString()=AbstractState [id=INSTALL, pseudoState=null, deferred=[], entryActions=[], exitActions=[], stateActions=[], regions=[], submachine=INSTALL_INSTALL INSTALL_EXIT  /  / uuid=fbcafd74-2879-4e86-81da-8372a5be31be / id=http-log-ingest-5], getClass()=class org.springframework.statemachine.state.StateMachineState]
skipper              | 2019-05-24 22:31:53.576  INFO 1 --- [eTaskExecutor-3] o.s.c.s.s.s.StateMachineConfiguration    : Entering state ObjectState [getIds()=[INSTALL_INSTALL], getClass()=class org.springframework.statemachine.state.ObjectState, hashCode()=1643670584, toString()=AbstractState [id=INSTALL_INSTALL, pseudoState=org.springframework.statemachine.state.DefaultPseudoState@12493450, deferred=[], entryActions=[org.springframework.cloud.skipper.server.statemachine.InstallInstallAction@149debbb], exitActions=[], stateActions=[], regions=[], submachine=null]]
skipper              | 2019-05-24 22:31:54.117  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Preparing to run an application from org.springframework.cloud.stream.app:log-sink-kafka:jar:2.1.1.RELEASE. This may take some time if the artifact must be downloaded from a remote host.
skipper              | 2019-05-24 22:31:54.179  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Command to be executed: /opt/openjdk/bin/java -jar /root/.m2/repository/org/springframework/cloud/stream/app/log-sink-kafka/2.1.1.RELEASE/log-sink-kafka-2.1.1.RELEASE.jar
skipper              | 2019-05-24 22:31:54.203  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Deploying app with deploymentId http-log-ingest-5.log-v1 instance 0.
skipper              |    Logs will be in /tmp/spring-cloud-deployer-3633167379998955348/http-log-ingest-5-1558737114000/http-log-ingest-5.log-v1
skipper              | 2019-05-24 22:31:54.310  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Preparing to run an application from org.springframework.cloud.stream.app:http-source-kafka:jar:2.1.0.RELEASE. This may take some time if the artifact must be downloaded from a remote host.
skipper              | 2019-05-24 22:31:54.312  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Command to be executed: /opt/openjdk/bin/java -jar /root/.m2/repository/org/springframework/cloud/stream/app/http-source-kafka/2.1.0.RELEASE/http-source-kafka-2.1.0.RELEASE.jar
skipper              | 2019-05-24 22:31:54.313  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Deploying app with deploymentId http-log-ingest-5.http-v1 instance 0.
skipper              |    Logs will be in /tmp/spring-cloud-deployer-3633167379998955348/http-log-ingest-5-1558737114208/http-log-ingest-5.http-v1
skipper              | 2019-05-24 22:31:54.369  INFO 1 --- [eTaskExecutor-3] o.s.s.support.LifecycleObjectSupport     : stopped org.springframework.statemachine.support.DefaultStateMachineExecutor@2c9d52c5
skipper              | 2019-05-24 22:31:54.370  INFO 1 --- [eTaskExecutor-3] o.s.s.support.LifecycleObjectSupport     : stopped INSTALL_INSTALL INSTALL_EXIT  /  / uuid=fbcafd74-2879-4e86-81da-8372a5be31be / id=http-log-ingest-5
skipper              | 2019-05-24 22:31:54.371  INFO 1 --- [eTaskExecutor-3] o.s.c.s.s.s.StateMachineConfiguration    : Entering state ObjectState [getIds()=[INITIAL], getClass()=class org.springframework.statemachine.state.ObjectState, hashCode()=1038812346, toString()=AbstractState [id=INITIAL, pseudoState=org.springframework.statemachine.state.DefaultPseudoState@12280a0a, deferred=[], entryActions=[], exitActions=[org.springframework.cloud.skipper.server.statemachine.ResetVariablesAction@6fd12c5], stateActions=[], regions=[], submachine=null]]
skipper              | 2019-05-24 22:31:54.372  INFO 1 --- [eTaskExecutor-3] o.s.c.s.s.s.SkipperStateMachineService   : setting future value org.springframework.cloud.skipper.domain.Release@279e0d49
skipper              | 2019-05-24 22:31:54.373  INFO 1 --- [eTaskExecutor-3] o.s.s.support.LifecycleObjectSupport     : started org.springframework.statemachine.support.DefaultStateMachineExecutor@2c9d52c5
skipper              | 2019-05-24 22:31:54.373  INFO 1 --- [eTaskExecutor-3] o.s.s.support.LifecycleObjectSupport     : started INSTALL_INSTALL INSTALL_EXIT  /  / uuid=fbcafd74-2879-4e86-81da-8372a5be31be / id=http-log-ingest-5
mysql_1              | 2019-05-24T22:32:45.648870Z 0 [Note] InnoDB: page_cleaner: 1000ms intended loop took 4662ms. The settings might not be optimal. (flushed=2 and evicted=0, during the time.)
zookeeper_1          | [2019-05-24 22:32:52,733] INFO Expiring session 0x10001d6560e0001, timeout of 6000ms exceeded (org.apache.zookeeper.server.ZooKeeperServer)
mysql_1              | 2019-05-24T22:33:08.378945Z 0 [Note] InnoDB: page_cleaner: 1000ms intended loop took 7338ms. The settings might not be optimal. (flushed=1 and evicted=0, during the time.)
mysql_1              | 2019-05-24T22:33:24.272169Z 0 [Note] InnoDB: page_cleaner: 1000ms intended loop took 5118ms. The settings might not be optimal. (flushed=0 and evicted=0, during the time.)
zookeeper_1          | [2019-05-24 22:33:28,644] INFO Processed session termination for sessionid: 0x10001d6560e0001 (org.apache.zookeeper.server.PrepRequestProcessor)
kafka_1              | [2019-05-24 22:33:40,709] INFO [GroupMetadataManager brokerId=1001] Removed 0 expired offsets in 2216 milliseconds. (kafka.coordinator.group.GroupMetadataManager)
kafka_1              | [2019-05-24 22:33:49,359] WARN Client session timed out, have not heard from server in 58623ms for sessionid 0x10001d6560e0001 (org.apache.zookeeper.ClientCnxn)
kafka_1              | [2019-05-24 22:33:56,611] TRACE [Controller id=1001] Checking need to trigger auto leader balancing (kafka.controller.KafkaController)
kafka_1              | [2019-05-24 22:34:06,529] DEBUG [Controller id=1001] Preferred replicas by broker Map(1001 -> Map(__consumer_offsets-22 -> Vector(1001), __consumer_offsets-30 -> Vector(1001), __consumer_offsets-8 -> Vector(1001), __consumer_offsets-21 -> Vector(1001), __consumer_offsets-4 -> Vector(1001), __consumer_offsets-27 -> Vector(1001), __consumer_offsets-7 -> Vector(1001), __consumer_offsets-9 -> Vector(1001), __consumer_offsets-46 -> Vector(1001), http-ingest-log-4.http-0 -> Vector(1001), __consumer_offsets-25 -> Vector(1001), __consumer_offsets-35 -> Vector(1001), __consumer_offsets-41 -> Vector(1001), __consumer_offsets-33 -> Vector(1001), __consumer_offsets-23 -> Vector(1001), __consumer_offsets-49 -> Vector(1001), __consumer_offsets-47 -> Vector(1001), __consumer_offsets-16 -> Vector(1001), __consumer_offsets-28 -> Vector(1001), __consumer_offsets-31 -> Vector(1001), __consumer_offsets-36 -> Vector(1001), __consumer_offsets-42 -> Vector(1001), __consumer_offsets-3 -> Vector(1001), __consumer_offsets-18 -> Vector(1001), __consumer_offsets-37 -> Vector(1001), http-ingest-log-3.http-0 -> Vector(1001), __consumer_offsets-15 -> Vector(1001), __consumer_offsets-24 -> Vector(1001), __consumer_offsets-38 -> Vector(1001), __consumer_offsets-17 -> Vector(1001), __consumer_offsets-48 -> Vector(1001), __confluent.support.metrics-0 -> Vector(1001), __consumer_offsets-19 -> Vector(1001), __consumer_offsets-11 -> Vector(1001), __consumer_offsets-13 -> Vector(1001), __consumer_offsets-2 -> Vector(1001), __consumer_offsets-43 -> Vector(1001), __consumer_offsets-6 -> Vector(1001), __consumer_offsets-14 -> Vector(1001), __consumer_offsets-20 -> Vector(1001), __consumer_offsets-0 -> Vector(1001), __consumer_offsets-44 -> Vector(1001), __consumer_offsets-39 -> Vector(1001), __consumer_offsets-12 -> Vector(1001), __consumer_offsets-45 -> Vector(1001), __consumer_offsets-1 -> Vector(1001), __consumer_offsets-5 -> Vector(1001), __consumer_offsets-26 -> Vector(1001), __consumer_offsets-29 -> Vector(1001), __consumer_offsets-34 -> Vector(1001), __consumer_offsets-10 -> Vector(1001), __consumer_offsets-32 -> Vector(1001), __consumer_offsets-40 -> Vector(1001))) (kafka.controller.KafkaController)
kafka_1              | [2019-05-24 22:34:11,269] DEBUG [Controller id=1001] Topics not in preferred replica for broker 1001 Map() (kafka.controller.KafkaController)
kafka_1              | [2019-05-24 22:34:11,993] TRACE [Controller id=1001] Leader imbalance ratio for broker 1001 is 0.0 (kafka.controller.KafkaController)
kafka_1              | [2019-05-24 22:34:23,483] INFO Client session timed out, have not heard from server in 58623ms for sessionid 0x10001d6560e0001, closing socket connection and attempting reconnect (org.apache.zookeeper.ClientCnxn)
mysql_1              | 2019-05-24T22:35:19.628193Z 0 [Note] InnoDB: page_cleaner: 1000ms intended loop took 4049ms. The settings might not be optimal. (flushed=0 and evicted=0, during the time.)
...
(several minutes later)
...
dataflow-server exited with code 137
</code>```

I get the same behavior when swapping out different parts of the stack; for example RabbitMQ for Kafka/Zookeeper, Postgres for MySQL.

My local stack:

OSX 10.14

Java openjdk 11.0.2

Docker engine 18.09.2

Docker Compose 1.23.2

Docker Machine 0.16.1

答:
The Docker Compose console won't include the exact reasoning as to what failed and why.

When the stream is deploying, you could view the application logs with the following command.

docker exec -it skipper tail -f /path/from/stdout/textbox/in/dashboard

That would indicate whether or not the applications start and specific reasoning, which would help in troubleshooting.

Body:
I am unable to deploy and execute a basic http | log stream following the
getting-started stream guide:

wget https://raw.githubusercontent.com/spring-cloud/spring-cloud-dataflow/2.1.0.RELEASE/spring-cloud-dataflow-server/docker-compose.yml;
export DATAFLOW_VERSION=2.1.0.RELEASE;
export SKIPPER_VERSION=2.0.2.RELEASE;
docker-compose up;
open http://localhost:9393/dashboard/#/streams/create;
echo "Then, create a stream via text input: `http | log`"
echo "Then, deploy the stream. The deployment fails with exit code 137."

I get the green "Successfully deployed stream definition".
The status shows as "Deploying", but it never fully deploys.
There are no ERROR messages in the logs, in the UI, or in the network requests.

Here is the console output of docker-compose up after I deploy the stream.

skipper              | 2019-05-24 22:31:53.363  INFO 1 --- [io-7577-exec-10] o.s.s.support.LifecycleObjectSupport     : started UPGRADE UPGRADE_DEPLOY_TARGET_APPS_SUCCEED UPGRADE_DEPLOY_TARGET_APPS UPGRADE_START UPGRADE_DELETE_SOURCE_APPS UPGRADE_CHECK_TARGET_APPS UPGRADE_WAIT_TARGET_APPS UPGRADE_CANCEL UPGRADE_DEPLOY_TARGET_APPS_FAILED UPGRADE_CHECK_CHOICE UPGRADE_EXIT INSTALL INSTALL_INSTALL INSTALL_EXIT ERROR DELETE DELETE_DELETE DELETE_EXIT ROLLBACK ROLLBACK_START ROLLBACK_EXIT_INSTALL ROLLBACK_EXIT ROLLBACK_EXIT_UPGRADE ROLLBACK_CHOICE INITIAL ERROR_JUNCTION  /  / uuid=f1ca31f2-ddcf-4203-88c8-de367c104151 / id=http-log-ingest-5
skipper              | 2019-05-24 22:31:53.504  INFO 1 --- [eTaskExecutor-1] o.s.c.s.s.s.StateMachineConfiguration    : Entering state ObjectState [getIds()=[INITIAL], getClass()=class org.springframework.statemachine.state.ObjectState, hashCode()=1038812346, toString()=AbstractState [id=INITIAL, pseudoState=org.springframework.statemachine.state.DefaultPseudoState@12280a0a, deferred=[], entryActions=[], exitActions=[org.springframework.cloud.skipper.server.statemachine.ResetVariablesAction@6fd12c5], stateActions=[], regions=[], submachine=null]]
skipper              | 2019-05-24 22:31:53.540  INFO 1 --- [eTaskExecutor-3] o.s.c.s.s.s.StateMachineConfiguration    : Entering state StateMachineState [getIds()=[INSTALL], toString()=AbstractState [id=INSTALL, pseudoState=null, deferred=[], entryActions=[], exitActions=[], stateActions=[], regions=[], submachine=INSTALL_INSTALL INSTALL_EXIT  /  / uuid=fbcafd74-2879-4e86-81da-8372a5be31be / id=http-log-ingest-5], getClass()=class org.springframework.statemachine.state.StateMachineState]
skipper              | 2019-05-24 22:31:53.576  INFO 1 --- [eTaskExecutor-3] o.s.c.s.s.s.StateMachineConfiguration    : Entering state ObjectState [getIds()=[INSTALL_INSTALL], getClass()=class org.springframework.statemachine.state.ObjectState, hashCode()=1643670584, toString()=AbstractState [id=INSTALL_INSTALL, pseudoState=org.springframework.statemachine.state.DefaultPseudoState@12493450, deferred=[], entryActions=[org.springframework.cloud.skipper.server.statemachine.InstallInstallAction@149debbb], exitActions=[], stateActions=[], regions=[], submachine=null]]
skipper              | 2019-05-24 22:31:54.117  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Preparing to run an application from org.springframework.cloud.stream.app:log-sink-kafka:jar:2.1.1.RELEASE. This may take some time if the artifact must be downloaded from a remote host.
skipper              | 2019-05-24 22:31:54.179  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Command to be executed: /opt/openjdk/bin/java -jar /root/.m2/repository/org/springframework/cloud/stream/app/log-sink-kafka/2.1.1.RELEASE/log-sink-kafka-2.1.1.RELEASE.jar
skipper              | 2019-05-24 22:31:54.203  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Deploying app with deploymentId http-log-ingest-5.log-v1 instance 0.
skipper              |    Logs will be in /tmp/spring-cloud-deployer-3633167379998955348/http-log-ingest-5-1558737114000/http-log-ingest-5.log-v1
skipper              | 2019-05-24 22:31:54.310  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Preparing to run an application from org.springframework.cloud.stream.app:http-source-kafka:jar:2.1.0.RELEASE. This may take some time if the artifact must be downloaded from a remote host.
skipper              | 2019-05-24 22:31:54.312  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Command to be executed: /opt/openjdk/bin/java -jar /root/.m2/repository/org/springframework/cloud/stream/app/http-source-kafka/2.1.0.RELEASE/http-source-kafka-2.1.0.RELEASE.jar
skipper              | 2019-05-24 22:31:54.313  INFO 1 --- [eTaskExecutor-3] o.s.c.d.spi.local.LocalAppDeployer       : Deploying app with deploymentId http-log-ingest-5.http-v1 instance 0.
skipper              |    Logs will be in /tmp/spring-cloud-deployer-3633167379998955348/http-log-ingest-5-1558737114208/http-log-ingest-5.http-v1
skipper              | 2019-05-24 22:31:54.369  INFO 1 --- [eTaskExecutor-3] o.s.s.support.LifecycleObjectSupport     : stopped org.springframework.statemachine.support.DefaultStateMachineExecutor@2c9d52c5
skipper              | 2019-05-24 22:31:54.370  INFO 1 --- [eTaskExecutor-3] o.s.s.support.LifecycleObjectSupport     : stopped INSTALL_INSTALL INSTALL_EXIT  /  / uuid=fbcafd74-2879-4e86-81da-8372a5be31be / id=http-log-ingest-5
skipper              | 2019-05-24 22:31:54.371  INFO 1 --- [eTaskExecutor-3] o.s.c.s.s.s.StateMachineConfiguration    : Entering state ObjectState [getIds()=[INITIAL], getClass()=class org.springframework.statemachine.state.ObjectState, hashCode()=1038812346, toString()=AbstractState [id=INITIAL, pseudoState=org.springframework.statemachine.state.DefaultPseudoState@12280a0a, deferred=[], entryActions=[], exitActions=[org.springframework.cloud.skipper.server.statemachine.ResetVariablesAction@6fd12c5], stateActions=[], regions=[], submachine=null]]
skipper              | 2019-05-24 22:31:54.372  INFO 1 --- [eTaskExecutor-3] o.s.c.s.s.s.SkipperStateMachineService   : setting future value org.springframework.cloud.skipper.domain.Release@279e0d49
skipper              | 2019-05-24 22:31:54.373  INFO 1 --- [eTaskExecutor-3] o.s.s.support.LifecycleObjectSupport     : started org.springframework.statemachine.support.DefaultStateMachineExecutor@2c9d52c5
skipper              | 2019-05-24 22:31:54.373  INFO 1 --- [eTaskExecutor-3] o.s.s.support.LifecycleObjectSupport     : started INSTALL_INSTALL INSTALL_EXIT  /  / uuid=fbcafd74-2879-4e86-81da-8372a5be31be / id=http-log-ingest-5
mysql_1              | 2019-05-24T22:32:45.648870Z 0 [Note] InnoDB: page_cleaner: 1000ms intended loop took 4662ms. The settings might not be optimal. (flushed=2 and evicted=0, during the time.)
zookeeper_1          | [2019-05-24 22:32:52,733] INFO Expiring session 0x10001d6560e0001, timeout of 6000ms exceeded (org.apache.zookeeper.server.ZooKeeperServer)
mysql_1              | 2019-05-24T22:33:08.378945Z 0 [Note] InnoDB: page_cleaner: 1000ms intended loop took 7338ms. The settings might not be optimal. (flushed=1 and evicted=0, during the time.)
mysql_1              | 2019-05-24T22:33:24.272169Z 0 [Note] InnoDB: page_cleaner: 1000ms intended loop took 5118ms. The settings might not be optimal. (flushed=0 and evicted=0, during the time.)
zookeeper_1          | [2019-05-24 22:33:28,644] INFO Processed session termination for sessionid: 0x10001d6560e0001 (org.apache.zookeeper.server.PrepRequestProcessor)
kafka_1              | [2019-05-24 22:33:40,709] INFO [GroupMetadataManager brokerId=1001] Removed 0 expired offsets in 2216 milliseconds. (kafka.coordinator.group.GroupMetadataManager)
kafka_1              | [2019-05-24 22:33:49,359] WARN Client session timed out, have not heard from server in 58623ms for sessionid 0x10001d6560e0001 (org.apache.zookeeper.ClientCnxn)
kafka_1              | [2019-05-24 22:33:56,611] TRACE [Controller id=1001] Checking need to trigger auto leader balancing (kafka.controller.KafkaController)
kafka_1              | [2019-05-24 22:34:06,529] DEBUG [Controller id=1001] Preferred replicas by broker Map(1001 -> Map(__consumer_offsets-22 -> Vector(1001), __consumer_offsets-30 -> Vector(1001), __consumer_offsets-8 -> Vector(1001), __consumer_offsets-21 -> Vector(1001), __consumer_offsets-4 -> Vector(1001), __consumer_offsets-27 -> Vector(1001), __consumer_offsets-7 -> Vector(1001), __consumer_offsets-9 -> Vector(1001), __consumer_offsets-46 -> Vector(1001), http-ingest-log-4.http-0 -> Vector(1001), __consumer_offsets-25 -> Vector(1001), __consumer_offsets-35 -> Vector(1001), __consumer_offsets-41 -> Vector(1001), __consumer_offsets-33 -> Vector(1001), __consumer_offsets-23 -> Vector(1001), __consumer_offsets-49 -> Vector(1001), __consumer_offsets-47 -> Vector(1001), __consumer_offsets-16 -> Vector(1001), __consumer_offsets-28 -> Vector(1001), __consumer_offsets-31 -> Vector(1001), __consumer_offsets-36 -> Vector(1001), __consumer_offsets-42 -> Vector(1001), __consumer_offsets-3 -> Vector(1001), __consumer_offsets-18 -> Vector(1001), __consumer_offsets-37 -> Vector(1001), http-ingest-log-3.http-0 -> Vector(1001), __consumer_offsets-15 -> Vector(1001), __consumer_offsets-24 -> Vector(1001), __consumer_offsets-38 -> Vector(1001), __consumer_offsets-17 -> Vector(1001), __consumer_offsets-48 -> Vector(1001), __confluent.support.metrics-0 -> Vector(1001), __consumer_offsets-19 -> Vector(1001), __consumer_offsets-11 -> Vector(1001), __consumer_offsets-13 -> Vector(1001), __consumer_offsets-2 -> Vector(1001), __consumer_offsets-43 -> Vector(1001), __consumer_offsets-6 -> Vector(1001), __consumer_offsets-14 -> Vector(1001), __consumer_offsets-20 -> Vector(1001), __consumer_offsets-0 -> Vector(1001), __consumer_offsets-44 -> Vector(1001), __consumer_offsets-39 -> Vector(1001), __consumer_offsets-12 -> Vector(1001), __consumer_offsets-45 -> Vector(1001), __consumer_offsets-1 -> Vector(1001), __consumer_offsets-5 -> Vector(1001), __consumer_offsets-26 -> Vector(1001), __consumer_offsets-29 -> Vector(1001), __consumer_offsets-34 -> Vector(1001), __consumer_offsets-10 -> Vector(1001), __consumer_offsets-32 -> Vector(1001), __consumer_offsets-40 -> Vector(1001))) (kafka.controller.KafkaController)
kafka_1              | [2019-05-24 22:34:11,269] DEBUG [Controller id=1001] Topics not in preferred replica for broker 1001 Map() (kafka.controller.KafkaController)
kafka_1              | [2019-05-24 22:34:11,993] TRACE [Controller id=1001] Leader imbalance ratio for broker 1001 is 0.0 (kafka.controller.KafkaController)
kafka_1              | [2019-05-24 22:34:23,483] INFO Client session timed out, have not heard from server in 58623ms for sessionid 0x10001d6560e0001, closing socket connection and attempting reconnect (org.apache.zookeeper.ClientCnxn)
mysql_1              | 2019-05-24T22:35:19.628193Z 0 [Note] InnoDB: page_cleaner: 1000ms intended loop took 4049ms. The settings might not be optimal. (flushed=0 and evicted=0, during the time.)
...
(several minutes later)
...
dataflow-server exited with code 137

I get the same behavior when swapping out different parts of the stack; for example RabbitMQ for Kafka/Zookeeper, Postgres for MySQL.

My local stack:

OSX 10.14

Java openjdk 11.0.2

Docker engine 18.09.2

Docker Compose 1.23.2

Docker Machine 0.16.1


问:
Why JavaScript implicitly stringify the parameter value when using objects as keys?
I have been studying some Javascript Interview Questions and the concept behind this specific question's answer is a bit hard to figure out. The output of the following code is 456 instead of 123 and the reason for this behavior stated as "JavaScript implicitly stringify the parameter value when Using Objects as Keys". Can anyone please explain this concept or provide me any resources to study? Thanks in advance.

var a = {};
var b = { key: "b" };
var c = { key: "c" };
a[b] = 123;
a[c] = 456;
console.log(a[b]); // Output is 456```

答:
Object properties are always either strings or Symbols. If you use something that isn't a string or a Symbol as an object property, it's converted to string as though you'd passed it through the String function. So your code is effectively:

```<code>    var a = /* whatever 'a' is, it wasn't in your question until someone else added
               it; I'm guessing they're probably right with `{}`  or similar */;
    var b = {key: "b"};
    var c = {key: "c"};
    a[String(b)] = 123;
// -- ^^^^^^^-^
    a[String(c)] = 456;
// -- ^^^^^^^-^
    console.log(a[String(b)]); // Output is 456
// ---------------^^^^^^^-^
</code>```

When you convert an object to string, if it has a toString method, that gets called. The toString on plain objects returns "[object Object]", so your keys are both "[object Object]", which means your code is effectively:

```<code>    var a = /* whatever 'a' is */;
    var b = {key: "b"};
    var c = {key: "c"};
    a["[object Object]"] = 123;
// ---^^^^^^^^^^^^^^^^^
    a["[object Object]"] = 456;
// ---^^^^^^^^^^^^^^^^^
    console.log(a["[object Object]"]); // Output is 456
// ---------------^^^^^^^^^^^^^^^^^
</code>```

which is why you see 456 instead of 123.

If you want to use an object as a key, use a Map (ES2015+):

var map = new Map();
var b = {key: "b"};
var c = {key: "c"};
map.set(b, 123);
map.set(c, 456);
console.log(map.get(b)); // 123
console.log(map.get(c)); // 456```

Body:
Object properties are always either strings or Symbols. If you use something that isn't a string or a Symbol as an object property, it's converted to string as though you'd passed it through the String function. So your code is effectively:

    var a = /* whatever 'a' is, it wasn't in your question until someone else added
               it; I'm guessing they're probably right with `{}`  or similar */;
    var b = {key: "b"};
    var c = {key: "c"};
    a[String(b)] = 123;
// -- ^^^^^^^-^
    a[String(c)] = 456;
// -- ^^^^^^^-^
    console.log(a[String(b)]); // Output is 456
// ---------------^^^^^^^-^

When you convert an object to string, if it has a toString method, that gets called. The toString on plain objects returns "[object Object]", so your keys are both "[object Object]", which means your code is effectively:

    var a = /* whatever 'a' is */;
    var b = {key: "b"};
    var c = {key: "c"};
    a["[object Object]"] = 123;
// ---^^^^^^^^^^^^^^^^^
    a["[object Object]"] = 456;
// ---^^^^^^^^^^^^^^^^^
    console.log(a["[object Object]"]); // Output is 456
// ---------------^^^^^^^^^^^^^^^^^

which is why you see 456 instead of 123.

If you want to use an object as a key, use a Map (ES2015+):

var map = new Map();
var b = {key: "b"};
var c = {key: "c"};
map.set(b, 123);
map.set(c, 456);
console.log(map.get(b)); // 123
console.log(map.get(c)); // 456


问:
Is any way that some method work each 1 hour in php?
For instance i have a function that take screenshot of google.com and store result at database . I want it works each 24 hour and don't know how .

I mean something cool like trigger in javascript   .
example in js:

```<code>function ChangeDate() {
    var changedate = ScriptApp.newTrigger('tOdAy')
      .timeBased()
      .everyDays(1)
      .create();
}
</code>```

I have tried sleep(time) before in a while(true)loop but it didn't work.

```<code>function ss(){
Mycode();
}
</code>```

答:
You can do this in two ways:

First one, is to create a simple script that does that, and executing it with a cron job. Plain and simple.

The other one is to create a long running script. The idea is that you create a loop, and inside that loop you call the timeout, and then execute your function. You can use reactphp/event-loop for implementing this very easily if you are using composer. Just check out the EventLoopInterface::addPeriodicTimer method.

Keep in mind that you have to keep that long running process alive with some tooling like systemd or supervisord.

Body:
For instance i have a function that take screenshot of google.com and store result at database . I want it works each 24 hour and don't know how .

I mean something cool like trigger in javascript   .
example in js:

function ChangeDate() {
    var changedate = ScriptApp.newTrigger('tOdAy')
      .timeBased()
      .everyDays(1)
      .create();
}

I have tried sleep(time) before in a while(true)loop but it didn't work.

function ss(){
Mycode();
}


问:
Is there a way for me to convert O'reilly to O'Reilly?
I would like to display names in title case and also convert the hyphenated names — such as O'Reilly — properly.

Right now, when I use the ToUpperCase function, I get "O'reilly", and that is not what I want.

Here's the function I am using:

```<code>@functions
{
    public static class TextConvert
    {
        public static string ToTitleCase(string s)
        {
            s = s.ToLower();
            return Regex.Replace(s, @"(^\w)|(\s\w)",b => b.Value.ToUpper());
        }
    }
}
</code>```

How can I do that, accounting for cases like O'Reilly?

答: You can't do this with technical tools alone. There are African names that do not start with a capital letter at all. As you can see in this utility (http://www.johncardinal.com/tmgutil/capitalizenames.htm), the easiest way out is to actually maintain a list of exceptions and match your name against it.</p>

Body:
I would like to display names in title case and also convert the hyphenated names — such as O'Reilly — properly.

Right now, when I use the ToUpperCase function, I get "O'reilly", and that is not what I want.

Here's the function I am using:

@functions
{
    public static class TextConvert
    {
        public static string ToTitleCase(string s)
        {
            s = s.ToLower();
            return Regex.Replace(s, @"(^\w)|(\s\w)",b => b.Value.ToUpper());
        }
    }
}

How can I do that, accounting for cases like O'Reilly?


问:
"Error initializing Java Runtime Environment. You may need to reinstall Flash"
I get this error starting up Flash Professional CS5 (on 32-bit XP). I don't even have to create/open a Flash file. I already reinstalled, but to no avail. Any suggestions?</p>

答:
In my case, it was Software Restriction Policy which I configured to block everything except application directories.

Adobe installs its JRE in ProgramData folder. So, I added a path rule for C:\ProgramData\Adobe\CS5\jre to my Additional Rules.

If you do not have Software Restriction Policy configured, then this solution does not apply to you.


问:
Why does the configuration of .NET Core options not work with a generic type parameter?
I have a .NET Core WebApi project. To read the appsettings in an easy way, I configure the options to be injected with DI. This works fine. However if I try to call Configure<>() with a generic type parameter, I get an error.

Argument 2: cannot convert from 'Microsoft.Extensions.Configuration.IConfigurationSection' to 'System.Action'

The method overloads apart from Configure<T>(Action<T> configureOptions) seem not to be available anymore.

Why does the call not work with generic type parameters?

Startup.cs

public class Startup
{
    public IConfiguration Configuration { get; }

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        // services.AddMvc() etc...

        services.AddOptions();

        // Works fine
        services.Configure<MyOption>(Configuration.GetSection(nameof(MyOption)));
    }

    private void AddOption<T>(IServiceCollection services)
    {
        // Wont work
        services.Configure<T>(Configuration.GetSection(nameof(T)));
        services.Configure<T>(Configuration.GetSection(""));
    }
}
```

<p>MyOption.cs</p>

<pre class="lang-cs prettyprint-override"><code>public class MyOption
{
    public bool MyProp { get; set; }
}
</code>```

appsettings.json

{
    "MyOption": {
        "MyProp": true
    }
}
```

答:
If you want to become a good programmer, then learn to read errors and rummage through the documentations and implementations of libraries, and not write for every reason here. @igor-cova has already given you the right answer. The next time, be careful because writing this question took much more time and effort than you yourself would have looked into the implementation of the Configure method. Good luck
Regards, Andrew

Body:
I have a .NET Core WebApi project. To read the appsettings in an easy way, I configure the options to be injected with DI. This works fine. However if I try to call Configure<>() with a generic type parameter, I get an error.

Argument 2: cannot convert from 'Microsoft.Extensions.Configuration.IConfigurationSection' to 'System.Action'

The method overloads apart from Configure<T>(Action<T> configureOptions) seem not to be available anymore.

Why does the call not work with generic type parameters?

Startup.cs

public class Startup
{
    public IConfiguration Configuration { get; }

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        // services.AddMvc() etc...

        services.AddOptions();

        // Works fine
        services.Configure<MyOption>(Configuration.GetSection(nameof(MyOption)));
    }

    private void AddOption<T>(IServiceCollection services)
    {
        // Wont work
        services.Configure<T>(Configuration.GetSection(nameof(T)));
        services.Configure<T>(Configuration.GetSection(""));
    }
}

MyOption.cs

public class MyOption
{
    public bool MyProp { get; set; }
}

appsettings.json

{
    "MyOption": {
        "MyProp": true
    }
}


问:
Making columns out of spans
I recive {patients} and place it into a div:

```<code><div className="patients">
   {patients}
</div>
</code>```

It contains Name and Surname, each row in two spans:

(Dev Tools)

(Current state)

How can style those spans into columns (table-like)?

(Expexted result)

---EDIT---

Content of {patients} changes. It's a result of searching, so different names come, sometimes more, sometimes less. I can't apply a style to them separatly.
See the code.

答:
Flexbox is perfect for this kind of layout. Create the flexbox layout in each row by giving the .patient wrapper display: flex;:

```<code>.patient {
  display: flex;
  justify-content: space-between;
}
</code>```

The justify-content: space-between rule puts the spans on the left and right ends of the available space, one of my favorite things flexbox can do.

.patients {
  border: 1px solid black;
  max-width: 250px;
}
.patient {
  display: flex;
  justify-content: space-between;
  border-top: 1px solid black;
}
.patient span {
  padding: 0 20px; // gives a little space around each span
}
.patient:first-child {
  border-top: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="patients">
   <div class="patient">
    <span>Eri</span>
    <span>Car</span>
   </div>
   <div class="patient">
    <span>Dude</span>
    <span>Ok</span>
   </div>
   <div class="patient">
    <span>Nice</span>
    <span>One</span>
   </div>
</div></code>```

Title: Making columns out of spans

Body:
I recive {patients} and place it into a div:

   {patients}

It contains Name and Surname, each row in two spans:

(Dev Tools)

(Current state)

How can style those spans into columns (table-like)?

(Expexted result)

---EDIT---

Content of {patients} changes. It's a result of searching, so different names come, sometimes more, sometimes less. I can't apply a style to them separatly.
See the code.

Body:
Flexbox is perfect for this kind of layout. Create the flexbox layout in each row by giving the .patient wrapper display: flex;:

.patient {
  display: flex;
  justify-content: space-between;
}

The justify-content: space-between rule puts the spans on the left and right ends of the available space, one of my favorite things flexbox can do.

.patients {
  border: 1px solid black;
  max-width: 250px;
}
.patient {
  display: flex;
  justify-content: space-between;
  border-top: 1px solid black;
}
.patient span {
  padding: 0 20px; // gives a little space around each span
}
.patient:first-child {
  border-top: none;
}

<div class="patients">
   <div class="patient">
    <span>Eri</span>
    <span>Car</span>
   </div>
   <div class="patient">
    <span>Dude</span>
    <span>Ok</span>
   </div>
   <div class="patient">
    <span>Nice</span>
    <span>One</span>
   </div>
</div>


答:
Javascript uses only strings or symbols as keys. of not on of the both type supplied, it uses toString and returns the default value for objects [object Object].

var a = {},
    b = { key: "b" },
    c = { key: "c" };

a[b] = 123;
a[c] = 456;

console.log(a[b]);
console.log(a);```

Title: Why JavaScript implicitly stringify the parameter value when using objects as keys?

Body:
I have been studying some Javascript Interview Questions and the concept behind this specific question's answer is a bit hard to figure out. The output of the following code is 456 instead of 123 and the reason for this behavior stated as "JavaScript implicitly stringify the parameter value when Using Objects as Keys". Can anyone please explain this concept or provide me any resources to study? Thanks in advance.

var a = {};
var b = { key: "b" };
var c = { key: "c" };
a[b] = 123;
a[c] = 456;
console.log(a[b]); // Output is 456


问:
Chessboard distance in the image matrix
Given an image matrix, how can I get the locations of the pixels whose chessboard distances from pixel A is less than D. I need to performed this for all pixels.

Using the MATLAB function bwdist I couldn't provide desired result. What's the solution?

```<code>[D,idx] = bwdist(Img,'chessboard');
</code>```

答:
Given an image, pixel and maximum distance:

```<code>% Test image
Image = zeros(20,30);

% Maximum chessboard distance from image
maxDist = 7;

% The pixel from which to measure distance
pix = [4,19];
</code>```

To find the pixels who's chessboard distance from the pix are
less than maxDist and in the image bounds:

Option 1: Using bwdist

```<code>% Create a binary image with all pixels zero except 'pix'
bw = zeros(size(Image));
bw(pix(1), pix(2)) = 1;

% Get the chessboard distance transform
[D,idx] = bwdist(bw,'chessboard');

% Get the linear index of 'pix'
pixInd = sub2ind(size(bw), pix(1), pix(2));

% Find linear indices of pixels who's chessboard distance from pixel are
% less than 'maxDist'
pointsInd = find(idx == pixInd & D < maxDist);

% Remove 'pix'
pointsInd(pointsInd == pixInd) = [];

% Get the pairs of (x,y) of the pixels
[pointsX, pointsY] = ind2sub(size(bw), pointsInd);
</code>```

Option 2: Using meshgrid

```<code>% Get the range of x and y indices who's chessboard distance from pixel are
% less than 'maxDist' and in the image bounds
xRange = max((pix(1)-(maxDist-1)),1):min((pix(1)+(maxDist-1)),size(Image,1));
yRange = max((pix(2)-(maxDist-1)),1):min((pix(2)+(maxDist-1)),size(Image,2));

% Create a mesgrid to get the pairs of (x,y) of the pixels
[pointsX, pointsY] = meshgrid(xRange, yRange);
pointsX = pointsX(:);
pointsY = pointsY(:);

% Remove 'pix'
pixIndToRemove = (pointsX == pix(1) & pointsY == pix(2));
pointsX(pixIndToRemove) = [];
pointsY(pixIndToRemove) = [];
</code>```

Displaying result:

```<code>% Get linear indices of pixels
pointsInd = sub2ind(size(Image), pointsX, pointsY);

% To display the result, create a binary image with all found pixels
% colored white
bwPoints = zeros(size(Image));
bwPoints(pointsInd) = 1;

% Show points
imshow(bwPoints, 'InitialMagnification', 2000)

% Show pixel grid lines
hold on
[rows, cols] = size(bwPoints);
for row = 0.5 : 1 : (rows + 0.5)
    line([0.5, cols+0.5], [row, row], 'Color', 'r', 'LineWidth', 0.5);
end
for col = 0.5 : 1 : (cols + 0.5)
    line([col, col], [0.5, rows+0.5], 'Color', 'r', 'LineWidth', 0.5);
end
</code>```

Efficiency and running in a loop over all image pixels:

Option 2 is way much faster than Option 1. I wrote first Option 1 because bwdist was mentioned in the question. Running Option 2 in a loop can be improved by calculating the pixels first and than shifting them to the location of each pixel:

```<code>% Get the range of x and y indices who's chessboard distance from pixel
% (0,0) are less than 'maxDist'
xRange = (-(maxDist-1)):(maxDist-1);
yRange = (-(maxDist-1)):(maxDist-1);

% Create a mesgrid to get the pairs of (x,y) of the pixels
[pointsX, pointsY] = meshgrid(xRange, yRange);
pointsX = pointsX(:);
pointsY = pointsY(:);

% Remove pixel (0,0)
pixIndToRemove = (pointsX == 0 & pointsY == 0);
pointsX(pixIndToRemove) = [];
pointsY(pixIndToRemove) = [];

for x=1:size(Image, 1)
    for y=1:size(Image, 2)
        % Get a shifted copy of 'pointsX' and 'pointsY' that is centered
        % around (x, y)
        pointsX1 = pointsX + x;
        pointsY1 = pointsY + y;

        % Remove the the pixels that are out of the image bounds
        inBounds =...
            pointsX1 >= 1 & pointsX1 <= size(Image, 1) &...
            pointsY1 >= 1 & pointsY1 <= size(Image, 2);

        pointsX1 = pointsX1(inBounds);
        pointsY1 = pointsY1(inBounds);

        % Do stuff with 'pointsX1' and 'pointsY1'
        % ...

    end
end
</code>```

Title: Chessboard distance in the image matrix

Body:
Given an image matrix, how can I get the locations of the pixels whose chessboard distances from pixel A is less than D. I need to performed this for all pixels.

Using the MATLAB function bwdist I couldn't provide desired result. What's the solution?

[D,idx] = bwdist(Img,'chessboard');

Body:
Given an image, pixel and maximum distance:

% Test image
Image = zeros(20,30);

% Maximum chessboard distance from image
maxDist = 7;

% The pixel from which to measure distance
pix = [4,19];

To find the pixels who's chessboard distance from the pix are
less than maxDist and in the image bounds:

Option 1: Using bwdist

% Create a binary image with all pixels zero except 'pix'
bw = zeros(size(Image));
bw(pix(1), pix(2)) = 1;

% Get the chessboard distance transform
[D,idx] = bwdist(bw,'chessboard');

% Get the linear index of 'pix'
pixInd = sub2ind(size(bw), pix(1), pix(2));

% Find linear indices of pixels who's chessboard distance from pixel are
% less than 'maxDist'
pointsInd = find(idx == pixInd & D < maxDist);

% Remove 'pix'
pointsInd(pointsInd == pixInd) = [];

% Get the pairs of (x,y) of the pixels
[pointsX, pointsY] = ind2sub(size(bw), pointsInd);

Option 2: Using meshgrid

% Get the range of x and y indices who's chessboard distance from pixel are
% less than 'maxDist' and in the image bounds
xRange = max((pix(1)-(maxDist-1)),1):min((pix(1)+(maxDist-1)),size(Image,1));
yRange = max((pix(2)-(maxDist-1)),1):min((pix(2)+(maxDist-1)),size(Image,2));

% Create a mesgrid to get the pairs of (x,y) of the pixels
[pointsX, pointsY] = meshgrid(xRange, yRange);
pointsX = pointsX(:);
pointsY = pointsY(:);

% Remove 'pix'
pixIndToRemove = (pointsX == pix(1) & pointsY == pix(2));
pointsX(pixIndToRemove) = [];
pointsY(pixIndToRemove) = [];

Displaying result:

% Get linear indices of pixels
pointsInd = sub2ind(size(Image), pointsX, pointsY);

% To display the result, create a binary image with all found pixels
% colored white
bwPoints = zeros(size(Image));
bwPoints(pointsInd) = 1;

% Show points
imshow(bwPoints, 'InitialMagnification', 2000)

% Show pixel grid lines
hold on
[rows, cols] = size(bwPoints);
for row = 0.5 : 1 : (rows + 0.5)
    line([0.5, cols+0.5], [row, row], 'Color', 'r', 'LineWidth', 0.5);
end
for col = 0.5 : 1 : (cols + 0.5)
    line([col, col], [0.5, rows+0.5], 'Color', 'r', 'LineWidth', 0.5);
end

Efficiency and running in a loop over all image pixels:

Option 2 is way much faster than Option 1. I wrote first Option 1 because bwdist was mentioned in the question. Running Option 2 in a loop can be improved by calculating the pixels first and than shifting them to the location of each pixel:

% Get the range of x and y indices who's chessboard distance from pixel
% (0,0) are less than 'maxDist'
xRange = (-(maxDist-1)):(maxDist-1);
yRange = (-(maxDist-1)):(maxDist-1);

% Create a mesgrid to get the pairs of (x,y) of the pixels
[pointsX, pointsY] = meshgrid(xRange, yRange);
pointsX = pointsX(:);
pointsY = pointsY(:);

% Remove pixel (0,0)
pixIndToRemove = (pointsX == 0 & pointsY == 0);
pointsX(pixIndToRemove) = [];
pointsY(pixIndToRemove) = [];

for x=1:size(Image, 1)
    for y=1:size(Image, 2)
        % Get a shifted copy of 'pointsX' and 'pointsY' that is centered
        % around (x, y)
        pointsX1 = pointsX + x;
        pointsY1 = pointsY + y;

        % Remove the the pixels that are out of the image bounds
        inBounds =...
            pointsX1 >= 1 & pointsX1 <= size(Image, 1) &...
            pointsY1 >= 1 & pointsY1 <= size(Image, 2);

        pointsX1 = pointsX1(inBounds);
        pointsY1 = pointsY1(inBounds);

        % Do stuff with 'pointsX1' and 'pointsY1'
        % ...

    end
end


问:
Using LAMP architecture
I want to use a LAMP architecture. I am currently using WAMP for PHP. How to install Linux in partition with Windows Vista? Can annyoone reply? Also I am going to use Debian 6. Is Debian good for using with LAMP. I am going to use LAMP for coding purpose only. I am hosting the site on another server. Should I switch to LAMP?</p>

答: Yes, Debian has the packages to run Apache, MySQL and PHP. This is probably not the forum to hunt down install advice for dual-booting.</p>

Title: Using LAMP architecture


问:
How to get data with pivot data attached?
I'm trying to get the data from my Lists table and include an array with the ID's of the tracks in that list.

This is a sample of the database model, with a relation N:M.

In my List model, I added this method:

public function tracks()
{
   return $this->belongsToMany(Track::class, 'List_Tracks', 'id_list', 'id_track');
}
```

<p>So, in my ListController, I'm doing the following:</p>

<pre class="lang-php prettyprint-override"><code>$list = List::find($id);
$list->tracks_list = $list->tracks->pluck('track_id');
return $list;
</code>```

And what I get is as many objects as tracks I have in a same list, for example:

```<code>[
{
 "id_track": 1,
 "name": "Yesterday",
 "tracks_list": [
  1,
  2
 ]
 "pivot": {
    "id_list": 1,
    "id_track": 1
 }
},
{
 "id_track": 2,
 "name": "Lucy in the sky with diamonds",
 "pivot": {
    "id_list": 1,
    "id_track": 2
 }
}
]
</code>```

But what I want to get is:

```<code>{
 "id_list": 1,
 "name": "The Best of The Beatles",
 "tracks_list": [
  1,
  2
]
}
</code>```

I think the things I've tried are much more complex than the proper solution.

How would you get the data in this way?

Thanks in advance.

答:
You need to load the relationship first and then write rest of the eloquent query, otherwise you will get only list of ids from the pivot table.

List::with('tracks')->where('id', '=', $id)->first();
// Following method should work too
List::with('tracks')->find($id);
```

<p><br></p>

<p>Based on your commentary - to get only array of ids related to the list you don't need to load the relationship and can use only:</p>

<pre class="lang-php prettyprint-override"><code>List::find($id)->tracks()->pluck('id');
// In case previous method will not work, you can try this one:
List::find($id)->tracks()->pluck('tracks.id');
// before dot should be name of the table, not relationship's.
</code>```

So if you need only ids of the tracks that are attached to the playlist. I would recommend adding to your List model following method:

```<code>// App\Models\List
public function getTrackIdsAttribute()
{
    return $this->tracks->pluck('id')->toArray();
}
</code>```

Then you should be able to simply call List::find($id)->trackIds to get all ids of tracks attached to the given list. If you're not sure why I am defining the method as  getTrackIdsAttribute and call only trackIds on the model, take a look at Eloquent: Mutators.

Body:
I'm trying to get the data from my Lists table and include an array with the ID's of the tracks in that list.

This is a sample of the database model, with a relation N:M.

In my List model, I added this method:

public function tracks()
{
   return $this->belongsToMany(Track::class, 'List_Tracks', 'id_list', 'id_track');
}

So, in my ListController, I'm doing the following:

$list = List::find($id);
$list->tracks_list = $list->tracks->pluck('track_id');
return $list;

And what I get is as many objects as tracks I have in a same list, for example:

[
{
 "id_track": 1,
 "name": "Yesterday",
 "tracks_list": [
  1,
  2
 ]
 "pivot": {
    "id_list": 1,
    "id_track": 1
 }
},
{
 "id_track": 2,
 "name": "Lucy in the sky with diamonds",
 "pivot": {
    "id_list": 1,
    "id_track": 2
 }
}
]

But what I want to get is:

{
 "id_list": 1,
 "name": "The Best of The Beatles",
 "tracks_list": [
  1,
  2
]
}

I think the things I've tried are much more complex than the proper solution.

How would you get the data in this way?

Thanks in advance.

Body:
You need to load the relationship first and then write rest of the eloquent query, otherwise you will get only list of ids from the pivot table.

List::with('tracks')->where('id', '=', $id)->first();
// Following method should work too
List::with('tracks')->find($id);

Based on your commentary - to get only array of ids related to the list you don't need to load the relationship and can use only:

List::find($id)->tracks()->pluck('id');
// In case previous method will not work, you can try this one:
List::find($id)->tracks()->pluck('tracks.id');
// before dot should be name of the table, not relationship's.

So if you need only ids of the tracks that are attached to the playlist. I would recommend adding to your List model following method:

// App\Models\List
public function getTrackIdsAttribute()
{
    return $this->tracks->pluck('id')->toArray();
}

Then you should be able to simply call List::find($id)->trackIds to get all ids of tracks attached to the given list. If you're not sure why I am defining the method as  getTrackIdsAttribute and call only trackIds on the model, take a look at Eloquent: Mutators.