问:
parallel operation execution time varies on allocating dynamic memory vs static memory
I have wrote a code to multiply two n by n matrices using openmp parallel for(for the outer loop).I have given the array size at compile time. I wish to give n as 2000. However as a second version I wrote the same code by dynamically allocating spaces for three matrices and giving the size of n (2000) as an argument. The two execution times I got for both versions when n = 2000 is differs in large. For 1st version (static allocation) it is around 13 seconds and for 2nd version (dynamic allocation) it is around 32 seconds. But both gives around same time for n<=1000. I only measure time for the parallel multiplying operation.So how could these two approaches give me different results? (the only change is the memory allocation type)

Here is version 1

```<code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <omp.h>

#define N 1000
double A[N][N], B[N][N], C[N][N]; // declaring matrices of NxN size
int main ()
{
  /* DECLARING VARIABLES */
  int i, j, m; // indices for matrix multiplication
  double t_1; // Execution time measures
  /* FILLING MATRICES WITH RANDOM NUMBERS */
  srand ( time(NULL) );
  for(i=0;i<N;i++) {
    for(j=0;j<N;j++) {
        A[i][j]= (rand()%10);
        B[i][j]= (rand()%10);
    }
  }
  double st=omp_get_wtime();
  for(i=0;i<N;i++)
  {
    for(j=0;j<N;j++)
    {
        for(m=0;m<N;m++)
        {
            C[i][j]+=A[i][m]*B[m][j];
        }
    }
  }
  /* TIME MEASURE + OUTPUT */
  double en=omp_get_wtime();
  printf("Serial: %lf\n",en-st);
}
</code>```

And here is the second version

```<code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <omp.h>

int N = 0; // no of columns and rows of a matrix
double **A, **B, **C; // declaring pointers for matrices of NxN size

void getArguments(int argc, char *argv[]);

int main (int argc, char *argv[])
{
/* DECLARING VARIABLES */
int i, j, m; // indices for matrix multiplication
double t_1; // Execution time MEASURES
getArguments(argc,argv);

/* ALLOCATE MEMORY FOR MATRIX A */
A = (double **) malloc( sizeof(double *) * N);
for(i = 0;i < N; i++)
{
    A[i] = (double *) malloc(sizeof(double *) * N);
}

/* ALLOCATE MEMORY FOR MATRIX B */
B = (double **) malloc( sizeof(double *) * N);
for(i = 0;i < N; i++)
{
    B[i] = (double *) malloc(sizeof(double *) * N);
}

/* ALLOCATE MEMORY FOR MATRIX C */
C = (double **) malloc( sizeof(double *) * N);
for(i = 0;i < N; i++)
{
    C[i] = (double *) malloc(sizeof(double *) * N);
}

/* FILLING MATRICES WITH RANDOM NUMBERS */
srand ( time(NULL) );
for(i = 0;i < N;i++) {
    for(j = 0;j < N;j++) {
        A[i][j] = (rand() % 10);
        B[i][j] = (rand() % 10);
    }
}

double st = omp_get_wtime();
#pragma omp parallel for private(m,j)
for(i = 0;i < N;i++) {
    for(j = 0;j < N;j++) {
        C[i][j] = 0.; // set initial value of resulting matrix C = 0
        for(m = 0;m < N;m++) {
            C[i][j] = A[i][m] * B[m][j] + C[i][j];
        }
    }
}

/* TIME MEASURE */
double en = omp_get_wtime();
printf("Parallel: %lf\n",en - st);

/* FREE MEMORY */
for(i = 0;i < N; i++){
    free(A[i]);
}
free(A);
for(i = 0;i < N; i++){
    free(B[i]);
}
free(B);
for(i = 0;i < N; i++){
    free(C[i]);
}
free(C);
}

void getArguments(int argc, char *argv[]){
// Check the N
if (argc != 2) {
    printf("Please give a valid number for N\n");
    exit(0);
}
N = (int) strtol(argv[1], (char **) NULL, 10);
if (N == 0) {
    printf("Please give a number for N more than 0\n");
    exit(0);
}

}
</code>```

答:
There are three major differences with the dynamic allocation:

The data is not allocated contiguously, as each row is allocated separately. This causes less efficient memory access, e.g. due to caching, prefetchers.

Each element access is indirect, through the pointer for the row. This is less efficient than computing the memory location just by the two indices.

N is no longer known at compile time, so the compiler has to generate more general purpose code for the loops over N.

Body:
I have wrote a code to multiply two n by n matrices using openmp parallel for(for the outer loop).I have given the array size at compile time. I wish to give n as 2000. However as a second version I wrote the same code by dynamically allocating spaces for three matrices and giving the size of n (2000) as an argument. The two execution times I got for both versions when n = 2000 is differs in large. For 1st version (static allocation) it is around 13 seconds and for 2nd version (dynamic allocation) it is around 32 seconds. But both gives around same time for n<=1000. I only measure time for the parallel multiplying operation.So how could these two approaches give me different results? (the only change is the memory allocation type)

Here is version 1

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <omp.h>

#define N 1000
double A[N][N], B[N][N], C[N][N]; // declaring matrices of NxN size
int main ()
{
  /* DECLARING VARIABLES */
  int i, j, m; // indices for matrix multiplication
  double t_1; // Execution time measures
  /* FILLING MATRICES WITH RANDOM NUMBERS */
  srand ( time(NULL) );
  for(i=0;i<N;i++) {
    for(j=0;j<N;j++) {
        A[i][j]= (rand()%10);
        B[i][j]= (rand()%10);
    }
  }
  double st=omp_get_wtime();
  for(i=0;i<N;i++)
  {
    for(j=0;j<N;j++)
    {
        for(m=0;m<N;m++)
        {
            C[i][j]+=A[i][m]*B[m][j];
        }
    }
  }
  /* TIME MEASURE + OUTPUT */
  double en=omp_get_wtime();
  printf("Serial: %lf\n",en-st);
}

And here is the second version

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <omp.h>

int N = 0; // no of columns and rows of a matrix
double **A, **B, **C; // declaring pointers for matrices of NxN size

void getArguments(int argc, char *argv[]);

int main (int argc, char *argv[])
{
/* DECLARING VARIABLES */
int i, j, m; // indices for matrix multiplication
double t_1; // Execution time MEASURES
getArguments(argc,argv);

/* ALLOCATE MEMORY FOR MATRIX A */
A = (double **) malloc( sizeof(double *) * N);
for(i = 0;i < N; i++)
{
    A[i] = (double *) malloc(sizeof(double *) * N);
}

/* ALLOCATE MEMORY FOR MATRIX B */
B = (double **) malloc( sizeof(double *) * N);
for(i = 0;i < N; i++)
{
    B[i] = (double *) malloc(sizeof(double *) * N);
}

/* ALLOCATE MEMORY FOR MATRIX C */
C = (double **) malloc( sizeof(double *) * N);
for(i = 0;i < N; i++)
{
    C[i] = (double *) malloc(sizeof(double *) * N);
}

/* FILLING MATRICES WITH RANDOM NUMBERS */
srand ( time(NULL) );
for(i = 0;i < N;i++) {
    for(j = 0;j < N;j++) {
        A[i][j] = (rand() % 10);
        B[i][j] = (rand() % 10);
    }
}

double st = omp_get_wtime();
#pragma omp parallel for private(m,j)
for(i = 0;i < N;i++) {
    for(j = 0;j < N;j++) {
        C[i][j] = 0.; // set initial value of resulting matrix C = 0
        for(m = 0;m < N;m++) {
            C[i][j] = A[i][m] * B[m][j] + C[i][j];
        }
    }
}

/* TIME MEASURE */
double en = omp_get_wtime();
printf("Parallel: %lf\n",en - st);

/* FREE MEMORY */
for(i = 0;i < N; i++){
    free(A[i]);
}
free(A);
for(i = 0;i < N; i++){
    free(B[i]);
}
free(B);
for(i = 0;i < N; i++){
    free(C[i]);
}
free(C);
}

void getArguments(int argc, char *argv[]){
// Check the N
if (argc != 2) {
    printf("Please give a valid number for N\n");
    exit(0);
}
N = (int) strtol(argv[1], (char **) NULL, 10);
if (N == 0) {
    printf("Please give a number for N more than 0\n");
    exit(0);
}

}


来源: stackexchange

问:
numpy.array operation / method: subtract value of one element from the value of next element
I tried to build the differences from the values of one element [n] to the next element [n+1] in the same numpy.array.

This must be repeated for all n, I expect n-1 result values.

Furthermore I want to avoid using loops, because loops may be a source of errors numbering the elements.

Now I'm looking for an operation like:

```<code>result = array[n+1] - array[n]
</code>```

for all n.

I tried much similar implementations, but I always get some error messages.

How can I make it work?

答:
Numpy's diff() function does what you ask.

Here is an example:

```<code>import numpy as np
a = np.arange(10)  # this instantiates a numpy array containing values from 0 to 9
result = np.diff(a)  # if you print this you'll see an array of 1 with length 9
</code>```

If you want you can use slicing instead (I add this for all newbies, as an example of slicing), as follows:

```<code>result = a[1:] - a[:-1]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I tried to build the differences from the values of one element [n] to the next element [n+1] in the same numpy.array.

This must be repeated for all n, I expect n-1 result values.

Furthermore I want to avoid using loops, because loops may be a source of errors numbering the elements.

Now I'm looking for an operation like:

result = array[n+1] - array[n]

for all n.

I tried much similar implementations, but I always get some error messages.

How can I make it work?

Body:
Numpy's diff() function does what you ask.

Here is an example:

import numpy as np
a = np.arange(10)  # this instantiates a numpy array containing values from 0 to 9
result = np.diff(a)  # if you print this you'll see an array of 1 with length 9

If you want you can use slicing instead (I add this for all newbies, as an example of slicing), as follows:

result = a[1:] - a[:-1]


问:
Applying css margin to content before images
I have text content and images mixed and want to apply css margin to elements directly before and after images (
, ,  can come before or after the image, but I have no control on which one and where)

I am using the following code to apply margin to the elements before the image

```<code>#single-pg * + img { margin-top: 75px; }
</code>```

Problem is that it adds the margin-top to other images aswell (I want it to apply to all elements EXCEPT images) and I want to add similar to affect content elements after the image

```<code>#single-pg img + * { margin-bottom: 75px; }
</code>```

html (Wordpress)

```<code><div id="single-pg" >
    <?php the_content(); ?>
