问:
Azure WebJobs Scheduler
Can we have multiple Schedules in a Single web Job of Microsoft Azure.
We have certain functionalities  to happen in a single job within particular time
i.e multiple schedules so we have tried through the timer but i need to know is there any other option.Thank you </p>

答:
You can use the TimerTriggerAttribute: Please refer https://github.com/Azure/azure-webjobs-sdk-extensions#timertrigger</p>

```<code>// Triggered every hours
public static void HourlyTimerJob([TimerTrigger("00:01:00")] TimerInfo timerInfo, TextWriter log)
{
    log.WriteLine("Your first scheduled job!");
}

// Triggered every 15 minutes
public static void MinutelyTimerJob([TimerTrigger("00:00:15")] TimerInfo timerInfo, TextWriter log)
{
    log.WriteLine("Your second scheduled job!");
}
</code>```

Title: Azure WebJobs Scheduler

Body:
You can use the TimerTriggerAttribute: Please refer https://github.com/Azure/azure-webjobs-sdk-extensions#timertrigger

// Triggered every hours
public static void HourlyTimerJob([TimerTrigger("00:01:00")] TimerInfo timerInfo, TextWriter log)
{
    log.WriteLine("Your first scheduled job!");
}

// Triggered every 15 minutes
public static void MinutelyTimerJob([TimerTrigger("00:00:15")] TimerInfo timerInfo, TextWriter log)
{
    log.WriteLine("Your second scheduled job!");
}


来源: stackexchange

问:
Tensorflow numpy to tensorflow
I have read a csv file using numpy genfromtxt

csv_file = np.genfromtxt(args.dataset, delimiter=',',skip_header=1,usecols=(0,1,2,3,4,5), dtype=None)

Ques: How to use string_input_producer to queue and batch the files.

答:
You can read a Numpy array from CSV as you do and chop it up into batches manually. However, TF has a built-in functionality of reading from multiple CSV files and putting rows together either into randomized or sequential batches. You can read cells of varying data-types and convert them into your relevant data-types as need be.

The working code to do this is discussed in this question:
Converting TensorFlow tutorial to work with my own data

In a nutshell, the key functions you need are tf.TextLineReader, tf.train.string_input_producer, and tf.train.shuffle_batch, or tf.train.batch, depending on your needs.

The only limitation of that method that I'm aware of is that your rows within the CSV file should be of equal length.

ContentLicense: CC BY-SA 3.0

Title: Tensorflow numpy to tensorflow


问:
Is there a maven jigsaw jlink plugin?
Does maven have a plugin for the new Java 9 jlink I have searched online but have not been able to find anything official from the maven team.

答:
Yes. There has been some progress made to create one on Github/maven-plugins for the same.

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jlink-plugin</artifactId>
    <version>3.0.0-SNAPSHOT</version>
</plugin>
</code>```

The plugin in its code reads to be adaptive to JEP-282 and JEP-220  from the proposals.

And though this might look like a link too many answer. There is a working example from @khmarbaise on Github as well for this, which requires a toolchain with -

```<code><configuration>
  <jdkHome>/Library/Java/JavaVirtualMachines/jdk1.9.0_ea+170.jdk/Contents/Home</jdkHome>
</configuration>
</code>```

Plus a side note from the author quoting -

Currently not more than a Proof of Concept. Everything here is speculative!

Edit1:- As shared in the comments, additional details could be found @ How to create a Java runtime with Maven.

Edit2:- Dated 10 November, 2018 one can upgrade to using maven-jlink-plugin:3.0.0-alpha-1 and still provide some valuable feedback.

Title: Is there a maven jigsaw jlink plugin?

Body:
Yes. There has been some progress made to create one on Github/maven-plugins for the same.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jlink-plugin</artifactId>
    <version>3.0.0-SNAPSHOT</version>
</plugin>

The plugin in its code reads to be adaptive to JEP-282 and JEP-220  from the proposals.

And though this might look like a link too many answer. There is a working example from @khmarbaise on Github as well for this, which requires a toolchain with -

<configuration>
  <jdkHome>/Library/Java/JavaVirtualMachines/jdk1.9.0_ea+170.jdk/Contents/Home</jdkHome>
</configuration>

Plus a side note from the author quoting -

Currently not more than a Proof of Concept. Everything here is speculative!

Edit1:- As shared in the comments, additional details could be found @ How to create a Java runtime with Maven.

Edit2:- Dated 10 November, 2018 one can upgrade to using maven-jlink-plugin:3.0.0-alpha-1 and still provide some valuable feedback.

ContentLicense: CC BY-SA 4.0


问:
How to get Google authentication to work with ReactJs?
I have been trying the whole day to get Google authentication to work with React, but after searching for hours trying everything i found i only get a buggy, sometimes-working, mess. Can anyone see what i am doing wrong? (This is for a school project so i'm learning!)

The project will be an online schedule creator.

My main Index.js has the following render-function:

```<code>  function renderApp() {
    ReactDOM.render(
      <Router history={browserHistory}>
        <Route path="/" component={Login}></Route>
        <Route component={AuthUserContainer}>
          <Route path="/auth" component={Layout}>
            <IndexRoute component={Overview}></IndexRoute>
            <Route path="schedule(/:scheduleid)" component={Schedule}></Route>
          </Route>
        </Route>
      </Router>,
    app);
  }
</code>```

The home-page is simply a login page, handled by the Login component which will redirect the user to /auth if the authentication is successful. Authentication is continually handled by AuthUserContainer everytime a protected route is accessed.

The Login component has the Google Sign In button, and all protected routes has (via Layout component) a Google Sign Out button.

My Header.js contains the "Google Sign Out button" (signOutHandler):

```<code>export default class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
    this.SignOutHandler = this.SignOutHandler.bind(this);
  }

  SignOutHandler() {
    var auth2 = gapi.auth2.getAuthInstance();
    auth2.signOut().then(function () {
      console.log('User signed out.');
      Authenticate.signOutUser();
    });
  }

  render() {
    return (
      <div class="header-content">
        <h2 class="header-title">Schedule</h2>
        <h3 class="header-user-button">
            <a href="/" onClick={this.SignOutHandler}>User First Name</a>
        </h3>
      </div>
    );
  }
}
</code>```

I used Googles own example code and tried to tweak it for React. Problems i get with this code is "Uncaught TypeError: Cannot read property 'getAuthInstance' of undefined". Since i split the Sign In and Sign Out buttons to separate pages auth2 doesn't get initialised properly, but clicking the button twice can make it work. Trying to initialise it manually here often gives me the error that Gapi is undefined...

Finally the Login.js:

```<code>export default class Login extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
    this.onSignIn = this.onSignIn.bind(this);
    this.renderGoogleLoginButton = this.renderGoogleLoginButton.bind(this);
  }

  renderGoogleLoginButton() {
      console.log('rendering google signin button')
      gapi.signin2.render('my-signin2', {
        'scope': 'https://www.googleapis.com/auth/plus.login',
        'width': 200,
        'height': 50,
        'longtitle': true,
        'theme': 'light',
        'onsuccess': this.onSignIn
      });

      gapi.load('auth2', function() {
        gapi.auth2.init();
      });
    }

  componentDidMount() {
      window.addEventListener('google-loaded', this.renderGoogleLoginButton);
  }

  onSignIn(googleUser) {
    Authenticate.signInUser(googleUser.getBasicProfile());
    this.props.router.push("/auth");
  }

  render() {
    return (
      <div class="container">
        <h2 class="form-signin-heading">
          Sign-in with Google account required
        </h2>
        <div id="my-signin2"></div>
      </div>
    );
  }
}
</code>```

I based this code also on Googles own, but that didn't work at all (either the button didn't load, simply nothing showed, or it never called onSignIn). I also found and tried this, which made it kinda work (sometimes). I also tried to initialise auth2 in renderGoogleLoginButton(), but that only works sometimes aswell...

renderGoogleLoginButton() is called by the even-handler of a custom event (google-loaded) which fires when the Google API loads (exactly like in the link). Authenticate is my own class which bundles together my creation of token, getUserName functions etc.

I also get the following error from gapi: "Uncaught TypeError: Cannot read property 'style' of null", i think it tries to reference the Sign In/ Sign Out buttons but since they aren't loaded at the time they are null.

I cannot find any good solutions that doesn't result in glitches or bugs. Googles own code places everything in the same HTML-document, but since i want to split it up into components then it all breaks. Am i doing this completly wrong perhaps? I'm very new to React but hopefully it's understandable!

Sorry for the long post, thank you so much for your time, and if you have any questions just ask!

答:
React google login components are available. Its work for me.

react google login

Body:
I have been trying the whole day to get Google authentication to work with React, but after searching for hours trying everything i found i only get a buggy, sometimes-working, mess. Can anyone see what i am doing wrong? (This is for a school project so i'm learning!)

The project will be an online schedule creator.

My main Index.js has the following render-function:

  function renderApp() {
    ReactDOM.render(
      <Router history={browserHistory}>
        <Route path="/" component={Login}></Route>
        <Route component={AuthUserContainer}>
          <Route path="/auth" component={Layout}>
            <IndexRoute component={Overview}></IndexRoute>
            <Route path="schedule(/:scheduleid)" component={Schedule}></Route>
          </Route>
        </Route>
      </Router>,
    app);
  }

The home-page is simply a login page, handled by the Login component which will redirect the user to /auth if the authentication is successful. Authentication is continually handled by AuthUserContainer everytime a protected route is accessed.

The Login component has the Google Sign In button, and all protected routes has (via Layout component) a Google Sign Out button.

My Header.js contains the "Google Sign Out button" (signOutHandler):

export default class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
    this.SignOutHandler = this.SignOutHandler.bind(this);
  }

  SignOutHandler() {
    var auth2 = gapi.auth2.getAuthInstance();
    auth2.signOut().then(function () {
      console.log('User signed out.');
      Authenticate.signOutUser();
    });
  }

  render() {
    return (

Schedule

            User First Name

    );
  }
}

I used Googles own example code and tried to tweak it for React. Problems i get with this code is "Uncaught TypeError: Cannot read property 'getAuthInstance' of undefined". Since i split the Sign In and Sign Out buttons to separate pages auth2 doesn't get initialised properly, but clicking the button twice can make it work. Trying to initialise it manually here often gives me the error that Gapi is undefined...

Finally the Login.js:

export default class Login extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
    this.onSignIn = this.onSignIn.bind(this);
    this.renderGoogleLoginButton = this.renderGoogleLoginButton.bind(this);
  }

  renderGoogleLoginButton() {
      console.log('rendering google signin button')
      gapi.signin2.render('my-signin2', {
        'scope': 'https://www.googleapis.com/auth/plus.login',
        'width': 200,
        'height': 50,
        'longtitle': true,
        'theme': 'light',
        'onsuccess': this.onSignIn
      });

      gapi.load('auth2', function() {
        gapi.auth2.init();
      });
    }

  componentDidMount() {
      window.addEventListener('google-loaded', this.renderGoogleLoginButton);
  }

  onSignIn(googleUser) {
    Authenticate.signInUser(googleUser.getBasicProfile());
    this.props.router.push("/auth");
  }

  render() {
    return (

          Sign-in with Google account required

    );
  }
}

I based this code also on Googles own, but that didn't work at all (either the button didn't load, simply nothing showed, or it never called onSignIn). I also found and tried this, which made it kinda work (sometimes). I also tried to initialise auth2 in renderGoogleLoginButton(), but that only works sometimes aswell...

renderGoogleLoginButton() is called by the even-handler of a custom event (google-loaded) which fires when the Google API loads (exactly like in the link). Authenticate is my own class which bundles together my creation of token, getUserName functions etc.

I also get the following error from gapi: "Uncaught TypeError: Cannot read property 'style' of null", i think it tries to reference the Sign In/ Sign Out buttons but since they aren't loaded at the time they are null.

I cannot find any good solutions that doesn't result in glitches or bugs. Googles own code places everything in the same HTML-document, but since i want to split it up into components then it all breaks. Am i doing this completly wrong perhaps? I'm very new to React but hopefully it's understandable!

Sorry for the long post, thank you so much for your time, and if you have any questions just ask!


问:
can't get all data from table in select query
this is my table in phpmyadmin name documents. In html form, dropdown of subject name in not compulsory to select. So it can be blank and get 0 that shown in table. But when I run select query to get all documents list, can't get data of sub_id which value is 0. I want all data from documents table. Plz solve this.

```<code>$list=mysqli_query($con,"select documents.*,courses.cour_name,subjects.sub_name from documents join courses on documents.cour_id=courses.cour_id join subjects on documents.sub_id=subjects.sub_id") or die(mysqli_error($con));

