问:
Capistrano Rollback breaking Whenever Cronjob
The issue seems to be that during a capistrano deploy the created cron job has RAILS_ENV=staging as expected since the deployment environment is staging.  However, in a capistrano rollback the created cron job has RAILS_ENV=new_staging where new_staging is the capistrano stage being rolled back.

my schedule file

```<code>set :job_template, nil
job_type :rake,    "cd :path && :environment_variable=:environment bundle exec rake :task :output"

every 15.minute, roles: [:db] do
  rake "jobs:publish", output: lambda { "2>&1 >> /path/to/capistrano_directory/shared/log/jobs.log" }
end
</code>```

My deploy/new_staging.rb file

```<code>set :branch, "develop"
set :deploy_env, 'staging'
set :rails_env, 'staging'

server "user@server_ip", :web, :app, :db, :metrics
role :db, "user@server_ip", :primary => true       # This is where Rails migrations will run
ssh_options[:forward_agent] = false                                # use local SSH keys remotely

ssh_options[:paranoid] = false

set :use_sudo, false
set :deploy_to, "/path/to/capistrano_directory"
set :unicorn_conf, "#{deploy_to}/current/config/environments/#{deploy_env}/unicorn.rb"
set :unicorn_pid, "#{deploy_to}/shared/pids/unicorn.pid"

before 'deploy:finalize_update', 'set_current_release'
before "deploy:finalize_update", "deploy:update_crontab"
after 'deploy:update_code', 'deploy:symlink_db'

namespace :deploy do
  task :symlink_db, :roles => :app do
    run "ln -nfs #{deploy_to}/shared/config/database.yml #{release_path}/config/database.yml"
  end

  task :start, :roles => :app, :except => { :no_release => true } do
    run "cd #{deploy_to}/current && bundle exec unicorn -c #{unicorn_conf} -E #{deploy_env} -D"
  end

  task :stop do
    run "#{try_sudo} kill -QUIT `cat #{unicorn_pid}`"
  end

  task :restart, :roles => :app, :except => { :no_release => true } do
    run "#{try_sudo} kill -s USR2 `cat #{unicorn_pid}`"
  end
end

task :set_current_release, :roles => :app, :except => { :no_release => true } do
  set :current_release, latest_release
end
</code>```

And my deploy.rb

```<code>require 'bundler/capistrano'
require 'capistrano/ext/multistage'
set :whenever_command, "bundle exec whenever"
set :whenever_environment, defer { stage }
set :whenever_roles, [:db, :metrics]
require "whenever/capistrano"

set :stages, %w(production staging new_staging)

set :application, "###"
set :repository,  "###"
set :deploy_via, :remote_cache
set :scm, :git

default_run_options[:shell] = '/bin/bash --login'

ssh_options[:forward_agent] = false
ssh_options[:paranoid] = false

namespace :deploy do
  desc "Update the crontab file"
  task :update_crontab do
    run "cd #{release_path} && RAILS_ENV=#{fetch(:rails_env)} bundle exec whenever --update-crontab #{application} --set environment=#{fetch(:rails_env)}"
  end
end
</code>```

Whenever Version (0.9.7)

Capistrano Version (2.12.0)

What is causing the rollback to use the capistrano stage instead of the rails_env when running Whenever gem? And how can I get it to properly use the rails_env?

答:
I'm a little confused by your staging setup (what is the difference between staging and new_staging?). That said, you should be able to do this by changing your whenever_environment to use rails_env instead of the stage value set by capistrano:

so

```<code>set :whenever_environment, defer { stage }
</code>```

Would become:

```<code>set :whenever_environment, defer { rails_env }
</code>```

whenever README

Body:
The issue seems to be that during a capistrano deploy the created cron job has RAILS_ENV=staging as expected since the deployment environment is staging.  However, in a capistrano rollback the created cron job has RAILS_ENV=new_staging where new_staging is the capistrano stage being rolled back.

my schedule file

set :job_template, nil
job_type :rake,    "cd :path && :environment_variable=:environment bundle exec rake :task :output"

every 15.minute, roles: [:db] do
  rake "jobs:publish", output: lambda { "2>&1 >> /path/to/capistrano_directory/shared/log/jobs.log" }
end

My deploy/new_staging.rb file

set :branch, "develop"
set :deploy_env, 'staging'
set :rails_env, 'staging'

server "user@server_ip", :web, :app, :db, :metrics
role :db, "user@server_ip", :primary => true       # This is where Rails migrations will run
ssh_options[:forward_agent] = false                                # use local SSH keys remotely

ssh_options[:paranoid] = false

set :use_sudo, false
set :deploy_to, "/path/to/capistrano_directory"
set :unicorn_conf, "#{deploy_to}/current/config/environments/#{deploy_env}/unicorn.rb"
set :unicorn_pid, "#{deploy_to}/shared/pids/unicorn.pid"

before 'deploy:finalize_update', 'set_current_release'
before "deploy:finalize_update", "deploy:update_crontab"
after 'deploy:update_code', 'deploy:symlink_db'

namespace :deploy do
  task :symlink_db, :roles => :app do
    run "ln -nfs #{deploy_to}/shared/config/database.yml #{release_path}/config/database.yml"
  end

  task :start, :roles => :app, :except => { :no_release => true } do
    run "cd #{deploy_to}/current && bundle exec unicorn -c #{unicorn_conf} -E #{deploy_env} -D"
  end

  task :stop do
    run "#{try_sudo} kill -QUIT `cat #{unicorn_pid}`"
  end

  task :restart, :roles => :app, :except => { :no_release => true } do
    run "#{try_sudo} kill -s USR2 `cat #{unicorn_pid}`"
  end
end

task :set_current_release, :roles => :app, :except => { :no_release => true } do
  set :current_release, latest_release
end

And my deploy.rb

require 'bundler/capistrano'
require 'capistrano/ext/multistage'
set :whenever_command, "bundle exec whenever"
set :whenever_environment, defer { stage }
set :whenever_roles, [:db, :metrics]
require "whenever/capistrano"

set :stages, %w(production staging new_staging)

set :application, "###"
set :repository,  "###"
set :deploy_via, :remote_cache
set :scm, :git

default_run_options[:shell] = '/bin/bash --login'

ssh_options[:forward_agent] = false
ssh_options[:paranoid] = false

namespace :deploy do
  desc "Update the crontab file"
  task :update_crontab do
    run "cd #{release_path} && RAILS_ENV=#{fetch(:rails_env)} bundle exec whenever --update-crontab #{application} --set environment=#{fetch(:rails_env)}"
  end
end

Whenever Version (0.9.7)

Capistrano Version (2.12.0)

What is causing the rollback to use the capistrano stage instead of the rails_env when running Whenever gem? And how can I get it to properly use the rails_env?

Body:
I'm a little confused by your staging setup (what is the difference between staging and new_staging?). That said, you should be able to do this by changing your whenever_environment to use rails_env instead of the stage value set by capistrano:

so

set :whenever_environment, defer { stage }

Would become:

set :whenever_environment, defer { rails_env }

whenever README


来源: stackexchange

问:
C++ -- Win32 API, GUI stuff
I've been messing with Win32 API for abit, and I've got a question regarding the GUI functions.

How does one handle user input that is not managed through popup windows? I've been reading http://www.winprog.org/ but right when the interesting features comes -- lesson9 -- it becomes more abstract and I'm not sure how to do it.
Basically what I am after is the user to write input in two windows and then press a button to send a message that the content of the input is to be processed.
I think the input windows would be some EDIT-class windows and the input BUTTON-class but that's about it.

Any ideas? I'm sure it's simple, it's just makes me want to rip my hair of in native code :p

Cheers

答: I'm not sure I follow 100%. Yes, you would use EDIT and BUTTON-class controls for that. Where are you getting stuck?</p>

ContentLicense: CC BY-SA 2.5

Title: C++ -- Win32 API, GUI stuff


问:
How do I output xml in the console in IE?
I am trying to inspect an xml file in the console in IE11. In every other browser, all I have to do is add the line console.log(myXML); and it will output the raw xml in the console. However, the same code will output an object representation with all its properties in IE11 and Edge. I just want to see the xml just like it's displayed in all other browsers. How do I accomplish this? And why the heck would IE do it differently than other browsers in the first place?

答:
Have you tried using the XMLSerializer?</p>