</div>
</code>```

so the outcome could be (but could also be in any other order based on the author)

```<code><h2>Title</h2>
<image></image>
<image<</image>
<p>text</p>
<p>text</p>
<p>text</p>
<image<</image>
</code>```

答: Put your images and text in a wrapper and each image and text in another wrapper and you can manage your margin for each image.</p>

Body:
I have text content and images mixed and want to apply css margin to elements directly before and after images (
, ,  can come before or after the image, but I have no control on which one and where)

I am using the following code to apply margin to the elements before the image

#single-pg * + img { margin-top: 75px; }

Problem is that it adds the margin-top to other images aswell (I want it to apply to all elements EXCEPT images) and I want to add similar to affect content elements after the image

#single-pg img + * { margin-bottom: 75px; }

html (Wordpress)

    <?php the_content(); ?>

so the outcome could be (but could also be in any other order based on the author)

Title

<image></image>
<image<</image>

text

text

text

<image<</image>


问:
HA *slave* node not syncing (1 of 2 nodes only) +neo4j
Neo4j Version: 3.2.1
Operating System: CentOs 7
API: Neo4J

Hi there I am having a weird issue where one of the slave nodes is not syncing to the master. I included the logs (the problem node is n2) and configuration file.

--removed links--

答:
The solution for me was to set a non default value to
ha.pull_interval</p>


问:
Rails & RSpec: Testing CRUD actions with shared examples
Testing RESTful actions of multiple Rails controllers with RSpec can generate a lot of code repetition. The following code is my first attempt at using shared examples to DRY things up.

Here is what I don't like about the code, could not find a better way and would like your help to improve:

The shared examples require that specific variables are set within let blocks within the controller spec (high coupling). I have tried to use the model name to infer the factory name and create the test data within the share examples. It works well to create the record and records variables. However, some models require the presence of associations and FactoryGirl.attributes_for does not create associated records, so validation fails. So, valid_attributes are created differently for different models. The only (likely bad) way I could think of creating valid_attributes within shared examples is to pass a string containing the code used to create the attributes and evaluate it (eval) within the shared examples

The tests that assert redirection use eval to call Rails' route/path helpers. Different controllers in this app have different redirect behaviors. After creating or updating a record, some controllers redirect to the #show action, others to #index. The problem is that when expecting a redirect to #show, AFAIK, we have to know the record ID in order to build the expected URL. And we don't know the record ID within the controller spec. We only know it within the shared examples. So how can we pass an expected redirect URL from the controller spec to the shared example if we do not yet know what that URL is (because we don't know the record ID)?

Also, please let me know if you spot any additional issues.

The controller spec:

```<code># spec/controllers/quotes_controller_spec.rb
require "rails_helper"

RSpec.describe QuotesController, :focus, :type => :controller do
  login_admin

  let(:model) { Quote }
  let(:record) { FactoryGirl.create(:quote) }
  let(:records) { FactoryGirl.create_pair(:quote) }
  let(:valid_attributes) { FactoryGirl.attributes_for(:quote, quote: "New quote") }
  let(:invalid_attributes) { valid_attributes.update(quote: nil) }

  include_examples "GET #index"
  include_examples "GET #show"
  include_examples "GET #new"
  include_examples "GET #edit"
  include_examples "POST #create", "quote_path(assigns(:quote))"
  include_examples "PATCH #update", "quote_url"
  include_examples "DELETE #destroy", "quotes_url"
end
</code>```

The shared examples:

```<code># spec/support/shared_examples/controller_restful_actions.rb
def ivar_name(model, plural: false)
  if plural
    model.name.pluralize.underscore.to_sym
  else
    model.name.underscore.to_sym
  end
end

def record_name(model)
  model.name.underscore.to_sym
end

RSpec.shared_examples "GET #index" do
  describe "GET #index" do
    it "requires login" do
      sign_out current_user
      get :index
      expect(response).to require_login
    end

    it "enforces authorization" do
      get :index
      expect(controller).to enforce_authorization
    end

    it "populates instance variable with an array of records" do
      get :index
      expect(assigns(ivar_name(model, plural: true))).to match_array(records)
    end
  end
end

RSpec.shared_examples "GET #show" do
  describe "GET #show" do

    it "requires login" do
      sign_out current_user
      get :show, id: record
      expect(response).to require_login
    end

    it "enforces authorization" do
      get :show, id: record
      expect(controller).to enforce_authorization
    end

    it "assigns the requested record to an instance variable" do
      get :show, id: record
      expect(assigns(ivar_name(model))).to eq(record)
    end
  end
end

RSpec.shared_examples "GET #new" do
  describe "GET #new" do
    it "requires login" do
      sign_out current_user
      get :new
      expect(response).to require_login
    end

    it "enforces authorization" do
      get :new
      expect(controller).to enforce_authorization
    end

    it "assigns a new record to an instance variable" do
      get :new
      expect(assigns(ivar_name(model))).to be_a_new(model)
    end
  end
end

RSpec.shared_examples "GET #edit" do
  describe "GET #edit" do
    let(:record) { FactoryGirl.create(factory_name(model)) }

    it "requires login" do
      sign_out current_user
      get :edit, id: record
      expect(response).to require_login
    end

    it "enforces authorization" do
      get :edit, id: record
      expect(controller).to enforce_authorization
    end

    it "assigns the requested record to an instance variable" do
      get :edit, id: record
      expect(assigns(ivar_name(model))).to eq(record)
    end
  end
end

RSpec.shared_examples "POST #create" do |redirect_path_helper|
  describe "POST #create" do
    it "requires login" do
      sign_out current_user
      post :create, { record_name(model) => valid_attributes }
      expect(response).to require_login
    end

    it "enforces authorization" do
      post :create, { record_name(model) => valid_attributes }
      expect(controller).to enforce_authorization
    end

    context "with valid attributes" do
      it "saves the new record in the database" do
        expect{
          post :create, { record_name(model) => valid_attributes }
        }.to change(model, :count).by(1)
      end

      it "assigns a newly created but unsaved record to an instance variable" do
        post :create, { record_name(model) => valid_attributes }
        expect(assigns(ivar_name(model))).to be_a(model)
        expect(assigns(ivar_name(model))).to be_persisted
      end

      it "redirects to #{redirect_path_helper}" do
        post :create, { record_name(model) => valid_attributes }
        expect(response).to redirect_to(eval(redirect_path_helper))
      end
    end

    context "with invalid attributes" do
      it "does not save the new record in the database" do
        expect{
          post :create, { record_name(model) => invalid_attributes }
        }.not_to change(model, :count)
      end

      it "assigns a newly created but unsaved record an instance variable" do
        post :create, { record_name(model) => invalid_attributes }
        expect(assigns(ivar_name(model))).to be_a_new(model)
      end

      it "re-renders the :new template" do
        post :create, { record_name(model) => invalid_attributes }
        expect(response).to render_template(:new)
      end
    end
  end
end

RSpec.shared_examples "PATCH #update" do |redirect_path_helper|
  describe "PATCH #update" do
    let(:record) { FactoryGirl.create(factory_name(model)) }

    it "requires login" do
      sign_out current_user
      patch :update, { :id => record, record_name(model) => valid_attributes }
      expect(response).to require_login
    end

    it "enforces authorization" do
      patch :update, { :id => record, record_name(model) => valid_attributes }
      expect(controller).to enforce_authorization
    end

    context "with valid attributes" do
      it "updates the requested record" do
        patch :update, { :id => record, record_name(model) => valid_attributes }
        record.reload
        expect(record).to have_attributes(valid_attributes)
      end

      it "assigns the requested record to an instance variable" do
        put :update,  { :id => record, record_name(model) => valid_attributes }
        expect(assigns(ivar_name(model))).to eq(record)
      end

      it "redirects to #{redirect_path_helper}" do
        patch :update,  { :id => record, record_name(model) => valid_attributes }
        expect(response).to redirect_to(eval(redirect_path_helper))
      end
    end

    context "with invalid attributes" do
      it "does not update the requested record" do
        expect {
          patch :update, { :id => record, record_name(model) => invalid_attributes }
        }.not_to change { record.reload.attributes }
      end

      it "assigns the record to an instance variable" do
        patch :update, { :id => record, record_name(model) => invalid_attributes }
        expect(assigns(ivar_name(model))).to eq(record)
      end

      it "re-renders the :edit template" do
        patch :update, { :id => record, record_name(model) => invalid_attributes }
        expect(response).to render_template(:edit)
      end
    end
  end
end

RSpec.shared_examples "DELETE #destroy" do |redirect_path_helper|
  describe "DELETE #destroy" do
    it "requires login" do
      sign_out current_user
      delete :destroy, id: record
      expect(response).to require_login
    end

    it "enforces authorization" do
      delete :destroy, id: record
      expect(controller).to enforce_authorization
    end

    it "deletes the record" do
      # Records are lazily created. Here we must force its creation.
      record
      expect{
        delete :destroy, id: record
      }.to change(model, :count).by(-1)
    end

    it "redirects to #{redirect_path_helper}" do
      delete :destroy, id: record
      expect(response).to redirect_to(eval(redirect_path_helper))
    end
  end