doc_id=primary key,
cour_id=index key,
sub_id=index kry

doc_id  cour_id  sub_id  doc_name
  1       1         0
  6       1         2     MB-C250D-AvantGarde-2012.JPG
  7       1         1     adview.sql
  8       1         2     crane.txt
  9       1         0     ui.txt
</code>```

result after run select query

```<code>Document Id     Document Name                  Course    Subject
6               MB-C250D-AvantGarde-2012.JPG   B.com     Statistics
7               adview.sql                     B.com     Accounting
8               crane.txt                      B.com     Statistics
</code>```

答:
```<code>$list=mysqli_query($con,"select documents.*,courses.cour_name,subjects.sub_name from documents left join courses on documents.cour_id=courses.cour_id left join subjects on documents.sub_id=subjects.sub_id") or die(mysqli_error($con));
</code>```

use left join because there may be some data which is not present in another table .so join will discard those data which is not common.

Body:
this is my table in phpmyadmin name documents. In html form, dropdown of subject name in not compulsory to select. So it can be blank and get 0 that shown in table. But when I run select query to get all documents list, can't get data of sub_id which value is 0. I want all data from documents table. Plz solve this.

$list=mysqli_query($con,"select documents.*,courses.cour_name,subjects.sub_name from documents join courses on documents.cour_id=courses.cour_id join subjects on documents.sub_id=subjects.sub_id") or die(mysqli_error($con));

doc_id=primary key,
cour_id=index key,
sub_id=index kry

doc_id  cour_id  sub_id  doc_name
  1       1         0
  6       1         2     MB-C250D-AvantGarde-2012.JPG
  7       1         1     adview.sql
  8       1         2     crane.txt
  9       1         0     ui.txt

result after run select query

Document Id     Document Name                  Course    Subject
6               MB-C250D-AvantGarde-2012.JPG   B.com     Statistics
7               adview.sql                     B.com     Accounting
8               crane.txt                      B.com     Statistics

Body:
$list=mysqli_query($con,"select documents.*,courses.cour_name,subjects.sub_name from documents left join courses on documents.cour_id=courses.cour_id left join subjects on documents.sub_id=subjects.sub_id") or die(mysqli_error($con));

use left join because there may be some data which is not present in another table .so join will discard those data which is not common.


问:
Query on twitterfall.com for accessing live Twitter feeds?
The site twitterfall.com provides all live Twitter feeds by almost everyone with some delay.
How can I access or get live tweets (of everybody) from this site or any other option, that you suggest to my C# .NET application?</p>

答: I don't know if Twitterfall has an API beyond the one you can use for searching replies. If you're looking to index a large volume of tweets I'd recommend using a service like Collecta instead: http://developer.collecta.com/</p>

ContentLicense: CC BY-SA 2.5


问:
Let other class know when data finished downloading
I have a separate class which gets called from my main view controller and starts downloading json data and parsing it into an array (instance variable) asynchronously

is there any way I can notify my view controller once this data has finished downloading completely and pass this array back?

ive tried using a few loops and sleep timers in my viewdidload method to wait for data to be downloaded, but this didn't help

答:
Use Notification Center pattern.

When the data is downloaded then notify the ViewController through the notification pattern.

For Example.

[[NSNotificationCenter defaultCenter] postNotificationName:@"SampleNotification" object:arrayObject];

Add this code into the data json parsing class and Pass the Array object.

Add the below code into the ViewController class. To get the Array object.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(smapleMethod:) name:@"SampleNotification" object:nil];

-(void)smapleMethod:(NSNotification *)notification{

```<code> NSString * message=notification.object;
NSLog(@"Message =%@",message);
</code>```

}

Body:
Use Notification Center pattern.

When the data is downloaded then notify the ViewController through the notification pattern.

For Example.

[[NSNotificationCenter defaultCenter] postNotificationName:@"SampleNotification" object:arrayObject];

Add this code into the data json parsing class and Pass the Array object.

Add the below code into the ViewController class. To get the Array object.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(smapleMethod:) name:@"SampleNotification" object:nil];

-(void)smapleMethod:(NSNotification *)notification{

 NSString * message=notification.object;
NSLog(@"Message =%@",message);

}


问:
Traffic manager endpoint Degraded
I deployed a traffic manager on MS Azure. It has 2 endpoints one of them is enabled and online. bizarrely it turned to degraded, as I scaled down some Vms then scaled them back to their original size as I suspected they may be the cause.  I went through all MS.support (which is not accurate when it comes to troubleshoot traffic manager) and run invoke-webrequest  powesrhell cmd in vain.
Here is my Traffic manager:

Here is part of my Json parameter file that created my endpoint:

How can I track my traffic manager and bring it back online.

As I wanted to redeploy the whole structure within Azure portal I got the following error:

Deployment template validation failed: 'Circular dependency detected on resource: '/subscriptions/xxxxx-xx-xx-xx/resourceGroups/PcloudOxa/providers/Microsoft.Compute/virtualMachines/PcloudOxa-mongo1'. Please see https://aka.ms/arm-template/#resources for usage details.'. (Code: InvalidTemplate)

答:
According to your description, it seems somethings wrong with your app.

Error "502 bad gateway" is often caused by application level issues, such as:

1.requests taking a long time

2.application using high memory/CPU

3.application crashing due to an exception.

As you mentioned, you scaled down some Vms, maybe your app in a wrong status, so we should check your app first, make sure it running correctly.

Maybe we can follow this link to troubleshoot this issue.

Title: Traffic manager endpoint Degraded


问:
How to create groups for in-app purchase monthly auto renewable multiple products in iOS?
Say there are two groups. Suppose group A is having one product which enables user to purchase entire content of the app. It costs 14$. My app has list of Models' profiles user can buy and see. Buying group A, user can view all model's content in app. What about users who do not want to purchase entire app but to purchase some individual model's content? Prices for all models are same: 3$. How do I manage individual model purchasing? They all cannot be in the same group as Apple allows only one in-app products to run at a time in same group.

So I created same type of product in separate number of groups. They rejected my app saying that the products should be in the same group.
There will be only one in-app product needs to be created for purchasing entire content. But how about individual artist content product?

答:
I would say, give your application a separate architecture.
Say you have 2 groups as you said. Group A and Group B

Group A - costs 10$
Group B - costs 100$

Have an API call to your own server, after the purchase to notify what group the user has purchased. Now you have the power to understand or write logic, that the user falls under what?
Group B can give separate unlocks for the same user, that you have to give the user to unlock about and sync with your server.
Group A just unlocks a particular song/album that again user has to choose after the purchase, then you sync that with your server.

Anyways what I am saying is that keep the logic of what is purchased and what should be unlocked, open to the User after the purchase and then sync with your server to know about it.

I hope i understood your question and I guess this kind of architecture falls under Apple's guidelines and it shouldnt technically be rejected.


问:
rename postgresql database from command line
I run this command from a bat-file:

```<code>start/wait/d "C:\Program Files\PostgreSQL\9.1\bin\" psql.exe --port 5432 --username postgres --dbname alter_db --file ./batch/rename_database.sql
</code>```

And I get this log-error:

CEST ERROR:  syntax error at or near

"ï»¿ALTER" at character 1 CEST STATEMENT:  ï»¿ALTER DATABASE postgres
  RENAME TO postgres_old;

rename_database.sql has the following content: ALTER DATABASE postgres RENAME TO postgres_old;

答:
Step 1->First of all disconnect from the database that has to be renamed

Step 2-> disconnect all the clients from the database to be renamed

```<code>SELECT pg_terminate_backend(pid )
FROM pg_stat_activity
WHERE pid <> pg_backend_pid( )
    AND datname = 'db_name_to_be_renamed';
</code>```

Step 3->Then rename the database

```<code>ALTER DATABASE "db_name_to_be_renamed" RENAME TO "new_db_name";
</code>```

Body:
I run this command from a bat-file:

start/wait/d "C:\Program Files\PostgreSQL\9.1\bin\" psql.exe --port 5432 --username postgres --dbname alter_db --file ./batch/rename_database.sql

And I get this log-error:

CEST ERROR:  syntax error at or near

"ï»¿ALTER" at character 1 CEST STATEMENT:  ï»¿ALTER DATABASE postgres
  RENAME TO postgres_old;

rename_database.sql has the following content: ALTER DATABASE postgres RENAME TO postgres_old;

Body:
Step 1->First of all disconnect from the database that has to be renamed

Step 2-> disconnect all the clients from the database to be renamed

SELECT pg_terminate_backend(pid )
FROM pg_stat_activity
WHERE pid <> pg_backend_pid( )
    AND datname = 'db_name_to_be_renamed';

Step 3->Then rename the database

ALTER DATABASE "db_name_to_be_renamed" RENAME TO "new_db_name";


问:
RSpec. Using `double` in class methods tests

Maybe, there will be too many code, but I want to understand why RSpec works in this way.
I am trying to double external object, that interacts with remote REST API.

Example code:

class App

  class << self
    def foo
      external.func1
    end

    def bar
      external.func2
    end

    def external
      @external ||= ExternalObject.new
    end
  end

end

class ExternalObject
  def func1
    puts 'func1'
  end

  def func2
    puts 'func2'
  end
end
```