```<code>var myXMLstring = new XMLSerializer().serializeToString(myXml)
console.log(myXMLstring)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Have you tried using the XMLSerializer?

var myXMLstring = new XMLSerializer().serializeToString(myXml)
console.log(myXMLstring)


问:
How can I pass a table name as a variable in SQL - Python 3.4
I am trying to write an SQL statement in python which passes a table name as a variable. However, I get the following error: Must declare the table variable "@P1".

```<code>pypyodbc.Programming Error: ('42000', '[42000]' [Miscrosoft] [SQL SERVER NATIVE CLIENT 10.0] [SQL SERVER] Must declare the table variable "@P1"
</code>```

The code yielding the ERROR is:

```<code>query = cursor.execute('''SELECT * FROM ?''', (table_variable,))
</code>```

I have other code where I pass variables to the SQL statement using the same syntax which works fine (code below works as intended).

```<code>query = cursor.execute('''SELECT column_name FROM information_schema.columns WHERE table_name = ?''', (table_variable,))
</code>```

The error seems to occur when I am using a variable to pass a table name.

Any help resolving this error would be much appreciated.

答:
You can define a string variable:

```<code>table_var_str = 'Table_name'
st = 'SELECT * FROM ' + table_var_str
query = cursor.execute(st)
</code>```

It will solve the problem.

You can also set the table_var_str as a list:

```<code>table_var_str = []
st = []
for i in range(N):
    table_var_str.append = 'Table_name' + str(i)
    st.append('SELECT * FROM ' + table_var_str[i])
for j in range(J):
    query = cursor.execute(st[j])
</code>```

If the query is very long, you should write them in a line instead of multi lines.

Body:
I am trying to write an SQL statement in python which passes a table name as a variable. However, I get the following error: Must declare the table variable "@P1".

pypyodbc.Programming Error: ('42000', '[42000]' [Miscrosoft] [SQL SERVER NATIVE CLIENT 10.0] [SQL SERVER] Must declare the table variable "@P1"

The code yielding the ERROR is:

query = cursor.execute('''SELECT * FROM ?''', (table_variable,))

I have other code where I pass variables to the SQL statement using the same syntax which works fine (code below works as intended).

query = cursor.execute('''SELECT column_name FROM information_schema.columns WHERE table_name = ?''', (table_variable,))

The error seems to occur when I am using a variable to pass a table name.

Any help resolving this error would be much appreciated.

Body:
You can define a string variable:

table_var_str = 'Table_name'
st = 'SELECT * FROM ' + table_var_str
query = cursor.execute(st)

It will solve the problem.

You can also set the table_var_str as a list:

table_var_str = []
st = []
for i in range(N):
    table_var_str.append = 'Table_name' + str(i)
    st.append('SELECT * FROM ' + table_var_str[i])
for j in range(J):
    query = cursor.execute(st[j])

If the query is very long, you should write them in a line instead of multi lines.


问:
How to group values in matrix with items of unequal length
Lets say I have a simple array:

```<code>a = np.arange(3)
</code>```

And an array of indices with the same length:

```<code>I = np.array([0, 0, 1])
</code>```

I now want to group the values based on the indices.
How would I group the elements of the first array to produce the result below?

```<code>np.array([[0, 1], [2], dtype=object)
</code>```

Here is what I tried:

```<code>a = np.arange(3)
I = np.array([0, 0, 1])
out = np.empty(2, dtype=object)
out.fill([])

aslists = np.vectorize(lambda x: [x], otypes=['object'])

out[I] += aslists(a)
</code>```

However, this approach does not concatenate the lists, but only maintains the last value for each index:

```<code>array([[1], [2]], dtype=object)
</code>```

Or, for a 2-dimensional case:

```<code>a = np.random.rand(100)
I = (np.random.random(100) * 5 //1).astype(int)
J = (np.random.random(100) * 5 //1).astype(int)

out = np.empty((5, 5), dtype=object)
out.fill([])
</code>```

How can I append the items from a to out based on the two index arrays?

答:
1D Case

Assuming I being sorted, for a list of arrays as output -

```<code>idx = np.unique(I, return_index=True)[1]
out = np.split(a,idx)[1:]
</code>```

Another with slicing to get idx for splitting a -

```<code>out = np.split(a, np.flatnonzero(I[1:] != I[:-1])+1)
</code>```

To get an array of lists as output -

```<code>np.array([i.tolist() for i in out])
</code>```

Sample run -

```<code>In [84]: a = np.arange(3)

In [85]: I = np.array([0, 0, 1])

In [86]: out = np.split(a, np.flatnonzero(I[1:] != I[:-1])+1)

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

In [88]: np.array([i.tolist() for i in out])
Out[88]: array([[0, 1], [2]], dtype=object)
</code>```

2D Case

For 2D case of filling into a 2D array with groupings made from indices in two arrays I and J that represent the rows and columns where the groups are to be assigned, we could do something like this -

```<code>ncols = 5
lidx = I*ncols+J
sidx = lidx.argsort() # Use kind='mergesort' to keep order
lidx_sorted = lidx[sidx]
unq_idx, split_idx = np.unique(lidx_sorted, return_index=True)
out.flat[unq_idx] = np.split(a[sidx], split_idx)[1:]
</code>```

Body:
Lets say I have a simple array:

a = np.arange(3)

And an array of indices with the same length:

I = np.array([0, 0, 1])

I now want to group the values based on the indices.
How would I group the elements of the first array to produce the result below?

np.array([[0, 1], [2], dtype=object)

Here is what I tried:

a = np.arange(3)
I = np.array([0, 0, 1])
out = np.empty(2, dtype=object)
out.fill([])

aslists = np.vectorize(lambda x: [x], otypes=['object'])

out[I] += aslists(a)

However, this approach does not concatenate the lists, but only maintains the last value for each index:

array([[1], [2]], dtype=object)

Or, for a 2-dimensional case:

a = np.random.rand(100)
I = (np.random.random(100) * 5 //1).astype(int)
J = (np.random.random(100) * 5 //1).astype(int)

out = np.empty((5, 5), dtype=object)
out.fill([])

How can I append the items from a to out based on the two index arrays?

Body:
1D Case

Assuming I being sorted, for a list of arrays as output -

idx = np.unique(I, return_index=True)[1]
out = np.split(a,idx)[1:]

Another with slicing to get idx for splitting a -

out = np.split(a, np.flatnonzero(I[1:] != I[:-1])+1)

To get an array of lists as output -

np.array([i.tolist() for i in out])

Sample run -

In [84]: a = np.arange(3)

In [85]: I = np.array([0, 0, 1])

In [86]: out = np.split(a, np.flatnonzero(I[1:] != I[:-1])+1)

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

In [88]: np.array([i.tolist() for i in out])
Out[88]: array([[0, 1], [2]], dtype=object)

2D Case

For 2D case of filling into a 2D array with groupings made from indices in two arrays I and J that represent the rows and columns where the groups are to be assigned, we could do something like this -

ncols = 5
lidx = I*ncols+J
sidx = lidx.argsort() # Use kind='mergesort' to keep order
lidx_sorted = lidx[sidx]
unq_idx, split_idx = np.unique(lidx_sorted, return_index=True)
out.flat[unq_idx] = np.split(a[sidx], split_idx)[1:]


问:
Is my website more vulnerable if API website gets hacked?
Say I have a website that is pulling data from Constant Contact or Mailchimp through their API. Then for some unfortunate reason, one of these websites get hacked. Is my site now more vulnerable to an attack since I am connected through an API?</p>

答:
A targeted attack would be possible but unlikely. When using an API you are making requests to some server, which inherently gives that server information on who you are in order to send a response back. With that, a hacker could use that information to attempt and send an attack to your address. This could be done by either using your address for an external program/script, or by sending malicious information back as a response instead of what was intended.

This entire scenario though is highly unlikely to ever occur though for many reasons. The main reason is, why would a hacker targeting specifically you go through trouble of taking control of another entity, their API, then attack you? It'd be much more likely for the hacker to attempt to gain access to the API owner's database and exploit information held there, rather than target people using their API.

So yes, if a hacker gained access to an API you use, there exists a chance they could make a targeted attack on you as well. Mind you that this chance exists with any foreign entity you connect with. Providing an entity information about who you are and where you are will always create some chance of an attack.


答:
Use the dirxml method.

Per the official documentation found here: https://msdn.microsoft.com/en-us/library/dn265067(v=vs.85).aspx

Dirxml: Logs an XML node object to the console.

```<code>var parser = new DOMParser();
var xml = parser.parseFromString("<books isbn=\"1111\"><book><title>Hello world!</title></book></books>", "application/xml");
console.dirxml(xml);
</code>```

Title: How do I output xml in the console in IE?

Body: I am trying to inspect an xml file in the console in IE11. In every other browser, all I have to do is add the line console.log(myXML); and it will output the raw xml in the console. However, the same code will output an object representation with all its properties in IE11 and Edge. I just want to see the xml just like it's displayed in all other browsers. How do I accomplish this? And why the heck would IE do it differently than other browsers in the first place?

Body:
Use the dirxml method.

Per the official documentation found here: https://msdn.microsoft.com/en-us/library/dn265067(v=vs.85).aspx

Dirxml: Logs an XML node object to the console.

var parser = new DOMParser();
var xml = parser.parseFromString("<books isbn=\"1111\"><book><title>Hello world!</title></book></books>", "application/xml");
console.dirxml(xml);


问:
DynamoDB + Store Values as Items or JSON
I'm creating a table with Primary Key 'UserID', Composite Key 'DateTime' and then I have the following as a value (note: I don't need to query any specifics in the below data - just write and read it):

```<code>UserID1
UserID2
Message
DateTime
</code>```

Questions:

is there any advantage in storing these 4 values as separate items or as one JSON string?

UserID1 and Datetime in the stored value also make up the Primary/Composite Key - am I right assuming there is no point in storing these in the data/value as I can access this from the returned Keys when quering?

答:
With DynamoMapper you could do this in Java:

```<code>@DynamoDBTable(tableName = "myClass")
public class MyClass {

    @DynamoDBHashKey(attributeName = "id")
    private String id;

    @DynamoDBRangeKey(attributeName = "rangeKey")
    private long rangeKey;

    @DynamoDBTypeConvertedJson
    private Content content;

}
</code>```

And the content class could be:

```<code>public class Content {

    @JsonProperty
    private List<Integer> integers = new ArrayList();

    @JsonProperty
    private List<String> strings = new ArrayList();

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm creating a table with Primary Key 'UserID', Composite Key 'DateTime' and then I have the following as a value (note: I don't need to query any specifics in the below data - just write and read it):

UserID1
UserID2
Message
DateTime

Questions:

is there any advantage in storing these 4 values as separate items or as one JSON string?

UserID1 and Datetime in the stored value also make up the Primary/Composite Key - am I right assuming there is no point in storing these in the data/value as I can access this from the returned Keys when quering?

Body:
With DynamoMapper you could do this in Java:

@DynamoDBTable(tableName = "myClass")
public class MyClass {

    @DynamoDBHashKey(attributeName = "id")
    private String id;

    @DynamoDBRangeKey(attributeName = "rangeKey")
    private long rangeKey;

    @DynamoDBTypeConvertedJson
    private Content content;

}

And the content class could be:

public class Content {

    @JsonProperty
    private List<Integer> integers = new ArrayList();

    @JsonProperty
    private List<String> strings = new ArrayList();

}


问:
What is the simplest way for an app to communicate with a website in asp.net?
I have a desktop application.
Users register to use it.
When they register, I need to make sure their email address is unique.
So I need to send a request to a website that keeps a list of all email addresses and returns the results.

What is the simplest, quickest way to do this is ASP.NET?

I could do this:

Send a webrequest:

```<code>http://www.site.com/validate.aspx?email=a@a.a
</code>```

And the aspx returns xml:

```<code><response>Valid</response>
</code>```

There are a few other simple tasks like this.
There is no need for heavy security or the need to make the system particularly robust due to high demand.

I have used web services before but that seems like too much overhead for this simple task.

Is there an elegant API that wraps up this communication system as it must be very common.

答:
HTTP has you covered. Just check the response code from your server.

http://en.wikipedia.org/wiki/List_of_HTTP_status_codes

I suggest you use

409 Conflict

  Indicates that the request could not be processed because of conflict in the request

but HTTP 418 is my favorite since I like OpenGL.

Body:
I have a desktop application.
Users register to use it.
When they register, I need to make sure their email address is unique.
So I need to send a request to a website that keeps a list of all email addresses and returns the results.

What is the simplest, quickest way to do this is ASP.NET?

I could do this:

Send a webrequest:

http://www.site.com/validate.aspx?email=a@a.a

And the aspx returns xml:

<response>Valid</response>

There are a few other simple tasks like this.
There is no need for heavy security or the need to make the system particularly robust due to high demand.

I have used web services before but that seems like too much overhead for this simple task.

Is there an elegant API that wraps up this communication system as it must be very common.


问:
Python: How do you intercept a method call to change function parameters?
What I am trying to do is write a wrapper around another module so that I can transform the parameters that are being passed to the methods of the other module. That was fairly confusing, so here is an example:

```<code>import somemodule

class Wrapper:
    def __init__(self):
        self.transforms = {}
        self.transforms["t"] = "test"

    # This next function is the one I want to exist
    # Please understand the lines below will not compile and are not real code
    def __intercept__(self, item, *args, **kwargs):
        if "t" in args:
            args[args.index("t")] = self.transforms["t"]
        return somemodule.item(*args, **kwargs)
</code>```

The goal is to allow users of the wrapper class to make simplified calls to the underlying module without having to rewrite all of the functions in the module. So in this case if somemodule had a function called print_uppercase then the user could do

```<code>w = Wrapper()
w.print_uppercase("t")
</code>```

and get the output

```<code>TEST
</code>```

I believe the answer lies in __getattr__ but I'm not totally sure how to use it for this application.

答: I would approach this by calling the intercept method, and entering the desired method to execute, as a parameter for intercept. Then, in the intercept method, you can search for a method with that name and execute it.</p>

Body:
What I am trying to do is write a wrapper around another module so that I can transform the parameters that are being passed to the methods of the other module. That was fairly confusing, so here is an example:

import somemodule

class Wrapper:
    def __init__(self):
        self.transforms = {}
        self.transforms["t"] = "test"

    # This next function is the one I want to exist
    # Please understand the lines below will not compile and are not real code
    def __intercept__(self, item, *args, **kwargs):
        if "t" in args:
            args[args.index("t")] = self.transforms["t"]
        return somemodule.item(*args, **kwargs)

The goal is to allow users of the wrapper class to make simplified calls to the underlying module without having to rewrite all of the functions in the module. So in this case if somemodule had a function called print_uppercase then the user could do

w = Wrapper()
w.print_uppercase("t")

and get the output

TEST

I believe the answer lies in __getattr__ but I'm not totally sure how to use it for this application.


问:
Error while build project Xcode says : "you don't have permission"
I have downloaded one project from the internet and, when I am trying to run it/build it the XCode, XCode says :

The file “PROJECT NAME” couldn’t be opened because you don’t have permission to view it.

I have also put read/write permission to the project folder as well but still not working.

Why does this is happen? Please help me to resolve this issue

答:
Clean the project inside Xcode.

Go to Product -> Clean

That worked for me.


问:
Devise after_create in overrided RegistrationsController, Rails 3
I need to call after_create :something inside overrided Devise class RegistrationsController.
Like this:

```<code>class RegistrationsController < Devise::RegistrationsController
  after_create :something
end
</code>```

But it does't work:

undefined method `after_create' for
  RegistrationsController:Class

What's wrong?

答: after_create is an ActiveRecord hook, not a controller hook. Maybe you're looking for after_filter?

Body:
I need to call after_create :something inside overrided Devise class RegistrationsController.
Like this:

class RegistrationsController < Devise::RegistrationsController
  after_create :something
end

But it does't work:

undefined method `after_create' for
  RegistrationsController:Class

What's wrong?


问:
Can not get database generated value after saving
I'm using SpringBoot, Spring data and postgresql.

In postgres I created one table.

```<code>CREATE EXTENSION "uuid-ossp";
CREATE TABLE user (
    id serial PRIMARY KEY not null,
    user_id varchar(255) not null default uuid_generate_v4()
);
</code>```

Than create entity

```<code>@Entity
public class User implements Serializable {

  private static final long serialVersionUID = 9129894781337596497L;

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(columnDefinition = "serial")
  private Integer id;

  @Column(insertable = false)
  private String userId;

  public static User create(){
    User user = new User();
    return user;
  }

  public String getUserId(){
    return userId;
  }

}
</code>```

Than create jpa repository like this

```<code>@Repository
public interface UserRepository extends JpaRepository<User, Integer> {}
</code>```

When I save the user I need to get id and userId but I get null instead and in database is generated UUID.

```<code>User user = userRepository.save(User.create());
assertThat(user.getUserId()).isNotNull();
</code>```

How can I get those generated values from database?

答: You should add missing getters and setters for properties id and userId into the User class.

Body:
I'm using SpringBoot, Spring data and postgresql.

In postgres I created one table.

CREATE EXTENSION "uuid-ossp";
CREATE TABLE user (
    id serial PRIMARY KEY not null,
    user_id varchar(255) not null default uuid_generate_v4()
);

Than create entity

@Entity
public class User implements Serializable {

  private static final long serialVersionUID = 9129894781337596497L;

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(columnDefinition = "serial")
  private Integer id;

  @Column(insertable = false)
  private String userId;

  public static User create(){
    User user = new User();
    return user;
  }

  public String getUserId(){
    return userId;
  }

}

Than create jpa repository like this

@Repository
public interface UserRepository extends JpaRepository<User, Integer> {}

When I save the user I need to get id and userId but I get null instead and in database is generated UUID.

User user = userRepository.save(User.create());
assertThat(user.getUserId()).isNotNull();

How can I get those generated values from database?


问:
Woocommerce: I want to make the shopping cart drop down after add to cart
I have been trying to do something rather simple: getting a cart to dropdown after a user added something to their cart and stay there, until they click it away.

I've tried adding a php function through functions.php in my childtheme, adding custom javascript code, but it doesn't react. I can't seem to capture the event with javascript/jquery.
Woocommerce reloads the page after adding something to the cart, since it's a variation product.

This is what the html code for the cart looks like:

```<code><div id="shoppingcart-dropdown" class="mkd-shopping-cart-dropdown">
                            <ul>
                                                                    <li>
                                        <div class="mkd-item-image-holder">
                                            <a itemprop="url" href="https://gemini-bracelets.com/collection/ladies/musthave-deluxe-vanilla-8mm/">
                                                <img src="//gemini-bracelets.com/wp-content/uploads/2017/06/Musthave-Deluxe-Summer-Night-8mm-300x200.jpg" class="attachment-shop_thumbnail size-shop_thumbnail wp-post-image" alt="" width="300" height="200">                                            </a>
                                        </div>
                                        <div class="mkd-item-info-holder">
                                            <h5 itemprop="name" class="mkd-product-title"><a itemprop="url" href="https://gemini-bracelets.com/collection/ladies/musthave-deluxe-vanilla-8mm/">Musthave Deluxe Summer Night 8mm</a></h5>
                                            <span class="mkd-quantity">2</span>
                                            <span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">€</span>39,95</span>                                            <a href="https://gemini-bracelets.com/cart/?remove_item=6c2e0a0990dacd72f16b437da82dc6cc&_wpnonce=663fbc7a93" class="remove" title="Remove this item"><span class="icon-arrows-remove"></span></a>                                        </div>
                                    </li>
                                                                    <li>
                                        <div class="mkd-item-image-holder">
                                            <a itemprop="url" href="https://gemini-bracelets.com/collection/ladies/musthave-deluxe-vanilla-8mm/">
                                                <img src="//gemini-bracelets.com/wp-content/uploads/2017/06/Musthave-Deluxe-Summer-Night-8mm-300x200.jpg" class="attachment-shop_thumbnail size-shop_thumbnail wp-post-image" alt="" width="300" height="200">                                            </a>
                                        </div>
                                        <div class="mkd-item-info-holder">
                                            <h5 itemprop="name" class="mkd-product-title"><a itemprop="url" href="https://gemini-bracelets.com/collection/ladies/musthave-deluxe-vanilla-8mm/">Musthave Deluxe Summer Night 8mm</a></h5>
                                            <span class="mkd-quantity">3</span>
                                            <span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">€</span>39,95</span>                                            <a href="https://gemini-bracelets.com/cart/?remove_item=8ed888de28bd08234d727d879e5f7a36&_wpnonce=663fbc7a93" class="remove" title="Remove this item"><span class="icon-arrows-remove"></span></a>                                        </div>
                                    </li>
                                                                <div class="mkd-cart-bottom">
                                    <div class="mkd-subtotal-holder clearfix">
                                        <span class="mkd-total">TOTAL:</span>
                                        <span class="mkd-total-amount">
                                        <span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">€</span>199,75</span>                                  </span>
                                    </div>
                                                                        <div class="mkd-btn-holder clearfix">
                                        <a itemprop="url" href="https://gemini-bracelets.com/cart/" class="mkd-view-cart" data-title="VIEW CART"><span>VIEW CART</span></a>
                                    </div>
                                    <div class="mkd-btn-holder clearfix">
                                        <a itemprop="url" href="https://gemini-bracelets.com/checkout/" class="mkd-view-cart" data-title="CHECKOUT"><span>CHECKOUT</span></a>
                                    </div>
                                </div>
                            </ul>
                        </div>
</code>```

And this is what I have been trying to do with jquery:

```<code>window.jQuery( document ).ready( function ( $ ) {
    $( 'body' ).on( 'added_to_cart', function ( event, fragments, cart_hash, $button ) {

        $('div#shoppingcart-dropdown').addClass('.after-add');
        $('body').on('click', function(){
            $('#shoppingcart-dropdown').removeClass('.after-add');
        })
    } );
} );
</code>```

答:
I found a way to target the specific moment after a successfull add to cart.
To the success.php file inside of the notices directory within the child-template woocoommerce folder, I added a script tag with my own javascript code.

success.php within notices directory in woocommerce:

```<code><?php
/**
 * Show messages
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/notices/success.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see         https://docs.woocommerce.com/document/template-structure/
 * @author      WooThemes
 * @package     WooCommerce/Templates
 * @version     1.6.4
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

if ( ! $messages ) {
    return;
}

?>

<?php foreach ( $messages as $message ) : ?>
    <div class="woocommerce-message"><?php echo wp_kses_post( $message ); ?></div>
<?php endforeach; ?>

//here is where I added my jquery/javascript code and this time it does target everything correctly.
<script>
    jQuery(document).ready(function($){

        //added specific hover class that I can remove the hover-css from.
        $("#cart-holder-div").removeClass("has-hover");

        //adding specific class so that I can add my own css.
        $('#shoppingcart-dropdown').addClass("after-add-cart");

        //once the customer clicks anywhere, the removed and added classes are undone.
        $(document).click(function(){

            $("#cart-holder-div").addClass("has-hover");
            $('#shoppingcart-dropdown').removeClass("after-add-cart");
            $("#shoppingcart-dropdown").hide();
        });

        //to make sure the previous click event doesn't target the actual shopping cart
        $("#shoppingcart-dropdown").click(function(e){
            e.stopPropagation();
        });

    });
</script>
</code>```

Body:
I have been trying to do something rather simple: getting a cart to dropdown after a user added something to their cart and stay there, until they click it away.

I've tried adding a php function through functions.php in my childtheme, adding custom javascript code, but it doesn't react. I can't seem to capture the event with javascript/jquery.
Woocommerce reloads the page after adding something to the cart, since it's a variation product.

This is what the html code for the cart looks like:

Musthave Deluxe Summer Night 8mm

                                            2
                                            €39,95

Musthave Deluxe Summer Night 8mm

                                            3
                                            €39,95

                                        TOTAL:

                                        €199,75

                                        VIEW CART

                                        CHECKOUT

And this is what I have been trying to do with jquery:

window.jQuery( document ).ready( function ( $ ) {
    $( 'body' ).on( 'added_to_cart', function ( event, fragments, cart_hash, $button ) {

        $('div#shoppingcart-dropdown').addClass('.after-add');
        $('body').on('click', function(){
            $('#shoppingcart-dropdown').removeClass('.after-add');
        })
    } );
} );

Body:
I found a way to target the specific moment after a successfull add to cart.
To the success.php file inside of the notices directory within the child-template woocoommerce folder, I added a script tag with my own javascript code.

success.php within notices directory in woocommerce:

<?php
/**
 * Show messages
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/notices/success.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see         https://docs.woocommerce.com/document/template-structure/
 * @author      WooThemes
 * @package     WooCommerce/Templates
 * @version     1.6.4
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

if ( ! $messages ) {
    return;
}

?>

<?php foreach ( $messages as $message ) : ?>
    <div class="woocommerce-message"><?php echo wp_kses_post( $message ); ?></div>
<?php endforeach; ?>

//here is where I added my jquery/javascript code and this time it does target everything correctly.
<script>
    jQuery(document).ready(function($){

        //added specific hover class that I can remove the hover-css from.
        $("#cart-holder-div").removeClass("has-hover");

        //adding specific class so that I can add my own css.
        $('#shoppingcart-dropdown').addClass("after-add-cart");

        //once the customer clicks anywhere, the removed and added classes are undone.
        $(document).click(function(){

            $("#cart-holder-div").addClass("has-hover");
            $('#shoppingcart-dropdown').removeClass("after-add-cart");
            $("#shoppingcart-dropdown").hide();
        });

        //to make sure the previous click event doesn't target the actual shopping cart
        $("#shoppingcart-dropdown").click(function(e){
            e.stopPropagation();
        });

    });
</script>


问:
Oracle SQL subqueries to link multiple tables
I have 3 different datasets

Data1:

```<code>ID  Rank_down
1
2
3
</code>```

data2:

```<code>ID  From    To
1   AB     CD
2   EF     JK
3   PQ  PQ
</code>```

data3:

```<code>From/To  rank
  AB     1
  CD     2
  EF     3
  JK     5
  PQ     9
</code>```

I need to populate the field rank_down as Y/N based on whether the ID has moved from a higher rank to a lower rank (1 being the lowest).This has to be done in Oracle SQl. I am new to this programming hence finding it difficult to write a subquery.

Can any one help?

答:
I'm just not following so I'll try some SQL and see if this gets us closer...

Does this select give the desired results in a select fashion?  (I may have the Y/N's inverted)

```<code>SELECT ID, Case when D3a.Rank < D3b.Rank then 'N'
                when D3a.Rank > D3b.Rank then 'Y'
                when D3a.Rank = D3b.Rank then 'N'
                end as Rank_down
FROM data2 D2
INNER JOIN data3 D3a
 on D3a.From_To = D2.From
INNER JOIN data3 D3b
 on D3b.From_To = D2.To
</code>```

if so we just need to do an update based on it.

```<code>UPDATE Data1 d1
INNER JOIN (    SELECT ID, Case when D3A.Rank < D3b.Rank then 'N'
                    when D3A.Rank > D3B.Rank then 'Y'
                    when D3A.Rank = D3B.Rank then 'N'
                    end as Rank_down
    FROM data2 D2
    INNER JOIN data3 D3a
     on D3a.From_To = D2.From
    INNER JOIN data3 D3b
     on D3B.From_To = D2.To) B
on B.ID = d1.ID
set d1.Rank_down = B.Rank_Down
</code>```

Body:
I have 3 different datasets

Data1:

ID  Rank_down
1
2
3

data2:

ID  From    To
1   AB     CD
2   EF     JK
3   PQ  PQ

data3:

From/To  rank
  AB     1
  CD     2
  EF     3
  JK     5
  PQ     9

I need to populate the field rank_down as Y/N based on whether the ID has moved from a higher rank to a lower rank (1 being the lowest).This has to be done in Oracle SQl. I am new to this programming hence finding it difficult to write a subquery.

Can any one help?

Body:
I'm just not following so I'll try some SQL and see if this gets us closer...

Does this select give the desired results in a select fashion?  (I may have the Y/N's inverted)

SELECT ID, Case when D3a.Rank < D3b.Rank then 'N'
                when D3a.Rank > D3b.Rank then 'Y'
                when D3a.Rank = D3b.Rank then 'N'
                end as Rank_down
FROM data2 D2
INNER JOIN data3 D3a
 on D3a.From_To = D2.From
INNER JOIN data3 D3b
 on D3b.From_To = D2.To

if so we just need to do an update based on it.

UPDATE Data1 d1
INNER JOIN (    SELECT ID, Case when D3A.Rank < D3b.Rank then 'N'
                    when D3A.Rank > D3B.Rank then 'Y'
                    when D3A.Rank = D3B.Rank then 'N'
                    end as Rank_down
    FROM data2 D2
    INNER JOIN data3 D3a
     on D3a.From_To = D2.From
    INNER JOIN data3 D3b
     on D3B.From_To = D2.To) B
on B.ID = d1.ID
set d1.Rank_down = B.Rank_Down


问:
Is a script in the footer "render-blocking"?
After discussing it with a colleague, we need an answer to the question: Is a script in the footer "render-blocking"? I mean, is any content showed to the user before the script is completely loaded?

Thank you

答:
When you place javascript in the footer of the page; i.e. before the closing without hte defer/async attribute then it is render blocking.

When the browser constructs the DOM and reads a script tag even in the footer and without the defer/async attribute, then, the browser can only continue the construction of the DOM if the script is completely downloaded.

Note that the DOM construction is not yet visible in the browser, until the browser paints the result.

The browser goes to 4 major steps before we can actually see the results.

DOM and CSSOM constructions.

Render Tree

Layout - computes the exact position and size of each object.

Paint - is the last step; renders the resulting pixels to the screen.

Links for Removing Render-Blocking Javascript and Render-tree Construction, Layout, and Paint

Body:
When you place javascript in the footer of the page; i.e. before the closing</body> without hte defer/async attribute then it is render blocking.

When the browser constructs the DOM and reads a script tag even in the footer and without the defer/async attribute, then, the browser can only continue the construction of the DOM if the script is completely downloaded.

Note that the DOM construction is not yet visible in the browser, until the browser paints the result.

The browser goes to 4 major steps before we can actually see the results.

DOM and CSSOM constructions.

Render Tree

Layout - computes the exact position and size of each object.

Paint - is the last step; renders the resulting pixels to the screen.

Links for Removing Render-Blocking Javascript and Render-tree Construction, Layout, and Paint


问:
How to use v-select but not repeat itself while using v-for
I have array of json in groupData, how to pass the data to v-select

I know what I am doing is wrong by using v-for inside v-select, but I am not sure how to pass data:

```<code><v-select multiple
  v-for="group in groupsData"
  :value.sync="selected"
  :options="[{label: group.group_name, value: group.id}]">
</v-select>
</code>```

Plugin URL: https://sagalbot.github.io/vue-select/

This is how it's done with vue.js without v-select plugin and this works:

```<code><select v-model="selected" multiple>
  <option v-for="group in groupsData" v-bind:value="group.group_id">{{group.group_name}}</option>
</select>
</code>```

Thanks in advance.

答:
v-for repeats the entire element, which is not what you want.

Instead, you want to transform your array into the options parameter.

: expressions accept arbitrary Javascript code, so you can do that exactly as you would in Javascript:

```<code>:options="groupsData.map(g => ({label: g.name, value: g.id}))"
</code>```

Body:
I have array of json in groupData, how to pass the data to v-select

I know what I am doing is wrong by using v-for inside v-select, but I am not sure how to pass data:

<v-select multiple
  v-for="group in groupsData"
  :value.sync="selected"
  :options="[{label: group.group_name, value: group.id}]">
</v-select>

Plugin URL: https://sagalbot.github.io/vue-select/

This is how it's done with vue.js without v-select plugin and this works:

<select v-model="selected" multiple>
  <option v-for="group in groupsData" v-bind:value="group.group_id">{{group.group_name}}</option>
</select>

Thanks in advance.

Body:
v-for repeats the entire element, which is not what you want.

Instead, you want to transform your array into the options parameter.

: expressions accept arbitrary Javascript code, so you can do that exactly as you would in Javascript:

:options="groupsData.map(g => ({label: g.name, value: g.id}))"


问:
How to call method inside module (same method name in 2 different module) using class object - ruby
Consider i have 2 modules, both contains the function 'foo'. If i need to call the Module1's foo using object of the class which includes it, how i need to call?

Code sample:

```<code>    module Module1
      def foo
        puts 'first one'
      end
    end

    module Module2
      def foo
        puts 'second one'
      end
    end

  class ClassName
      include Module1
      include Module2

      def initialize
        Module1.instance_method(:foo).bind( self ).call
        Module2.instance_method(:foo).bind( self ).call
      end
    end

    cls = ClassName.new
</code>```

How to call the methods foo using the object 'cls' (If i need to call Module1's foo)?

Thanks!

答:
If you want to keep the usual instance method semantics, the simplest solution is probably to just alias the method before you include the second module:

```<code>class ClassName
  include Module1
  alias :module_1_foo :foo
  include Module2
end

cls = ClassName.new
cls.module_1_foo
# => first one
cls.foo
# => second one
</code>```

See it on repl.it: https://repl.it/JQ73

Alternatively, you could pass the UnboundMethod object returned by Module1.instance_method(:foo) to define_method:

```<code>class ClassName
  include Module1
  include Module2
  define_method(:module_1_foo, Module1.instance_method(:foo))
end
</code>```

The caveat with both of these is that if there are other instance methods in Module1 that call foo, they will wind up calling Module2#foo. They have no way of knowing that Method1#foo has been "renamed." This is, at best, a stopgap, and if your code has any complexity at all you should just redesign the whole thing so you don't have name collisions.

Body:
Consider i have 2 modules, both contains the function 'foo'. If i need to call the Module1's foo using object of the class which includes it, how i need to call?

Code sample:

    module Module1
      def foo
        puts 'first one'
      end
    end

    module Module2
      def foo
        puts 'second one'
      end
    end

  class ClassName
      include Module1
      include Module2

      def initialize
        Module1.instance_method(:foo).bind( self ).call
        Module2.instance_method(:foo).bind( self ).call
      end
    end

    cls = ClassName.new

How to call the methods foo using the object 'cls' (If i need to call Module1's foo)?

Thanks!

Body:
If you want to keep the usual instance method semantics, the simplest solution is probably to just alias the method before you include the second module:

class ClassName
  include Module1
  alias :module_1_foo :foo
  include Module2
end

cls = ClassName.new
cls.module_1_foo
# => first one
cls.foo
# => second one

See it on repl.it: https://repl.it/JQ73

Alternatively, you could pass the UnboundMethod object returned by Module1.instance_method(:foo) to define_method:

class ClassName
  include Module1
  include Module2
  define_method(:module_1_foo, Module1.instance_method(:foo))
end

The caveat with both of these is that if there are other instance methods in Module1 that call foo, they will wind up calling Module2#foo. They have no way of knowing that Method1#foo has been "renamed." This is, at best, a stopgap, and if your code has any complexity at all you should just redesign the whole thing so you don't have name collisions.


问:
Tips/Resources on Structuring Shared Code Libraries in C#/WPF?
I've written a simple desktop application with C#/WPF and I'm now looking to create another, larger application which will share much of the functionality. I'm thinking that I should create three separate projects: one containing the shared code, and one each for the two apps.

My problem is that I'm not entirely familiar with .NET/WPF so I don't know if there are some best practices for this sort of thing. Can anyone offer some good sources of information, example projects or just some brief advice?

Edit: To put a little more detail on the scenario, the first application is a specialised editor and the second application is taking this file editor and wrapping a project model around it to create a sort of basic IDE.

答:
Honestly it depends on what level the code you intend to share is.  For instance, it's entirely plausable to put all of your business logic code into one project/class library and maintain it independantly, but mixing biz logic with WPF custom controls should be STRONGLY discouraged.  Think about the layers of abstraction you are modularizing, and the dependancy heiarchy you are introducing and refactor accordingly.

Edit:

In response to your above changes I suggest the following:  The logic and DAL associated with the above should be pushed into a project as seperate namespaces. The visual elements (the view, viewmodel) should most likely be moved into a seperate project and namespace set as well.  Once you can merge these together and launch them from an exe that contains a host window and a UserControl for the rest of your hosted visual content, you can then probably move forward with integration into your larger IDE project.  The key here is:

Visual Layer and View Logic -> Editor.Visual.dll

Biz Logic & Data Access     -> Editor.Core.dll

I hope this helps.


问:
How to randomly choose columns from a text file
I have a text file (tab delimited)

```<code>Name Attribute1 Attribute2 ..........Attribute1000
aaaa   1           100                  0
bbbb   0            20                  50
cccc   10           20                  30
</code>```

I want to randomly choose 25 columns from the Attributes but always keep the first column (Name). How can I do this?

答:
OK -- given all the info in the comments, we get the columns like this:

```<code>$ columns=1,$( for (( ii=2; ii<=1000; ii++ )); do echo $ii; done | sort -R | head -25 | sort -n | tr '\n' ',' | sed 's/,$//' )
</code>```

Then, we print out those columns like so:

```<code>$ cut --fields=${columns} columns.txt
</code>```

I've just put in the headers in a one-line file:

```<code>$ for (( ii=1; ii<=1000; ii++ )); do
> echo -n "col${ii}<tab>" >> columns.txt
> done
</code>```

(Note that that <tab> is just a placeholder I put in so you could see it.  Don't actually type <tab>.)

So now, when I run those commands:

```<code>$ columns=1,$( for (( ii=2; ii<=1000; ii++ )); do echo $ii; done | sort -R | head -25 | sort -n | tr '\n' ',' | sed 's/,$//' )

$ echo $columns
1,2,99,122,129,158,187,268,323,351,353,385,404,408,441,464,538,548,575,617,670,705,716,718,721,810

$ cut --fields=${columns} columns.txt
col1    col2    col99   col122  col129  col158  col187  col268  col323  col351  col353  col385  col404  col408  col441  col464  col538  col548  col575      col617  col670  col705  col716  col718  col721  col810
</code>```

Body:
I have a text file (tab delimited)

Name Attribute1 Attribute2 ..........Attribute1000
aaaa   1           100                  0
bbbb   0            20                  50
cccc   10           20                  30

I want to randomly choose 25 columns from the Attributes but always keep the first column (Name). How can I do this?

Body:
OK -- given all the info in the comments, we get the columns like this:

$ columns=1,$( for (( ii=2; ii<=1000; ii++ )); do echo $ii; done | sort -R | head -25 | sort -n | tr '\n' ',' | sed 's/,$//' )

Then, we print out those columns like so:

$ cut --fields=${columns} columns.txt

I've just put in the headers in a one-line file:

$ for (( ii=1; ii<=1000; ii++ )); do
> echo -n "col${ii}<tab>" >> columns.txt
> done

(Note that that <tab> is just a placeholder I put in so you could see it.  Don't actually type <tab>.)

So now, when I run those commands:

$ columns=1,$( for (( ii=2; ii<=1000; ii++ )); do echo $ii; done | sort -R | head -25 | sort -n | tr '\n' ',' | sed 's/,$//' )

$ echo $columns
1,2,99,122,129,158,187,268,323,351,353,385,404,408,441,464,538,548,575,617,670,705,716,718,721,810

$ cut --fields=${columns} columns.txt
col1    col2    col99   col122  col129  col158  col187  col268  col323  col351  col353  col385  col404  col408  col441  col464  col538  col548  col575      col617  col670  col705  col716  col718  col721  col810


问:
Javascript RegExp to check if any other character in string
only following characters are allowed in the string

1 2 3 4 5 6 7 8 9 0 ( ) -

I want to check if string contains any other characters

答:
This should get you what you need, but it will also detect spaces:

```<code>/[^\d()-]/g
</code>```

Example:

```<code>var foo = 'hello1234567890()-world';

// Will match 'hello' and 'world'
var bar = foo.match(/[^\d()-]/g);

if(bar) {
   // Invalid input
} else {
   // Is valid
}
</code>```

Body:
This should get you what you need, but it will also detect spaces:

/[^\d()-]/g

Example:

var foo = 'hello1234567890()-world';

// Will match 'hello' and 'world'
var bar = foo.match(/[^\d()-]/g);

if(bar) {
   // Invalid input
} else {
   // Is valid
}


问:
Kotlin's data class, Android Room and custom setter
I got an entity for Android Room which looks like that. So far, no worries.

```<code>@Entity(tableName = "users",
        indices = arrayOf(Index(value = "nickName", unique = true)))
data class User(@ColumnInfo(name = "nickName") var nickName: String,
                @ColumnInfo(name = "password") var password: String) {

    @ColumnInfo(name = "id")
    @PrimaryKey(autoGenerate = true)
    var id: Long = 0
}
</code>```

Now I need to encrypt the password. With Java, this would simply be done with a setter and that would work.

How would you do that with Kotlin. I cannot find a solution to combine Android Room, custom setters and data classes.

答:
```<code>    @Entity(tableName = "users",
            indices = arrayOf(Index(value = "nickName", unique = true)))
    data class User(@ColumnInfo(name = "nickName") var nickName: String,
                    @ColumnInfo(name = "password") var password: String) {
    var _password = password
        set(value): String{
           //encrypt password
        }
        @ColumnInfo(name = "id")
        @PrimaryKey(autoGenerate = true)
        var id: Long = 0
    }
</code>```

<p>This will create a custom setter so every time you set your password you can encrypt it as well inside the setter. </p>

Body:
I got an entity for Android Room which looks like that. So far, no worries.

@Entity(tableName = "users",
        indices = arrayOf(Index(value = "nickName", unique = true)))
data class User(@ColumnInfo(name = "nickName") var nickName: String,
                @ColumnInfo(name = "password") var password: String) {

    @ColumnInfo(name = "id")
    @PrimaryKey(autoGenerate = true)
    var id: Long = 0
}

Now I need to encrypt the password. With Java, this would simply be done with a setter and that would work.

How would you do that with Kotlin. I cannot find a solution to combine Android Room, custom setters and data classes.

Body:
    @Entity(tableName = "users",
            indices = arrayOf(Index(value = "nickName", unique = true)))
    data class User(@ColumnInfo(name = "nickName") var nickName: String,
                    @ColumnInfo(name = "password") var password: String) {
    var _password = password
        set(value): String{
           //encrypt password
        }
        @ColumnInfo(name = "id")
        @PrimaryKey(autoGenerate = true)
        var id: Long = 0
    }

This will create a custom setter so every time you set your password you can encrypt it as well inside the setter.


问:
R ggplot2 faceting standardizing date limits
I am trying to create a graph with 3 survey seasons, each crossing over a year boundary (ie 2009-2010, 2010-2011, 2016-2017), but where survey effort starts and ends at a different point in each survey season. What I currently have is:

I'd like to end up with each x-axis showing November-April of that survey season (ie the 2009-2010 survey season would show November 2009-April 2010) to better show where survey effort is lacking in terms of interannual comparison. I'm just not sure how to do that within the context of scale_x_date(). My current scale statement is simply scale_x_date(date_breaks = '1 month',date_labels='%b')+ My only thought so far is to basically just create a bunch of NA data with the relevant dates and continue to let the dates scale automatically, but for my future reference I'm wondering if there's a better way to create those kind of "year-less" date limits.

Some more information:

the head of my data (which in this case will be in the top-left facet of the plot):

```<code>structure(list(SPID = c("Cho_001", "Cho_001", "Cho_001", "Cho_001",
"Cho_001", "Cho_001"), season = c(2009, 2009, 2009, 2009, 2009,
2009), Date = structure(c(14579, 14580, 14581, 14582, 14583,
14584), class = "Date"), DayOfYear = c(335, 336, 337, 338, 339,
340), year = c(2009L, 2009L, 2009L, 2009L, 2009L, 2009L), month = c(12L,
12L, 12L, 12L, 12L, 12L), day = 1:6, RatePerMin = c(3.6667, 4.8667,
13.1667, 23.0333, 24.6667, 25.4667), N = c(3L, 30L, 30L, 30L,
30L, 30L), sd = c(3.5119, 6.9269, 8.1074, 4.2789, 4.9434, 4.2729
), se = c(2.0276, 1.2647, 1.4802, 0.7812, 0.9025, 0.7801), Illu = c(0.999348417128253,
0.999986511310919, 0.991435775301254, 0.955915838251852, 0.894428866388813,
0.810868946410883)), .Names = c("SPID", "season", "Date", "DayOfYear",
"year", "month", "day", "RatePerMin", "N", "sd", "se", "Illu"
), row.names = c(NA, -6L), class = c("grouped_df", "tbl_df",
"tbl", "data.frame"), vars = c("SPID", "season", "year", "month",
"day", "Date"), drop = TRUE, indices = list(0L, 1L, 2L, 3L, 4L,
    5L), group_sizes = c(1L, 1L, 1L, 1L, 1L, 1L), biggest_group_size = 1L, labels = structure(list(
    SPID = c("Cho_001", "Cho_001", "Cho_001", "Cho_001", "Cho_001",
    "Cho_001"), season = c(2009, 2009, 2009, 2009, 2009, 2009
    ), year = c(2009L, 2009L, 2009L, 2009L, 2009L, 2009L), month = c(12L,
    12L, 12L, 12L, 12L, 12L), day = 1:6, Date = structure(c(14579,
    14580, 14581, 14582, 14583, 14584), class = "Date")), row.names = c(NA,
-6L), class = "data.frame", vars = c("SPID", "season", "year",
"month", "day", "Date"), drop = TRUE, .Names = c("SPID", "season",
"year", "month", "day", "Date")))
</code>```

答:
Figured this one out, based on some of the stuff that ed_sans suggested. Ended up creating a new column:

```<code>Rate_by_site_night$DaysSinceNov1<-as.numeric(Rate_by_site_night$Date-
as.Date(paste0(Rate_by_site_night$season, '-11-01')))
</code>```

and using that as the x-axis variable with a scale_x_continuous argument using these variables as breaks and labels:

```<code>test_breaks=c(0,30,61,92,120,151) #month boundaries in terms of days since Nov 1
test_labels=format(as.Date(test_breaks, origin='2016-11-01'), format= '%b')
</code>```

Luckily none of my years was a leap year, in which case my month-boundary breaks for March and April would be off.

Body:
I am trying to create a graph with 3 survey seasons, each crossing over a year boundary (ie 2009-2010, 2010-2011, 2016-2017), but where survey effort starts and ends at a different point in each survey season. What I currently have is:

I'd like to end up with each x-axis showing November-April of that survey season (ie the 2009-2010 survey season would show November 2009-April 2010) to better show where survey effort is lacking in terms of interannual comparison. I'm just not sure how to do that within the context of scale_x_date(). My current scale statement is simply scale_x_date(date_breaks = '1 month',date_labels='%b')+ My only thought so far is to basically just create a bunch of NA data with the relevant dates and continue to let the dates scale automatically, but for my future reference I'm wondering if there's a better way to create those kind of "year-less" date limits.

Some more information:

the head of my data (which in this case will be in the top-left facet of the plot):

structure(list(SPID = c("Cho_001", "Cho_001", "Cho_001", "Cho_001",
"Cho_001", "Cho_001"), season = c(2009, 2009, 2009, 2009, 2009,
2009), Date = structure(c(14579, 14580, 14581, 14582, 14583,
14584), class = "Date"), DayOfYear = c(335, 336, 337, 338, 339,
340), year = c(2009L, 2009L, 2009L, 2009L, 2009L, 2009L), month = c(12L,
12L, 12L, 12L, 12L, 12L), day = 1:6, RatePerMin = c(3.6667, 4.8667,
13.1667, 23.0333, 24.6667, 25.4667), N = c(3L, 30L, 30L, 30L,
30L, 30L), sd = c(3.5119, 6.9269, 8.1074, 4.2789, 4.9434, 4.2729
), se = c(2.0276, 1.2647, 1.4802, 0.7812, 0.9025, 0.7801), Illu = c(0.999348417128253,
0.999986511310919, 0.991435775301254, 0.955915838251852, 0.894428866388813,
0.810868946410883)), .Names = c("SPID", "season", "Date", "DayOfYear",
"year", "month", "day", "RatePerMin", "N", "sd", "se", "Illu"
), row.names = c(NA, -6L), class = c("grouped_df", "tbl_df",
"tbl", "data.frame"), vars = c("SPID", "season", "year", "month",
"day", "Date"), drop = TRUE, indices = list(0L, 1L, 2L, 3L, 4L,
    5L), group_sizes = c(1L, 1L, 1L, 1L, 1L, 1L), biggest_group_size = 1L, labels = structure(list(
    SPID = c("Cho_001", "Cho_001", "Cho_001", "Cho_001", "Cho_001",
    "Cho_001"), season = c(2009, 2009, 2009, 2009, 2009, 2009
    ), year = c(2009L, 2009L, 2009L, 2009L, 2009L, 2009L), month = c(12L,
    12L, 12L, 12L, 12L, 12L), day = 1:6, Date = structure(c(14579,
    14580, 14581, 14582, 14583, 14584), class = "Date")), row.names = c(NA,
-6L), class = "data.frame", vars = c("SPID", "season", "year",
"month", "day", "Date"), drop = TRUE, .Names = c("SPID", "season",
"year", "month", "day", "Date")))

Body:
Figured this one out, based on some of the stuff that ed_sans suggested. Ended up creating a new column:

Rate_by_site_night$DaysSinceNov1<-as.numeric(Rate_by_site_night$Date-
as.Date(paste0(Rate_by_site_night$season, '-11-01')))

and using that as the x-axis variable with a scale_x_continuous argument using these variables as breaks and labels:

test_breaks=c(0,30,61,92,120,151) #month boundaries in terms of days since Nov 1
test_labels=format(as.Date(test_breaks, origin='2016-11-01'), format= '%b')

Luckily none of my years was a leap year, in which case my month-boundary breaks for March and April would be off.


问:
Redux: Generic update action
I'm working with Redux and my state is a normalized one with a lot of different models. Now I was wondering myself if it was better to have specific actions like:

```<code>{type: CHANGE_MODEL_NAME, modelId, name}
</code>```

vs

```<code>{type: UPDATE_MODEL, modelId, {name}}
</code>```

I did a bit of searching and I found this question:

Is it ok to create generic redux update action

Now what I'm wondering is that no one is adressing the fact that having specific action types allow for different reducers to 'react' to an action in a cleaner way.

IE: I have a model that is copied from another model like so:

```<code>{
  name: 'foo',
  originalModel: id_0
}
</code>```

It then becomes easier to react to specific actions in my reducer of copied models if I only want to react to the name change action.

Is it wrong for 2 reducers to react to the same actions? Is that why nobody adressed this issue in the original question?

答:
Having multiple slice reducers respond to the same actions is absolutely an intended use case for Redux.  I covered that background in my post The Tao of Redux, Part 1 - Implementation and Intent.

As for your specific question: I think it's entirely valid to have an update action for normalized data that contains the item type name and the item ID.  In fact, I demonstrated this exact approach in my post Practical Redux, Part 7: Form Change Handling, Data Editing, and Feature Reducers.

Overall, Redux itself doesn't care what specific action types you have and how generic they are.  You are encouraged to define whatever actions are appropriate for your app, and what level of "abstraction" they represent.  It's very reasonable to make them a bit more generic - for example, I'd prefer UPDATE_USER_ATTRIBUTES instead of SET_USER_FIRST_NAME and SET_USER_LAST_NAME, but ultimately it's up to you.

Title: Redux: Generic update action

Body:
I'm working with Redux and my state is a normalized one with a lot of different models. Now I was wondering myself if it was better to have specific actions like:

{type: CHANGE_MODEL_NAME, modelId, name}

vs

{type: UPDATE_MODEL, modelId, {name}}

I did a bit of searching and I found this question:

Is it ok to create generic redux update action

Now what I'm wondering is that no one is adressing the fact that having specific action types allow for different reducers to 'react' to an action in a cleaner way.

IE: I have a model that is copied from another model like so:

{
  name: 'foo',
  originalModel: id_0
}

It then becomes easier to react to specific actions in my reducer of copied models if I only want to react to the name change action.

Is it wrong for 2 reducers to react to the same actions? Is that why nobody adressed this issue in the original question?


问:
Parsing list of variants with boost spirit X3
I try to parse a simple list of float or int into a vector of variant. I'm using boost 1.64 on Windows (mingw 64bit).

Here is a minimal example:

```<code>#include <boost/spirit/home/x3/support/ast/variant.hpp>
#include <boost/fusion/adapted/struct.hpp>
#include <boost/spirit/home/x3.hpp>

#include <iostream>
#include <vector>

namespace x3 = boost::spirit::x3;

struct var : x3::variant<int, float> {
    using base_type::base_type;
    using base_type::operator=;
};

struct block {
    bool dummy; // needed to make newer boost version compile
    std::vector<var> vars;
};

BOOST_FUSION_ADAPT_STRUCT(block,
    (bool, dummy),
    (std::vector<var>, vars)
);

x3::rule<class var,   var>     const r_var   = "var";
x3::rule<class block, block>   const r_block = "block";

auto const r_var_def   = x3::float_ | x3::int_;
auto const r_block_def = x3::attr(true) >> *x3::lit(";") >> *(r_var >> -x3::lit(","));

BOOST_SPIRIT_DEFINE(r_var, r_block);

bool parse(std::string const &txt, block &ast)
{
    using boost::spirit::x3::phrase_parse;
    using boost::spirit::x3::space;

    auto iter = txt.begin();
    auto end = txt.end();

    const bool parsed = phrase_parse(iter, end, r_block, space, ast);
    return parsed && iter == end;
}

int main() {
    std::vector<std::string> list = {
        "1, 3, 5.5",
        ";1.0, 2.0, 3.0, 4.0"
    };

    for (const auto&i : list) {
        block ast;
        if (parse(i, ast)) {
            std::cout << "OK: " << i << std::endl;
        } else {
            std::cout << "FAIL: " << i << std::endl;
        }
    }
}
</code>```

GCC 7.1 gives the following error:

```<code>..\parser\parser.cpp:41:68:   required from here
..\..\win64\include/boost/spirit/home/x3/nonterminal/detai/rule.hpp:313:24: error: use of deleted function 'var::var(const var&)'
             value_type made_attr = make_attribute::call(attr);
                        ^~~~~~~~~
</code>```

Any ideas, why GCC doesn't compile it? It works with Clang though.

Live on Coliru (switch to clang++ to see it work).

答:
It seems that there is a problem using the inherited special members. Two workarounds:

```<code>using var = x3::variant<int, float>;
</code>```

Alternatively:

```<code>struct var : x3::variant<int, float> {
    var            (          ) = default;
    var            (var const&) = default;
    var& operator= (var const&) = default;
    using base_type::base_type;
    using base_type::operator=;
};
</code>```

Body:
I try to parse a simple list of float or int into a vector of variant. I'm using boost 1.64 on Windows (mingw 64bit).

Here is a minimal example:

#include <boost/spirit/home/x3/support/ast/variant.hpp>
#include <boost/fusion/adapted/struct.hpp>
#include <boost/spirit/home/x3.hpp>

#include <iostream>
#include <vector>

namespace x3 = boost::spirit::x3;

struct var : x3::variant<int, float> {
    using base_type::base_type;
    using base_type::operator=;
};

struct block {
    bool dummy; // needed to make newer boost version compile
    std::vector<var> vars;
};

BOOST_FUSION_ADAPT_STRUCT(block,
    (bool, dummy),
    (std::vector<var>, vars)
);

x3::rule<class var,   var>     const r_var   = "var";
x3::rule<class block, block>   const r_block = "block";

auto const r_var_def   = x3::float_ | x3::int_;
auto const r_block_def = x3::attr(true) >> *x3::lit(";") >> *(r_var >> -x3::lit(","));

BOOST_SPIRIT_DEFINE(r_var, r_block);

bool parse(std::string const &txt, block &ast)
{
    using boost::spirit::x3::phrase_parse;
    using boost::spirit::x3::space;

    auto iter = txt.begin();
    auto end = txt.end();

    const bool parsed = phrase_parse(iter, end, r_block, space, ast);
    return parsed && iter == end;
}

int main() {
    std::vector<std::string> list = {
        "1, 3, 5.5",
        ";1.0, 2.0, 3.0, 4.0"
    };

    for (const auto&i : list) {
        block ast;
        if (parse(i, ast)) {
            std::cout << "OK: " << i << std::endl;
        } else {
            std::cout << "FAIL: " << i << std::endl;
        }
    }
}

GCC 7.1 gives the following error:

..\parser\parser.cpp:41:68:   required from here
..\..\win64\include/boost/spirit/home/x3/nonterminal/detai/rule.hpp:313:24: error: use of deleted function 'var::var(const var&)'
             value_type made_attr = make_attribute::call(attr);
                        ^~~~~~~~~

Any ideas, why GCC doesn't compile it? It works with Clang though.

Live on Coliru (switch to clang++ to see it work).

Body:
It seems that there is a problem using the inherited special members. Two workarounds:

using var = x3::variant<int, float>;

Alternatively:

struct var : x3::variant<int, float> {
    var            (          ) = default;
    var            (var const&) = default;
    var& operator= (var const&) = default;
    using base_type::base_type;
    using base_type::operator=;
};


问:
request file not working in asp.net
i need to request file from fileupload that is created in html. my question is quite simple how do i do this?
i know there is this option : HttpPostedFile File = Request.Files["imagem"]; but when i try to do that my File returns NULL.
I dont know what am i doing wrong, but even this simple code example is not working and i dont know why .

```<code><body>
    <form id="form1" runat="server">
    <div>
    protected void Button1_Click(object sender, EventArgs e)
        {
            HttpPostedFile File = Request.Files["imagem"];
      if ( File != null)
     Response.Write("Sucesso");
    }
   </form>
</body>
</code>```

and here is my aspx code example :

```<code>  <input type="file" name="image"  class="image-upload" /></div>
 <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</code>```

can any one explain what am i doing wrong ? thank you

答:
Might just be a typo on here, but change your imagem to image

```<code>protected void Button1_Click(object sender, EventArgs e)
{
    HttpPostedFile File = Request.Files["image"];

    if ( File != null)
        Response.Write("Sucesso");
}
</code>```

In your aspx page you need to tell the form that it will be using files.  I don't think its required but its good practice to also include an id in your input that matches your name.

```<code><body>
    <form id="form1" runat="server" method="post" enctype="multipart/form-data">
        <input type="file" id="image" name="image"  class="image-upload" />
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    </form>
</body>
</code>```

Title: request file not working in asp.net

Body:
i need to request file from fileupload that is created in html. my question is quite simple how do i do this?
i know there is this option : HttpPostedFile File = Request.Files["imagem"]; but when i try to do that my File returns NULL.
I dont know what am i doing wrong, but even this simple code example is not working and i dont know why .

    <form id="form1" runat="server">

    protected void Button1_Click(object sender, EventArgs e)
        {
            HttpPostedFile File = Request.Files["imagem"];
      if ( File != null)
     Response.Write("Sucesso");
    }
   </form>

and here is my aspx code example :

  <input type="file" name="image"  class="image-upload" />

 <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

can any one explain what am i doing wrong ? thank you

Body:
Might just be a typo on here, but change your imagem to image

protected void Button1_Click(object sender, EventArgs e)
{
    HttpPostedFile File = Request.Files["image"];

    if ( File != null)
        Response.Write("Sucesso");
}

In your aspx page you need to tell the form that it will be using files.  I don't think its required but its good practice to also include an id in your input that matches your name.

<body>
    <form id="form1" runat="server" method="post" enctype="multipart/form-data">
        <input type="file" id="image" name="image"  class="image-upload" />
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    </form>
</body>


问:
C++ virtual method, that doesn't require "this" pointer - optimization
I'd like to implement access to a certain class:

```<code>class A { some properties and methods };
</code>```

The problem is there are multiple states A can be in and the methods need to behave accordingly. One way is this:

```<code>class A
{
    void Method1() {
        if (A is in state 1) { do something }
        else if (A is in state 2) { do something else }
        ...
    }
};
</code>```

That obviously isn't very optimal, if the methods are called many times. So a solution, which is simple to implement, would be to create several classes for different states:

```<code>class A
{
    class State1 {
        virtual void Method1(A& a) { do something; }
        ...
    } State1Instance;

    class State2 { ... }
    ...
};
</code>```

And then manage a pointer to the object depending on current state (e.g. State1Instance) and call methods of this object. That avoids the CPU consuming condition.

BUT the State# methods also receive the completely useless "this" pointer to the State object. Is there a way to avoid this? I know the difference is minimal, but I'm trying to make this as optimal as possible and using a CPU register for a completely pointless value is not ideal. This would actually be a good use for "virtual static", which is forbidden however.

答:
Just use good old function pointers if you're really concerned about the repeated branches, which usually you shouldn't.

```<code>struct A
{
    using StateFn = void (*)(A&);

    static void State1(A& a) { a.i = 42; }
    static void State2(A& a) { a.i = 420; }

    void Method1() { s(*this); }

    StateFn s = State1;
    int i;
};
</code>```

If you have multiple methods associated with each state, a table of methods can be constructed as such

```<code>struct A
{
    static void State1M1(A& a) { a.i = 42; }
    static void State2M1(A& a) { a.i = 420; }

    static int State1M2(A& a) { return a.i * 42; }
    static int State2M2(A& a) { return a.i * 420; }

    // The naming sucks, you should find something better

    static constexpr struct {
        void (*Method1)(A&);
        int (*Method2)(A&);
    } State[] = {{State1M1, State1M2}, {State2M1, State2M2}};

    void Method1() { State[s].Method1(*this); }
    int Method2() { return State[s].Method2(*this); }

    int s, i;
};
</code>```

I'm curious if this is even a speedup over a switch statement, do benchmark before you adopt it. You really aren't doing something too different from polymorphism, in a rather un-optimized manner, when you start constructing a method table like in the second case.

Body:
I'd like to implement access to a certain class:

class A { some properties and methods };

The problem is there are multiple states A can be in and the methods need to behave accordingly. One way is this:

class A
{
    void Method1() {
        if (A is in state 1) { do something }
        else if (A is in state 2) { do something else }
        ...
    }
};

That obviously isn't very optimal, if the methods are called many times. So a solution, which is simple to implement, would be to create several classes for different states:

class A
{
    class State1 {
        virtual void Method1(A& a) { do something; }
        ...
    } State1Instance;

    class State2 { ... }
    ...
};

And then manage a pointer to the object depending on current state (e.g. State1Instance) and call methods of this object. That avoids the CPU consuming condition.

BUT the State# methods also receive the completely useless "this" pointer to the State object. Is there a way to avoid this? I know the difference is minimal, but I'm trying to make this as optimal as possible and using a CPU register for a completely pointless value is not ideal. This would actually be a good use for "virtual static", which is forbidden however.

Body:
Just use good old function pointers if you're really concerned about the repeated branches, which usually you shouldn't.

struct A
{
    using StateFn = void (*)(A&);

    static void State1(A& a) { a.i = 42; }
    static void State2(A& a) { a.i = 420; }

    void Method1() { s(*this); }

    StateFn s = State1;
    int i;
};

If you have multiple methods associated with each state, a table of methods can be constructed as such

struct A
{
    static void State1M1(A& a) { a.i = 42; }
    static void State2M1(A& a) { a.i = 420; }

    static int State1M2(A& a) { return a.i * 42; }
    static int State2M2(A& a) { return a.i * 420; }

    // The naming sucks, you should find something better

    static constexpr struct {
        void (*Method1)(A&);
        int (*Method2)(A&);
    } State[] = {{State1M1, State1M2}, {State2M1, State2M2}};

    void Method1() { State[s].Method1(*this); }
    int Method2() { return State[s].Method2(*this); }

    int s, i;
};

I'm curious if this is even a speedup over a switch statement, do benchmark before you adopt it. You really aren't doing something too different from polymorphism, in a rather un-optimized manner, when you start constructing a method table like in the second case.


问:
How can I extract data from OData API to SQL
I'm wondering what the community suggests for extracting data from an OData API to SQL 2008 R2. I need to create a nightly job that imports the data to SQL. Should I create a simple console app that iterates through the OData API and imports to SQL? Or can I create some type of SQL Server BI app? Or is there a better way to do this?</p>

答:
This is going to be sooo slow. OData is not an API for bulk operations. It is designed for clients to access individual entities and navigate relations between them, at most paginate across some filtered lists.

Extracting a entire dump via OData is not going to make anybody happy. The OData API owner will have to investigate who is doing all these nightly crawls over his API and discover it is you and likely cut you off. You on the other hand will discover that OData is not an efficient bulk transport format and marshaling HTTP encoded entities back and forth is not exactly the best way to spend your bandwidth. And crawling the entire database every time, as opposed to just discovering the deltagrams from last crawl, is only going to work until the database reaches that critical size S at which the update takes longer than the frequency you're pooling!

Besides, if is not your data, it is extremely likely that the use terms for the OData API explicitly prevent such bulk crawls.

Get a dump of the data, archive it, and copy it using FTP.


问:
Custom ContextConfiguration Loader issues when upgrading from Spring Framework 4.2.9 to 4.3+
I  am having some issues running my integration tests after upgrading the Spring Framework spring-test dependency from 4.2.9 to 4.3.9.

I am using a ContextConfiguration class which implements the spring test SmartContextLoader which allowed me to load different .xml config files which are split by profile. Based on the current spring profile it will run the specific beans for that profile.

This ContextConfigurationLoader I have ran perfectly fine in version 4.2.9 but after upgrading to version 4.3 and I am struggling to resolve this issue.

I am including the ContextConfigurationLoader I created in my integration tests like so.

```<code>@ContextConfiguration(loader=ContextConfigurationLoader.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class MyIntegrationTest {
     // Test Body
}
</code>```

The ContextConfigurationLoader looks like this,

```<code>public class ContextConfigurationLoader implements SmartContextLoader {

    @Override
    public void processContextConfiguration(ContextConfigurationAttributes contextConfigurationAttributes) {

    }

    @Override
    public ApplicationContext loadContext(MergedContextConfiguration mergedContextConfiguration) throws Exception {

        GenericXmlApplicationContext context = new GenericXmlApplicationContext();

        context.getEnvironment().setActiveProfiles(mergedContextConfiguration.getActiveProfiles());

        new XmlBeanDefinitionReader(context).
                loadBeanDefinitions(mergedContextConfiguration.getLocations());

        context.load(
                "/development.xml",
                "/staging.xml",
                "/production.xml",
        );

        AnnotationConfigUtils.registerAnnotationConfigProcessors(context);

        context.refresh();
        context.registerShutdownHook();

        return context;
    }

    @Override
    public String[] processLocations(Class<?> aClass, String... strings) {
        return new String[0];
    }

    @Override
    public ApplicationContext loadContext(String... strings) throws Exception {
        ApplicationContext context = ApplicationContextFactory.create();

        context.getBean("dbUnitDatabaseConnection");
        return ApplicationContextFactory.create();
    }
}
</code>```

Lastly this is the error response I get after attempting to run my tests.

```<code>java.lang.IllegalStateException: ContextConfigurationLoader was unable to detect defaults, and no ApplicationContextInitializers or ContextCustomizers were declared for context configuration attributes [[ContextConfigurationAttributes@53ca01a2 declaringClass = 'com.class.path.to.MyIntegrationTest', classes = '{}', locations = '{}', inheritLocations = true, initializers = '{}', inheritInitializers = true, name = [null], contextLoaderClass = 'com.class.path.to.ContextConfigurationLoader']]
</code>```

Thanks for your help, let me know if you need anymore information.

One solution I have found is including all of the .xml config files into one file and using the @ContextConfiguration annotation like this.

```<code>@ContextConfiguration("/config.xml")
</code>```

But this would require some other changes to the rest of the code outside of the tests. This also doesn't help explain why my current implementation doesn't work on the latest Spring Framework spring-test version.

答:
From the Javadoc of SmartContextLoader.processContextConfiguration(ContextConfigurationAttributes):

Note: in contrast to a standard ContextLoader, a SmartContextLoader must preemptively verify that a generated or detected default actually exists before setting the corresponding locations or classes property in the supplied ContextConfigurationAttributes. Consequently, leaving the locations or classes property empty signals that this SmartContextLoader was not able to generate or detect defaults.

The behavior described in the last sentence is what is causing you problems.

Thus, a solution to your problem would be to actually implement processContextConfiguration() and set a bogus location in the supplied ContextConfigurationAttributes. That would instruct Spring that your custom loader was able to properly detect defaults (which you hard code in loadContext()). You could then remove the bogus location from a copy of mergedContextConfiguration.getLocations() before passing them to loadBeanDefinitions().

That would make it cleaner for end users; however, an alternative (if you don't really have any end users other than yourself) would be to declare the location of an existing XML configuration file (via @ContextConfiguration) that simply does not actually declare any beans.

Regards,

Sam (author of the Spring TestContext Framework)

Body:
I  am having some issues running my integration tests after upgrading the Spring Framework spring-test dependency from 4.2.9 to 4.3.9.

I am using a ContextConfiguration class which implements the spring test SmartContextLoader which allowed me to load different .xml config files which are split by profile. Based on the current spring profile it will run the specific beans for that profile.

This ContextConfigurationLoader I have ran perfectly fine in version 4.2.9 but after upgrading to version 4.3 and I am struggling to resolve this issue.

I am including the ContextConfigurationLoader I created in my integration tests like so.

@ContextConfiguration(loader=ContextConfigurationLoader.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class MyIntegrationTest {
     // Test Body
}

The ContextConfigurationLoader looks like this,

public class ContextConfigurationLoader implements SmartContextLoader {

    @Override
    public void processContextConfiguration(ContextConfigurationAttributes contextConfigurationAttributes) {

    }

    @Override
    public ApplicationContext loadContext(MergedContextConfiguration mergedContextConfiguration) throws Exception {

        GenericXmlApplicationContext context = new GenericXmlApplicationContext();

        context.getEnvironment().setActiveProfiles(mergedContextConfiguration.getActiveProfiles());

        new XmlBeanDefinitionReader(context).
                loadBeanDefinitions(mergedContextConfiguration.getLocations());

        context.load(
                "/development.xml",
                "/staging.xml",
                "/production.xml",
        );

        AnnotationConfigUtils.registerAnnotationConfigProcessors(context);

        context.refresh();
        context.registerShutdownHook();

        return context;
    }

    @Override
    public String[] processLocations(Class<?> aClass, String... strings) {
        return new String[0];
    }

    @Override
    public ApplicationContext loadContext(String... strings) throws Exception {
        ApplicationContext context = ApplicationContextFactory.create();

        context.getBean("dbUnitDatabaseConnection");
        return ApplicationContextFactory.create();
    }
}

Lastly this is the error response I get after attempting to run my tests.

java.lang.IllegalStateException: ContextConfigurationLoader was unable to detect defaults, and no ApplicationContextInitializers or ContextCustomizers were declared for context configuration attributes [[ContextConfigurationAttributes@53ca01a2 declaringClass = 'com.class.path.to.MyIntegrationTest', classes = '{}', locations = '{}', inheritLocations = true, initializers = '{}', inheritInitializers = true, name = [null], contextLoaderClass = 'com.class.path.to.ContextConfigurationLoader']]

Thanks for your help, let me know if you need anymore information.

One solution I have found is including all of the .xml config files into one file and using the @ContextConfiguration annotation like this.

@ContextConfiguration("/config.xml")

But this would require some other changes to the rest of the code outside of the tests. This also doesn't help explain why my current implementation doesn't work on the latest Spring Framework spring-test version.


问:
socket lagging every few seconds
i am beginner with the network programming actually this is my first networking code ever ,

my problem is i was trying to make simple online game but the game keep lagging its not lagging when i open the server code and the client code on the same computer

but when i open the client code on different  computer it start to lagging
it work very great for few seconds then suddenly it stop working for like one or two seconds or less , then it come back working again with no problems,

after trying to found out where the lagging happen it was looking like it happen on both the server and the client in the same time and they come back working also on the same time

after searching for solution for while i didn't found anything working for me as long as most of the solutions i found was for more advance problems but i found that i should use "PodSixNet" for online games not socket but i am still going to try with the socket , here is my code :

the server :

```<code>import socket,pygame,os,sys
from pygame.locals import*
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (0,30)
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverSocket.bind((socket.gethostbyname(socket.gethostname()), 23000))
serverSocket.listen(1)
screen=pygame.display.set_mode((250,250))
pygame.init()
clock = pygame.time.Clock()
WHITE = (250, 250, 250)
x=0
y=0
chx=0
chy=0
while True:
        screen.fill((0,0,0))
        for event in pygame.event.get():
            if event.type == QUIT :
                pygame.quit()
                quit()
        clientSocket, (remoteHost, remotePort) = serverSocket.accept()
        rec = clientSocket.recv(100)
        clientSocket.close()
        chx=rec[0]
        chy=rec[1]
        if rec[0]==2:
                chx=-1
        if rec[1]==2:
                chy=-1
        x+=chx
        y+=chy
        pygame.draw.rect(screen, WHITE, (x,y,10,10))
        pygame.display.update()
        clock.tick_busy_loop(60)
</code>```

the client :

```<code>import socket,pygame
from pygame.locals import*
screen=pygame.display.set_mode((250,250))
pygame.init()
clock=pygame.time.Clock()
WHITE = (250, 250, 250)
chx=0
chy=0
x=0
y=0
chxx=0
chyy=0
while True:
        screen.fill((0,0,0))
        for event in pygame.event.get():
            if event.type == QUIT :
                pygame.quit()
                quit()
            if event.type == KEYDOWN:
                    if event.key==K_w:
                        chy=2
                    if event.key==K_d:
                        chx=1
                    if event.key==K_s:
                        chy=1
                    if event.key==K_a:
                        chx=2
            if event.type==KEYUP:
                    if event.key==K_w or event.key==K_s:
                        chy=0
                    if event.key==K_d or event.key==K_a:
                        chx=0
        clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        clientSocket.connect(('192.168.0.112', 23000))
        clientSocket.send(bytearray([chx,chy]))
        clientSocket.close()
        chxx=chx
        chyy=chy
        if chx==2:
                chxx=-1
        if chy==2:
                chyy=-1
        x+=chxx
        y+=chyy
        pygame.draw.rect(screen, WHITE, (x,y,10,10))
        pygame.display.update()
        clock.tick_busy_loop(60)
</code>```

and i know there is lot of lazy and wrong things on that code its because this is not the code i will use in the game ,

in that code iam just trying to make the online working with out lagging

答:
It looks like you're opening and closing the socket with every loop iteration.

Try opening the socket before the loop and then closing it when the loop exits.

Title: socket lagging every few seconds

Body:
i am beginner with the network programming actually this is my first networking code ever ,

my problem is i was trying to make simple online game but the game keep lagging its not lagging when i open the server code and the client code on the same computer

but when i open the client code on different  computer it start to lagging
it work very great for few seconds then suddenly it stop working for like one or two seconds or less , then it come back working again with no problems,

after trying to found out where the lagging happen it was looking like it happen on both the server and the client in the same time and they come back working also on the same time

after searching for solution for while i didn't found anything working for me as long as most of the solutions i found was for more advance problems but i found that i should use "PodSixNet" for online games not socket but i am still going to try with the socket , here is my code :

the server :

import socket,pygame,os,sys
from pygame.locals import*
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (0,30)
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverSocket.bind((socket.gethostbyname(socket.gethostname()), 23000))
serverSocket.listen(1)
screen=pygame.display.set_mode((250,250))
pygame.init()
clock = pygame.time.Clock()
WHITE = (250, 250, 250)
x=0
y=0
chx=0
chy=0
while True:
        screen.fill((0,0,0))
        for event in pygame.event.get():
            if event.type == QUIT :
                pygame.quit()
                quit()
        clientSocket, (remoteHost, remotePort) = serverSocket.accept()
        rec = clientSocket.recv(100)
        clientSocket.close()
        chx=rec[0]
        chy=rec[1]
        if rec[0]==2:
                chx=-1
        if rec[1]==2:
                chy=-1
        x+=chx
        y+=chy
        pygame.draw.rect(screen, WHITE, (x,y,10,10))
        pygame.display.update()
        clock.tick_busy_loop(60)

the client :

import socket,pygame
from pygame.locals import*
screen=pygame.display.set_mode((250,250))
pygame.init()
clock=pygame.time.Clock()
WHITE = (250, 250, 250)
chx=0
chy=0
x=0
y=0
chxx=0
chyy=0
while True:
        screen.fill((0,0,0))
        for event in pygame.event.get():
            if event.type == QUIT :
                pygame.quit()
                quit()
            if event.type == KEYDOWN:
                    if event.key==K_w:
                        chy=2
                    if event.key==K_d:
                        chx=1
                    if event.key==K_s:
                        chy=1
                    if event.key==K_a:
                        chx=2
            if event.type==KEYUP:
                    if event.key==K_w or event.key==K_s:
                        chy=0
                    if event.key==K_d or event.key==K_a:
                        chx=0
        clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        clientSocket.connect(('192.168.0.112', 23000))
        clientSocket.send(bytearray([chx,chy]))
        clientSocket.close()
        chxx=chx
        chyy=chy
        if chx==2:
                chxx=-1
        if chy==2:
                chyy=-1
        x+=chxx
        y+=chyy
        pygame.draw.rect(screen, WHITE, (x,y,10,10))
        pygame.display.update()
        clock.tick_busy_loop(60)

and i know there is lot of lazy and wrong things on that code its because this is not the code i will use in the game ,

in that code iam just trying to make the online working with out lagging