end
</code>```

答:
For the let blocks, does it not work if you pass in the model as a parameter to the shared example like you do with the redirect_path_helper?

```<code>include_examples "GET #index", Quote
</code>```

and then in your shared_example you can use the record_name method to create record and records from FactoryGirl and generate valid_attributes and invalid_attributes (you could create an :invalid_quote factory as well for invalid attributes, not sure if that's considered a good practice/idea with FactoryGirl though) from there.

For the second problem, you don't need to use the named route helpers, url_for(controller: :quote) and url_for(@quote) should both work.

Body:
Testing RESTful actions of multiple Rails controllers with RSpec can generate a lot of code repetition. The following code is my first attempt at using shared examples to DRY things up.

Here is what I don't like about the code, could not find a better way and would like your help to improve:

The shared examples require that specific variables are set within let blocks within the controller spec (high coupling). I have tried to use the model name to infer the factory name and create the test data within the share examples. It works well to create the record and records variables. However, some models require the presence of associations and FactoryGirl.attributes_for does not create associated records, so validation fails. So, valid_attributes are created differently for different models. The only (likely bad) way I could think of creating valid_attributes within shared examples is to pass a string containing the code used to create the attributes and evaluate it (eval) within the shared examples

The tests that assert redirection use eval to call Rails' route/path helpers. Different controllers in this app have different redirect behaviors. After creating or updating a record, some controllers redirect to the #show action, others to #index. The problem is that when expecting a redirect to #show, AFAIK, we have to know the record ID in order to build the expected URL. And we don't know the record ID within the controller spec. We only know it within the shared examples. So how can we pass an expected redirect URL from the controller spec to the shared example if we do not yet know what that URL is (because we don't know the record ID)?

Also, please let me know if you spot any additional issues.

The controller spec:

# spec/controllers/quotes_controller_spec.rb
require "rails_helper"

RSpec.describe QuotesController, :focus, :type => :controller do
  login_admin

  let(:model) { Quote }
  let(:record) { FactoryGirl.create(:quote) }
  let(:records) { FactoryGirl.create_pair(:quote) }
  let(:valid_attributes) { FactoryGirl.attributes_for(:quote, quote: "New quote") }
  let(:invalid_attributes) { valid_attributes.update(quote: nil) }

  include_examples "GET #index"
  include_examples "GET #show"
  include_examples "GET #new"
  include_examples "GET #edit"
  include_examples "POST #create", "quote_path(assigns(:quote))"
  include_examples "PATCH #update", "quote_url"
  include_examples "DELETE #destroy", "quotes_url"
end

The shared examples:

# spec/support/shared_examples/controller_restful_actions.rb
def ivar_name(model, plural: false)
  if plural
    model.name.pluralize.underscore.to_sym
  else
    model.name.underscore.to_sym
  end
end

def record_name(model)
  model.name.underscore.to_sym
end

RSpec.shared_examples "GET #index" do
  describe "GET #index" do
    it "requires login" do
      sign_out current_user
      get :index
      expect(response).to require_login
    end

    it "enforces authorization" do
      get :index
      expect(controller).to enforce_authorization
    end

    it "populates instance variable with an array of records" do
      get :index
      expect(assigns(ivar_name(model, plural: true))).to match_array(records)
    end
  end
end

RSpec.shared_examples "GET #show" do
  describe "GET #show" do

    it "requires login" do
      sign_out current_user
      get :show, id: record
      expect(response).to require_login
    end

    it "enforces authorization" do
      get :show, id: record
      expect(controller).to enforce_authorization
    end

    it "assigns the requested record to an instance variable" do
      get :show, id: record
      expect(assigns(ivar_name(model))).to eq(record)
    end
  end
end

RSpec.shared_examples "GET #new" do
  describe "GET #new" do
    it "requires login" do
      sign_out current_user
      get :new
      expect(response).to require_login
    end

    it "enforces authorization" do
      get :new
      expect(controller).to enforce_authorization
    end

    it "assigns a new record to an instance variable" do
      get :new
      expect(assigns(ivar_name(model))).to be_a_new(model)
    end
  end
end

RSpec.shared_examples "GET #edit" do
  describe "GET #edit" do
    let(:record) { FactoryGirl.create(factory_name(model)) }

    it "requires login" do
      sign_out current_user
      get :edit, id: record
      expect(response).to require_login
    end

    it "enforces authorization" do
      get :edit, id: record
      expect(controller).to enforce_authorization
    end

    it "assigns the requested record to an instance variable" do
      get :edit, id: record
      expect(assigns(ivar_name(model))).to eq(record)
    end
  end
end

RSpec.shared_examples "POST #create" do |redirect_path_helper|
  describe "POST #create" do
    it "requires login" do
      sign_out current_user
      post :create, { record_name(model) => valid_attributes }
      expect(response).to require_login
    end

    it "enforces authorization" do
      post :create, { record_name(model) => valid_attributes }
      expect(controller).to enforce_authorization
    end

    context "with valid attributes" do
      it "saves the new record in the database" do
        expect{
          post :create, { record_name(model) => valid_attributes }
        }.to change(model, :count).by(1)
      end

      it "assigns a newly created but unsaved record to an instance variable" do
        post :create, { record_name(model) => valid_attributes }
        expect(assigns(ivar_name(model))).to be_a(model)
        expect(assigns(ivar_name(model))).to be_persisted
      end

      it "redirects to #{redirect_path_helper}" do
        post :create, { record_name(model) => valid_attributes }
        expect(response).to redirect_to(eval(redirect_path_helper))
      end
    end

    context "with invalid attributes" do
      it "does not save the new record in the database" do
        expect{
          post :create, { record_name(model) => invalid_attributes }
        }.not_to change(model, :count)
      end

      it "assigns a newly created but unsaved record an instance variable" do
        post :create, { record_name(model) => invalid_attributes }
        expect(assigns(ivar_name(model))).to be_a_new(model)
      end

      it "re-renders the :new template" do
        post :create, { record_name(model) => invalid_attributes }
        expect(response).to render_template(:new)
      end
    end
  end
end

RSpec.shared_examples "PATCH #update" do |redirect_path_helper|
  describe "PATCH #update" do
    let(:record) { FactoryGirl.create(factory_name(model)) }

    it "requires login" do
      sign_out current_user
      patch :update, { :id => record, record_name(model) => valid_attributes }
      expect(response).to require_login
    end

    it "enforces authorization" do
      patch :update, { :id => record, record_name(model) => valid_attributes }
      expect(controller).to enforce_authorization
    end

    context "with valid attributes" do
      it "updates the requested record" do
        patch :update, { :id => record, record_name(model) => valid_attributes }
        record.reload
        expect(record).to have_attributes(valid_attributes)
      end

      it "assigns the requested record to an instance variable" do
        put :update,  { :id => record, record_name(model) => valid_attributes }
        expect(assigns(ivar_name(model))).to eq(record)
      end

      it "redirects to #{redirect_path_helper}" do
        patch :update,  { :id => record, record_name(model) => valid_attributes }
        expect(response).to redirect_to(eval(redirect_path_helper))
      end
    end

    context "with invalid attributes" do
      it "does not update the requested record" do
        expect {
          patch :update, { :id => record, record_name(model) => invalid_attributes }
        }.not_to change { record.reload.attributes }
      end

      it "assigns the record to an instance variable" do
        patch :update, { :id => record, record_name(model) => invalid_attributes }
        expect(assigns(ivar_name(model))).to eq(record)
      end

      it "re-renders the :edit template" do
        patch :update, { :id => record, record_name(model) => invalid_attributes }
        expect(response).to render_template(:edit)
      end
    end
  end
end

RSpec.shared_examples "DELETE #destroy" do |redirect_path_helper|
  describe "DELETE #destroy" do
    it "requires login" do
      sign_out current_user
      delete :destroy, id: record
      expect(response).to require_login
    end

    it "enforces authorization" do
      delete :destroy, id: record
      expect(controller).to enforce_authorization
    end

    it "deletes the record" do
      # Records are lazily created. Here we must force its creation.
      record
      expect{
        delete :destroy, id: record
      }.to change(model, :count).by(-1)
    end

    it "redirects to #{redirect_path_helper}" do
      delete :destroy, id: record
      expect(response).to redirect_to(eval(redirect_path_helper))
    end
  end
end

Body:
For the let blocks, does it not work if you pass in the model as a parameter to the shared example like you do with the redirect_path_helper?

include_examples "GET #index", Quote

and then in your shared_example you can use the record_name method to create record and records from FactoryGirl and generate valid_attributes and invalid_attributes (you could create an :invalid_quote factory as well for invalid attributes, not sure if that's considered a good practice/idea with FactoryGirl though) from there.

For the second problem, you don't need to use the named route helpers, url_for(controller: :quote) and url_for(@quote) should both work.


问:
C# using streamwriter and streamreader at the same time to change line
so i searched a lot about how to change specific line in file, so i found the code which deletes line. I managed to edit the code and it changes exact line, but when i want to change other line after, previous word resets, and I dont know why.

This is the code which i found:

```<code>using (StreamReader reader = new StreamReader("C:\\input")) {
using (StreamWriter writer = new StreamWriter("C:\\output")) {
    while ((line = reader.ReadLine()) != null) {
        if (String.Compare(line, line_to_delete) == 0)
            continue;

        writer.WriteLine(line);
    }
}
</code>```

}

This is my edited code:

```<code>public void ChangeLineInFile(string file, string file2, string linetochange, string changedline) {
            string line = null;

            using (StreamReader reader = new StreamReader(file)) {
                using (StreamWriter writer = new StreamWriter(file2)) {
                    while ((line = reader.ReadLine()) != null) {
                        if (String.Equals(line, linetochange)) {
                            writer.WriteLine(string.Format("{0}", changedline));
                        } else {
                            writer.WriteLine(line);
                        }
                    }
                }
            }
            File.Delete(file);
            File.Move(file2, file);
            File.Delete(file2);
        }
</code>```

答:
As I just explained above in the comments.

You are probably including your source file, the file you want to change, in Visual Studio in your project.

When you run your code from Visual Studio it will copy that source file to the output directory even if there is already a file present from the last execution.

The original file in your Visual Studio Project is not altered, only the copy that is included with the build output.

With each execution you are starting with the original file you have included in the project, you are not continuing with the file you had changed as this file is overwritten.

That said there are ways that you can specify if you want to include files as output during a build or if they should overwrite an existing file or not. Click on the file in the solution explorer and go to the properties (F4 shortcut on the keyboard). Both the Build Action and the Copy to Output Directory have to be taken into account.

Body:
so i searched a lot about how to change specific line in file, so i found the code which deletes line. I managed to edit the code and it changes exact line, but when i want to change other line after, previous word resets, and I dont know why.

This is the code which i found:

using (StreamReader reader = new StreamReader("C:\\input")) {
using (StreamWriter writer = new StreamWriter("C:\\output")) {
    while ((line = reader.ReadLine()) != null) {
        if (String.Compare(line, line_to_delete) == 0)
            continue;

        writer.WriteLine(line);
    }
}

}

This is my edited code:

public void ChangeLineInFile(string file, string file2, string linetochange, string changedline) {
            string line = null;

            using (StreamReader reader = new StreamReader(file)) {
                using (StreamWriter writer = new StreamWriter(file2)) {
                    while ((line = reader.ReadLine()) != null) {
                        if (String.Equals(line, linetochange)) {
                            writer.WriteLine(string.Format("{0}", changedline));
                        } else {
                            writer.WriteLine(line);
                        }
                    }
                }
            }
            File.Delete(file);
            File.Move(file2, file);
            File.Delete(file2);
        }


问:
Switching to Doctrine: how to realize such query?
I had a TaskManager builded on flat PHP, and now I want to build it on Symfony.

I had such query string to fill TasksTable for the current day:

```<code> (SELECT id, name, description, time, length
                           FROM daily
                           WHERE
                           (day = DAYNAME(:date)
                           OR day = 'all'
                           OR (DAYNAME(:date) IN ('Sunday','Saturday') AND day = 'weekend' )
                           OR (DAYNAME(:date) NOT IN ('Sunday','Saturday') AND day = 'workday' ))
                           AND time IS NOT NULL)
                           UNION
                           (SELECT id, name, description,
                           DATE_FORMAT(date, '%H:%i') as time, length
                           FROM events
                           WHERE DATE_FORMAT(date, '%Y-%m-%d') = :date)
                           ORDER BY time
</code>```

As you see, it gets daily tasks for the current weekday (and for workday/weekend) and events for the current day.
Now I have two Doctrine entities - DailyTask and Event, with two appropriate tables and I want to convert this query to DQL to get an array with DailyTasks and Events as the query's result.

The problem - such trick doesn't work:

```<code>$em = $this->getDoctrine()->getManager();
        $query = $em->createQuery("(SELECT id, name, description, time, length
                           FROM OrganizerBundle:DailyTask
                           WHERE
                           (day = DAYNAME(:date)
                           OR day = 'all'
                           OR (DAYNAME(:date) IN ('Sunday','Saturday') AND day = 'weekend' )
                           OR (DAYNAME(:date) NOT IN ('Sunday','Saturday') AND day = 'workday' ))
                           AND time IS NOT NULL)
                           UNION
                           (SELECT id, name, description,
                           DATE_FORMAT(date, '%H:%i') as time, length
                           FROM OrganizerBundle:Event
                           WHERE DATE_FORMAT(date, '%Y-%m-%d') = :date)
                           ORDER BY time")->setParameter('date', $day);
</code>```

As far as I see, Doctrine doesn't support such Union (it simply shows error for leading parenthesis '(' ), and seems like it has problems with parentheses at all (in nested OR conditions, etc).

What will be the best solution here? So far I don't see any advantages from using Doctrine :( - it just makes things difficult and causes me to use some solutions on PHP which could be made using MySQL engine (date formatting, conditions, ordering, etc)

答:
The easiest approach is to move that into a subquery. That's effectively what you're already doing anyway by placing your ORDER BY outside the last ).

SELECT  -- notice how I simply put the SELECT statement outside
    * -- you're grabbing all of the unioned content.
FROM
(
    -- I cleared away your spare `()` from in here and re-indented for clarity.
    SELECT id, name, description, time, length
    FROM daily
        WHERE (
                day = DAYNAME(:date)
                OR day = 'all'
                OR (DAYNAME(:date) IN ('Sunday','Saturday') AND day = 'weekend' )
                OR (DAYNAME(:date) NOT IN ('Sunday','Saturday') AND day = 'workday' )
            )
            AND time IS NOT NULL
UNION
    SELECT id, name, description, DATE_FORMAT(date, '%H:%i') as time, length
    FROM events
        WHERE DATE_FORMAT(date, '%Y-%m-%d') = :date
) subqry -- This lets SQL know that all of the above
         -- needs to be viewed as "one table"
ORDER BY time
```

Body:
I had a TaskManager builded on flat PHP, and now I want to build it on Symfony.

I had such query string to fill TasksTable for the current day:

 (SELECT id, name, description, time, length
                           FROM daily
                           WHERE
                           (day = DAYNAME(:date)
                           OR day = 'all'
                           OR (DAYNAME(:date) IN ('Sunday','Saturday') AND day = 'weekend' )
                           OR (DAYNAME(:date) NOT IN ('Sunday','Saturday') AND day = 'workday' ))
                           AND time IS NOT NULL)
                           UNION
                           (SELECT id, name, description,
                           DATE_FORMAT(date, '%H:%i') as time, length
                           FROM events
                           WHERE DATE_FORMAT(date, '%Y-%m-%d') = :date)
                           ORDER BY time

As you see, it gets daily tasks for the current weekday (and for workday/weekend) and events for the current day.
Now I have two Doctrine entities - DailyTask and Event, with two appropriate tables and I want to convert this query to DQL to get an array with DailyTasks and Events as the query's result.

The problem - such trick doesn't work:

$em = $this->getDoctrine()->getManager();
        $query = $em->createQuery("(SELECT id, name, description, time, length
                           FROM OrganizerBundle:DailyTask
                           WHERE
                           (day = DAYNAME(:date)
                           OR day = 'all'
                           OR (DAYNAME(:date) IN ('Sunday','Saturday') AND day = 'weekend' )
                           OR (DAYNAME(:date) NOT IN ('Sunday','Saturday') AND day = 'workday' ))
                           AND time IS NOT NULL)
                           UNION
                           (SELECT id, name, description,
                           DATE_FORMAT(date, '%H:%i') as time, length
                           FROM OrganizerBundle:Event
                           WHERE DATE_FORMAT(date, '%Y-%m-%d') = :date)
                           ORDER BY time")->setParameter('date', $day);

As far as I see, Doctrine doesn't support such Union (it simply shows error for leading parenthesis '(' ), and seems like it has problems with parentheses at all (in nested OR conditions, etc).

What will be the best solution here? So far I don't see any advantages from using Doctrine :( - it just makes things difficult and causes me to use some solutions on PHP which could be made using MySQL engine (date formatting, conditions, ordering, etc)


问:
How to reference a value at time in day to create a binary vector (xts)
There is an xts object with data in 15 minute intervals. Everyday at 930 I average the values of the 900 & 915 periods, and, if average > 5, I record a 1 in vector of 1s and 0s BinVect. The script below achieves that:

```<code>library('xts')
XTS1 <- structure(c(12, 7, 7, 22, 24, 30, 26, 23, 27, 30), .indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "", tclass = c("POSIXct", "POSIXt"), tzone = "", class = c("xts", "zoo"), .CLASS = structure("double", class = "CLASS"), formattable = structure(list(formatter = "formatC", format = structure(list(format = "f", digits = 2), .Names = c("format", "digits")), preproc = "percent_preproc", postproc = "percent_postproc"), .Names = c("formatter", "format", "preproc", "postproc")), index = structure(c(1413981900, 1413982800, 1413983700, 1413984600, 1413985500, 1413986400, 1413987300, 1413988200, 1413989100, 1413990000), tzone = "", tclass = c("POSIXct", "POSIXt")), .Dim = c(10L, 1L))

AvgPrior2 <- lag((XTS1 + lag(XTS1)) / 2)
BinVect <- ifelse(AvgPrior2 > 5, 1, 0) & .indexhour(XTS1) == 9 & .indexmin(XTS1) == 30
XTS1 <- merge.xts(XTS1,AvgPrior2,BinVect)

#Output:
                    XTS1 AvgPrior2 BinVect
2014-10-22 08:45:00   12        NA       0
2014-10-22 09:00:00    7        NA       0
2014-10-22 09:15:00    7       9.5       0
2014-10-22 09:30:00   22       7.0       1
2014-10-22 09:45:00   24      14.5       0
2014-10-22 10:00:00   30      23.0       0
2014-10-22 10:15:00   26      27.0       0
2014-10-22 10:30:00   23      28.0       0
2014-10-22 10:45:00   27      24.5       0
2014-10-22 11:00:00   30      25.0       0
</code>```

Now the part that I can't figure out: would like to create a new vector that will have 1s every day between 09:30:00 and 10:15:00 whenever on that day BinVect==1 @ 09:30:00. Think need to use function apply.daily, question is how.

```<code>#Desired Output:
                        XTS1 AvgPrior2 BinVect NewBinVect
2014-10-22 08:45:00   12        NA       0              0
2014-10-22 09:00:00    7        NA       0              0
2014-10-22 09:15:00    7       9.5       0              0
2014-10-22 09:30:00   22       7.0       1              1
2014-10-22 09:45:00   24      14.5       0              1
2014-10-22 10:00:00   30      23.0       0              1
2014-10-22 10:15:00   26      27.0       0              1
2014-10-22 10:30:00   23      28.0       0              0
2014-10-22 10:45:00   27      24.5       0              0
2014-10-22 11:00:00   30      25.0       0              0

#This is the closest I got to getting anywhere (out of several trials):
XTS1$NewBinVect <- apply.daily(BinVect, function(x) ifelse(x == 1, 1, 0))
#Think it says if BinVect=1 on a given day => NewBinVect=1 on that day (but doesn't do that)
</code>```

答:
I think I had misinterpreted your question at first. This code should get you a single column with the 9:30 BinVect value at the timestamps between 9:30 and 10:15 for each day. I will leave the previous code I wrote below in case you find it useful for another application.

```<code>library('xts')

XTS1 <- structure(c(12, 7, 7, 22, 24, 30, 26, 23, 27, 30), .indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "", tclass = c("POSIXct", "POSIXt"), tzone = "", class = c("xts", "zoo"), .CLASS = structure("double", class = "CLASS"), formattable = structure(list(formatter = "formatC", format = structure(list(format = "f", digits = 2), .Names = c("format", "digits")), preproc = "percent_preproc", postproc = "percent_postproc"), .Names = c("formatter", "format", "preproc", "postproc")), index = structure(c(1413981900, 1413982800, 1413983700, 1413984600, 1413985500, 1413986400, 1413987300, 1413988200, 1413989100, 1413990000), tzone = "", tclass = c("POSIXct", "POSIXt")), .Dim = c(10L, 1L))

# Set XTS1 column name
colnames(XTS1) <- "XTS1"

# Create empty AvgPrior2 column
XTS1$AvgPrior2 <- NA
# Get daily XTS1 Averages
XTS1$AvgPrior2 <- as.vector(t(apply.daily(XTS1, function(x) as.vector(lag((x$XTS1 + lag(x$XTS1)) / 2)))))

# Create BinVect column filled with zeros
XTS1$BinVect <- 0
# Assign value of 1 to BinVect rows at 9:30 time stamps if AvgPrior2 > 5
XTS1['T09:30/T09:30:59', "BinVect"] <- ifelse(XTS1['T09:30/T09:30:59', "AvgPrior2"] > 5, 1, 0)

# Create NewBinVect column filled with zeros
XTS1$NewBinVect <- 0
# Assign 1 to timestamps between 9:30 and 10:15 if BinVect value for that day is 1
XTS1$NewBinVect <- as.vector(t(apply.daily(XTS1, function(x){
                                    x['T09:30/T10:15', "NewBinVect"] <- as.numeric(x[.indexhour(x) == 9 & .indexmin(x) == 30]$BinVect)

                                    return(as.vector(x$NewBinVect))
                                })))
</code>```

Previous code

```<code>library('xts')

XTS1 <- structure(c(12, 7, 7, 22, 24, 30, 26, 23, 27, 30), .indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "", tclass = c("POSIXct", "POSIXt"), tzone = "", class = c("xts", "zoo"), .CLASS = structure("double", class = "CLASS"), formattable = structure(list(formatter = "formatC", format = structure(list(format = "f", digits = 2), .Names = c("format", "digits")), preproc = "percent_preproc", postproc = "percent_postproc"), .Names = c("formatter", "format", "preproc", "postproc")), index = structure(c(1413981900, 1413982800, 1413983700, 1413984600, 1413985500, 1413986400, 1413987300, 1413988200, 1413989100, 1413990000), tzone = "", tclass = c("POSIXct", "POSIXt")), .Dim = c(10L, 1L))

colnames(XTS1) <- "XTS1"

XTS1$AvgPrior2 <- lag((XTS1 + lag(XTS1)) / 2)
XTS1$BinVect <- ifelse(XTS1$AvgPrior2 > 5, 1, 0) & .indexhour(XTS1) == 9 & .indexmin(XTS1) == 30

XTS1$BinVect2 <- ifelse(XTS1$AvgPrior2 > 5, 1, 0) & .indexhour(XTS1) == 9 & .indexmin(XTS1) == 30

h.m.combos <- data.frame(hour = c(rep(9,4), rep(10,4)), min = c(rep(c(0,15,30,45),2)))

BinVects <- mapply(function(h,m){
                    apply.daily(XTS1, function(x){
                                       val <- ifelse(!is.na(x$AvgPrior2) & x$AvgPrior2 > 5 & .indexhour(x) == h & .indexmin(x) == m, 1, 0)
                                       val <- as.vector(val$AvgPrior2)
                                       names(val) <- paste0(h,m)
                                       return(val)
                                      })
                  },
                  h.m.combos$hour,
                  h.m.combos$min)

colnames(BinVects) <- paste(h.m.combos$hour, h.m.combos$min, sep = ":")

XTS1 <- cbind(XTS1, BinVects)
</code>```

Body:
There is an xts object with data in 15 minute intervals. Everyday at 930 I average the values of the 900 & 915 periods, and, if average > 5, I record a 1 in vector of 1s and 0s BinVect. The script below achieves that:

library('xts')
XTS1 <- structure(c(12, 7, 7, 22, 24, 30, 26, 23, 27, 30), .indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "", tclass = c("POSIXct", "POSIXt"), tzone = "", class = c("xts", "zoo"), .CLASS = structure("double", class = "CLASS"), formattable = structure(list(formatter = "formatC", format = structure(list(format = "f", digits = 2), .Names = c("format", "digits")), preproc = "percent_preproc", postproc = "percent_postproc"), .Names = c("formatter", "format", "preproc", "postproc")), index = structure(c(1413981900, 1413982800, 1413983700, 1413984600, 1413985500, 1413986400, 1413987300, 1413988200, 1413989100, 1413990000), tzone = "", tclass = c("POSIXct", "POSIXt")), .Dim = c(10L, 1L))

AvgPrior2 <- lag((XTS1 + lag(XTS1)) / 2)
BinVect <- ifelse(AvgPrior2 > 5, 1, 0) & .indexhour(XTS1) == 9 & .indexmin(XTS1) == 30
XTS1 <- merge.xts(XTS1,AvgPrior2,BinVect)

#Output:
                    XTS1 AvgPrior2 BinVect
2014-10-22 08:45:00   12        NA       0
2014-10-22 09:00:00    7        NA       0
2014-10-22 09:15:00    7       9.5       0
2014-10-22 09:30:00   22       7.0       1
2014-10-22 09:45:00   24      14.5       0
2014-10-22 10:00:00   30      23.0       0
2014-10-22 10:15:00   26      27.0       0
2014-10-22 10:30:00   23      28.0       0
2014-10-22 10:45:00   27      24.5       0
2014-10-22 11:00:00   30      25.0       0

Now the part that I can't figure out: would like to create a new vector that will have 1s every day between 09:30:00 and 10:15:00 whenever on that day BinVect==1 @ 09:30:00. Think need to use function apply.daily, question is how.

#Desired Output:
                        XTS1 AvgPrior2 BinVect NewBinVect
2014-10-22 08:45:00   12        NA       0              0
2014-10-22 09:00:00    7        NA       0              0
2014-10-22 09:15:00    7       9.5       0              0
2014-10-22 09:30:00   22       7.0       1              1
2014-10-22 09:45:00   24      14.5       0              1
2014-10-22 10:00:00   30      23.0       0              1
2014-10-22 10:15:00   26      27.0       0              1
2014-10-22 10:30:00   23      28.0       0              0
2014-10-22 10:45:00   27      24.5       0              0
2014-10-22 11:00:00   30      25.0       0              0

#This is the closest I got to getting anywhere (out of several trials):
XTS1$NewBinVect <- apply.daily(BinVect, function(x) ifelse(x == 1, 1, 0))
#Think it says if BinVect=1 on a given day => NewBinVect=1 on that day (but doesn't do that)

Body:
I think I had misinterpreted your question at first. This code should get you a single column with the 9:30 BinVect value at the timestamps between 9:30 and 10:15 for each day. I will leave the previous code I wrote below in case you find it useful for another application.

library('xts')

XTS1 <- structure(c(12, 7, 7, 22, 24, 30, 26, 23, 27, 30), .indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "", tclass = c("POSIXct", "POSIXt"), tzone = "", class = c("xts", "zoo"), .CLASS = structure("double", class = "CLASS"), formattable = structure(list(formatter = "formatC", format = structure(list(format = "f", digits = 2), .Names = c("format", "digits")), preproc = "percent_preproc", postproc = "percent_postproc"), .Names = c("formatter", "format", "preproc", "postproc")), index = structure(c(1413981900, 1413982800, 1413983700, 1413984600, 1413985500, 1413986400, 1413987300, 1413988200, 1413989100, 1413990000), tzone = "", tclass = c("POSIXct", "POSIXt")), .Dim = c(10L, 1L))

# Set XTS1 column name
colnames(XTS1) <- "XTS1"

# Create empty AvgPrior2 column
XTS1$AvgPrior2 <- NA
# Get daily XTS1 Averages
XTS1$AvgPrior2 <- as.vector(t(apply.daily(XTS1, function(x) as.vector(lag((x$XTS1 + lag(x$XTS1)) / 2)))))

# Create BinVect column filled with zeros
XTS1$BinVect <- 0
# Assign value of 1 to BinVect rows at 9:30 time stamps if AvgPrior2 > 5
XTS1['T09:30/T09:30:59', "BinVect"] <- ifelse(XTS1['T09:30/T09:30:59', "AvgPrior2"] > 5, 1, 0)

# Create NewBinVect column filled with zeros
XTS1$NewBinVect <- 0
# Assign 1 to timestamps between 9:30 and 10:15 if BinVect value for that day is 1
XTS1$NewBinVect <- as.vector(t(apply.daily(XTS1, function(x){
                                    x['T09:30/T10:15', "NewBinVect"] <- as.numeric(x[.indexhour(x) == 9 & .indexmin(x) == 30]$BinVect)

                                    return(as.vector(x$NewBinVect))
                                })))

Previous code

library('xts')

XTS1 <- structure(c(12, 7, 7, 22, 24, 30, 26, 23, 27, 30), .indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "", tclass = c("POSIXct", "POSIXt"), tzone = "", class = c("xts", "zoo"), .CLASS = structure("double", class = "CLASS"), formattable = structure(list(formatter = "formatC", format = structure(list(format = "f", digits = 2), .Names = c("format", "digits")), preproc = "percent_preproc", postproc = "percent_postproc"), .Names = c("formatter", "format", "preproc", "postproc")), index = structure(c(1413981900, 1413982800, 1413983700, 1413984600, 1413985500, 1413986400, 1413987300, 1413988200, 1413989100, 1413990000), tzone = "", tclass = c("POSIXct", "POSIXt")), .Dim = c(10L, 1L))

colnames(XTS1) <- "XTS1"

XTS1$AvgPrior2 <- lag((XTS1 + lag(XTS1)) / 2)
XTS1$BinVect <- ifelse(XTS1$AvgPrior2 > 5, 1, 0) & .indexhour(XTS1) == 9 & .indexmin(XTS1) == 30

XTS1$BinVect2 <- ifelse(XTS1$AvgPrior2 > 5, 1, 0) & .indexhour(XTS1) == 9 & .indexmin(XTS1) == 30

h.m.combos <- data.frame(hour = c(rep(9,4), rep(10,4)), min = c(rep(c(0,15,30,45),2)))

BinVects <- mapply(function(h,m){
                    apply.daily(XTS1, function(x){
                                       val <- ifelse(!is.na(x$AvgPrior2) & x$AvgPrior2 > 5 & .indexhour(x) == h & .indexmin(x) == m, 1, 0)
                                       val <- as.vector(val$AvgPrior2)
                                       names(val) <- paste0(h,m)
                                       return(val)
                                      })
                  },
                  h.m.combos$hour,
                  h.m.combos$min)

colnames(BinVects) <- paste(h.m.combos$hour, h.m.combos$min, sep = ":")

XTS1 <- cbind(XTS1, BinVects)


问:
How to change results in Access query?
I have a table, we'll call it users.

```<code>id username type
</code>```

The type field is a two character type, so each user either has US, MO, AD.  Not sure why the original developer did this, but I cannot change this method, unfortunately.

```<code>1 mike US
2 Tim AD
3 mark MO
</code>```

Instead of returning US, AD... etc types in Access, I'd like the query to replace the US with USER, replace MO with MODERATOR, and replace AD with ADMIN.

Is this possible?

Kind of like SELECT * FROM USERS and then if statements within Access (if US, then USER).  Not sure how to proceed?

答:
I agree that you should have a table for this -- anything else verges on storing data in your SQL statements.

For completeness, let me mention Switch() and Choose(). The former takes an arbitrary number of value pairs, the latter takes an index and a list of values. The former works for strings or numbers, as with CASE WHEN, while Choose() works only with numbers.

Both are of limited utility, since use of them amounts to storing a lookup table in your SQL, but it's good to know about these things for cases where it's simply not feasible to add a lookup table.

ContentLicense: CC BY-SA 2.5

Title: How to change results in Access query?

Body:
I have a table, we'll call it users.

id username type

The type field is a two character type, so each user either has US, MO, AD.  Not sure why the original developer did this, but I cannot change this method, unfortunately.

1 mike US
2 Tim AD
3 mark MO

Instead of returning US, AD... etc types in Access, I'd like the query to replace the US with USER, replace MO with MODERATOR, and replace AD with ADMIN.

Is this possible?

Kind of like SELECT * FROM USERS and then if statements within Access (if US, then USER).  Not sure how to proceed?


问:
Cast sender object in event handler using GetType().Name
I have an event handler for a Textbox and a RichTextBox.
The code is identical, but

In handler #1 I do:

```<code>RichTextBox tb = (RichTextBox)sender
</code>```

In handler #2 accordingly:

```<code>TextBox tb = (TextBox)sender
</code>```

Doing so I can fully manipulate the sending control.
How can I cast the sending object to Textbox or RichTextbox according to its type using

```<code>sender.GetType().Name
</code>```

and then create the control at runtime and work with it? That way I only need one event handler function: less code, less errors, easier to maintain and DRY :-)

答:
You can also use an inline-temporary variable to handle the cast for you.</p>

```<code>if (sender is RichTextBox tb)
{
    // ... //
}
else if (sender is TextBox tb)
{
    // ... //
}
</code>```

OwnerDisplayName: tfl

ContentLicense: CC BY-SA 4.0

Body:
I have an event handler for a Textbox and a RichTextBox.
The code is identical, but

In handler #1 I do:

RichTextBox tb = (RichTextBox)sender

In handler #2 accordingly:

TextBox tb = (TextBox)sender

Doing so I can fully manipulate the sending control.
How can I cast the sending object to Textbox or RichTextbox according to its type using

sender.GetType().Name

and then create the control at runtime and work with it? That way I only need one event handler function: less code, less errors, easier to maintain and DRY :-)