<p>This spec works:</p>

<pre class="lang-rb prettyprint-override"><code>require 'rspec'
require_relative 'app'

describe App do

  describe '.foo' do
    it 'calls func1' do
      expect_any_instance_of(ExternalObject).to receive(:func1)

      described_class.foo
    end
  end

  describe '.bar' do
    it 'calls func2' do
      expect_any_instance_of(ExternalObject).to receive(:func2)

      described_class.bar
    end
  end

end
</code>```

But this doesn't work:

require 'rspec'
require_relative 'app'

describe App do

  let(:external) { double('ExternalObject', func1: 1, func2: 2) }
  before(:each) do
    allow(ExternalObject).to receive(:new).and_return(external)
  end

  describe '.foo' do
    it 'calls func1' do
      expect(external).to receive(:func1)

      described_class.foo
    end
  end

  describe '.bar' do
    it 'calls func2' do
      expect(external).to receive(:func2)

      described_class.bar
    end
  end

end
```

<p>RSpec output looks, like <code>double</code> doesn't contain stubs anymore, when execute second example:</p>

<pre class="lang-rb prettyprint-override"><code>1) App.bar calls func2
     Failure/Error: described_class.bar
       Double "ExternalObject" received unexpected message :func2 with (no args)
</code>```

If replace code in App.external to this:

@external = ExternalObject.new
```

<p>everything works well.</p>

<p>I searched for reasons of that error, but haven't found anything.</p>

<p><strong>UPDATE</strong></p>

<p>Also, for prevent memoization of the class it's possible to clone object. Maybe it's not a good idea, but it works.</p>

<pre class="lang-rb prettyprint-override"><code>require 'rspec'
require_relative 'app'

describe App do

  let(:external) { double('ExternalObject', func1: 1, func2: 2) }
  before(:each) do
    stub_const('App', App.clone)
    allow(ExternalObject).to receive(:new).and_return(external)
  end

  describe '.foo' do
    it 'calls func1' do
      expect(external).to receive(:func1)

      App.foo
    end
  end

  describe '.bar' do
    it 'calls func2' do
      expect(external).to receive(:func2)

      App.bar
    end
  end

end
</code>```

UPDATE 2

I concretize my question: why double memoized in @external between tests, but without stubbed methods?

答:
Because let creates a new double for each example.

Try running this spec with the newest (3.6) rspec, and you will get the following error:

```<code>1) App.bar calls func2
   Failure/Error: external.func2
     #<Double "ExternalObject"> was originally created in one example but has leaked into another example and can no longer be used. rspec-mocks' doubles are designed to only last for one example, and you need to create a new one in each example you wish to use it for.
</code>```

This happens because of the memoization of the object on the class level.

When the first example gets ran, let creates the first double with first expectation and it gets memoized.

In the next example the let creates a new double and the expectation is set on that new double, however when the test code calls for the described_class.external it receives the first memoized test double and not the new one with the new expectation.

You can try see in the following example:

```<code>RSpec.describe App do
  let(:external) { double('ExternalObject', func1: 1, func2: 2) }

  before { allow(ExternalObject).to receive(:new).and_return(external) }

  describe '.foo' do
    it 'calls func1' do
      p external.object_id # => 70184943614340
      p described_class.external.object_id # => 70184943614340
      expect(external).to receive(:func1)

      described_class.foo
    end
  end

  describe '.bar' do
    it 'calls func2' do
      p external.object_id # => 70184942937140
      p described_class.external.object_id # => 70184943614340
      expect(external).to receive(:func2)

      described_class.bar
    end
  end
end
</code>```

Body:
Maybe, there will be too many code, but I want to understand why RSpec works in this way.
I am trying to double external object, that interacts with remote REST API.

Example code:

class App

  class << self
    def foo
      external.func1
    end

    def bar
      external.func2
    end

    def external
      @external ||= ExternalObject.new
    end
  end

end

class ExternalObject
  def func1
    puts 'func1'
  end

  def func2
    puts 'func2'
  end
end

This spec works:

require 'rspec'
require_relative 'app'

describe App do

  describe '.foo' do
    it 'calls func1' do
      expect_any_instance_of(ExternalObject).to receive(:func1)

      described_class.foo
    end
  end

  describe '.bar' do
    it 'calls func2' do
      expect_any_instance_of(ExternalObject).to receive(:func2)

      described_class.bar
    end
  end

end

But this doesn't work:

require 'rspec'
require_relative 'app'

describe App do

  let(:external) { double('ExternalObject', func1: 1, func2: 2) }
  before(:each) do
    allow(ExternalObject).to receive(:new).and_return(external)
  end

  describe '.foo' do
    it 'calls func1' do
      expect(external).to receive(:func1)

      described_class.foo
    end
  end

  describe '.bar' do
    it 'calls func2' do
      expect(external).to receive(:func2)

      described_class.bar
    end
  end

end

RSpec output looks, like double doesn't contain stubs anymore, when execute second example:

1) App.bar calls func2
     Failure/Error: described_class.bar
       Double "ExternalObject" received unexpected message :func2 with (no args)

If replace code in App.external to this:

@external = ExternalObject.new

everything works well.

I searched for reasons of that error, but haven't found anything.

UPDATE

Also, for prevent memoization of the class it's possible to clone object. Maybe it's not a good idea, but it works.

require 'rspec'
require_relative 'app'

describe App do

  let(:external) { double('ExternalObject', func1: 1, func2: 2) }
  before(:each) do
    stub_const('App', App.clone)
    allow(ExternalObject).to receive(:new).and_return(external)
  end

  describe '.foo' do
    it 'calls func1' do
      expect(external).to receive(:func1)

      App.foo
    end
  end

  describe '.bar' do
    it 'calls func2' do
      expect(external).to receive(:func2)

      App.bar
    end
  end

end

UPDATE 2

I concretize my question: why double memoized in @external between tests, but without stubbed methods?

Body:
Because let creates a new double for each example.

Try running this spec with the newest (3.6) rspec, and you will get the following error:

1) App.bar calls func2
   Failure/Error: external.func2
     #<Double "ExternalObject"> was originally created in one example but has leaked into another example and can no longer be used. rspec-mocks' doubles are designed to only last for one example, and you need to create a new one in each example you wish to use it for.

This happens because of the memoization of the object on the class level.

When the first example gets ran, let creates the first double with first expectation and it gets memoized.

In the next example the let creates a new double and the expectation is set on that new double, however when the test code calls for the described_class.external it receives the first memoized test double and not the new one with the new expectation.

You can try see in the following example:

RSpec.describe App do
  let(:external) { double('ExternalObject', func1: 1, func2: 2) }

  before { allow(ExternalObject).to receive(:new).and_return(external) }

  describe '.foo' do
    it 'calls func1' do
      p external.object_id # => 70184943614340
      p described_class.external.object_id # => 70184943614340
      expect(external).to receive(:func1)

      described_class.foo
    end
  end

  describe '.bar' do
    it 'calls func2' do
      p external.object_id # => 70184942937140
      p described_class.external.object_id # => 70184943614340
      expect(external).to receive(:func2)

      described_class.bar
    end
  end
end


问:
When loading images from a sprite sheet in PIXI.JS is the order or amount of sprite sheets important?
I'm using Texture Packer to create sprite sheets for all of my game image resources. I end up using a multipack of 5 sheets with a max of 2048x2048. I have a good amount of sprites being loaded into various containers, sprites, tilingsprites, etc. Should I be creating these sprite sheets more intelligently based off of what container they are going to be loaded on?

I feel like i'm doing something fundamentally wrong because my performance doesn't seem to be the greatest. I stripped my game down to only load 6 sprites to try to get to the root cause of the problem. I even split up my sprite sheets to individual containers. So container 'A' uses images from sprite sheet 'A' while container 'B' uses images from sprite sheet 'B'.

Even with these very minimal graphics being loaded my CPU usage skyrockets and my computer fan goes wild. It just seems like the computer is working extremely hard to only show 6 sprites. I don't notice that when I try the demos/examples from the pixijs website.

I'm really not sure what I'm doing wrong. Are my images too large? I have a few that are about 1440x900 pixels. The images all get compressed so the size isn't too large but do large dimension sprites slow things down? I'd show some code but my code base is quite large. I've tried this out on canvas and webgl. Webgl performce better but I get the same cpu spikes for both.

答:
On webGL, displaying the graphics is GPUs responsibility. So if the CPU is choking, when using webGL, I would be fairly sure myself, that the issue is in your code and not in the sprite size. Basically webGL just has limitations to how big textures it can display: https://www.khronos.org/registry/webgl/sdk/tests/conformance/limits/gl-max-texture-dimensions.html , https://webglstats.com/webgl/parameter/MAX_TEXTURE_SIZE

So in webGL, optimally CPU should upload the sprites to GPU only once, after that CPU changes the position of sprites and sends the new positions to GPU, with each animation cycle and GPU redraws the sprites. But you mentioned that your codebase is big, so I would doubt that as the core issue personally.

You should find out which part of your code causes the spikes. You can use e.g. chrome devtools profiling for that and continue from there forward.


问:
Error installing ionic on windows 10
```<code>C:\Program Files>npm install -g ionic cordova
C:\Users\myname\AppData\Roaming\npm
</code>```

`-- ionic@2.1.4

```<code>npm ERR! Windows_NT 10.0.14393
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "-g" "ionic"    "cordova"
npm ERR! node v7.0.0
npm ERR! npm  v3.10.8
npm ERR! path C:\Users\myname\AppData\Roaming\npm\node_modules\.staging\abbrev-514e00ac
npm ERR! code ENOENT
npm ERR! errno -4058
npm ERR! syscall rename

npm ERR! enoent ENOENT: no such file or directory, rename 'C:\Users\myname\AppData\Roaming\npm\node_modules\.staging\abbrev-514e00ac' ->     'C:\Users\myname\AppData\Roaming\npm\node_modules\cordova\node_modules\npm\node_modules\ab brev'
 npm ERR! enoent ENOENT: no such file or directory, rename 'C:\Users\myname\AppData\Roaming\npm\node_modules\.staging\abbrev-514e00ac' ->  'C:\Users\myname\AppData\Roaming\npm\node_modules\cordova\node_modules\npm\node_modules\abbrev'
 npm ERR! enoent This is most likely not a problem with npm itself
 npm ERR! enoent and is related to npm not being able to find a file.
 npm ERR! enoent
 npm ERR! Windows_NT 10.0.14393
 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "-g" "ionic" "cordova"
npm ERR! node v7.0.0
npm ERR! npm  v3.10.8
npm ERR! path C:\Program Files\npm-debug.log.3790864127
npm ERR! code EPERM
npm ERR! errno -4048
npm ERR! syscall open

npm ERR! Error: EPERM: operation not permitted, open 'C:\Program Files\npm-debug.log.3790864127'
npm ERR!  { Error: EPERM: operation not permitted, open 'C:\Program Files\npm-debug.log.3790864127'
npm ERR!   errno: -4048,
npm ERR!   code: 'EPERM',
npm ERR!   syscall: 'open',
npm ERR!   path: 'C:\\Program Files\\npm-debug.log.3790864127' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Program Files\npm-debug.log
</code>```