Body:
You can also use an inline-temporary variable to handle the cast for you.

if (sender is RichTextBox tb)
{
    // ... //
}
else if (sender is TextBox tb)
{
    // ... //
}


问:
Turning simple c algorithm into matlab
It's simple, I want to pick the biggest value of a line, make all other elements in a line equal to zero and then the position with the biggest value shall be transformed into 1.

This is the code:

```<code>float A [3][3];
 A [0][0] = 1.1, A [0][1] = 3.2, A [0][2] = 1.3;
 A [1][0] = 2.1, A [1][1] = 2.2, A [1][2] = 2.3;
 A [2][0] = 3.1, A [2][1] = 3.2, A [2][2] = 3.3;
for (int i=0; i<3; i++) {
  float biggest=-1000000;
  int biggest_position=0;
  for (int y=0; y<3; y++)
     if (A [i][y]>biggest) {
        biggest_position = y;
        biggest = A[i][y];
        cout << "biggest position" << biggest_position << endl;
     }
  for (int y=0; y<3; y++)
     A [i][y] = 0;
  A [i][biggest_position] = 1;
}
for (int i=0; i<3; i++)
   for (int j=0; j<3; j++)
     cout << A [i][j] << endl;
</code>```

So what I need to do to rewrite properly this code in matlab language?

答:
You can use max to find maximum, and create a all zero element matrix and put the max in first column of the matrix:

```<code>  newA = zeros(size(A));
  newA(:,1) = max(A,[],2);
</code>```

Title: Turning simple c algorithm into matlab

Body:
It's simple, I want to pick the biggest value of a line, make all other elements in a line equal to zero and then the position with the biggest value shall be transformed into 1.

This is the code:

float A [3][3];
 A [0][0] = 1.1, A [0][1] = 3.2, A [0][2] = 1.3;
 A [1][0] = 2.1, A [1][1] = 2.2, A [1][2] = 2.3;
 A [2][0] = 3.1, A [2][1] = 3.2, A [2][2] = 3.3;
for (int i=0; i<3; i++) {
  float biggest=-1000000;
  int biggest_position=0;
  for (int y=0; y<3; y++)
     if (A [i][y]>biggest) {
        biggest_position = y;
        biggest = A[i][y];
        cout << "biggest position" << biggest_position << endl;
     }
  for (int y=0; y<3; y++)
     A [i][y] = 0;
  A [i][biggest_position] = 1;
}
for (int i=0; i<3; i++)
   for (int j=0; j<3; j++)
     cout << A [i][j] << endl;

So what I need to do to rewrite properly this code in matlab language?

Body:
You can use max to find maximum, and create a all zero element matrix and put the max in first column of the matrix:

  newA = zeros(size(A));
  newA(:,1) = max(A,[],2);