I have been trying to install ionic on my windows laptop. Before installing ionic on my laptop, I installed nodejs. But after that, everytime I try to install ionic, it shows this error on my command prompt. I also looked for similar problems on this website as well as other but couldn't find any that actually solves my problem. I also looked at npm install -g cordova and ionic 2 error ionic on window 10][1]
but the solution provided there would not work either.

答:
Please Follow These Steps:-

1- First check that you have the latest node version.
2- Then search for Command Prompt and RUN IT AS ADMINISTRATOR.
3- then type the above commands :-

```<code> npm install -g ionic
    npm install -g cordova
</code>```

Title: Error installing ionic on windows 10

Body:
C:\Program Files>npm install -g ionic cordova
C:\Users\myname\AppData\Roaming\npm

`-- ionic@2.1.4

npm ERR! Windows_NT 10.0.14393
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "-g" "ionic"    "cordova"
npm ERR! node v7.0.0
npm ERR! npm  v3.10.8
npm ERR! path C:\Users\myname\AppData\Roaming\npm\node_modules\.staging\abbrev-514e00ac
npm ERR! code ENOENT
npm ERR! errno -4058
npm ERR! syscall rename

npm ERR! enoent ENOENT: no such file or directory, rename 'C:\Users\myname\AppData\Roaming\npm\node_modules\.staging\abbrev-514e00ac' ->     'C:\Users\myname\AppData\Roaming\npm\node_modules\cordova\node_modules\npm\node_modules\ab brev'
 npm ERR! enoent ENOENT: no such file or directory, rename 'C:\Users\myname\AppData\Roaming\npm\node_modules\.staging\abbrev-514e00ac' ->  'C:\Users\myname\AppData\Roaming\npm\node_modules\cordova\node_modules\npm\node_modules\abbrev'
 npm ERR! enoent This is most likely not a problem with npm itself
 npm ERR! enoent and is related to npm not being able to find a file.
 npm ERR! enoent
 npm ERR! Windows_NT 10.0.14393
 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "-g" "ionic" "cordova"
npm ERR! node v7.0.0
npm ERR! npm  v3.10.8
npm ERR! path C:\Program Files\npm-debug.log.3790864127
npm ERR! code EPERM
npm ERR! errno -4048
npm ERR! syscall open

npm ERR! Error: EPERM: operation not permitted, open 'C:\Program Files\npm-debug.log.3790864127'
npm ERR!  { Error: EPERM: operation not permitted, open 'C:\Program Files\npm-debug.log.3790864127'
npm ERR!   errno: -4048,
npm ERR!   code: 'EPERM',
npm ERR!   syscall: 'open',
npm ERR!   path: 'C:\\Program Files\\npm-debug.log.3790864127' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Program Files\npm-debug.log

I have been trying to install ionic on my windows laptop. Before installing ionic on my laptop, I installed nodejs. But after that, everytime I try to install ionic, it shows this error on my command prompt. I also looked for similar problems on this website as well as other but couldn't find any that actually solves my problem. I also looked at npm install -g cordova and ionic 2 error ionic on window 10][1]
but the solution provided there would not work either.

Body:
Please Follow These Steps:-

1- First check that you have the latest node version.
2- Then search for Command Prompt and RUN IT AS ADMINISTRATOR.
3- then type the above commands :-

 npm install -g ionic
    npm install -g cordova


问:
Merge notifications with OneSignal
Using Ionic and OneSignal.

I am developing a messaging service in my app which sends push notifications when a new message is received. Ok so far.

But, I would like to merge notifications if they exceed a certain number, to avoid spamming the user with to much notifications.

Let's say if someone answer to one of my message with 3 different messages and that my app is in background, I would like the following to happen:

receive 1 notification

receive 1 other distinct notification

display only one notification which merge the previous two + a new one

Someone know, if possible and how?

答:
I have just implemented something similar. You can look at the following documentation link
stacked notification

I just set the android_group parameter in all of my one signal api call and send a string key on every notification message.

```<code>{
    app_id = "xxxxxxxxxxxx"; // one signal app id
    headings = "One Signal Title Test";
    content = "The demo test message";
    android_group = "demo-application";
    included_segments = "Active Users"; // to send notification to all active users
}
</code>```

use postman to test

Title: Merge notifications with OneSignal

Body:
I have just implemented something similar. You can look at the following documentation link
stacked notification

I just set the android_group parameter in all of my one signal api call and send a string key on every notification message.

{
    app_id = "xxxxxxxxxxxx"; // one signal app id
    headings = "One Signal Title Test";
    content = "The demo test message";
    android_group = "demo-application";
    included_segments = "Active Users"; // to send notification to all active users
}

use postman to test


问:
Avoid circular reference for classes
I have a function that creates and returns a "Person".  The "Person" has a "Spouse" property which is, of course, another "Person".  This causes an endless recursion since the "Person" being created is always a "new" one each time the function is called.  Is there a way to use the same function (as shown below) without causing an endless loop?</p>

```<code>public PersonModel Load(int personID)
{
    PersonModel person = new PersonModel();
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = Helpers.ConnectionDB;
        SqlCommand command = new SqlCommand();
        command.Connection = conn;
        command.CommandType = CommandType.StoredProcedure;
        command.CommandText = "LoadPerson";
        command.Parameters.Add(new SqlParameter("@PersonID", personID));
        conn.Open();
        SqlDataReader reader = command.ExecuteReader();
        if (reader.Read())
        {
            person.PersonID = int.Parse(reader["PersonID"].ToString());
            person.FirstName = reader["FirstName"].ToString();
            person.LastName = reader["LastName"].ToString();
            person.MiddleName = reader["MiddleName"].ToString();
            person.Age = reader["Age"] != DBNull.Value ? int.Parse(reader["Age"].ToString()) : (int?)null;
            person.SpouseID = reader["SpouseID"] != DBNull.Value ? int.Parse(reader["SpouseID"].ToString()) : (int?)null;
            if (person.SpouseID != null && person.Spouse == null)
            {
                person.Spouse = this.Load(person.SpouseID.Value);
            }
        }
        conn.Close();
    }
    return person;
}
</code>```

答:
Not exactly per the OPs question, but since I landed here because of the title, it might be beneficial adding a general answer to this.

So in my scenario I needed to change a property in an entire graph setting all its sub properties to any depth.

In order to ensure I don't get an instance performed twice (thus allowing StackOverflowException), I'm passing a HashSet<T> along each call, so we know to skip the performed items:

```<code>//The executed parameter needn't ever be provided externally.
static void SetState(IObject obj, State state, HashSet<IObject> executed = null)
{
  if(executed == null) executed = new HashSet<IObject>(/* provide comparer if needed*/);
  if(!executed.Add(obj)) return;

  //safe to continue walking graph
  obj.State = state;
  var props = obj.GetObjectPropertyValues().OfType<IObject>();
  foreach (var prop in props)
    SetState(obj, state, executed);
}
</code>```

Note, the items must implement proper equality and GetHashCode functions, or a comparer argument should be passed to the HashSet's constructor.

Title: Avoid circular reference for classes

Body:
I have a function that creates and returns a "Person".  The "Person" has a "Spouse" property which is, of course, another "Person".  This causes an endless recursion since the "Person" being created is always a "new" one each time the function is called.  Is there a way to use the same function (as shown below) without causing an endless loop?

public PersonModel Load(int personID)
{
    PersonModel person = new PersonModel();
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = Helpers.ConnectionDB;
        SqlCommand command = new SqlCommand();
        command.Connection = conn;
        command.CommandType = CommandType.StoredProcedure;
        command.CommandText = "LoadPerson";
        command.Parameters.Add(new SqlParameter("@PersonID", personID));
        conn.Open();
        SqlDataReader reader = command.ExecuteReader();
        if (reader.Read())
        {
            person.PersonID = int.Parse(reader["PersonID"].ToString());
            person.FirstName = reader["FirstName"].ToString();
            person.LastName = reader["LastName"].ToString();
            person.MiddleName = reader["MiddleName"].ToString();
            person.Age = reader["Age"] != DBNull.Value ? int.Parse(reader["Age"].ToString()) : (int?)null;
            person.SpouseID = reader["SpouseID"] != DBNull.Value ? int.Parse(reader["SpouseID"].ToString()) : (int?)null;
            if (person.SpouseID != null && person.Spouse == null)
            {
                person.Spouse = this.Load(person.SpouseID.Value);
            }
        }
        conn.Close();
    }
    return person;
}

Body:
Not exactly per the OPs question, but since I landed here because of the title, it might be beneficial adding a general answer to this.

So in my scenario I needed to change a property in an entire graph setting all its sub properties to any depth.

In order to ensure I don't get an instance performed twice (thus allowing StackOverflowException), I'm passing a HashSet<T> along each call, so we know to skip the performed items:

//The executed parameter needn't ever be provided externally.
static void SetState(IObject obj, State state, HashSet<IObject> executed = null)
{
  if(executed == null) executed = new HashSet<IObject>(/* provide comparer if needed*/);
  if(!executed.Add(obj)) return;

  //safe to continue walking graph
  obj.State = state;
  var props = obj.GetObjectPropertyValues().OfType<IObject>();
  foreach (var prop in props)
    SetState(obj, state, executed);
}

Note, the items must implement proper equality and GetHashCode functions, or a comparer argument should be passed to the HashSet's constructor.


问:
start xAxis and yAxis value from 0 and set custom xAxis value in Charts library
How to start xAxis and yAxis value from 0 and set custom xAxis value in Charts library?

As library will take values manually.

答:
You can set custom values for xAxis by using following code,

```<code>self.barChartView.xAxis.valueFormatter = IndexAxisValueFormatter(values: self.arrUserCount)
self.barChartView.xAxis.granularity = 1
self.barChartView.xAxis.labelCount = self.arrUserCount.count
</code>```

use this lines to start xAxis and yAxis value from 0

```<code>self.barChartView.leftAxis.axisMinimum = 0.0
self.barChartView.xAxis.axisMinimum = 0.0
</code>```

Body:
You can set custom values for xAxis by using following code,

self.barChartView.xAxis.valueFormatter = IndexAxisValueFormatter(values: self.arrUserCount)
self.barChartView.xAxis.granularity = 1
self.barChartView.xAxis.labelCount = self.arrUserCount.count

use this lines to start xAxis and yAxis value from 0

self.barChartView.leftAxis.axisMinimum = 0.0
self.barChartView.xAxis.axisMinimum = 0.0


问:
UIBarButtonItem clicked side menu not open
I am developing iOS App.Add UIBarButtonItem on Custom UIView.Button Added Successfully.But, when I click on button enter on selector action.But Side menu not open.
Please Help thanks in Advance.

Here is the Code:

```<code>- (void)sideButton{
    UIImage *menuButtonImage = [UIImage imageNamed:@"menu-icon.png"];// set your image Name here
    UIButton *btnToggle = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnToggle setImage:menuButtonImage forState:UIControlStateNormal];
    [btnToggle addTarget:self action:@selector(checkButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    btnToggle.frame = CGRectMake(10, 30, 25, 25);
    [_sideView addSubview:btnToggle]; //sideView is UIView

    _menuBarButton = [[UIBarButtonItem alloc] initWithCustomView:btnToggle];
    self.navigationItem.leftBarButtonItem = _menuBarButton;
}
- (IBAction)checkButtonTapped:(id)sender{
    SWRevealViewController *revealViewController = self.revealViewController;
    if ( revealViewController ){
        [_menuBarButton setTarget: self.revealViewController];
        [_menuBarButton setAction: @selector( revealToggle: )];
        [self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
    }
}
</code>```

答:
Try to change this

```<code>UIButton *btnToggle = [UIButton buttonWithType:UIButtonTypeCustom];
</code>```

Into this

```<code>UIButton *btnToggle = [[UIButton alloc]initWithFrame:CGRectMake(0,0,50,50)];
</code>```

Tell me if this works

Body:
I am developing iOS App.Add UIBarButtonItem on Custom UIView.Button Added Successfully.But, when I click on button enter on selector action.But Side menu not open.
Please Help thanks in Advance.

Here is the Code:

- (void)sideButton{
    UIImage *menuButtonImage = [UIImage imageNamed:@"menu-icon.png"];// set your image Name here
    UIButton *btnToggle = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnToggle setImage:menuButtonImage forState:UIControlStateNormal];
    [btnToggle addTarget:self action:@selector(checkButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    btnToggle.frame = CGRectMake(10, 30, 25, 25);
    [_sideView addSubview:btnToggle]; //sideView is UIView

    _menuBarButton = [[UIBarButtonItem alloc] initWithCustomView:btnToggle];
    self.navigationItem.leftBarButtonItem = _menuBarButton;
}
- (IBAction)checkButtonTapped:(id)sender{
    SWRevealViewController *revealViewController = self.revealViewController;
    if ( revealViewController ){
        [_menuBarButton setTarget: self.revealViewController];
        [_menuBarButton setAction: @selector( revealToggle: )];
        [self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
    }
}

Body:
Try to change this

UIButton *btnToggle = [UIButton buttonWithType:UIButtonTypeCustom];

Into this

UIButton *btnToggle = [[UIButton alloc]initWithFrame:CGRectMake(0,0,50,50)];

Tell me if this works


问:
How to use Android Tablet emulator?
I want to start android tablet application development. i have created a new avd with 1024X600 emulator and launched, but how to come back from emulator when i click any application? is there any specific api available for developing android tablet applications or can we use the same android api for development.

Please help ?

答:
You'll use the same APIs for tablets.

At least this is what I have known till now.

You may get emulator skins for some tablets if their manufacturers are providing them as add-ons

In the new SDK released with Gingerbread, you get an option to download the add-on of Samsung Galaxy Tab, which will give you the emulator skin and feel of the Galaxy tab.
try that out.

Title: How to use Android Tablet emulator?


问:
BrowserModule has already been loaded Error
I've updated my application to RC6 and now i keep getting this error:

zone.js:484 Unhandled Promise rejection: BrowserModule has already
  been loaded. If you need access to common directives such as NgIf and
  NgFor from a lazy loaded module...

I'm using lazy loading and my application is broken up in to a lot of lazy loaded modules. However in RC5 everything worked fine.

The only change I've managed to find in the changelog for RC6 is this:

compiler: throw descriptive error meesage for invalid NgModule
  providers

But since i haven't seen any errors in RC5 this probably doesn't apply here.

I'm kind of out of ideas so any help is greatly appreciated.

答:
I think you are using 'NoopAnimationsModule' or 'BrowserAnimationsModule',
Which already contain 'BrowserModule' and loading your module lazily.
SO the solution is Replace the BrowserModule with 'NoopAnimationsModule or 'BrowserAnimationsModule' in your 'app.module.ts'.</p>

```<code>import { Router } from '@angular/router';
import { AdminsModule } from './admins/admins.module';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
//import { BrowserModule } from '@angular/platform-browser';
import { NgModule,OnInit } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
    declarations: [
        AppComponent,
    ],
    imports: [
    //BrowserModule,
    NoopAnimationsModule,
    FormsModule
],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule {}
</code>```

Body:
I think you are using 'NoopAnimationsModule' or 'BrowserAnimationsModule',
Which already contain 'BrowserModule' and loading your module lazily.
SO the solution is Replace the BrowserModule with 'NoopAnimationsModule or 'BrowserAnimationsModule' in your 'app.module.ts'.

import { Router } from '@angular/router';
import { AdminsModule } from './admins/admins.module';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
//import { BrowserModule } from '@angular/platform-browser';
import { NgModule,OnInit } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
    declarations: [
        AppComponent,
    ],
    imports: [
    //BrowserModule,
    NoopAnimationsModule,
    FormsModule
],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule {}


问:
Appending line to a existing file having extra new line in Python
I have a text file

```
apple
banana

```

Now you watch closely there is blank line at the end.

When in do append

```
f = open("file.txt",'a')
f.write("orange")
f.close()
```

I get output:

```
apple
banana

orange
```

I want to remove the blank line in between during appends.

I know i can do that manually going to the file and removing the extra new line. But i want to do it in python. So every time the blank line is there its gets removed automatically like this:

```
apple
banana
orange
```

I search and experimented but no avail

答:
I would write this code to add a new line to a file:

```<code>f=open('newfile.txt','a')

t=raw_input('write here something you like: ')

f.write(t+'\n')
</code>```

and then to read what is there in the file, fire up the shell and type:

```<code>with open('newfile.txt','a') as f:
   for l in f:
       print l
</code>```

This will print everything from the file.

I hope it answers your question!!

Body:
I have a text file

apple
banana

Now you watch closely there is blank line at the end.

When in do append

f = open("file.txt",'a')
f.write("orange")
f.close()

I get output:

apple
banana

orange

I want to remove the blank line in between during appends.

I know i can do that manually going to the file and removing the extra new line. But i want to do it in python. So every time the blank line is there its gets removed automatically like this:

apple
banana
orange

I search and experimented but no avail

Body:
I would write this code to add a new line to a file:

f=open('newfile.txt','a')

t=raw_input('write here something you like: ')

f.write(t+'\n')

and then to read what is there in the file, fire up the shell and type:

with open('newfile.txt','a') as f:
   for l in f:
       print l

This will print everything from the file.

I hope it answers your question!!


问:
VBA Data missing on the copied Pivot Table
I am working on my VBA code in Excel. The first Pivot Table was generated by VBA and works well. However I need more Pivot Tables based on the same data source with different row or column items. I tried to copy the first Pivot Table to cell L8, however after pasted, the data in the new Pivot Table disappears. When I manually refresh the pivot table, the data comes up again. Here's my code -

```<code>wsPvtTbl.PivotTables("PivotTable1").TableRange2.Copy Destination:=wsPvtTbl.Range("L8")
</code>```

This is the screen shot of the second Pivot Table

is there a way to fix? Thanks.

*****Update*****

I tired to refresh pivot tables with following code attached to a different button and it worked. I thought it would be working within the same sub but I'm not sure why it only works separately?

```<code>ThisWorkbook.refreshall
</code>```

答:
Maybe you can try something like this...</p>

```<code>Sub CopyPivotTable()
Dim wsPvtTbl As Worksheet
Dim pt As PivotTable
Dim pf As PivotField

Set wsPvtTbl = ActiveSheet

wsPvtTbl.PivotTables("PivotTable1").TableRange2.Copy Destination:=wsPvtTbl.Range("L8")

For Each pt In wsPvtTbl.PivotTables
    If pt.Name <> "PivotTable1" Then
        For Each pf In pt.PivotFields
            pf.ClearAllFilters
        Next pf
    End If
Next pt
End Sub
</code>```

Body:
I am working on my VBA code in Excel. The first Pivot Table was generated by VBA and works well. However I need more Pivot Tables based on the same data source with different row or column items. I tried to copy the first Pivot Table to cell L8, however after pasted, the data in the new Pivot Table disappears. When I manually refresh the pivot table, the data comes up again. Here's my code -

wsPvtTbl.PivotTables("PivotTable1").TableRange2.Copy Destination:=wsPvtTbl.Range("L8")

This is the screen shot of the second Pivot Table

is there a way to fix? Thanks.

*****Update*****

I tired to refresh pivot tables with following code attached to a different button and it worked. I thought it would be working within the same sub but I'm not sure why it only works separately?

ThisWorkbook.refreshall

Body:
Maybe you can try something like this...

Sub CopyPivotTable()
Dim wsPvtTbl As Worksheet
Dim pt As PivotTable
Dim pf As PivotField

Set wsPvtTbl = ActiveSheet

wsPvtTbl.PivotTables("PivotTable1").TableRange2.Copy Destination:=wsPvtTbl.Range("L8")

For Each pt In wsPvtTbl.PivotTables
    If pt.Name <> "PivotTable1" Then
        For Each pf In pt.PivotFields
            pf.ClearAllFilters
        Next pf
    End If
Next pt
End Sub


问:
Python: for loop iteration accumulate values in string variable
Say I have a for loop that iterates through the characters in a string one by one.

Ex:

```<code>string_x = "abc"
 for i in range (0, len(string_x))
     data = str(string_x[i])
     print(data)
</code>```

The output gives me a, b, c one by one.

Now I want to group this back into a different string after I scramble it character by character. I already figured out how to scramble it, but I can't just append it back to a string inside the loop because it overrides the string value each iteration and only ends up with one character such as 'b'.
I want the for loop to create a new string named string_y that can incrementally have new characters appended to it without overriding the whole string every loop iteration.
Any ideas?

答:
Try using += (as suggested by xzoert in his comment)

```<code>string_x = 'abc'
string_y = ''  # init to empty string
for c in string_x:
    string_y += c  # add a character to string_y
print string_y
</code>```

Body:
Say I have a for loop that iterates through the characters in a string one by one.

Ex:

string_x = "abc"
 for i in range (0, len(string_x))
     data = str(string_x[i])
     print(data)

The output gives me a, b, c one by one.

Now I want to group this back into a different string after I scramble it character by character. I already figured out how to scramble it, but I can't just append it back to a string inside the loop because it overrides the string value each iteration and only ends up with one character such as 'b'.
I want the for loop to create a new string named string_y that can incrementally have new characters appended to it without overriding the whole string every loop iteration.
Any ideas?

Body:
Try using += (as suggested by xzoert in his comment)

string_x = 'abc'
string_y = ''  # init to empty string
for c in string_x:
    string_y += c  # add a character to string_y
print string_y


问:
How to find a string from a column
I have a df as below

df:

```<code>Name               |Code
-------------------+-----
aman               |abc
akash              |bcd
rudra              |cde
Tushar             |def
Kartik             |efg
aman,akash         |fgh
akash,rudra        |ghi
akash,rudra,aman   |ijk
aman,Tushar        |jkl
Kartik,Tushar      |klm
rudra,Kartik,akash |lmn
</code>```

i want to search code for combo "aman,akash,rudra" and "Tushar,aman" to get result as "ijk" and "jkl"....

let me know if there is some way to achieve this.

答:
It can be used regular expressions in MySQL:

```<code>SELECT * FROM `table` WHERE `Name` REGEXP '/(aman,akash,rudra)|(Tushar,aman)/';
</code>```

P.S. It's just as an example... not the final solution

Title: How to find a string from a column

Body:
I have a df as below

df:

Name               |Code
-------------------+-----
aman               |abc
akash              |bcd
rudra              |cde
Tushar             |def
Kartik             |efg
aman,akash         |fgh
akash,rudra        |ghi
akash,rudra,aman   |ijk
aman,Tushar        |jkl
Kartik,Tushar      |klm
rudra,Kartik,akash |lmn

i want to search code for combo "aman,akash,rudra" and "Tushar,aman" to get result as "ijk" and "jkl"....

let me know if there is some way to achieve this.

Body:
It can be used regular expressions in MySQL:

SELECT * FROM `table` WHERE `Name` REGEXP '/(aman,akash,rudra)|(Tushar,aman)/';

P.S. It's just as an example... not the final solution


答:
We can use %in%

```<code>df$Code[df$Name %in% c("akash,rudra,aman", "aman,Tushar")]
#[1] "ijk" "jkl"
</code>```

If the order is flexible

```<code>df$Code[sapply(strsplit(df$Name, ","), function(x)
   all(c("akash", "rudra", "aman") %in% x) | all(c("aman", "Tushar") %in% x))]
#[1] "ijk" "jkl"
</code>```

Title: How to find a string from a column

Body:
We can use %in%

df$Code[df$Name %in% c("akash,rudra,aman", "aman,Tushar")]
#[1] "ijk" "jkl"

If the order is flexible

df$Code[sapply(strsplit(df$Name, ","), function(x)
   all(c("akash", "rudra", "aman") %in% x) | all(c("aman", "Tushar") %in% x))]
#[1] "ijk" "jkl"


问:
PHP writing to file on server
I'm  trying to write to a file on my local server and I can't figure out why, I haven't found any good reason why what I'm doing should not work.

What I've tryed:

```<code>file_put_contents("./lol.txt", "Contents");
file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/lil.txt", "Contents");
file_put_contents($_SERVER['DOCUMENT_ROOT'] . "lal.txt", "Contents");
file_put_contents("lel.txt", "Contents");
</code>```

I will provide any additional info if needed.

答:
Use realpath — Returns canonicalized absolute pathname

file_put_contents(realpath("somedirectory/somefile.txt"),$content);

and check the permission for folder and file whether you have write
  access.

Title: PHP writing to file on server

Body:
I'm  trying to write to a file on my local server and I can't figure out why, I haven't found any good reason why what I'm doing should not work.

What I've tryed:

file_put_contents("./lol.txt", "Contents");
file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/lil.txt", "Contents");
file_put_contents($_SERVER['DOCUMENT_ROOT'] . "lal.txt", "Contents");
file_put_contents("lel.txt", "Contents");

I will provide any additional info if needed.


问:
How to get last inserted date of a certain record using php and mysql?
Below I have a working code:

```<code>$p_code = "R-BIGANTE-010";
$date = date("m/d/Y");
$statement=$pdo->prepare("SELECT * FROM items WHERE p_code=? AND date=?");
$statement->execute(array($p_code, $date));
</code>```

And what it does is to get a certain item with p_code and date equal to TODAY. What I want to know is how can I query a specific item with the last latest update?

For example, in my items table I have

As you can see, I have two p_code with value "R-BIGANTE-010". Let's say the current date today is 05/06/2017 and I want to get the highlighted one because the date field is much latest than the other value.

How can I query it? By the way the date value is in varchar since the code is old and I will clean everything later.

Any help would be much appreciated.

答:
You can get the the last updated date by making a select query with order by and limit like:

```<code>SELECT * from tablename ORDER BY date DESC LIMIT 1
</code>```

Your date is stored in varchar column, so try STR_TO_DATE function

```<code>SELECT * from tablename
ORDER BY STR_TO_DATE(date, '%m/%d/%Y %h:%i:%s');
</code>```

Body:
Below I have a working code:

$p_code = "R-BIGANTE-010";
$date = date("m/d/Y");
$statement=$pdo->prepare("SELECT * FROM items WHERE p_code=? AND date=?");
$statement->execute(array($p_code, $date));

And what it does is to get a certain item with p_code and date equal to TODAY. What I want to know is how can I query a specific item with the last latest update?

For example, in my items table I have

As you can see, I have two p_code with value "R-BIGANTE-010". Let's say the current date today is 05/06/2017 and I want to get the highlighted one because the date field is much latest than the other value.

How can I query it? By the way the date value is in varchar since the code is old and I will clean everything later.

Any help would be much appreciated.

Body:
You can get the the last updated date by making a select query with order by and limit like:

SELECT * from tablename ORDER BY date DESC LIMIT 1

Your date is stored in varchar column, so try STR_TO_DATE function

SELECT * from tablename
ORDER BY STR_TO_DATE(date, '%m/%d/%Y %h:%i:%s');


问:
how can i track users without cookies
ok... im looking to have a good round of brainstorming here...

say i was google... the adword/adsense/analytics division. i would be getting a little worried about the future, when users start to disable cookies (or at least delete them on a regular basis), use private browsing, roam on multiple devices. how could google alternatively track users without the benefits of cookies?

some ideas to get started (please elaborate on these and any others):

-track users using some other persistent local/client side storage

-use user-agent string fingerprinting

-test cache response - if user 304's an image, they were here

-track mac address

-any random/out of the box ideas?

答:
I think you could do it using custom urls.  You would basically ecrypt a cookie and attach it as part of the URL you send to the browser.  When it returns, your web server would be smart enough to decode it and track whoever sent it. </p>

<p>I believe the Spring framework can do this in fact. </p>

Title: how can i track users without cookies

Body:
I think you could do it using custom urls.  You would basically ecrypt a cookie and attach it as part of the URL you send to the browser.  When it returns, your web server would be smart enough to decode it and track whoever sent it.

I believe the Spring framework can do this in fact.


问:
replace values of keys in json1 from Json2
I am very very new to php.. actually i am from java domain. But, i have to do some work in php for integration. My scenario is, i have one json array which will have 4 keys for ex:

```<code> one json --> {"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"}.
</code>```

I will be getting another JSON which ever edited from admin panel. for example if i updated any key, only that key will coming in the

```<code> second JSON --> for ex: {"blog_heading":"def"}
</code>```

Now, i have to replace the value of second json to first json. example output for above scenario like  I am very very new to php.. actually i am from java domain. But, i have to do some work in php for integration. My scenario is, i have one json array which will have 4 keys for ex:

```<code>  output json --> {"id":7,"active":1,"blogId":"abc","blog_heading":"def"}.
</code>```

So i am trying as below,

```<code>$id = json_decode($data_string);
$id2 = json_encode($post);
$id5 = json_decode($id2);
$id6 = array();
foreach ($id as $key => $value)
{

    $log->debug($key . ': ' . $value);
    if (array_key_exists($key, $id5->data)) {
        $log->debug($key . 'element is in the array');
        $log->debug($value . 'element is in the array');
        //array_push($id5, "apple", "raspberry");

        $id3 = array($key  => $value);
        $id3[$key] = $value;
        $log->debug($id3);

    }else{
        $log->debug($key . 'element is not in the array');
    }

}
$id7 = json_encode($id2);
$log->debug($id7);
</code>```

id5 data is : $id5

```<code>  DEBUG - 2017-06-05T02:26:20-04:00 - stdClass Object
   (
[meta] => stdClass Object
    (
        [table] => story
        [type] => item
    )

[data] => stdClass Object
    (
        [id] => 7
        [active] => 1
        [blogId] => abc
        [blog_heading] => xyz

    )

    )

 ==================
</code>```

Log of $id :

```<code>stdClass Object
   (
[active] => 1
[blog_heading] => def
[id] => 7
 )
</code>```

Please suggest me how can i achieve this... Anything i am doing wrong here

答:
Please try that:</p>

```<code>$j1 = '{"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"}';
$j2 = '{"blog_heading":"def"}';

$result = json_encode(
    array_merge(
        json_decode($j1, true),
        json_decode($j2, true)
   )
);
</code>```

Body:
I am very very new to php.. actually i am from java domain. But, i have to do some work in php for integration. My scenario is, i have one json array which will have 4 keys for ex:

 one json --> {"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"}.

I will be getting another JSON which ever edited from admin panel. for example if i updated any key, only that key will coming in the

 second JSON --> for ex: {"blog_heading":"def"}

Now, i have to replace the value of second json to first json. example output for above scenario like  I am very very new to php.. actually i am from java domain. But, i have to do some work in php for integration. My scenario is, i have one json array which will have 4 keys for ex:

  output json --> {"id":7,"active":1,"blogId":"abc","blog_heading":"def"}.

So i am trying as below,

$id = json_decode($data_string);
$id2 = json_encode($post);
$id5 = json_decode($id2);
$id6 = array();
foreach ($id as $key => $value)
{

    $log->debug($key . ': ' . $value);
    if (array_key_exists($key, $id5->data)) {
        $log->debug($key . 'element is in the array');
        $log->debug($value . 'element is in the array');
        //array_push($id5, "apple", "raspberry");

        $id3 = array($key  => $value);
        $id3[$key] = $value;
        $log->debug($id3);

    }else{
        $log->debug($key . 'element is not in the array');
    }

}
$id7 = json_encode($id2);
$log->debug($id7);

id5 data is : $id5

  DEBUG - 2017-06-05T02:26:20-04:00 - stdClass Object
   (
[meta] => stdClass Object
    (
        [table] => story
        [type] => item
    )

[data] => stdClass Object
    (
        [id] => 7
        [active] => 1
        [blogId] => abc
        [blog_heading] => xyz

    )

    )

 ==================

Log of $id :

stdClass Object
   (
[active] => 1
[blog_heading] => def
[id] => 7
 )

Please suggest me how can i achieve this... Anything i am doing wrong here

Body:
Please try that:

$j1 = '{"id":7,"active":1,"blogId":"abc","blog_heading":"xyz"}';
$j2 = '{"blog_heading":"def"}';

$result = json_encode(
    array_merge(
        json_decode($j1, true),
        json_decode($j2, true)
   )
);


问:
can I use the same class of some ViewResolver in spring-mvc two times with different property "order" to resovler the result from controller?
In one webapp project ,I need to use two ViewResolver, one is for .jsp. Another one is for .html, others say that I can user two ViewResolver with different property named order,i just wanna know can the two ViewResolvers use the same class such as InternalResourceViewResolver?

And how do the two resolvers work? the order?If the one with highest priority can not find a file using the String or
ModelAndView returned from controller ,the next one resolver continues resolving ??

答:
InternalResourceViewResolver extends UrlBasedViewResolver
You can override 2 methods. Gor them from the Spring sources

```<code>@Override
protected View loadView(String viewName, Locale locale) throws Exception {
    AbstractUrlBasedView view = buildView(viewName);
    View result = applyLifecycleMethods(viewName, view);
    return (view.checkResource(locale) ? result : null);
}

protected AbstractUrlBasedView buildView(String viewName) throws Exception {
    AbstractUrlBasedView view = (AbstractUrlBasedView) BeanUtils.instantiateClass(getViewClass());
    view.setUrl(getPrefix() + viewName + getSuffix());

    String contentType = getContentType();
    if (contentType != null) {
        view.setContentType(contentType);
    }

    view.setRequestContextAttribute(getRequestContextAttribute());
    view.setAttributesMap(getAttributesMap());

    Boolean exposePathVariables = getExposePathVariables();
    if (exposePathVariables != null) {
        view.setExposePathVariables(exposePathVariables);
    }
    Boolean exposeContextBeansAsAttributes = getExposeContextBeansAsAttributes();
    if (exposeContextBeansAsAttributes != null) {
        view.setExposeContextBeansAsAttributes(exposeContextBeansAsAttributes);
    }
    String[] exposedContextBeanNames = getExposedContextBeanNames();
    if (exposedContextBeanNames != null) {
        view.setExposedContextBeanNames(exposedContextBeanNames);
    }

    return view;
}
</code>```

As you can see loadView() creates view and then checks view.checkResource(locale)

if the result is null you replace suffix and try to get the secondary view for the same name.

Body:
InternalResourceViewResolver extends UrlBasedViewResolver
You can override 2 methods. Gor them from the Spring sources

@Override
protected View loadView(String viewName, Locale locale) throws Exception {
    AbstractUrlBasedView view = buildView(viewName);
    View result = applyLifecycleMethods(viewName, view);
    return (view.checkResource(locale) ? result : null);
}

protected AbstractUrlBasedView buildView(String viewName) throws Exception {
    AbstractUrlBasedView view = (AbstractUrlBasedView) BeanUtils.instantiateClass(getViewClass());
    view.setUrl(getPrefix() + viewName + getSuffix());

    String contentType = getContentType();
    if (contentType != null) {
        view.setContentType(contentType);
    }

    view.setRequestContextAttribute(getRequestContextAttribute());
    view.setAttributesMap(getAttributesMap());

    Boolean exposePathVariables = getExposePathVariables();
    if (exposePathVariables != null) {
        view.setExposePathVariables(exposePathVariables);
    }
    Boolean exposeContextBeansAsAttributes = getExposeContextBeansAsAttributes();
    if (exposeContextBeansAsAttributes != null) {
        view.setExposeContextBeansAsAttributes(exposeContextBeansAsAttributes);
    }
    String[] exposedContextBeanNames = getExposedContextBeanNames();
    if (exposedContextBeanNames != null) {
        view.setExposedContextBeanNames(exposedContextBeanNames);
    }

    return view;
}

As you can see loadView() creates view and then checks view.checkResource(locale)

if the result is null you replace suffix and try to get the secondary view for the same name.


问:
Why do some consider 2nd-order (aka persistent) XSS to not be true XSS?
I'm reading "The Web Application Hacker's Handbook", and it talks about the differences between 1st-order (aka reflected) XSS and 2nd-order (aka persistent) XSS.  It mentions how reflected XSS takes advantage of incomplete or nonexistent sanitization of query string params to execute arbitrary scripts into the user's DOM without persisting any malicious code to the application's database, and how 2nd-order XSS does in fact persist that malicious code, to be executed in the user's DOM at some later time.

My question relates to the author's desription of 2nd-order XSS (on page 438, if you've got a copy handy).  The description from the book states that:

Attacks against stored XSS vulnerabilities typically involve at least
  two requests to the application. In the first, the attacker posts some
  crafted data containing malicious code that the application stores. In
  the second, a victim views a page containing the attacker’s data, and
  the malicious code is executed when the script is executed in the
  victim’s browser. For this reason, the vulnerability is also sometimes
  called second-order cross-site scripting. (In this instance, “XSS” is
  really a misnomer, because the attack has no cross-site element. [emphasis mine] The
  name is widely used, however, so we will retain it here.)

In 2nd-order XSS, the malicious code that the attacker still injects is (presumably) still some arbitrary script pointing to an external server (for example, injecting an img tag with a src attribute of "http://www.malicioussite.dom" + document.cookie).  I'm confused why the author then states that this attack has no cross-site element.  Making a request to the malicious external server seems to me like a proper cross-site element.  Am I missing something?

答:
To me, 'cross-site' in XSS means that the malicious script itself is directly sent from another site. Like for example in case of reflected XSS on an url parameter, a malicious website A.com can craft a link to the victim website B.com with its attack in a vulnerable parameter of B, and when a user visits A and clicks the link, he will execute the script on B.

So I think it's not about what the malicious script is doing, it's where it comes from (and how).

In case of stored XSS, the script is usually entered on the vulnerable website directly, however that may not always be the case, such maintaining the original 'cross-site' element. But it doesn't matter, the name is the same, because the underlying problem and also the solution in code are the same, so the name of the vulnerability is the same too. :)

Whatever people call it though, the important thing is to avoid it. :)


问:
Meteor: Detect if token has expired before submission?
I am building a reset password screen in Meteor and I would like to detect if the reset password token has expired BEFORE I ask the user to fill out the form (password + confirm password) and click the submit button. It just seems like better UX.

However, I can't seem to find any methods or helpers in the Meteor docs that allow you to pass in a token and check to see if it's still valid or not. The only thing I can find is an error message that the token is expired AFTER the user submits. Which could be annoying to the customer, to have taken the time to fill out the form when we knew from the start that it wouldn't work. They would then have to go and get a new link, and re-fill out the form.

Is there not a better way to do this in Meteor?

答:
It is fairly easy to check if a token is still valid.

You can do something in the lines of:

Meteor.methods({
  checkResetToken(token) {
    check(token, String);

    const user = Meteor.users.findOne({
      "services.password.reset.token": token});
    if (!user) { // never existed or already been used
      throw new Meteor.Error(403, "Token expired");
    }

    const when = user.services.password.reset.when;
    const reason = user.services.password.reset.reason;
    let tokenLifetimeMs = Accounts._getPasswordResetTokenLifetimeMs();
    if (reason === "enroll") {
      tokenLifetimeMs = Accounts._getPasswordEnrollTokenLifetimeMs();
    }
    const currentTimeMs = Date.now();
    if ((currentTimeMs - when) > tokenLifetimeMs) { // timeout
      throw new Meteor.Error(403, "Token expired");
    }

    // you can return some of the user's details to further improve the UX.
  }
});
```

adapted from the code of the accounts-password package.

Then, use it in your client-side hook in order to determine whether the token is still valid and perhaps get some of the user's details from the server (e.g, whether it is an enrollment token or the user's name/email) to display a more personalized view.

Note that the user includes all of the secret fields, so don't return all of it to the client.

Body:
It is fairly easy to check if a token is still valid.

You can do something in the lines of:

Meteor.methods({
  checkResetToken(token) {
    check(token, String);

    const user = Meteor.users.findOne({
      "services.password.reset.token": token});
    if (!user) { // never existed or already been used
      throw new Meteor.Error(403, "Token expired");
    }

    const when = user.services.password.reset.when;
    const reason = user.services.password.reset.reason;
    let tokenLifetimeMs = Accounts._getPasswordResetTokenLifetimeMs();
    if (reason === "enroll") {
      tokenLifetimeMs = Accounts._getPasswordEnrollTokenLifetimeMs();
    }
    const currentTimeMs = Date.now();
    if ((currentTimeMs - when) > tokenLifetimeMs) { // timeout
      throw new Meteor.Error(403, "Token expired");
    }

    // you can return some of the user's details to further improve the UX.
  }
});

adapted from the code of the accounts-password package.

Then, use it in your client-side hook in order to determine whether the token is still valid and perhaps get some of the user's details from the server (e.g, whether it is an enrollment token or the user's name/email) to display a more personalized view.