问:
How to automatically update a SQL database
So I'm working with a professor who wants me to create a SQL Database containing information from csv files (from the New York City Department of Transportation). I've written program that takes the csv file and converts it into the appropriate sql commands. So my question is, how do i automate the database so that every 5 minutes or so a program downloads the new csv file, runs it through my csv-to-SQL command program, and then enters the output from my csv-to-SQL command program into terminal (what I use to interface with my SQL database)? Is there a specific language I should look into, I've seen people talk about cron?</p>

答:
What you can do is use Sql Server Integration Services (SSIS).  It's basically a workflow package built into Sql that will let you handle tasks like this.  You should be able to import the CSV into a temp table and then run your appropriate queries against it.

This is Azure specific but working against hosted SQL should be similar.
https://learn.microsoft.com/en-us/sql/integration-services/import-export-data/import-data-from-excel-to-sql


问:
Extract text by line from PDF using iTextSharp c#
I need to run some analysis my extracting data from a PDF document.

Using iTextSharp, I used the PdfTextExtractor.GetTextFromPage method to extract contents from a PDF document and it returned me in a single long line.

Is there a way to get the text by line so that i can store them in an array? So that i can analyze the data by line which will be more flexible.

Below is the code I used:

```<code>       string urlFileName1 = "pdf_link";
        PdfReader reader = new PdfReader(urlFileName1);
        string text = string.Empty;
        for (int page = 1; page <= reader.NumberOfPages; page++)
        {
            text += PdfTextExtractor.GetTextFromPage(reader, page);
        }
        reader.Close();
        candidate3.Text = text.ToString();
</code>```

答:
LocationTextExtractionStrategy will automatically insert '\n' in the output text. However, sometimes it will insert '\n' where it shouldn't.
In that case you need to build a custom TextExtractionStrategy or RenderListener. Bascially the code that detects newline is the method

```<code>public virtual bool SameLine(ITextChunkLocation other) {
            return OrientationMagnitude == other.OrientationMagnitude &&
                   DistPerpendicular == other.DistPerpendicular;
        }
</code>```

In some cases '\n' shouldn't be inserted if there is only small difference between DistPerpendicular and other.DistPerpendicular, so you need to change it to something like Math.Abs(DistPerpendicular - other.DistPerpendicular) < 10

Or you can put that piece of code in the RenderText method of your custom TextExtractionStrategy/RenderListener class

Body:
I need to run some analysis my extracting data from a PDF document.

Using iTextSharp, I used the PdfTextExtractor.GetTextFromPage method to extract contents from a PDF document and it returned me in a single long line.

Is there a way to get the text by line so that i can store them in an array? So that i can analyze the data by line which will be more flexible.

Below is the code I used:

       string urlFileName1 = "pdf_link";
        PdfReader reader = new PdfReader(urlFileName1);
        string text = string.Empty;
        for (int page = 1; page <= reader.NumberOfPages; page++)
        {
            text += PdfTextExtractor.GetTextFromPage(reader, page);
        }
        reader.Close();
        candidate3.Text = text.ToString();

Body:
LocationTextExtractionStrategy will automatically insert '\n' in the output text. However, sometimes it will insert '\n' where it shouldn't.
In that case you need to build a custom TextExtractionStrategy or RenderListener. Bascially the code that detects newline is the method

public virtual bool SameLine(ITextChunkLocation other) {
            return OrientationMagnitude == other.OrientationMagnitude &&
                   DistPerpendicular == other.DistPerpendicular;
        }

In some cases '\n' shouldn't be inserted if there is only small difference between DistPerpendicular and other.DistPerpendicular, so you need to change it to something like Math.Abs(DistPerpendicular - other.DistPerpendicular) < 10

Or you can put that piece of code in the RenderText method of your custom TextExtractionStrategy/RenderListener class


问:
C++ Concatenate containers of polymorphic objects
Assume I have a virtual base class and some derived concrete classes:

```<code>class Base { ... }
class DerivedA : public Base { ... }
class DerivedB : public Base { ... }
class DerivedC : public Base { ... }
</code>```

And somewhere I have vectors of objects of each derived class:

```<code>std::vector<DerivedA> my_a;
std::vector<DerivedB> my_b;
std::vector<DerivedC> my_c;
</code>```

Now, quite often I need to iterate over all elements in all three vectors and exercise the base class interface. I could write three for-loops, doing exactly the same in each. But obviously that's a far from optimal solution.

Is there a clever way to concatenate the vectors into a common container with base-class pointers/references, such that I need to iterate only once? Or any other idea how to solve this elegantly?

答:
I would just create a function template or a generic lambda and call it three times:</p>

```<code>auto my_loop = [](auto& vec){
  for (auto& base : vec) {
      // do something with base...
  }
};
my_loop(my_a);
my_loop(my_b);
my_loop(my_c);
</code>```

Body:
Assume I have a virtual base class and some derived concrete classes:

class Base { ... }
class DerivedA : public Base { ... }
class DerivedB : public Base { ... }
class DerivedC : public Base { ... }

And somewhere I have vectors of objects of each derived class:

std::vector<DerivedA> my_a;
std::vector<DerivedB> my_b;
std::vector<DerivedC> my_c;

Now, quite often I need to iterate over all elements in all three vectors and exercise the base class interface. I could write three for-loops, doing exactly the same in each. But obviously that's a far from optimal solution.

Is there a clever way to concatenate the vectors into a common container with base-class pointers/references, such that I need to iterate only once? Or any other idea how to solve this elegantly?

Body:
I would just create a function template or a generic lambda and call it three times:

auto my_loop = [](auto& vec){
  for (auto& base : vec) {
      // do something with base...
  }
};
my_loop(my_a);
my_loop(my_b);
my_loop(my_c);


问:
Super expression must either be null or a function, not object
I get Super expression must either be null or a function, not object error when I run index.js

I see another post here with similar error message. But looks like that is related to react!

base.js

```<code>   export default class Base{
        constructor(title){
            console.log(title);
        }
    }
</code>```

Class1.js

```<code>import * as Base from './base';

export default class Class1 extends Base{
    constructor(title){
        super(title);
    }
}
</code>```

index.js

```<code>import * as Class1 from './class1';
'use strict';

function check() {
    var c = new Class1('from Index.js');
}

check();
</code>```

.babelrc

{
    "presets": [
        "es2015",
        "stage-1"
    ]
}

dependencies

```<code>dependencies": {
    "babel-cli": "^6.24.1",
    "babel-eslint": "^7.2.3",
    "babel-plugin-add-module-exports": "^0.2.1",
    "babel-plugin-syntax-export-extensions": "^6.13.0",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-stage-1": "^6.24.1",
    "babel-register": "^6.24.1"
  }
</code>```

Please help! Thanks in advance !

答:
When you import, you are importing the entire js file, which is an object. You need to import just the class from your js file.

To use just a class do

```<code>import {myMember} from 'my-module';
</code>```

Which imports just the member called myMember.

You are doing this

```<code>import * as myModule from 'my-module';
</code>```

Which imports all of the members of your file as sub-members of the myModule object.

See Importing in JS (examples from here)