Note that the user includes all of the secret fields, so don't return all of it to the client.


答:
I think you are looking for this

```<code>string_x = "abc"
data = ""
for i in range (0, len(string_x)):
    data += str(string_x[i])
print(data)
</code>```

output

```<code>abc
</code>```

you can use += or data = data + str(string_x[i])

Title: Python: for loop iteration accumulate values in string variable

Body:
I think you are looking for this

string_x = "abc"
data = ""
for i in range (0, len(string_x)):
    data += str(string_x[i])
print(data)

output

abc

you can use += or data = data + str(string_x[i])


问:
<identifier> expected in HackerRank code
I have been trying this code on hackerRank, and I get the following error.

```<code>Solution.java:36: error: <identifier> expected
  System.out.print(ans);
                  ^
Solution.java:36: error: <identifier> expected
  System.out.print(ans);
                      ^
2 errors
</code>```

code:

```<code>import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
  int n = scan.nextInt();
  scan.close();
  String ans="";

  // if 'n' is NOT evenly divisible by 2 (i.e.: n is odd)
  if(n%2==1){
     ans = "Weird";
  }

   else if (n%2==0)//even no
       {
       if(n>2 && n<=5)
      ans="Not Wierd";
       }

        if(n>6 && n<20)
            {
               ans="Wierd";
             }
        else
        {
     ans="Not Wierd";
           }

  }
  System.out.print(ans);
}
</code>```

What is my mistake?

答:
The variable ans doesn't exist in the scope where you are trying to print it.

Please do proper indentation to the code while debugging to better understand the issue.

```<code>import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {

 public static void main(String[] args) {
  Scanner scan = new Scanner(System.in);
  int n = scan.nextInt();
  scan.close();
  String ans = "";

  // if 'n' is NOT evenly divisible by 2 (i.e.: n is odd)
  if (n % 2 == 1) {
   ans = "Weird";
  }
  else if (n % 2 == 0) //even no
  {
   if (n > 2 && n <= 5)
    ans = "Not Wierd";
  }

  if (n > 6 && n < 20) {
   ans = "Wierd";
  }
  else {
   ans = "Not Wierd";
  }
 }
 System.out.print(ans);
}
</code>```

Body:
I have been trying this code on hackerRank, and I get the following error.

Solution.java:36: error: <identifier> expected
  System.out.print(ans);
                  ^
Solution.java:36: error: <identifier> expected
  System.out.print(ans);
                      ^
2 errors

code:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
  int n = scan.nextInt();
  scan.close();
  String ans="";

  // if 'n' is NOT evenly divisible by 2 (i.e.: n is odd)
  if(n%2==1){
     ans = "Weird";
  }

   else if (n%2==0)//even no
       {
       if(n>2 && n<=5)
      ans="Not Wierd";
       }

        if(n>6 && n<20)
            {
               ans="Wierd";
             }
        else
        {
     ans="Not Wierd";
           }

  }
  System.out.print(ans);
}