Body:
I get Super expression must either be null or a function, not object error when I run index.js

I see another post here with similar error message. But looks like that is related to react!

base.js

   export default class Base{
        constructor(title){
            console.log(title);
        }
    }

Class1.js

import * as Base from './base';

export default class Class1 extends Base{
    constructor(title){
        super(title);
    }
}

index.js

import * as Class1 from './class1';
'use strict';

function check() {
    var c = new Class1('from Index.js');
}

check();

.babelrc

{
    "presets": [
        "es2015",
        "stage-1"
    ]
}

dependencies

dependencies": {
    "babel-cli": "^6.24.1",
    "babel-eslint": "^7.2.3",
    "babel-plugin-add-module-exports": "^0.2.1",
    "babel-plugin-syntax-export-extensions": "^6.13.0",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-stage-1": "^6.24.1",
    "babel-register": "^6.24.1"
  }

Please help! Thanks in advance !

Body:
When you import, you are importing the entire js file, which is an object. You need to import just the class from your js file.

To use just a class do

import {myMember} from 'my-module';

Which imports just the member called myMember.

You are doing this

import * as myModule from 'my-module';

Which imports all of the members of your file as sub-members of the myModule object.

See Importing in JS (examples from here)


答:
A simple solution would be to use a template function that iterates over the members of a vector and calls the respective function:</p>

```<code>class Base {
public:
    virtual int getX() = 0;
};

class Derived1 : public Base {
public:
    int x1=1;
    virtual int getX() { return x1; };
};

class Derived2 : public Base {
public:
    int x2=2;
    virtual int getX() { return x2; };
};

template<typename T>
void callPolymorphic(std::vector<T> &v) {
    for (T& a : v) {
        cout << a.getX() << " ";
    }
}

int main() {

    std::vector<Derived1> my_1(5);
    std::vector<Derived2> my_2(5);

    callPolymorphic(my_1);
    callPolymorphic(my_2);

    return 0;
}
</code>```

Title: C++ Concatenate containers of polymorphic objects

Body:
A simple solution would be to use a template function that iterates over the members of a vector and calls the respective function:

class Base {
public:
    virtual int getX() = 0;
};

class Derived1 : public Base {
public:
    int x1=1;
    virtual int getX() { return x1; };
};

class Derived2 : public Base {
public:
    int x2=2;
    virtual int getX() { return x2; };
};

template<typename T>
void callPolymorphic(std::vector<T> &v) {
    for (T& a : v) {
        cout << a.getX() << " ";
    }
}

int main() {

    std::vector<Derived1> my_1(5);
    std::vector<Derived2> my_2(5);

    callPolymorphic(my_1);
    callPolymorphic(my_2);

    return 0;
}


问:
How to map enums to integers implicitliy
I know I'm not using the right jargon, but basically I want to take this code in C++ and port it over to Java

```<code>public enum Packets {

    // Maps enums to integers 0-3
    PACKET_NONE = 0, PACKET_SYNC,
    PACKET_EXPECT_TO_RECEIVE, PACKET_AVAIL_1,

    // Maps enums to integers 13-16
    PACKET_FILL = 13,  PACKET_GLASS, PACKET_FILLi, PACKET_GLASSi
}
</code>```

I want to explicitly map an enum to an int, and then have every subsequent enum implicitly map to the next increment of that integer (or some solution as close to this C code as possible).

答:
You can add a field to your enum, intialize this field in the enumeration constant's constructor call and then return this field from a public getter. This should look about like this:</p>

```<code>public enum Packets
{
    PACKET_NONE(0),
    PACKET_SYNC(1),
    PACKET_EXPECT_TO_RECEIVE(2),
    PACKET_AVAIL_1(3),
    PACKET_FILL(13),
    PACKET_GLASS(14),
    PACKET_FILLI(15),
    PACKET_GLASSI(16);

    private final int id;

    private MyEnum(final int id) {
        this.id = id;
    }

    public final int getId() {
        return index;
    }
}
</code>```

Body:
I know I'm not using the right jargon, but basically I want to take this code in C++ and port it over to Java

public enum Packets {

    // Maps enums to integers 0-3
    PACKET_NONE = 0, PACKET_SYNC,
    PACKET_EXPECT_TO_RECEIVE, PACKET_AVAIL_1,

    // Maps enums to integers 13-16
    PACKET_FILL = 13,  PACKET_GLASS, PACKET_FILLi, PACKET_GLASSi
}

I want to explicitly map an enum to an int, and then have every subsequent enum implicitly map to the next increment of that integer (or some solution as close to this C code as possible).

Body:
You can add a field to your enum, intialize this field in the enumeration constant's constructor call and then return this field from a public getter. This should look about like this:

public enum Packets
{
    PACKET_NONE(0),
    PACKET_SYNC(1),
    PACKET_EXPECT_TO_RECEIVE(2),
    PACKET_AVAIL_1(3),
    PACKET_FILL(13),
    PACKET_GLASS(14),
    PACKET_FILLI(15),
    PACKET_GLASSI(16);

    private final int id;

    private MyEnum(final int id) {
        this.id = id;
    }

    public final int getId() {
        return index;
    }
}


问:
How to display both data in Edittext without losing one of them?
I have two Edittexts in MainActivity: etFrom and etTo.
When clicked etFrom goes to ListFrom activity and etTo to ListTo activity.ListFrom and ListTo activities contain Listview and after choosing an item it comes back to Main activity and displays results in edittexts. I use MainActivity.putExtra("To",v); and etTo.setText(getIntent().getStringExtra("To")); to get data from an activity.

After clicking on first edittext, choosing an item from Listview and coming back to Main Activity, when I do the same for second edittext the first edittext becomes empty. And the same when I do first one, second one becomes empty.First Second

ListTo Code

```<code>    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list_to);

    etSearchTo=(EditText) findViewById(R.id.etSearchTo);
    listViewTo=(ListView) findViewById(R.id.listViewTo);

    initList();
    listViewTo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String v="";
            Intent intent=new Intent(ListTo.this,SearchRide.class);
            switch (position) {
                case 0:
                    v = items[0];
                    break;
                case 1:
                    v = items[1];
                    break;
                case 2:
                    v = items[2];
                    break;
                case 3:
                    v = items[3];
                    break;
                case 4:
                    v = items[4];
                    break;
                case 5:
                    v = items[5];
                    break;
            }

            intent.putExtra("To",v);
            startActivity(intent);
        }
    });
</code>```

ListFrom Code

```<code> protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list_from);

    listView=(ListView) findViewById(R.id.listviewFrom);
    editText=(EditText) findViewById(R.id.etsearchFrom);

    initList();
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String v="";
            Intent intent=new Intent(ListFrom.this,SearchRide.class);
            switch (position) {
                case 0:
                    v = items[0];
                    break;
                case 1:
                    v = items[1];
                    break;
                case 2:
                    v = items[2];
                    break;
                case 3:
                    v = items[3];
                    break;
                case 4:
                    v = items[4];
                    break;
                case 5:
                    v = items[5];
                    break;
            }

            intent.putExtra("From",v);
            startActivity(intent);

        }
    });
</code>```

SearchRide as Main Activity

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search_ride);

    etDate=(EditText) findViewById(R.id.etDate);
    TextView tFrom=(TextView) findViewById(R.id.tFrom);
    TextView tTo=(TextView) findViewById(R.id.tTo);
    etFrom=(EditText) findViewById(R.id.etFrom);
    etTo=(EditText) findViewById(R.id.etTo);
    Button bSearch=(Button) findViewById(R.id.bSearch);
    ImageView iplussign=(ImageView) findViewById(R.id.iplussign);
    ImageView iminussign=(ImageView) findViewById(R.id.iminussign);
    final TextView tNumber=(TextView) findViewById(R.id.tNumber);

    etTo.setText(getIntent().getStringExtra("To"));

    tNumber.setText(String.valueOf(p));
    iplussign.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(p<=9) {
                p++;
                tNumber.setText(String.valueOf(p));
            }
        }
    });
    iminussign.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(p>=2) {
                p--;
                tNumber.setText(String.valueOf(p));
            }
        }
    });

    etFrom.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent ListFrom=new Intent(SearchRide.this,ListFrom.class);
            startActivity(ListFrom);
        }
    });
    etFrom.setText(getIntent().getStringExtra("From"));

    etTo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent ToList =new Intent(SearchRide.this,ListTo.class);
            startActivity(ToList);
        }
    });
    etTo.setText(getIntent().getStringExtra("To"));

    etDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DatePickerDialog dialog= new DatePickerDialog(SearchRide.this,R.style.MyDatePickerStyle,listener,calendar.get(Calendar.DAY_OF_MONTH),calendar.get(Calendar.MONTH),calendar.get(Calendar.YEAR));
            dialog.getDatePicker().setMinDate(calendar.getTimeInMillis());
            dialog.show();
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

}
</code>```

答:
Here is what you can do. Put both from and to values as extra when starting an activity and return them both as result. This way you will be able to remember it. I am assuming you just do not want to use static variables.

```<code>// in ListTo activity
intent.putExtra("To",v);
intent.putExtra("From", getIntent().getStringExtra("From"));

// in ListFrom activity
intent.putExtra("From",v);
intent.putExtra("To", getIntent().getStringExtra("To"));

// in Main activity
etTo.setText(getIntent().getStringExtra("To"));
etFrom.setText(getIntent().getStringExtra("From"));

// when starting ListFrom activity
Intent ListFrom=new Intent(SearchRide.this,ListFrom.class);
intent.putExtra("From", getIntent().getStringExtra("From"));
intent.putExtra("To", getIntent().getStringExtra("To"));
startActivity(ListFrom);