What is my mistake?

Body:
The variable ans doesn't exist in the scope where you are trying to print it.

Please do proper indentation to the code while debugging to better understand the issue.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {

 public static void main(String[] args) {
  Scanner scan = new Scanner(System.in);
  int n = scan.nextInt();
  scan.close();
  String ans = "";

  // if 'n' is NOT evenly divisible by 2 (i.e.: n is odd)
  if (n % 2 == 1) {
   ans = "Weird";
  }
  else if (n % 2 == 0) //even no
  {
   if (n > 2 && n <= 5)
    ans = "Not Wierd";
  }

  if (n > 6 && n < 20) {
   ans = "Wierd";
  }
  else {
   ans = "Not Wierd";
  }
 }
 System.out.print(ans);
}


问:
Xcode5: unit test linking errors
I seem to get this strange issue when testing an XCTestCase. I created a unit testing bundle, and set my main app as the "target"; now I can write tests against my Core Data NSManagedObjects just fine, but if I include anything else in my app that isn't an NSManagedObject, I get linking errors:

Undefined symbols for architecture x86_64:
    "_OBJC_CLASS_$_iCloudListener", referenced from:
        objc-class-ref in SLTestToDoWithRepeatInterval.o
  ld: symbol(s) not found for architecture x86_64
  clang: error: linker command failed with exit code 1 (use -v to see invocation)

This only happens with non-NSManagedObjects. And iCloudListener is definitely in the Compiled Sources for the main app target. The problem is that though I can go and add this particular iCloudListener class into the test target -> Build Phases -> Compile Sources list, and that will make this particular linking error go away, but it introduces new ones since it starts giving linking errors about all the header files from the iCLoudListener class; and if I start adding those, they require more and more files, to the point where I have to include pretty much all of my code into the test target "Compile Sources" section.

Is there something I'm doing wrong here? Is there a setting which might be causing Xcode to ignore the non-NSManagedObject classes?

答:
It's because the project inserted the core data's xcdatamodeld file in compile sources. Select your project -> Build Phases -> Compile Sources and delete projectName.xcdatamodeld file.
And also check if you have imported .m file instead of .h file, it also gives the same linker error.
Check all the #import codes.
And check if you have added core data frame work in library and imported core data .h file. Check for creation of NSManagedObject and import it's file.
Just try it and reply me if still any error.

Title: Xcode5: unit test linking errors


问:
python simple iteration
i would like to ask what is the best way to make simple iteration. suppose i want to repeat certain task 1000 times, which one of the following is the best? or is there a better way?

```<code>for i in range(1000):
    do something with no reference to i

i = 0
while i < 1000:
    do something with no reference to i
    i += 1
</code>```

thanks very much

答:
In Python 2, use

```<code>for i in xrange(1000):
    pass
</code>```

In Python 3, use

```<code>for i in range(1000):
    pass
</code>```

Performance figures for Python 2.6:

```<code>$ python -s -m timeit '' 'i = 0
> while i < 1000:
>     i += 1'
10000 loops, best of 3: 71.1 usec per loop

$ python -s -m timeit '' 'for i in range(1000): pass'
10000 loops, best of 3: 28.8 usec per loop

$ python -s -m timeit '' 'for i in xrange(1000): pass'
10000 loops, best of 3: 21.9 usec per loop
</code>```

xrange is preferable to range in this case because it produces a generator rather than the whole list [0, 1, 2, ..., 998, 999]. It'll use less memory, too. If you needed the actual list to work with all at once, that's when you use range. Normally you want xrange: that's why in Python 3, xrange(...) becomes range(...) and range(...) becomes list(range(...)).

Title: python simple iteration

Body:
i would like to ask what is the best way to make simple iteration. suppose i want to repeat certain task 1000 times, which one of the following is the best? or is there a better way?

for i in range(1000):
    do something with no reference to i

i = 0
while i < 1000:
    do something with no reference to i
    i += 1

thanks very much

Body:
In Python 2, use

for i in xrange(1000):
    pass

In Python 3, use

for i in range(1000):
    pass

Performance figures for Python 2.6:

$ python -s -m timeit '' 'i = 0
> while i < 1000:
>     i += 1'
10000 loops, best of 3: 71.1 usec per loop

$ python -s -m timeit '' 'for i in range(1000): pass'
10000 loops, best of 3: 28.8 usec per loop

$ python -s -m timeit '' 'for i in xrange(1000): pass'
10000 loops, best of 3: 21.9 usec per loop

xrange is preferable to range in this case because it produces a generator rather than the whole list [0, 1, 2, ..., 998, 999]. It'll use less memory, too. If you needed the actual list to work with all at once, that's when you use range. Normally you want xrange: that's why in Python 3, xrange(...) becomes range(...) and range(...) becomes list(range(...)).


问:
Typescript - Extending Error class
I'm trying to throw a custom error with my "CustomError" class name printed in the console instead of "Error", with no success:

```<code>class CustomError extends Error {
    constructor(message: string) {
      super(`Lorem "${message}" ipsum dolor.`);
      this.name = 'CustomError';
    }
}
throw new CustomError('foo');
</code>```

The output is Uncaught Error: Lorem "foo" ipsum dolor.

What I expect: Uncaught CustomError: Lorem "foo" ipsum dolor.

I wonder if that can be done using TS only (without messing with JS prototypes)?

答:
I ran into the same problem in my typescript project a few days ago. To make it work, I use the implementation from MDN using only vanilla js. So your error would look something like the following:

function CustomError(message) {
  this.name = 'CustomError';
  this.message = message || 'Default Message';
  this.stack = (new Error()).stack;
}
CustomError.prototype = Object.create(Error.prototype);
CustomError.prototype.constructor = CustomError;

throw new CustomError('foo');```

It doesn't seem to work in SO code snippet, but it does in the chrome console and in my typescript project:

Title: Typescript - Extending Error class

Body:
I'm trying to throw a custom error with my "CustomError" class name printed in the console instead of "Error", with no success:

class CustomError extends Error {
    constructor(message: string) {
      super(`Lorem "${message}" ipsum dolor.`);
      this.name = 'CustomError';
    }
}
throw new CustomError('foo');

The output is Uncaught Error: Lorem "foo" ipsum dolor.

What I expect: Uncaught CustomError: Lorem "foo" ipsum dolor.

I wonder if that can be done using TS only (without messing with JS prototypes)?

Body:
I ran into the same problem in my typescript project a few days ago. To make it work, I use the implementation from MDN using only vanilla js. So your error would look something like the following:

function CustomError(message) {
  this.name = 'CustomError';
  this.message = message || 'Default Message';
  this.stack = (new Error()).stack;
}
CustomError.prototype = Object.create(Error.prototype);
CustomError.prototype.constructor = CustomError;

throw new CustomError('foo');

It doesn't seem to work in SO code snippet, but it does in the chrome console and in my typescript project:


问:
How to commit changes to local SQL DB In Visual Studio 2015?
I am new to working with databases. I made a simple form app to display this data table however, I can't get the data into the database so that the form displays it. I initially had only 1 employee listed here and he shows up in my application. I just added the last 3 employees into this table view but if I run the app, only the original employee (id 1) shows up. How do I commit the last 3 employees' info into the database? I Googled some info on this and found a select * from dbo.EmployeeInfo query and ran it, it displays the employee info right but it doesn't seem to change the database with the new info. Thank you.

答:
I was stuck here too.
What I did was -
1) Updated the values and after updating the last values, I pressed Enter

It seems to work for me.
Enter button on keyboard makes life simple. :)


问:
In Kafka streams, what does VALUE_SERDE_CLASS_CONFIG do
In Kafka streams, what is purpose of:

props.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
props.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
```

<p>...considering that the Serdes are called out in <code>builder</code>:</p>

```final KStream<String, String> textLines = builder.stream(stringSerde, stringSerde, "TextLinesTopic");
```

<p>...and in <code>to</code>:</p>

<pre class="lang-java prettyprint-override"><code>wordCounts.to(stringSerde, longSerde, "WordsWithCountsTopic");
</code>```

In my code I removed the above two props.put calls and everything seemed to still work fine. Also, note that we don't pass Serdes.Long() to VALUE_SERDE_CLASS_CONFIG, even though it's used in to call.

Snippets taken from confluent sample.

答:
It sets the default key or value serde for all operations that don't specify a serde.

For example, you can create a stream without specifying serdes like

final KStream<String, String> textLines = builder.stream("TextLinesTopic");
```

For this case, Streams would use whatever is specified as key/value Serde in the config for topic "TextLinexTopic". (Btw, both parameters are renamed to default.key.serde and default.value.serde in upcoming 0.11 to make their semantic clearer.)

For the example you linked to: I did not double check, but if all operators specify Serdes anyway, the config is actually not necessary.

Body:
In Kafka streams, what is purpose of:

props.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
props.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());

...considering that the Serdes are called out in builder:

final KStream<String, String> textLines = builder.stream(stringSerde, stringSerde, "TextLinesTopic");

...and in to:

wordCounts.to(stringSerde, longSerde, "WordsWithCountsTopic");

In my code I removed the above two props.put calls and everything seemed to still work fine. Also, note that we don't pass Serdes.Long() to VALUE_SERDE_CLASS_CONFIG, even though it's used in to call.

Snippets taken from confluent sample.

Body:
It sets the default key or value serde for all operations that don't specify a serde.

For example, you can create a stream without specifying serdes like

final KStream<String, String> textLines = builder.stream("TextLinesTopic");

For this case, Streams would use whatever is specified as key/value Serde in the config for topic "TextLinexTopic". (Btw, both parameters are renamed to default.key.serde and default.value.serde in upcoming 0.11 to make their semantic clearer.)

For the example you linked to: I did not double check, but if all operators specify Serdes anyway, the config is actually not necessary.


答:
```<code>SELECT * from tablename  WHERE p_code=? ORDER BY date DESC LIMIT 1
</code>```

Title: How to get last inserted date of a certain record using php and mysql?