// when starting ListTo activity
Intent ToList =new Intent(SearchRide.this,ListTo.class);
intent.putExtra("From", getIntent().getStringExtra("From"));
intent.putExtra("To", getIntent().getStringExtra("To"));
startActivity(ToList);
</code>```

PS: I have not tested the above code. You can experience null pointer errors, but it should give you the general idea.

Body:
I have two Edittexts in MainActivity: etFrom and etTo.
When clicked etFrom goes to ListFrom activity and etTo to ListTo activity.ListFrom and ListTo activities contain Listview and after choosing an item it comes back to Main activity and displays results in edittexts. I use MainActivity.putExtra("To",v); and etTo.setText(getIntent().getStringExtra("To")); to get data from an activity.

After clicking on first edittext, choosing an item from Listview and coming back to Main Activity, when I do the same for second edittext the first edittext becomes empty. And the same when I do first one, second one becomes empty.First Second

ListTo Code

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list_to);

    etSearchTo=(EditText) findViewById(R.id.etSearchTo);
    listViewTo=(ListView) findViewById(R.id.listViewTo);

    initList();
    listViewTo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String v="";
            Intent intent=new Intent(ListTo.this,SearchRide.class);
            switch (position) {
                case 0:
                    v = items[0];
                    break;
                case 1:
                    v = items[1];
                    break;
                case 2:
                    v = items[2];
                    break;
                case 3:
                    v = items[3];
                    break;
                case 4:
                    v = items[4];
                    break;
                case 5:
                    v = items[5];
                    break;
            }

            intent.putExtra("To",v);
            startActivity(intent);
        }
    });

ListFrom Code

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list_from);

    listView=(ListView) findViewById(R.id.listviewFrom);
    editText=(EditText) findViewById(R.id.etsearchFrom);

    initList();
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String v="";
            Intent intent=new Intent(ListFrom.this,SearchRide.class);
            switch (position) {
                case 0:
                    v = items[0];
                    break;
                case 1:
                    v = items[1];
                    break;
                case 2:
                    v = items[2];
                    break;
                case 3:
                    v = items[3];
                    break;
                case 4:
                    v = items[4];
                    break;
                case 5:
                    v = items[5];
                    break;
            }

            intent.putExtra("From",v);
            startActivity(intent);

        }
    });

SearchRide as Main Activity

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search_ride);

    etDate=(EditText) findViewById(R.id.etDate);
    TextView tFrom=(TextView) findViewById(R.id.tFrom);
    TextView tTo=(TextView) findViewById(R.id.tTo);
    etFrom=(EditText) findViewById(R.id.etFrom);
    etTo=(EditText) findViewById(R.id.etTo);
    Button bSearch=(Button) findViewById(R.id.bSearch);
    ImageView iplussign=(ImageView) findViewById(R.id.iplussign);
    ImageView iminussign=(ImageView) findViewById(R.id.iminussign);
    final TextView tNumber=(TextView) findViewById(R.id.tNumber);

    etTo.setText(getIntent().getStringExtra("To"));

    tNumber.setText(String.valueOf(p));
    iplussign.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(p<=9) {
                p++;
                tNumber.setText(String.valueOf(p));
            }
        }
    });
    iminussign.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(p>=2) {
                p--;
                tNumber.setText(String.valueOf(p));
            }
        }
    });

    etFrom.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent ListFrom=new Intent(SearchRide.this,ListFrom.class);
            startActivity(ListFrom);
        }
    });
    etFrom.setText(getIntent().getStringExtra("From"));

    etTo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent ToList =new Intent(SearchRide.this,ListTo.class);
            startActivity(ToList);
        }
    });
    etTo.setText(getIntent().getStringExtra("To"));

    etDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DatePickerDialog dialog= new DatePickerDialog(SearchRide.this,R.style.MyDatePickerStyle,listener,calendar.get(Calendar.DAY_OF_MONTH),calendar.get(Calendar.MONTH),calendar.get(Calendar.YEAR));
            dialog.getDatePicker().setMinDate(calendar.getTimeInMillis());
            dialog.show();
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

}

Body:
Here is what you can do. Put both from and to values as extra when starting an activity and return them both as result. This way you will be able to remember it. I am assuming you just do not want to use static variables.

// in ListTo activity
intent.putExtra("To",v);
intent.putExtra("From", getIntent().getStringExtra("From"));

// in ListFrom activity
intent.putExtra("From",v);
intent.putExtra("To", getIntent().getStringExtra("To"));

// in Main activity
etTo.setText(getIntent().getStringExtra("To"));
etFrom.setText(getIntent().getStringExtra("From"));

// when starting ListFrom activity
Intent ListFrom=new Intent(SearchRide.this,ListFrom.class);
intent.putExtra("From", getIntent().getStringExtra("From"));
intent.putExtra("To", getIntent().getStringExtra("To"));
startActivity(ListFrom);

// when starting ListTo activity
Intent ToList =new Intent(SearchRide.this,ListTo.class);
intent.putExtra("From", getIntent().getStringExtra("From"));
intent.putExtra("To", getIntent().getStringExtra("To"));
startActivity(ToList);

PS: I have not tested the above code. You can experience null pointer errors, but it should give you the general idea.


问:
UIAlertController in static method giving error: extra argument animated in cell
I wish to create a static method which I can place in a utility class which would launch a UIAlertController. However, I am getting the following error:

"extra argument animated in cell"

```<code>static func simpleAlertBox1(msg : String) -> Void{
    let alertController = UIAlertController(title: "Alert!", message: msg, preferredStyle: .actionSheet)
    let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
    alertController.addAction(defaultAction)
    present(alertController, animated: true, completion: nil)// error is being generated here
}
</code>```

I tried this but it still gave me the same error:

```<code>presentViewController(alertController, animated: true, completion: nil)
</code>```

but if I were to remove the static, then it works fine.

答:
The method present(_:animated:completion:) is an instance method of UIViewController. You need to send that method to a specific instance of UIViewController. By making your function a static function, it is a function of the class, not of an instance of a class.

(It's like sending a message to a car factory saying "set the radio station to 99.5 FM. That message only makes sense when sent to an instance of a car, not to the car factory, or to the entire Toyota Prius class of cars.)

Body:
I wish to create a static method which I can place in a utility class which would launch a UIAlertController. However, I am getting the following error:

"extra argument animated in cell"

static func simpleAlertBox1(msg : String) -> Void{
    let alertController = UIAlertController(title: "Alert!", message: msg, preferredStyle: .actionSheet)
    let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
    alertController.addAction(defaultAction)
    present(alertController, animated: true, completion: nil)// error is being generated here
}

I tried this but it still gave me the same error:

presentViewController(alertController, animated: true, completion: nil)

but if I were to remove the static, then it works fine.


问:
C# How to fill datagridview with a property of an object that is stored inside an object of a List<object>
```<code>  public abstract class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    public class Manager:Person
    {
        public int Trophies { get; set; }

    }
    public class Team
    {
        public string Name { get; set; }
        public Manager manager { get; set; }
        public Team() { }

        public Team(string _name,Manager _mananger)
        {
            Name = _name;
            manager = _mananger;
        Lists.ListOfTeams.Add(this);
        }
    }
    public static class Lists {
        public static List<Team> ListOfTeams = new List<Team>();
    }

My code :
datagridTeams.Datasource = Lists.ListOfTeams;
</code>```

<p>I want to populate a datagrid with the List of teams , also their managers name but I can not achieve that , it just gives me the result ListOfTeams.Manger;
Can anyone help me how to achieve that </p>

答:
You can expose a public get only property that gets the manager's name (ManagerName) in the Team class. This will help you achieve what you are looking for. </p>

```<code>public class Team
{
    public string Name { get; set; }
    public string ManagerName => Manager.Name;
    public Manager manager { get; set; }
    public Team() { }

    public Team(string _name,Manager _mananger)
    {
        Name = _name;
        manager = _mananger;
    Lists.ListOfTeams.Add(this);
    }
}
</code>```

Body:
  public abstract class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    public class Manager:Person
    {
        public int Trophies { get; set; }

    }
    public class Team
    {
        public string Name { get; set; }
        public Manager manager { get; set; }
        public Team() { }

        public Team(string _name,Manager _mananger)
        {
            Name = _name;
            manager = _mananger;
        Lists.ListOfTeams.Add(this);
        }
    }
    public static class Lists {
        public static List<Team> ListOfTeams = new List<Team>();
    }

My code :
datagridTeams.Datasource = Lists.ListOfTeams;

I want to populate a datagrid with the List of teams , also their managers name but I can not achieve that , it just gives me the result ListOfTeams.Manger;
Can anyone help me how to achieve that

Body:
You can expose a public get only property that gets the manager's name (ManagerName) in the Team class. This will help you achieve what you are looking for.

public class Team
{
    public string Name { get; set; }
    public string ManagerName => Manager.Name;
    public Manager manager { get; set; }
    public Team() { }

    public Team(string _name,Manager _mananger)
    {
        Name = _name;
        manager = _mananger;
    Lists.ListOfTeams.Add(this);
    }
}


问:
Using static method from generic class
I have problem as above. My code:

```<code>public abstract class BaseFactory<T> where T: class
{
    protected static dbModelContainer context = new dbModelContainer();

    public static int UpdateDataBase_static()
    {
        return context.SaveChanges();
    }
 }
</code>```

and my question is how can I call

```<code>BaseFactory.UpdateDataBase_static();
</code>```

instead of:

```<code>BaseFactory<SomeClass>.UpdateDataBase_static();
</code>```

Any ideas?

答:
You don't.

You always need to supply the generic type arguments when accessing a class, even though you aren't using that type argument in your method.  Since you don't actually use the generic type in the method it means you could move that method out of that class, and into one that isn't generic, but for as long as it's in that class you'll need to supply the generic argument.

Title: Using static method from generic class

Body:
I have problem as above. My code:

public abstract class BaseFactory<T> where T: class
{
    protected static dbModelContainer context = new dbModelContainer();

    public static int UpdateDataBase_static()
    {
        return context.SaveChanges();
    }
 }

and my question is how can I call

BaseFactory.UpdateDataBase_static();

instead of:

BaseFactory<SomeClass>.UpdateDataBase_static();

Any ideas?


问:
Is there a way to merge these two tables?
I have two tables :

```<code>question_likes:

question_id references question(id)
user_id references users(id)
primary key (user_id, question_id)

answer_likes:

answer_id references answers(id)
user_id references users(id)
primary key (user_id, answer_id)
</code>```

A colleague suggested that I can use inheritance in Postgres to merge these into one table.

Is there a way to design this requirement?

答:
Well, you don't need that certainly I believe. You can perform a JOIN between the tables and display the required fields like below. Or, create a view with the below SQL statement.

```<code>select q.question_id,
q.user_id,
a.answer_id
from  question_likes q
join answer_likes a on a.user_id = q.user_id;
</code>```

(or) a full outer join as suggested in comment by klin

```<code>from  question_likes
full join answer_likes using(user_id);
</code>```

Body:
I have two tables :

question_likes:

question_id references question(id)
user_id references users(id)
primary key (user_id, question_id)

answer_likes:

answer_id references answers(id)
user_id references users(id)
primary key (user_id, answer_id)

A colleague suggested that I can use inheritance in Postgres to merge these into one table.

Is there a way to design this requirement?

Body:
Well, you don't need that certainly I believe. You can perform a JOIN between the tables and display the required fields like below. Or, create a view with the below SQL statement.

select q.question_id,
q.user_id,
a.answer_id
from  question_likes q
join answer_likes a on a.user_id = q.user_id;

(or) a full outer join as suggested in comment by klin

from  question_likes
full join answer_likes using(user_id);