问:
Processing a String with ANTLR4
I'm trying to convert my grammar from v3 to v4 and having some trouble finding all the right pieces.

In v3 to process a String, I used:

```<code>public static DataExtractor create(String dataspec) {
    CharStream stream = new ANTLRStringStream(dataspec);
    DataSpecificationLexer lexer = new DataSpecificationLexer(stream);
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    DataSpecificationParser parser = new DataSpecificationParser(tokens);

    return parser.dataspec();
}
</code>```

How do I change this to work in v4?

答:
For ANTLR 4.7 the API was changed a little (ANTLRInputStream is deprecated):

```<code>InputStream stream = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8));
lexer.setInputStream(CharStreams.fromStream(stream, StandardCharsets.UTF_8));
parser.setInputStream(new CommonTokenStream(lexer));
</code>```

Hint: if you want to re-use the parser+lexer instances, call their 'reset()' methods after setting their input streams.

Title: Processing a String with ANTLR4

Body:
I'm trying to convert my grammar from v3 to v4 and having some trouble finding all the right pieces.

In v3 to process a String, I used:

public static DataExtractor create(String dataspec) {
    CharStream stream = new ANTLRStringStream(dataspec);
    DataSpecificationLexer lexer = new DataSpecificationLexer(stream);
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    DataSpecificationParser parser = new DataSpecificationParser(tokens);

    return parser.dataspec();
}

How do I change this to work in v4?

Body:
For ANTLR 4.7 the API was changed a little (ANTLRInputStream is deprecated):

InputStream stream = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8));
lexer.setInputStream(CharStreams.fromStream(stream, StandardCharsets.UTF_8));
parser.setInputStream(new CommonTokenStream(lexer));

Hint: if you want to re-use the parser+lexer instances, call their 'reset()' methods after setting their input streams.


来源: stackexchange

问:
combining 2 activities together
ok so I'm making an app where I use an edit text to write anything and when I press a button it adds whatever I wrote in the edit to a listView, and it works, but I want the List to be in a different activity than the button and edit text, so I moved it without changing the code.can anyone figure this out,

BTW all the variables are public.

```<code>public class MainActivity extends AppCompatActivity {
    public ArrayList<String> arrayList2;
    public ArrayAdapter<String> adapter,adapter2;
    public EditText editText,editText2;
    public ArrayList<String> itemList,itemList2;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String[] items = {};
        itemList = new ArrayList<String>(Arrays.asList(items));
        adapter = new ArrayAdapter<String>(this, R.layout.activity_list_layout,R.id.txtItem,itemList);
        ListView listV = (ListView)findViewById(R.id.list_layout);
        listV.setAdapter(adapter);
        editText = (EditText)findViewById(R.id.thingadd);
        Button btAdd = (Button)findViewById(R.id.add);

        String[] age = {};
        arrayList2 = new ArrayList<String>(Arrays.asList(age));
        itemList2 = new ArrayList<String>(Arrays.asList(age));
        adapter2 = new ArrayAdapter<String>(this, R.layout.activity_list__layout2,R.id.txtage,itemList2);
        ListView listV2 = (ListView)findViewById(R.id.Age);
        listV2.setAdapter(adapter2);
        editText2 = (EditText)findViewById(R.id.agetxt);

        btAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String newItem=editText.getText().toString();
                String newItem2=editText2.getText().toString();

                itemList.add(newItem);
                itemList2.add(newItem2);

                adapter.notifyDataSetChanged();
                adapter2.notifyDataSetChanged();
            }
        });
    }
}
</code>```

答: You can use SQLite Database for that, where you would be saving data in database from one activity and reading it and displaying it in listview from another.</p>

ContentLicense: CC BY-SA 3.0

Title: combining 2 activities together

Body:
ok so I'm making an app where I use an edit text to write anything and when I press a button it adds whatever I wrote in the edit to a listView, and it works, but I want the List to be in a different activity than the button and edit text, so I moved it without changing the code.can anyone figure this out,

BTW all the variables are public.

public class MainActivity extends AppCompatActivity {
    public ArrayList<String> arrayList2;
    public ArrayAdapter<String> adapter,adapter2;
    public EditText editText,editText2;
    public ArrayList<String> itemList,itemList2;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String[] items = {};
        itemList = new ArrayList<String>(Arrays.asList(items));
        adapter = new ArrayAdapter<String>(this, R.layout.activity_list_layout,R.id.txtItem,itemList);
        ListView listV = (ListView)findViewById(R.id.list_layout);
        listV.setAdapter(adapter);
        editText = (EditText)findViewById(R.id.thingadd);
        Button btAdd = (Button)findViewById(R.id.add);

        String[] age = {};
        arrayList2 = new ArrayList<String>(Arrays.asList(age));
        itemList2 = new ArrayList<String>(Arrays.asList(age));
        adapter2 = new ArrayAdapter<String>(this, R.layout.activity_list__layout2,R.id.txtage,itemList2);
        ListView listV2 = (ListView)findViewById(R.id.Age);
        listV2.setAdapter(adapter2);
        editText2 = (EditText)findViewById(R.id.agetxt);

        btAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String newItem=editText.getText().toString();
                String newItem2=editText2.getText().toString();

                itemList.add(newItem);
                itemList2.add(newItem2);

                adapter.notifyDataSetChanged();
                adapter2.notifyDataSetChanged();
            }
        });
    }
}


问:
Internal Server Error 500 on a blank php file
Sorry if this seems obvious. I'm very new to this, but I've been stuck on this problem for hours even after searching around for similar problems.

I am using the cpanel for managing the files.

Initially, I tried uploading a simple php file, but I kept on getting problems, so I tried an empty php file. This is the error I constantly receive.

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.`

Please contact the server administrator at webmaster@mywebsite.com to inform them of the time this error occurred, and the actions you performed just before this error.

More information about this error may be available in the server error log.

Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.`

After some more searching, I read about the .htaccess file.

I couldn't find the .htaccess, even after enabling "Show Hidden Files (dotfiles)" in the setting, so I created one. An empty one didn't work. I tried to look for what to place there and tried this.

```<code><IfModule mod_rewrite.c>
   RewriteEngine On

   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-l

   RewriteRule ^(.*)$ file.php?url=$1 [QSA,L]
</IfModule>
</code>```

In the error of the cpanel, this is what I receive

:error] [pid xxxx:tid xxxx] (12)Cannot allocate memory: [client xxxx] couldn't create child process: /usr/sbin/suphp for /home3/xxxx/public_html/file.php

I also tried to set the file permission to 644, and the folder to 755, but to no avail.

There were some other posts here about the php.ini and some commands in the command line, but I don't really know where to find them. There was also something about apache? but in the cpanel menu, there was only the apache handlers. Any help would be greatly appreciated! Again, sorry. I'm really new and I have no idea what I'm doing.

If it helps, the web hosting that I am using is zoom.ph (not sure if that is the proper term)

答:
if you are using Mac localhost thats is normal because Mac doesn't show .htacces files you can enable hidden files open terminal and enter

```<code>defaults write com.apple.finder AppleShowAllFiles YES
</code>```

after that enter ;

```<code>killall Finder /System/Library/CoreServices/Finder.app
</code>```

this problem has many causes please be sure your project directory is correct ! and change your code with this;

```<code>    RewriteEngine On

    RewriteCond %{REQUEST_URI}::$1 ^(.*?/)(.*)::\2$

    RewriteEngine On Options All -Indexes RewriteBase /directoryname/ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d

    RewriteCond %{REQUEST_FILENAME} !-f

    RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ file.php?url=$1 [QSA,L]
</code>```

Body:
Sorry if this seems obvious. I'm very new to this, but I've been stuck on this problem for hours even after searching around for similar problems.

I am using the cpanel for managing the files.

Initially, I tried uploading a simple php file, but I kept on getting problems, so I tried an empty php file. This is the error I constantly receive.

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.`

Please contact the server administrator at webmaster@mywebsite.com to inform them of the time this error occurred, and the actions you performed just before this error.

More information about this error may be available in the server error log.

Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.`

After some more searching, I read about the .htaccess file.

I couldn't find the .htaccess, even after enabling "Show Hidden Files (dotfiles)" in the setting, so I created one. An empty one didn't work. I tried to look for what to place there and tried this.

<IfModule mod_rewrite.c>
   RewriteEngine On

   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-l

   RewriteRule ^(.*)$ file.php?url=$1 [QSA,L]
</IfModule>

In the error of the cpanel, this is what I receive

:error] [pid xxxx:tid xxxx] (12)Cannot allocate memory: [client xxxx] couldn't create child process: /usr/sbin/suphp for /home3/xxxx/public_html/file.php

I also tried to set the file permission to 644, and the folder to 755, but to no avail.

There were some other posts here about the php.ini and some commands in the command line, but I don't really know where to find them. There was also something about apache? but in the cpanel menu, there was only the apache handlers. Any help would be greatly appreciated! Again, sorry. I'm really new and I have no idea what I'm doing.

If it helps, the web hosting that I am using is zoom.ph (not sure if that is the proper term)

Body:
if you are using Mac localhost thats is normal because Mac doesn't show .htacces files you can enable hidden files open terminal and enter

defaults write com.apple.finder AppleShowAllFiles YES

after that enter ;

killall Finder /System/Library/CoreServices/Finder.app

this problem has many causes please be sure your project directory is correct ! and change your code with this;

    RewriteEngine On

    RewriteCond %{REQUEST_URI}::$1 ^(.*?/)(.*)::\2$

    RewriteEngine On Options All -Indexes RewriteBase /directoryname/ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d

    RewriteCond %{REQUEST_FILENAME} !-f

    RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ file.php?url=$1 [QSA,L]


问:
personal version control system to recommend
For personal use. Anyone can recommend the version control system for Windows</p>

答:
Use a distributed version control system. There are many out there the most popular ones being git and mercurial. Distributed SCM is really the way to go because they tend to have much better branch merging and branch management algorithms. Also, by their very nature they are stand-alone programs processing your filesystem. So you don't need to install or manage a server which is another plus for a personal version control system.

Like Tyler, I would personally encourage you to learn git (because all the cool boys use it :-) but I know it is not for everybody. If you like GUI Plastic SCM looks very good. It's commercial but free for teams of less than 5 people. Fossil is another one that's easy to use (I would say easier than git to learn) but it uses an SQLite file to store your code and I'm not sure if it scales to really big projects. On the other hand SQLite itself is a fairly big project that uses Fossil (both written by the same author for the same reason: he couldn't find anything else out there that he liked).

ContentLicense: CC BY-SA 2.5


问:
TensorFlow - Gradients across post-processing assign ops?
If an assign operation is applied to a weight tensor after that weight tensor is used in its portion of the forward pass of a network, does TensorFlow's backpropagation take into account the assign operation when determining the gradient for that weight? For example, if I have

```<code>weights = tf.Variable(...)
bias = tf.Variable(...)
output = tf.tanh(tf.matmul(weights, input) + bias)
weight_assign_op = weights.assign(weights + 1.0)
with tf.control_dependencies(weight_assign_op):
    output2 = tf.identity(output)
</code>```

the output is calculated, and then a change is made to the weights. If the output is then used to calculate a loss and gradients to update the variables, will the gradients be created taking into account the change to weights? That is, will the gradients for weights be the correct gradients for old_weights + 1.0 or will they still be the gradients for old_weights which when applied to the new weights won't necessarily be "correct" gradients for gradient descent?

答:
I ended up testing it experimentally. The gradient calculation does take the assign op into account. I used the below code to test. Running it as it results in a positive gradient. Commenting out the weight assign op line and the control dependency lines results in a negative gradient. This is because the gradient is either being considered for the original starting value weight of 0.0 or of the updated weight after the assign of 2.0.

```<code>import tensorflow as tf

data = [[1.0], [2.0], [3.0]]
labels = [[1.0], [2.1], [2.9]]

input_data = tf.placeholder(dtype=tf.float32, shape=[3, 1])
input_labels = tf.placeholder(dtype=tf.float32, shape=[3, 1])
weights = tf.Variable(tf.constant([0.0]))
bias = tf.Variable(tf.constant([0.0]))
output = (weights * input_data) + bias
weight_assign_op = weights.assign(tf.constant([2.0]))
with tf.control_dependencies([weight_assign_op]):
    output = tf.identity(output)
loss = tf.reduce_sum(tf.norm(output - input_labels))
weight_gradient = tf.gradients(loss, weights)
initialize_op = tf.global_variables_initializer()

session = tf.Session()
session.run([initialize_op])
weight_gradient_value = session.run([weight_gradient], feed_dict={input_data: data, input_labels: labels})
print(weight_gradient_value)
</code>```

Body:
If an assign operation is applied to a weight tensor after that weight tensor is used in its portion of the forward pass of a network, does TensorFlow's backpropagation take into account the assign operation when determining the gradient for that weight? For example, if I have

weights = tf.Variable(...)
bias = tf.Variable(...)
output = tf.tanh(tf.matmul(weights, input) + bias)
weight_assign_op = weights.assign(weights + 1.0)
with tf.control_dependencies(weight_assign_op):
    output2 = tf.identity(output)

the output is calculated, and then a change is made to the weights. If the output is then used to calculate a loss and gradients to update the variables, will the gradients be created taking into account the change to weights? That is, will the gradients for weights be the correct gradients for old_weights + 1.0 or will they still be the gradients for old_weights which when applied to the new weights won't necessarily be "correct" gradients for gradient descent?

Body:
I ended up testing it experimentally. The gradient calculation does take the assign op into account. I used the below code to test. Running it as it results in a positive gradient. Commenting out the weight assign op line and the control dependency lines results in a negative gradient. This is because the gradient is either being considered for the original starting value weight of 0.0 or of the updated weight after the assign of 2.0.

import tensorflow as tf

data = [[1.0], [2.0], [3.0]]
labels = [[1.0], [2.1], [2.9]]

input_data = tf.placeholder(dtype=tf.float32, shape=[3, 1])
input_labels = tf.placeholder(dtype=tf.float32, shape=[3, 1])
weights = tf.Variable(tf.constant([0.0]))
bias = tf.Variable(tf.constant([0.0]))
output = (weights * input_data) + bias
weight_assign_op = weights.assign(tf.constant([2.0]))
with tf.control_dependencies([weight_assign_op]):
    output = tf.identity(output)
loss = tf.reduce_sum(tf.norm(output - input_labels))
weight_gradient = tf.gradients(loss, weights)
initialize_op = tf.global_variables_initializer()

session = tf.Session()
session.run([initialize_op])
weight_gradient_value = session.run([weight_gradient], feed_dict={input_data: data, input_labels: labels})
print(weight_gradient_value)


问:
Optimizing Mandelbrot fractal
This is a code that outputs in a .ppm file the mandelbrot fractal. How can I optimize this?

```<code>#include<bits/stdc++.h>
using namespace std;

int findMandelbrot(double cr, double ci, int max_iterations)
{
    int i = 0;
    double zr = 0.0, zi = 0.0;
    while (i < max_iterations && zr * zr + zi * zi < 4.0)
    {
        double temp = zr * zr - zi * zi + cr;
        zi = 2.0 * zr * zi + ci;
        zr = temp;
        ++i;
    }
    return i;
}

double mapToReal(int x, int imageWidth, double minR, double maxR)
{
    double range = maxR - minR;
    return x * (range / imageWidth) + minR;
}

double mapToImaginary(int y, int imageHeight, double minI, double maxI)
{
    double range = maxI - minI;
    return y * (range / imageHeight) + minI;
}

int main()
{
    ifstream f("input.txt");
    int imageWidth, imageHeight, maxN;
    double minR, maxR, minI, maxI;

    if (!f)
    {
        cout << "Could not open file!" << endl;
        return 1;
    }

    f >> imageWidth >> imageHeight >> maxN;
    f >> minR >> maxR >> minI >> maxI;

    ofstream g("output_image.ppm");
    g << "P3" << endl;
    g << imageWidth << " " << imageHeight << endl;
    g << "255" << endl;

    double start = clock();

    for (int i = 0; i < imageHeight; i++)
    {
        for (int j = 0; j < imageWidth; j++)
        {
            double cr = mapToReal(j, imageWidth, minR, maxR);
            double ci = mapToImaginary(i, imageHeight, minI, maxI);

            int n = findMandelbrot(cr, ci, maxN);

            int r = ((int)sqrt(n) % 256);
            int gr = (2*n % 256);
            int b = (n % 256);

            g << r << " " << gr << " " << b << " ";
        }
        g << endl;

        if(i == imageHeight / 2) break;
    }

    cout << "Finished!" << endl;

    double stop = clock();

    cout << (stop-start)/CLOCKS_PER_SEC;
    return 0;
}
</code>```

I go until imageHeight / 2 because in a photoshop I can just copy the other half.
I was thinking about loghartimic power but tried something and only works with integers...

答:
In findMandelbrot you use the expressions zr * zr and zi * zi in the loop test but then recalculate the same two expressions if the test succeeds.  So one obvious improvement might be to cache those with something like...

```<code>int findMandelbrot (double cr, double ci, int max_iterations)
{
  int i = 0;
  double zr = 0.0, zi = 0.0;
  double zr2 = 0.0, zi2 = 0.0;
  while (i < max_iterations && zr2 + zi2 < 4.0) {
    double temp = zr2 - zi2 + cr;
    zi = 2.0 * zr * zi + ci;
    zr = temp;
    zr2 = zr * zr;
    zi2 = zi * zi;
    ++i;
  }
  return(i - 1);
}
</code>```

Title: Optimizing Mandelbrot fractal

Body:
This is a code that outputs in a .ppm file the mandelbrot fractal. How can I optimize this?

#include<bits/stdc++.h>
using namespace std;

int findMandelbrot(double cr, double ci, int max_iterations)
{
    int i = 0;
    double zr = 0.0, zi = 0.0;
    while (i < max_iterations && zr * zr + zi * zi < 4.0)
    {
        double temp = zr * zr - zi * zi + cr;
        zi = 2.0 * zr * zi + ci;
        zr = temp;
        ++i;
    }
    return i;
}

double mapToReal(int x, int imageWidth, double minR, double maxR)
{
    double range = maxR - minR;
    return x * (range / imageWidth) + minR;
}

double mapToImaginary(int y, int imageHeight, double minI, double maxI)
{
    double range = maxI - minI;
    return y * (range / imageHeight) + minI;
}

int main()
{
    ifstream f("input.txt");
    int imageWidth, imageHeight, maxN;
    double minR, maxR, minI, maxI;

    if (!f)
    {
        cout << "Could not open file!" << endl;
        return 1;
    }

    f >> imageWidth >> imageHeight >> maxN;
    f >> minR >> maxR >> minI >> maxI;

    ofstream g("output_image.ppm");
    g << "P3" << endl;
    g << imageWidth << " " << imageHeight << endl;
    g << "255" << endl;

    double start = clock();

    for (int i = 0; i < imageHeight; i++)
    {
        for (int j = 0; j < imageWidth; j++)
        {
            double cr = mapToReal(j, imageWidth, minR, maxR);
            double ci = mapToImaginary(i, imageHeight, minI, maxI);

            int n = findMandelbrot(cr, ci, maxN);

            int r = ((int)sqrt(n) % 256);
            int gr = (2*n % 256);
            int b = (n % 256);

            g << r << " " << gr << " " << b << " ";
        }
        g << endl;

        if(i == imageHeight / 2) break;
    }

    cout << "Finished!" << endl;

    double stop = clock();

    cout << (stop-start)/CLOCKS_PER_SEC;
    return 0;
}

I go until imageHeight / 2 because in a photoshop I can just copy the other half.
I was thinking about loghartimic power but tried something and only works with integers...

Body:
In findMandelbrot you use the expressions zr * zr and zi * zi in the loop test but then recalculate the same two expressions if the test succeeds.  So one obvious improvement might be to cache those with something like...

int findMandelbrot (double cr, double ci, int max_iterations)
{
  int i = 0;
  double zr = 0.0, zi = 0.0;
  double zr2 = 0.0, zi2 = 0.0;
  while (i < max_iterations && zr2 + zi2 < 4.0) {
    double temp = zr2 - zi2 + cr;
    zi = 2.0 * zr * zi + ci;
    zr = temp;
    zr2 = zr * zr;
    zi2 = zi * zi;
    ++i;
  }
  return(i - 1);
}


问:
Rails 3 Fixture Join Table Ids are Incorrect
I am trying to work with fixtures in rails.  The rake db:fixtures:load runs without error, and table populates my data, but my many to many join table contains incorrect ids:

Example:

```<code>**tags.yml**
one:
  id: 1
  tag: pie
  posts: two

two:
  id: 2
  tag: cake
  posts: one, two

**posts.yml**
one:
  id: 1
  subject: subject
  content: content
  slug: woot
  tags: cake

two:
  id: 2
  subject: subject2
  content: content2
  slug: this_is_good
  tags: pie, cake
</code>```

After running migrations and db:fixtures:load my tables get populated as:

tags:

id------tag

1 ...... pie

2 ...... cake

posts_tags:

rowid - post_id - tag_id

1 ...... 1 ...... 974324064

2 ...... 2 ...... 576189563

3 ...... 3 ...... 974324064

For some reason an auto-generated tag_id is getting created and being populated in my join table. Why?

Edit

The migrations are defined as:

```<code>  def self.up
    create_table :posts do |t|
      t.string :subject
      t.text :content

      t.timestamps
    end
  end
</code>```

and

```<code>  def self.up
    create_table :tags do |t|
      t.string :tag

      t.timestamps
    end

    create_table :posts_tags, :id => false do |t|
      t.integer :post_id
      t.integer :tag_id
    end
  end
</code>```

答:
I am assuming you have proper associations defined. You just need a small change in your fixtures:

```<code>**tags.yml**
one:
  tag: pie
  posts: two

two:
  tag: cake
  posts: one, two

**posts.yml**
one:
  subject: subject
  content: content
  slug: woot
  tags:
    - two

two:
  subject: subject2
  content: content2
  slug: this_is_good
  tags:
    - one
    - two
</code>```

EDIT: I deleted all the IDs from fixtures. That generates correct references. But this isn't quite the correct answer.

Body:
I am trying to work with fixtures in rails.  The rake db:fixtures:load runs without error, and table populates my data, but my many to many join table contains incorrect ids:

Example:

**tags.yml**
one:
  id: 1
  tag: pie
  posts: two

two:
  id: 2
  tag: cake
  posts: one, two

**posts.yml**
one:
  id: 1
  subject: subject
  content: content
  slug: woot
  tags: cake

two:
  id: 2
  subject: subject2
  content: content2
  slug: this_is_good
  tags: pie, cake

After running migrations and db:fixtures:load my tables get populated as:

tags:

id------tag

1 ...... pie

2 ...... cake

posts_tags:

rowid - post_id - tag_id

1 ...... 1 ...... 974324064

2 ...... 2 ...... 576189563

3 ...... 3 ...... 974324064

For some reason an auto-generated tag_id is getting created and being populated in my join table. Why?

Edit

The migrations are defined as:

  def self.up
    create_table :posts do |t|
      t.string :subject
      t.text :content

      t.timestamps
    end
  end

and

  def self.up
    create_table :tags do |t|
      t.string :tag

      t.timestamps
    end

    create_table :posts_tags, :id => false do |t|
      t.integer :post_id
      t.integer :tag_id
    end
  end

Body:
I am assuming you have proper associations defined. You just need a small change in your fixtures:

**tags.yml**
one:
  tag: pie
  posts: two

two:
  tag: cake
  posts: one, two

**posts.yml**
one:
  subject: subject
  content: content
  slug: woot
  tags:
    - two

two:
  subject: subject2
  content: content2
  slug: this_is_good
  tags:
    - one
    - two

EDIT: I deleted all the IDs from fixtures. That generates correct references. But this isn't quite the correct answer.


问:
How to pass multiple regexpression extracted values to a single http request?
I am sending First request to server:
POST http://192.168.7.101/r2.web/Planning/Scheduling/TimelinefromR3 -->(A)

I have written Regular Expression extractor((?<=\"Values":")(.*?)(?=\")) to extract Resourcenames like "Ray Gwilliams" and "James Mark" from the response of (A),

Now, I have another request(as mentioned below) to which, I need to pass all the Resource names("Ray Gwilliams" and "James Mark") extracted above.

Please let me know how to achieve this.

http://192.168.7.101/R2.Web/Planning/Scheduling/SchedulesAndGroups

POST data:
[{"ColumnName":"CONTACTNAME","ColumnIId":0,"UdfIId":null,"ConditionIId":0,"OperatorIId":1,"SequenceNo":0,"Values":"Ray Gwilliams
","Lookup":null,"LookupIId":0,"LookupSource":0,"LookupType":0,"MultipleOperatorIIds":null,"MultipleValues":null,"ColumnDataType":null},{"ColumnName":"CONTACTNAME","ColumnIId":0,"UdfIId":null,"ConditionIId":0,"OperatorIId":1,"SequenceNo":0,"Values":"James Mark
","Lookup":null,"LookupIId":0,"LookupSource":0,"LookupType":0,"MultipleOperatorIIds":null,"MultipleValues":null,"ColumnDataType":null}

答:
I have not used the regular expression but if you use the JSON Extractor element and put the extracted value into a variable, you would just add the variable into the 2nd POST request.  For example:

```<code>POST data:
[{"ColumnName":"CONTACTNAME",
"ColumnIId":0,"UdfIId":null,"ConditionIId":0,
"OperatorIId":1,"SequenceNo":0,
"Values":"${variable1} ","Lookup":null,"LookupIId":0,
"LookupSource":0,"LookupType":0,
"MultipleOperatorIIds":null,"MultipleValues":null,
"ColumnDataType":null},  {"ColumnName":"CONTACTNAME",
"ColumnIId":0,"UdfIId":null,
"ConditionIId":0,"OperatorIId":1,
"SequenceNo":0,
"Values":"${variable2} ","Lookup":null,"LookupIId":0,
"LookupSource":0,"LookupType":0,
"MultipleOperatorIIds":null,
"MultipleValues":null,"ColumnDataType":null}
</code>```

Tip:  To get the value you want extracted, use jmeter's JSON Path Tester in the View Results in Tree listenter element or this helper tool: http://jsonpath.com/

Body:
I have not used the regular expression but if you use the JSON Extractor element and put the extracted value into a variable, you would just add the variable into the 2nd POST request.  For example:

POST data:
[{"ColumnName":"CONTACTNAME",
"ColumnIId":0,"UdfIId":null,"ConditionIId":0,
"OperatorIId":1,"SequenceNo":0,
"Values":"${variable1} ","Lookup":null,"LookupIId":0,
"LookupSource":0,"LookupType":0,
"MultipleOperatorIIds":null,"MultipleValues":null,
"ColumnDataType":null},  {"ColumnName":"CONTACTNAME",
"ColumnIId":0,"UdfIId":null,
"ConditionIId":0,"OperatorIId":1,
"SequenceNo":0,
"Values":"${variable2} ","Lookup":null,"LookupIId":0,
"LookupSource":0,"LookupType":0,
"MultipleOperatorIIds":null,
"MultipleValues":null,"ColumnDataType":null}

Tip:  To get the value you want extracted, use jmeter's JSON Path Tester in the View Results in Tree listenter element or this helper tool: http://jsonpath.com/


问:
How to get a number starting from 4 and transforming it?
I have the following 3 operations:

Add 4 at the end of the number ( 13 becomes 134 ).

Add 0 at the end of the number ( 13 becomes 130 ).

If number is even divide it by 2.

Using these operations and starting from 4 I have to compute a user input number and output the value of each operation made. For n = 7 it should output 3 3 1 3 because ((((4 / 2) / 2) * 10) + 4) / 2 = 7. I just can't find a solution. I just wrote some code to output the result for n = 5. n is smaller than 100.000.

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

int one( int n )
{
    printf( "1 " );
    return n * 10 + 4;
}

int two( int n )
{
    printf( "2 " );
    return n * 10;
}

int three( int n )
{
    printf( "3 " );
    return n / 2;
}

int main()
{
    int n;
    scanf( "%d", &n );
    three( two( three( three( n ))));
    return 0;
}
</code>```

Could someone please help me?
Thank you!

Edit!
The following picture will show expected results for some input.

答:
This can be done by dynamic programming.

Say the user input n = K. You can reach to K in three ways.

```<code>If K has 4 or 0 as last digit, then from the number formed by removing last digit.
Else from 2 * K
</code>```

So if you prepopulate ways to reach every number, then you can backtrack from input number back to starting number 4.

Lets S is the array storing a pair of numbers i.e. previous number and method from which S can be reached. There can be multiple ways to reach S but you can store any.
so as example, S[44] = {88,3} or {4,1}.

But the difficult task is to find upper limit of array till where to prepopulate. Maximum value of N can be 100. 100 can be achieved from 10, so not a problem. Lets check for smaller numbers

```<code>99 <- 198 <- 396 <- 792 <- 1584 <- 158
98 <- 196 <- 392 <- 784 <- 78
</code>```

So pre-populating data is required till S[1584]

Let M = 1584

Lets fill the array S. Initially set all indices of S to null

```<code>for i from 1 to M
    if i has 0 or 4 at unit place
        S[i] = {no formed by removing unit place digit, method 1 or 2}

        There are gaps remaining which were to be filled by method 3, lets also fill them, i/2 and furthur if i is even
        J = i
        k = i/2
        while(j is even and S[k] is null)
            S[k] = {j, 3}
            j = k;
            k = j/2
</code>```

When all S all filled, lets do for N = 7 giving in original problem
Some values for S are as follows

```<code>S[1] = {2,3}
S[2] = {4,3}
S[3] = {6,3}
S[4] = {0,1}
S[5] = {10,3}
S[6] = {12,3}
S[7] = {14,3}
S[8] = {16,3}
S[9] = {18,3}
S[10] = {1,2}
S[11] = {22,3}
S[12] = {24,3}
S[13] = {26,3}
S[14] = {1,1}

S[7] = {14,3} , so store 3 and check for 14
S[14] = {1,1}, so store 1 and check for 1
S[1] = {2,3}, so store 3 and check for 2
S[2] = {4,2}, so store 3 and 4 is reached, and you are done.
</code>```

Print stored value in reverse format are 3,3,1,3.

Body:
I have the following 3 operations:

Add 4 at the end of the number ( 13 becomes 134 ).

Add 0 at the end of the number ( 13 becomes 130 ).

If number is even divide it by 2.

Using these operations and starting from 4 I have to compute a user input number and output the value of each operation made. For n = 7 it should output 3 3 1 3 because ((((4 / 2) / 2) * 10) + 4) / 2 = 7. I just can't find a solution. I just wrote some code to output the result for n = 5. n is smaller than 100.000.

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

int one( int n )
{
    printf( "1 " );
    return n * 10 + 4;
}

int two( int n )
{
    printf( "2 " );
    return n * 10;
}

int three( int n )
{
    printf( "3 " );
    return n / 2;
}

int main()
{
    int n;
    scanf( "%d", &n );
    three( two( three( three( n ))));
    return 0;
}

Could someone please help me?
Thank you!

Edit!
The following picture will show expected results for some input.

Body:
This can be done by dynamic programming.

Say the user input n = K. You can reach to K in three ways.

If K has 4 or 0 as last digit, then from the number formed by removing last digit.
Else from 2 * K

So if you prepopulate ways to reach every number, then you can backtrack from input number back to starting number 4.

Lets S is the array storing a pair of numbers i.e. previous number and method from which S can be reached. There can be multiple ways to reach S but you can store any.
so as example, S[44] = {88,3} or {4,1}.

But the difficult task is to find upper limit of array till where to prepopulate. Maximum value of N can be 100. 100 can be achieved from 10, so not a problem. Lets check for smaller numbers

99 <- 198 <- 396 <- 792 <- 1584 <- 158
98 <- 196 <- 392 <- 784 <- 78

So pre-populating data is required till S[1584]

Let M = 1584

Lets fill the array S. Initially set all indices of S to null

for i from 1 to M
    if i has 0 or 4 at unit place
        S[i] = {no formed by removing unit place digit, method 1 or 2}

        There are gaps remaining which were to be filled by method 3, lets also fill them, i/2 and furthur if i is even
        J = i
        k = i/2
        while(j is even and S[k] is null)
            S[k] = {j, 3}
            j = k;
            k = j/2

When all S all filled, lets do for N = 7 giving in original problem
Some values for S are as follows

S[1] = {2,3}
S[2] = {4,3}
S[3] = {6,3}
S[4] = {0,1}
S[5] = {10,3}
S[6] = {12,3}
S[7] = {14,3}
S[8] = {16,3}
S[9] = {18,3}
S[10] = {1,2}
S[11] = {22,3}
S[12] = {24,3}
S[13] = {26,3}
S[14] = {1,1}

S[7] = {14,3} , so store 3 and check for 14
S[14] = {1,1}, so store 1 and check for 1
S[1] = {2,3}, so store 3 and check for 2
S[2] = {4,2}, so store 3 and 4 is reached, and you are done.

Print stored value in reverse format are 3,3,1,3.


问:
how can i hidden and prevent download source of css, js?
how can I hidden and prevent download source of css, js and images files in my website ?
like this web site:

www[dot]sales.4080.ir/themes/corporate3/index.html

I want to protect my template and prevent download my theme js,css and images files,
I thought this work was impossible but i saw this website :

www[dot]sales.4080.ir/themes/corporate3/index.html

and I understood that work is possible and I wanna help me that how to do them?

for example :

1- http://sales.4080.ir/themes/corporate3/js/limite/limite.js

2- http://sales.4080.ir/Themes/corporate3/css/menuResize/menuResize.css

The files that I mentioned above, neither of them can not download...
and I want to do like that trick...

please help me...

thanks...

答:
Normally you can use file permission to do that, but if you want to prevent download to you're css and js file, i think thats same like you want browser to ignore that file on you're website, how to say this, i dont think you can do that, you need browser to access that file, not ignore it,
But if you want to prevent someone using ctrl+u or right click, i think you can find much article on google.
Btw, that's just my opinion. Maybe someone can explain :v </p>


问:
Dividing strings in python 2.7
I have been working on a automated blinds/ curtains project for some time now It all works well but I would like to add the function of the Blinds gradually opening in the morning. I am reading my values from a config file and have converted the values into strings which works fine, just can't divide that value for some reason. I have tried many ways of doing this but I seem to come across errors such as- SyntaxError: can't assign to operator and TypeError: cannot concatenate 'str' and 'int' objects. Has anyone got any idea's on how I can divide a python string then use that string as a sleep value??

I am fairly new to programming (I'm 13)

```<code>from ConfigParser import SafeConfigParser
config = SafeConfigParser()

config.read('/home/pi/config.conf') #read config file
openTime = config.get('blinds', 'open time(secs)') # -> "openTime"
print 'Overall open time ' + openTime + ' seconds'

## code to divide openTime by 5 and print the value

print 'gradual open time' + DividedOpenTime + ' seconds'

## code to repeat in a loop 5 times with a sleep of the value of
## DividedOpenTime
</code>```

EDIT 1

Hi again I have done what I was told to add to the code and it has solved the issue of the division and sleep time but for some reason I can't print the values. Both lines 11 and 15 have the following error:

```<code>Traceback (most recent call last):
  File "test.py", line 11, in <module>
    print 'gradual open time' + divOpenTime + ' this will repeat 5 times'
TypeError: cannot concatenate 'str' and 'float' objects
</code>```

Does anyone know how I can fix this issue?

```<code>from ConfigParser import SafeConfigParser
config = SafeConfigParser()
import time

config.read('/home/pi/config.conf') #read config file
openTime = config.get('blinds', 'open time(secs)') # -> "openTime"
print 'Overall open time ' + openTime + ' seconds'

divOpenTime = float(openTime)/5 #working (:
loop = 0
print 'gradual open time' + divOpenTime + ' this will repeat 5 times'

for x in range(0, 5):
    loop += 1
    print 'gradual opening stage ' + loop + '/5'
    #GPIO true- I know how to do this
    time.sleep(divOpenTime) #working (:
    #GPIO False- I know how to do this
    time.sleep(15) #time between each interval fixed value
</code>```

Thanks Ed

答:
I worked it out

```<code> print 'Gradual open time ' + str(divOpenTime) + ' seconds this will repeat 5
 times'
</code>```

you have to add/convert your float value into a string so it can print. You do
this with:

```<code>str(Your_float_value_here)
</code>```

Thanks again for all your help Ed

Title: Dividing strings in python 2.7

Body:
I have been working on a automated blinds/ curtains project for some time now It all works well but I would like to add the function of the Blinds gradually opening in the morning. I am reading my values from a config file and have converted the values into strings which works fine, just can't divide that value for some reason. I have tried many ways of doing this but I seem to come across errors such as- SyntaxError: can't assign to operator and TypeError: cannot concatenate 'str' and 'int' objects. Has anyone got any idea's on how I can divide a python string then use that string as a sleep value??

I am fairly new to programming (I'm 13)

from ConfigParser import SafeConfigParser
config = SafeConfigParser()

config.read('/home/pi/config.conf') #read config file
openTime = config.get('blinds', 'open time(secs)') # -> "openTime"
print 'Overall open time ' + openTime + ' seconds'

## code to divide openTime by 5 and print the value

print 'gradual open time' + DividedOpenTime + ' seconds'

## code to repeat in a loop 5 times with a sleep of the value of
## DividedOpenTime

EDIT 1

Hi again I have done what I was told to add to the code and it has solved the issue of the division and sleep time but for some reason I can't print the values. Both lines 11 and 15 have the following error:

Traceback (most recent call last):
  File "test.py", line 11, in <module>
    print 'gradual open time' + divOpenTime + ' this will repeat 5 times'
TypeError: cannot concatenate 'str' and 'float' objects

Does anyone know how I can fix this issue?

from ConfigParser import SafeConfigParser
config = SafeConfigParser()
import time

config.read('/home/pi/config.conf') #read config file
openTime = config.get('blinds', 'open time(secs)') # -> "openTime"
print 'Overall open time ' + openTime + ' seconds'

divOpenTime = float(openTime)/5 #working (:
loop = 0
print 'gradual open time' + divOpenTime + ' this will repeat 5 times'

for x in range(0, 5):
    loop += 1
    print 'gradual opening stage ' + loop + '/5'
    #GPIO true- I know how to do this
    time.sleep(divOpenTime) #working (:
    #GPIO False- I know how to do this
    time.sleep(15) #time between each interval fixed value

Thanks Ed

Body:
I worked it out

 print 'Gradual open time ' + str(divOpenTime) + ' seconds this will repeat 5
 times'

you have to add/convert your float value into a string so it can print. You do
this with:

str(Your_float_value_here)

Thanks again for all your help Ed


问:
Angular2 - Compile to AOT using absolute path in component templateUrl
I am using Angular2 and pre-compiling code using AOT.

I am able to compile code when I am using relative path in Component's templateUrl.

But compilation is failing when using absolute path in component's templateUrl

Compilation command: "node_modules/.bin/ngc" -p tsconfig-aot.json

I am getting below error while using absolute templateUrl:

Error: Compilation failed. Resource file not found: {Absolute htmlUrl
  path}
      at ModuleResolutionHostAdapter.readResource (C:\Dipendra\stash-workspace\angular2Aot\WebContent\node_modules\@angular\compiler-cli\src\compiler_host.js:291:19)
      at CompilerHost.loadResource (C:\Dipendra\stash-workspace\angular2Aot\WebContent\node_modules\@angular\compiler-cli\src\compiler_host.js:230:85)
      at Object.get (C:\Dipendra\stash-workspace\angular2Aot\WebContent\node_modules\@angular\compiler\bundles\compiler.umd.js:26374:111)
      at DirectiveNormalizer._fetch (C:\Dipendra\stash-workspace\angular2Aot\WebContent\node_modules\@angular\compiler\bundles\compiler.umd.js:13753:47)
      at DirectiveNormalizer.normalizeTemplateAsync (C:\Dipendra\stash-workspace\angular2Aot\WebContent\node_modules\@angular\compiler\bundles\compiler.umd.js:13799:25)
      at DirectiveNormalizer.normalizeTemplate (C:\Dipendra\stash-workspace\angular2Aot\WebContent\node_modules\@angular\compiler\bundles\compiler.umd.js:13771:48)
      at CompileMetadataResolver._loadDirectiveMetadata (C:\Dipendra\stash-workspace\angular2Aot\WebContent\node_modules\@angular\compiler\bundles\compiler.umd.js:18074:79)
      at C:\Dipendra\stash-workspace\angular2Aot\WebContent\node_modules\@angular\compiler\bundles\compiler.umd.js:18250:58
      at Array.forEach (native)
      at CompileMetadataResolver.loadNgModuleDirectiveAndPipeMetadata (C:\Dipendra\stash-workspace\angular2Aot\WebContent\node_modules\@angular\compiler\bundles\compiler.umd.js:18249:45)
  Compilation failed

答:
Angular AOT compiler requires the template files to be in the SAME folder as the component, even though this is not required with the JIT compiler.

It was an incredibly bad decision on the part of the designers. The answer is to redesign your entire application so that the template files are in the same folder as the component.

There are several supposed work arounds, but I am not clear if they really work. I will update this post if I am successful.


问:
Python - filter column from a .dat file and return a given value from other columns
I'm new to Python and been practicing with sample data I created (150 rows) of student ID numbers, grades, age, class_code, area_code, etc. What I'm trying to do with the data is not only filtered by a certain column (by grade, age, etc), but then to also create a list of a different column from that row (student ID). I've manged to find how to isolate the column I need to find the certain value by, but then can't figure out how to create that list of the values I need to return.

So here's a sample of 5 rows of the data:

```<code>1/A/15/13/43214
2/I/15/21/58322
3/C/17/89/68470
4/I/18/6/57362
5/I/14/4/00000
6/A/16/23/34567
</code>```

I need a list of the 1st column (student ID), based on filtering the second column (grade)...(and eventually the 3rd column, 4th column, etc. But if I see how it looks with just the 2nd, I think I can figure out the others) Also note: I didn't use headers in the .dat file.

I figured out how to isolate/view the 2nd column.

```<code>import numpy

data = numpy.genfromtxt('/testdata.dat', delimiter='/', dtype='unicode')

grades = data[:,1]
print (grades)
</code>```

to print:

```<code>['A' 'I' 'C' 'I' 'I' 'A']
</code>```

But now, how can I pull just the first column's that correspond to the A's, C's, I's into separate  lists?

So I'd want to see a list, also with the commas between the integers of column 1 for the A's, C's, and I's

```<code>list from A = [1, 6]
list from C = [3]
list from I = [2, 4, 5]
</code>```

Again, if I can just see how it's done with just the 2nd column, with just one of the values (say A's), I think I could figure out how to do it for B's, C's, D's, etc and probably the other columns. I just need to see one example to how the syntax would be applied and then like to play around with the rest.

Also, I've been using numpy, but also read about panda, csv and I think those libraries could be possibilities too. But like I said, been using numpy for the .dat files. I don't know if the other libraries would be easier to use?

答:
You can go through the list and make a boolean to select arrays matching a particular grade. This may require some refinement.</p>

```<code>import numpy as np

grades = np.genfromtxt('data.txt', delimiter='/', skip_header=0, dtype='unicode')

res = {}
for grade in set(grades[:, 1].tolist()):
    res[grade] = grades[grades[:, 1]==grade][:,0].tolist()

print res
</code>```

Body:
I'm new to Python and been practicing with sample data I created (150 rows) of student ID numbers, grades, age, class_code, area_code, etc. What I'm trying to do with the data is not only filtered by a certain column (by grade, age, etc), but then to also create a list of a different column from that row (student ID). I've manged to find how to isolate the column I need to find the certain value by, but then can't figure out how to create that list of the values I need to return.

So here's a sample of 5 rows of the data:

1/A/15/13/43214
2/I/15/21/58322
3/C/17/89/68470
4/I/18/6/57362
5/I/14/4/00000
6/A/16/23/34567

I need a list of the 1st column (student ID), based on filtering the second column (grade)...(and eventually the 3rd column, 4th column, etc. But if I see how it looks with just the 2nd, I think I can figure out the others) Also note: I didn't use headers in the .dat file.

I figured out how to isolate/view the 2nd column.

import numpy

data = numpy.genfromtxt('/testdata.dat', delimiter='/', dtype='unicode')

grades = data[:,1]
print (grades)

to print:

['A' 'I' 'C' 'I' 'I' 'A']

But now, how can I pull just the first column's that correspond to the A's, C's, I's into separate  lists?

So I'd want to see a list, also with the commas between the integers of column 1 for the A's, C's, and I's

list from A = [1, 6]
list from C = [3]
list from I = [2, 4, 5]

Again, if I can just see how it's done with just the 2nd column, with just one of the values (say A's), I think I could figure out how to do it for B's, C's, D's, etc and probably the other columns. I just need to see one example to how the syntax would be applied and then like to play around with the rest.

Also, I've been using numpy, but also read about panda, csv and I think those libraries could be possibilities too. But like I said, been using numpy for the .dat files. I don't know if the other libraries would be easier to use?

Body:
You can go through the list and make a boolean to select arrays matching a particular grade. This may require some refinement.

import numpy as np

grades = np.genfromtxt('data.txt', delimiter='/', skip_header=0, dtype='unicode')

res = {}
for grade in set(grades[:, 1].tolist()):
    res[grade] = grades[grades[:, 1]==grade][:,0].tolist()

print res


问:
How to send multiple emails from database as CC with PHPMailer?
I have a database. The fields are id, email and city. I want to send some email to all emails in my database.

In e.g case: I live in a city, so I want to send an email to all emails matchting my city.

I have wrote my method code like this:

```<code> $kota = mysql_real_escape_string(stripcslashes( $_POST['kota']));
        $baca_kota = mysql_query("SELECT email FROM conselor WHERE kota='$kota'");
        while($read = mysql_fetch_array($baca_kota))

        {

            $emailcc = $read['email'];
        }

        require '../phpmailer/PHPMailerAutoload.php';
        require '../phpmailer/class.phpmailer.php';

        $mail = new PHPMailer;
        //$mail->SMTPDebug = 3;                               // Enable verbose debug output

        $mail->isSMTP();                                      // Set mailer to use SMTP
            $mail->Host = 'xxxxxxxxxxxxxxxxxx';  // Specify main and backup SMTP servers
            $mail->SMTPAuth = true;                               // Enable SMTP authentication
            $mail->Username = 'xxxxxxxxxxxxxxx';                 // SMTP username
            $mail->Password = 'xxxxxxxxxxxxxxx';                           // SMTP password
            $mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
            $mail->Port = 465;                                    // TCP port to connect to

        $mail->setFrom($email,$name);
        $mail->addAddress('stevanlai04@gmail.com');     // Add a recipient
        $mail->addReplyTo($email);
        $mail->addCC($emailcc);
</code>```

答:
Do $mail->addCC($emailcc); inside the loop:

```<code>while ($read = mysql_fetch_array($baca_kota)) {
    $emailcc = $read['email'];
    $mail->addCC($emailcc);
}
</code>```

Body:
I have a database. The fields are id, email and city. I want to send some email to all emails in my database.

In e.g case: I live in a city, so I want to send an email to all emails matchting my city.

I have wrote my method code like this:

 $kota = mysql_real_escape_string(stripcslashes( $_POST['kota']));
        $baca_kota = mysql_query("SELECT email FROM conselor WHERE kota='$kota'");
        while($read = mysql_fetch_array($baca_kota))

        {

            $emailcc = $read['email'];
        }

        require '../phpmailer/PHPMailerAutoload.php';
        require '../phpmailer/class.phpmailer.php';

        $mail = new PHPMailer;
        //$mail->SMTPDebug = 3;                               // Enable verbose debug output

        $mail->isSMTP();                                      // Set mailer to use SMTP
            $mail->Host = 'xxxxxxxxxxxxxxxxxx';  // Specify main and backup SMTP servers
            $mail->SMTPAuth = true;                               // Enable SMTP authentication
            $mail->Username = 'xxxxxxxxxxxxxxx';                 // SMTP username
            $mail->Password = 'xxxxxxxxxxxxxxx';                           // SMTP password
            $mail->SMTPSecure = 'ssl';                            // Enable TLS encryption, `ssl` also accepted
            $mail->Port = 465;                                    // TCP port to connect to

        $mail->setFrom($email,$name);
        $mail->addAddress('stevanlai04@gmail.com');     // Add a recipient
        $mail->addReplyTo($email);
        $mail->addCC($emailcc);

Body:
Do $mail->addCC($emailcc); inside the loop:

while ($read = mysql_fetch_array($baca_kota)) {
    $emailcc = $read['email'];
    $mail->addCC($emailcc);
}


问:
In C, why this statement- 'i = 5i' compiles & sets 'i' to zero?
In GCC the following C code compiles correctly-

```<code>int i = 7;
i = 5i;
printf("%d", i);
</code>```

And prints- 0.

The statement i = 5i clearly makes no sense. Then why on earth the code does not give any compilation error? And why i becomes 0?

答:
This is a GCC extension for representing the imaginary component of complex numbers.

The compiler complains if you compile with -pedantic and -Werror: http://ideone.com/PMlZr5.

Body:
In GCC the following C code compiles correctly-

int i = 7;
i = 5i;
printf("%d", i);

And prints- 0.

The statement i = 5i clearly makes no sense. Then why on earth the code does not give any compilation error? And why i becomes 0?


问:
How to detect which dynamically created button inside a Fragment was clicked, from Activity?
I have a Fragment class that dynamically creates a grid of Buttons. An instance of that fragment is then created within the main activity which displays the grid. Here is my code:

Grid.java

```<code>public class Grid extends Fragment {

    LinearLayout myLayout;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myLayout = new LinearLayout(getActivity());
        LayoutParams lparams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        myLayout.setLayoutParams(lparams);
        myLayout.setOrientation(LinearLayout.VERTICAL);

        for (int i = 0; i < 4; i++) {
            LinearLayout row = new LinearLayout(getActivity());
            LayoutParams rowParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
            row.setLayoutParams(rowParams);

            for (int j = 0; j < 4; j++) {
                final Button btnTag = new Button(getActivity());
                LayoutParams btnParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

                btnTag.setLayoutParams(btnParams);
                btnTag.setText(" " + (j + 1 + (i * 4)));
                btnTag.setId(j + 1 + (i * 4));
                row.addView(btnTag);
            }

            myLayout.addView(row);
        }
        return myLayout;
    }
}
</code>```

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_mainactivity);
        Grid grid = new Grid();
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.add(R.id.grid, grid);
        transaction.commit();
    }
}
</code>```

And in addition here is my content_mainactivity.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/content_mainactivity"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.owner.tables.MainActivity"
    tools:showIn="@layout/activity_mainactivity">

    <FrameLayout
        android:layout_width="320dp"
        android:layout_height="320dp"
        android:id="@+id/grid"
        android:layout_centerHorizontal="true">
    </FrameLayout>

</RelativeLayout>
</code>```

So my question is, how can I detect if and which button was clicked in fragment from the Activity? Or if I can do this in the fragment, how to pass on the information to the activity?

答: Use an interface to pass the click event to your activity. Call its method inside the OnClickListener.</p>

Body:
I have a Fragment class that dynamically creates a grid of Buttons. An instance of that fragment is then created within the main activity which displays the grid. Here is my code:

Grid.java

public class Grid extends Fragment {

    LinearLayout myLayout;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myLayout = new LinearLayout(getActivity());
        LayoutParams lparams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        myLayout.setLayoutParams(lparams);
        myLayout.setOrientation(LinearLayout.VERTICAL);

        for (int i = 0; i < 4; i++) {
            LinearLayout row = new LinearLayout(getActivity());
            LayoutParams rowParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
            row.setLayoutParams(rowParams);

            for (int j = 0; j < 4; j++) {
                final Button btnTag = new Button(getActivity());
                LayoutParams btnParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

                btnTag.setLayoutParams(btnParams);
                btnTag.setText(" " + (j + 1 + (i * 4)));
                btnTag.setId(j + 1 + (i * 4));
                row.addView(btnTag);
            }

            myLayout.addView(row);
        }
        return myLayout;
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_mainactivity);
        Grid grid = new Grid();
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.add(R.id.grid, grid);
        transaction.commit();
    }
}

And in addition here is my content_mainactivity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/content_mainactivity"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.owner.tables.MainActivity"
    tools:showIn="@layout/activity_mainactivity">

    <FrameLayout
        android:layout_width="320dp"
        android:layout_height="320dp"
        android:id="@+id/grid"
        android:layout_centerHorizontal="true">
    </FrameLayout>

</RelativeLayout>

So my question is, how can I detect if and which button was clicked in fragment from the Activity? Or if I can do this in the fragment, how to pass on the information to the activity?


问:
Replace parameter into expression
Given:

```<code>var paramA = Expression.Parameter(typeof(string), "a");
</code>```

and:

```<code>Expression<Func<string, bool>> expr = b => b == "Something";
</code>```

Is there anyway to replace b by paramA into the expression expr?

答:
You can walk the expression tree of expr, and replace all occurrences of b with paramA using the approach described in this Q&A: "Combine two lambda expressions with inner expression".

However, if you simply need a lambda expression that uses paramA as its parameter, it is easier to make a lambda that wraps expr instead:

```<code>var res = (Expression<Func<string,bool>>)Expression.Lambda(
    Expression.Invoke(expr, paramA)
,   paramA
);
</code>```

Title: Replace parameter into expression

Body:
Given:

var paramA = Expression.Parameter(typeof(string), "a");

and:

Expression<Func<string, bool>> expr = b => b == "Something";

Is there anyway to replace b by paramA into the expression expr?

Body:
You can walk the expression tree of expr, and replace all occurrences of b with paramA using the approach described in this Q&A: "Combine two lambda expressions with inner expression".

However, if you simply need a lambda expression that uses paramA as its parameter, it is easier to make a lambda that wraps expr instead:

var res = (Expression<Func<string,bool>>)Expression.Lambda(
    Expression.Invoke(expr, paramA)
,   paramA
);


问:
Div bottom of div

div.div1 {
  border: 1px solid red;
  height: 100px;
}
div.div2 {
  border: 1px solid yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class = "div1">
  <div class = "div2">Test1</div>
  <div class = "div2">Test2</div>
</div></code>```

I use the above code to make a big div contain two smallers. The first one should be on the top and the second on the bottom. The top part works good but for the second div I can't make it to be on the bottom of the bigger div... What should I use?

答:
You can use position: absolute; on the second DIV, with position: relative; on the wrapper/parent and position settings as shown below.

div.div1 {
  border: 1px solid red;
  height: 100px;
  position: relative;
}
div.div2 {
  border: 1px solid yellow;
}
div.div2:nth-child(2) {
  position: absolute;
  bottom: 0;
  width: 100%;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class = "div1">
  <div class = "div2">Test1</div>
  <div class = "div2">Test2</div>
</div></code>```

Title: Div bottom of div

Body:
div.div1 {
  border: 1px solid red;
  height: 100px;
}
div.div2 {
  border: 1px solid yellow;
}

Test1

Test2

I use the above code to make a big div contain two smallers. The first one should be on the top and the second on the bottom. The top part works good but for the second div I can't make it to be on the bottom of the bigger div... What should I use?

Body:
You can use position: absolute; on the second DIV, with position: relative; on the wrapper/parent and position settings as shown below.

div.div1 {
  border: 1px solid red;
  height: 100px;
  position: relative;
}
div.div2 {
  border: 1px solid yellow;
}
div.div2:nth-child(2) {
  position: absolute;
  bottom: 0;
  width: 100%;
  }

<div class = "div1">
  <div class = "div2">Test1</div>
  <div class = "div2">Test2</div>
</div>


问:
How to draw a square with getting center points in Matlab?
I want to plot several squares defined by their center points. Here is my current code:

```<code>x1=0;
x2=1;
y1=0;
y2=1;
x = [x1, x2, x2, x1, x1];
y = [y1, y1, y2, y2, y1];
plot(x, y, 'b-', 'LineWidth', 3);
hold on;
x1=0.25;
x2=.75;
y1=0.25;
y2=.75;
x = [x1, x2, x2, x1, x1];
y = [y1, y1, y2, y2, y1];
plot(x, y, 'b-');
xlim([-1, 2]);
ylim([-1, 2]);
</code>```

I want to use this in the form:

```<code>points  = [1,4];
lengthSquare = 5;
square(points, lengthSquare);
</code>```

答:
Something like this should work. It's based on a previous answer I gave for hexagons</p>

```<code>function square( centers, sides )
h = figure(47);
close(h)
h = figure(47);

nSides = 4; % number of sides of regular polygon
rot = 0;    % rotation angle in degrees

% every polygon has the same side length?
if length(sides) == 1
    sides = sides * ones(size(centers, 1),1);
end

x0 = centers(:,1);
y0 = centers(:,2);

filledShape = true;

[x, y] = arrayfun(@(X0, Y0, S) vertexCoords(X0, Y0, S, nSides, ~filledShape, rot), x0,y0,sides, 'uni', 0);

if filledShape
    for i = 1:length(x)
        patch('Faces', 1:length(x{i}), 'Vertices', [x{i}, y{i}],'FaceColor','red')
    end

else
    T = [x, y]';
    plot(T{:},'LineWidth',2)
end

axis equal

end

function [x, y] = vertexCoords(x0, y0, s, nSides, rot, closed)
        %Need nSides+1 to close the figure.
        theta = linspace(0, 2*pi, nSides+1)' - (pi/nSides) - rot;

    if ~closed
        theta(end) = [];
    end

    % convert from side length to diameter
    D = 2*s ./ sqrt(2 - 2*cos(2*pi/nSides));

        %Convert from polar to Cartesian coordinates
        x = D/2 * cos(theta) + x0;
        y = D/2 * sin(theta) + y0;
end
</code>```

Body:
I want to plot several squares defined by their center points. Here is my current code:

x1=0;
x2=1;
y1=0;
y2=1;
x = [x1, x2, x2, x1, x1];
y = [y1, y1, y2, y2, y1];
plot(x, y, 'b-', 'LineWidth', 3);
hold on;
x1=0.25;
x2=.75;
y1=0.25;
y2=.75;
x = [x1, x2, x2, x1, x1];
y = [y1, y1, y2, y2, y1];
plot(x, y, 'b-');
xlim([-1, 2]);
ylim([-1, 2]);

I want to use this in the form:

points  = [1,4];
lengthSquare = 5;
square(points, lengthSquare);

Body:
Something like this should work. It's based on a previous answer I gave for hexagons

function square( centers, sides )
h = figure(47);
close(h)
h = figure(47);

nSides = 4; % number of sides of regular polygon
rot = 0;    % rotation angle in degrees

% every polygon has the same side length?
if length(sides) == 1
    sides = sides * ones(size(centers, 1),1);
end

x0 = centers(:,1);
y0 = centers(:,2);

filledShape = true;

[x, y] = arrayfun(@(X0, Y0, S) vertexCoords(X0, Y0, S, nSides, ~filledShape, rot), x0,y0,sides, 'uni', 0);

if filledShape
    for i = 1:length(x)
        patch('Faces', 1:length(x{i}), 'Vertices', [x{i}, y{i}],'FaceColor','red')
    end

else
    T = [x, y]';
    plot(T{:},'LineWidth',2)
end

axis equal

end

function [x, y] = vertexCoords(x0, y0, s, nSides, rot, closed)
        %Need nSides+1 to close the figure.
        theta = linspace(0, 2*pi, nSides+1)' - (pi/nSides) - rot;

    if ~closed
        theta(end) = [];
    end

    % convert from side length to diameter
    D = 2*s ./ sqrt(2 - 2*cos(2*pi/nSides));

        %Convert from polar to Cartesian coordinates
        x = D/2 * cos(theta) + x0;
        y = D/2 * sin(theta) + y0;
end


问:
Connect AWS CloudFront to Single Sign-On (SSO)
I'm working on a website deployed to AWS using S3 as storage and CloudFront CDN. It's a static website with a single html file using JS to display the content based on the querystring. The owner is an enterprise that already has established SSO within their organization, they use IBM Tivoli as the IdP. The part I'm missing is how does the request for authorization get generated?

I've read through these:

http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers.html
http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml.html
http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-idp.html
http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-idp_saml.html
http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml.html
http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml_relying-party.html

Many of these are close but just off the mark. It's not an EC2 instance, it's not Elastic Beanstalk, I'm not trying access the AWS console, and they don't use AD for SSO. It's just a website.

So far I have:

created the SAML provider in AWS and imported the metadata from their IdP

created the IAM role

established the trust relationship between role and provider

established the s3:getObject permission for the role

provided them with the metadata from AWS with the specifics about the SAML assertions that need to be provided.

My question is how the two sides get connected. Is it automatically done by AWS when anyone attempts to access the site? Does the enterprise create a special link in their portal to start the site with the SAML? What happens if the user just types in the domain name in the browser? Does code need to be added to the website?

TIA,
Mike

答:
Circling back to close out this question. I found that AWS doesn't have a way to add an SSO layer to your CloudFront hosted website. That needs to be implemented within the website's code.

I wound up using the npm module 'express-saml' to handle the saml exchange and a really simple DynamoDB table for storing the login on the SP side. The aws-sdk is used for DynamoDB.

Mike


问:
bash: oneliner to convert hex numbers in output to decimals
Does anyone know of a oneliner into which some output can be piped into in bash, to match and convert all occurrences of hexadecimal numbers and leave all other text untouched?

maybe match rather arbitrary output which could be a hexadecimal
shall somehow converted through a regexp, i.e.
/(0x)?[0-9a-fA-F]{5,}/

a leading 0x shall not be neccessary, but
also be handled properly

there can be false-positives, if not
specifying a minimum length of the numbers, but that should not be an
issue

the goal is to find solution which can be used with as much possible outputs having hex numbers in them

It should work on output like:

```<code>ssg sjas # cat /proc/net/stat/arp_cache | column -t
entries   allocs    destroys  hash_grows  lookups   hits      res_failed  rcv_probes_mcast  rcv_probes_ucast  periodic_gc_runs  forced_gc_runs  unresolved_discards  table_fulls
0000000d  00000006  00000004  00000000    0000c3b9  0000c35e  00000000    00000000          00000000          0000965b          00000000        00000000             00000000
0000000d  0000000d  00000004  00000001    00000000  00000000  00000000    00000000          00000000          000007cd          00000000        00000000             00000000
0000000d  00000008  00000008  00000001    00000000  00000000  00000000    00000000          00000000          000006e0          00000000        00000000             00000000
0000000d  0000000a  00000008  00000000    00000000  00000000  00000002    00000000          00000000          00000704          00000000        00000000             00000000
</code>```

Most other questions on stackoverflow only tackle the issue of how to convert single numbers between number systems, only do the conversion for a specified column or completely kill the formatting being present in the input.

Desired output should look like: (column -t is there anyway, it really just need to replace the hex values it can find, and adding leading zeroes to a printf statement is also not a problem)

```<code>ssg sjas # cat /proc/net/stat/arp_cache | perl -pe 's/(?:0x)?[0-9a-f]{5,}/hex($&)/ge' | column -t
entries  allocs  destroys  hash_grows  lookups  hits   res_failed  rcv_probes_mcast  rcv_probes_ucast  periodic_gc_runs  forced_gc_runs  unresolved_discards  table_fulls
13       6       4         0           50105    50014  0           0                 0                 38491             0               0                    0
13       13      4         1           0        0      0           0                 0                 1997              0               0                    0
13       8       8         1           0        0      0           0                 0                 1760              0               0                    0
13       10      8         0           0        0      2           0                 0                 1796              0               0                    0
</code>```

I could not find a short viable/reliable solution via sed/awk/perl in the last two hours, so I came here for help.

答:
With mawk: for every row but first row (NR!=1) loop from first to last column (NF) and convert current column ($i) from hex to decimal.

```<code>mawk 'NR!=1 {for (i=1; i<=NF; i++) $i=sprintf("%d ","0x"$i)}1' file | column -t
</code>```

Output:

```
entries  allocs  destroys  hash_grows  lookups  hits   res_failed  rcv_probes_mcast  rcv_probes_ucast  periodic_gc_runs  forced_gc_runs  unresolved_discards  table_fulls
13       6       4         0           49696    49605  0           0                 0                 38201             0               0                    0
13       13      4         1           0        0      0           0                 0                 1984              0               0                    0
13       8       8         1           0        0      0           0                 0                 1752              0               0                    0
13       10      8         0           0        0      2           0                 0                 1775              0               0                    0
```

Body:
Does anyone know of a oneliner into which some output can be piped into in bash, to match and convert all occurrences of hexadecimal numbers and leave all other text untouched?

maybe match rather arbitrary output which could be a hexadecimal
shall somehow converted through a regexp, i.e.
/(0x)?[0-9a-fA-F]{5,}/

a leading 0x shall not be neccessary, but
also be handled properly

there can be false-positives, if not
specifying a minimum length of the numbers, but that should not be an
issue

the goal is to find solution which can be used with as much possible outputs having hex numbers in them

It should work on output like:

ssg sjas # cat /proc/net/stat/arp_cache | column -t
entries   allocs    destroys  hash_grows  lookups   hits      res_failed  rcv_probes_mcast  rcv_probes_ucast  periodic_gc_runs  forced_gc_runs  unresolved_discards  table_fulls
0000000d  00000006  00000004  00000000    0000c3b9  0000c35e  00000000    00000000          00000000          0000965b          00000000        00000000             00000000
0000000d  0000000d  00000004  00000001    00000000  00000000  00000000    00000000          00000000          000007cd          00000000        00000000             00000000
0000000d  00000008  00000008  00000001    00000000  00000000  00000000    00000000          00000000          000006e0          00000000        00000000             00000000
0000000d  0000000a  00000008  00000000    00000000  00000000  00000002    00000000          00000000          00000704          00000000        00000000             00000000

Most other questions on stackoverflow only tackle the issue of how to convert single numbers between number systems, only do the conversion for a specified column or completely kill the formatting being present in the input.

Desired output should look like: (column -t is there anyway, it really just need to replace the hex values it can find, and adding leading zeroes to a printf statement is also not a problem)

ssg sjas # cat /proc/net/stat/arp_cache | perl -pe 's/(?:0x)?[0-9a-f]{5,}/hex($&)/ge' | column -t
entries  allocs  destroys  hash_grows  lookups  hits   res_failed  rcv_probes_mcast  rcv_probes_ucast  periodic_gc_runs  forced_gc_runs  unresolved_discards  table_fulls
13       6       4         0           50105    50014  0           0                 0                 38491             0               0                    0
13       13      4         1           0        0      0           0                 0                 1997              0               0                    0
13       8       8         1           0        0      0           0                 0                 1760              0               0                    0
13       10      8         0           0        0      2           0                 0                 1796              0               0                    0

I could not find a short viable/reliable solution via sed/awk/perl in the last two hours, so I came here for help.

Body:
With mawk: for every row but first row (NR!=1) loop from first to last column (NF) and convert current column ($i) from hex to decimal.

mawk 'NR!=1 {for (i=1; i<=NF; i++) $i=sprintf("%d ","0x"$i)}1' file | column -t

Output:

entries  allocs  destroys  hash_grows  lookups  hits   res_failed  rcv_probes_mcast  rcv_probes_ucast  periodic_gc_runs  forced_gc_runs  unresolved_discards  table_fulls
13       6       4         0           49696    49605  0           0                 0                 38201             0               0                    0
13       13      4         1           0        0      0           0                 0                 1984              0               0                    0
13       8       8         1           0        0      0           0                 0                 1752              0               0                    0
13       10      8         0           0        0      2           0                 0                 1775              0               0                    0


问:
Tic Tac Toe AI does 2+ moves at the same time to block
I have this tic tac toe game:

```<code>import random
boardX = int(raw_input("How many X boards do you want? > "))
boardY = int(raw_input("How many Y boards do you want? > "))
Matrix = [[0-0 for x in range(boardX)] for y in range(boardY)]
Matrix_2 = [[" "for x in range(boardX)] for y in range(boardY)]
l = len(Matrix)

def turnX():
    global Player1_row
    global Player1_column
    Player1_row = int(raw_input("P1 What row do you want?"))
    Player1_row = Player1_row - 1
    Player1_column = int(raw_input("P1 What column do you want?"))
    Player1_column = Player1_column - 1
    if Player1_row > boardX:
        turnX()
    if Player1_column > boardY:
        turnX()
    if (1 == Matrix[Player1_column][Player1_row] or 500 == Matrix[Player1_column][Player1_row]):
        print "This is an invaild move!"
        turnX()
    else:
        Matrix[Player1_column][Player1_row] = 1
        Matrix_2[Player1_column][Player1_row] = "X"

def turnY():
    Player2_row = random.randint(1, boardX)
    Player2_column = random.randint(1, boardY)
    Player2_column = Player2_column - 1
    Player2_row = Player2_row - 1
    if (1 == Matrix[Player2_column][Player2_row] or 500 == Matrix[Player2_column][Player2_row]):
      turnY()
    print "AI Turn:"
    if result[e] == boardY - 1 * 500:
      Matrix[Player1_column - 1][Player1_row] = 500
      Matrix_2[Player1_column - 1][Player1_row] = "O"
    if Player1_column == boardY - 1:
      Matrix[Player1_column][Player1_row - 1] = 500
      Matrix_2[Player1_column][Player1_row - 1] = "O"
    if Player1_column != boardY - 1:
      Matrix[Player2_column][Player2_row] = 500
      Matrix_2[Player2_column][Player2_row] = "O"

def printArray(boardX, boardY):
    for i in range(boardX):
        print ""
        print boardY * "  _    "
        for j in range(boardY):
            print "|", Matrix_2[i][j],"| ",
    print ""
    print boardY * "  _    "
win = False

def win_condition():
      global Row
      global result
      global diagonal1
      global diagonal2
      global e
      #Row
      row = [sum(row) for row in Matrix]
    #Column
      result = [sum(row[i] for row in Matrix) for i in range(len(Matrix[0]))]

    #Diagonal
      diagonal1 = [sum(Matrix[i][i] for i in range(l))]
      diagonal2 = [sum(Matrix[l-1-i][i] for i in range(l-1,-1,-1))]

    #Column

      result = [sum(row[i] for row in Matrix) for i in range(len(Matrix[0]))]
      for h in range(0, boardX):
        if row[h] == boardX * 500:
          print "The AI won! Row!"
          win = True
          printArray(boardX, boardY)
          quit()
        if row[h] == boardX:
          print "Player 1 won! Row!"
          win = True
          printArray(boardX, boardY)
          quit()

        for e in range(0, boardY):
          if result[e] == boardY * 500:
            print "The AI won! Column!"
            win = True
            printArray(boardX, boardY)
            quit()
          if result[e] == boardY:
            print "Player 1 won! Column!"
            win = True
            printArray(boardX, boardY)
            quit()
      if diagonal1[0] == boardY:
        print "Player 1 Won! Diagonal!"
        win = True
        printArray(boardX, boardY)
        quit()
      if diagonal1[0] == boardY * 500:
        print "The AI won! Diagonal!"
        win = True
        printArray(boardX, boardY)
        quit()
      if diagonal2[0] == boardY:
        print "Player 1 Won! Diagonal!"
        win = True
        printArray(boardX, boardY)
        quit()
      if diagonal2[0]== boardY * 500:
        print "The AI won! Diagonal!"
        win = True
        printArray(boardX, boardY)
        quit()

while win == False:
      win_condition()
      turnX()
      win_condition()
      printArray(boardX, boardY)
      win_condition()
      turnY()
      win_condition()
      printArray(boardX, boardY)
</code>```

But when my input was this, it did 2 turn because the AI wanted to block all of my positions.

Is there a way that I can fix it?

Is there a way to make the AI try to win, and then make him block?

答:
Write return after recursively calling turnX or turnY.

Edit: Or put the rest of the function in an else-block or put the testing of the input in a while loop.

Body:
I have this tic tac toe game:

import random
boardX = int(raw_input("How many X boards do you want? > "))
boardY = int(raw_input("How many Y boards do you want? > "))
Matrix = [[0-0 for x in range(boardX)] for y in range(boardY)]
Matrix_2 = [[" "for x in range(boardX)] for y in range(boardY)]
l = len(Matrix)

def turnX():
    global Player1_row
    global Player1_column
    Player1_row = int(raw_input("P1 What row do you want?"))
    Player1_row = Player1_row - 1
    Player1_column = int(raw_input("P1 What column do you want?"))
    Player1_column = Player1_column - 1
    if Player1_row > boardX:
        turnX()
    if Player1_column > boardY:
        turnX()
    if (1 == Matrix[Player1_column][Player1_row] or 500 == Matrix[Player1_column][Player1_row]):
        print "This is an invaild move!"
        turnX()
    else:
        Matrix[Player1_column][Player1_row] = 1
        Matrix_2[Player1_column][Player1_row] = "X"

def turnY():
    Player2_row = random.randint(1, boardX)
    Player2_column = random.randint(1, boardY)
    Player2_column = Player2_column - 1
    Player2_row = Player2_row - 1
    if (1 == Matrix[Player2_column][Player2_row] or 500 == Matrix[Player2_column][Player2_row]):
      turnY()
    print "AI Turn:"
    if result[e] == boardY - 1 * 500:
      Matrix[Player1_column - 1][Player1_row] = 500
      Matrix_2[Player1_column - 1][Player1_row] = "O"
    if Player1_column == boardY - 1:
      Matrix[Player1_column][Player1_row - 1] = 500
      Matrix_2[Player1_column][Player1_row - 1] = "O"
    if Player1_column != boardY - 1:
      Matrix[Player2_column][Player2_row] = 500
      Matrix_2[Player2_column][Player2_row] = "O"

def printArray(boardX, boardY):
    for i in range(boardX):
        print ""
        print boardY * "  _    "
        for j in range(boardY):
            print "|", Matrix_2[i][j],"| ",
    print ""
    print boardY * "  _    "
win = False

def win_condition():
      global Row
      global result
      global diagonal1
      global diagonal2
      global e
      #Row
      row = [sum(row) for row in Matrix]
    #Column
      result = [sum(row[i] for row in Matrix) for i in range(len(Matrix[0]))]

    #Diagonal
      diagonal1 = [sum(Matrix[i][i] for i in range(l))]
      diagonal2 = [sum(Matrix[l-1-i][i] for i in range(l-1,-1,-1))]

    #Column

      result = [sum(row[i] for row in Matrix) for i in range(len(Matrix[0]))]
      for h in range(0, boardX):
        if row[h] == boardX * 500:
          print "The AI won! Row!"
          win = True
          printArray(boardX, boardY)
          quit()
        if row[h] == boardX:
          print "Player 1 won! Row!"
          win = True
          printArray(boardX, boardY)
          quit()

        for e in range(0, boardY):
          if result[e] == boardY * 500:
            print "The AI won! Column!"
            win = True
            printArray(boardX, boardY)
            quit()
          if result[e] == boardY:
            print "Player 1 won! Column!"
            win = True
            printArray(boardX, boardY)
            quit()
      if diagonal1[0] == boardY:
        print "Player 1 Won! Diagonal!"
        win = True
        printArray(boardX, boardY)
        quit()
      if diagonal1[0] == boardY * 500:
        print "The AI won! Diagonal!"
        win = True
        printArray(boardX, boardY)
        quit()
      if diagonal2[0] == boardY:
        print "Player 1 Won! Diagonal!"
        win = True
        printArray(boardX, boardY)
        quit()
      if diagonal2[0]== boardY * 500:
        print "The AI won! Diagonal!"
        win = True
        printArray(boardX, boardY)
        quit()

while win == False:
      win_condition()
      turnX()
      win_condition()
      printArray(boardX, boardY)
      win_condition()
      turnY()
      win_condition()
      printArray(boardX, boardY)

But when my input was this, it did 2 turn because the AI wanted to block all of my positions.

Is there a way that I can fix it?

Is there a way to make the AI try to win, and then make him block?


答:
What are you really trying to achieve

you need to be able to always control your divs so make sure you always define them better

```<code>div.div1 {
 border: 1px solid red;
 height: 100px;
}
div.div2 {
 border: 1px solid yellow;
 width:100px;
min-height: 10 px;
float:left;
}

<div class = "div1">
  <div class = "div2">Test1</div>
  <div class = "div2">Test2</div>
</div>
</code>```

since your div one does not define its own space you dont know what the bottom is . so you can add clear property to make sure anything you put above div 2 is cleared.

Good luck

Title: Div bottom of div

Body:
What are you really trying to achieve

you need to be able to always control your divs so make sure you always define them better

div.div1 {
 border: 1px solid red;
 height: 100px;
}
div.div2 {
 border: 1px solid yellow;
 width:100px;
min-height: 10 px;
float:left;
}

<div class = "div1">
  <div class = "div2">Test1</div>
  <div class = "div2">Test2</div>
</div>

since your div one does not define its own space you dont know what the bottom is . so you can add clear property to make sure anything you put above div 2 is cleared.

Good luck


问:
Should data go in a redux state tree?
I am a bit lost on what to keep in the state tree of Redux.

I saw two conflicting statements on what to store in the state tree(s).

React doc tell us that only user input should be stored in state trees.

The original list of products is passed in as props, so that's not state. The search text and the checkbox seem to be state since they change over time and can't be computed from anything. And finally, the filtered list of products isn't state because it can be computed by combining the original list of products with the search text and value of the checkbox.

Redux doc tells us that we often should store UI state and data in the single state tree:

For our todo app, we want to store two different things:

The currently selected visibility filter;

The actual list of todos.

You’ll often find that you need to store some data, as well as some UI state**, in the state tree. This is fine, but try to keep the data separate from the UI state.

So React tells that we should not store data (I am talking about data of the todos) and, for me, Redux tells the opposite.

In my understand I would tend on the React side because both React and Redux aims to predict a UI state by storing:

all what can't be computed (eg: all human inputs) and are part of the UI:

checkbox value

input value

radio value

...

All minimal data that could be use to build a query and send it to the API/database that will return the complete user profil, friends lists, whatever...:

user Id

creation dates range

items Ids

...

For me that excludes all database/API results because:

that stands on data level

could be computed by sending the right (and computed by pure reducers) query.

So what is your opinion here?

答:
I feel that the problem is that originally Redux was pushed really hard, and some people were so purists, that they argued for separating everything to Redux and re-rendering the whole application on every change. And then we ended up with this response of the creator, which actually only added a confusion, because redux was and still is a de-facto standard for new react applications, and a lot of tutorials assume it.

So, I feel that people are pressured from each side, and often they do some things without real understanding why they should (especially newcomers creating constants, actions and reducers). So, for those who read it, please start without redux, and keep it just in local state (but try to keep in some component like DataContainer).
For those who need redux, rule thumb is to put all async data (so all requests go through redux), and data which is needed for independent components. If components obviously located nearby, keep it in a local state and pass as props.

Redux is a very helpful library, but it's power is needed only after you start to have at least several routes, different query options and some complex UI. Before that there is a good chance that you are overengineering (but, of course, if you are sure that you will exceed this size, feel free to start with Redux). And again, you'll literally never will want to put your slider or small dropdown position in the store -- react's state serves perfectly for it.

Title: Should data go in a redux state tree?


问:
sql case statement IN with group by
I have a 2 column table with the columns : "user_name" and "characteristic".   Each user_name may appear multiple times with a different characteristic.

The values in characteristic are:

Online

Instore

Account

Email

I want to write a sql statement that goes like this - but obviously this isn't working:

```<code>SELECT user_name,
       case
          when characteristic in ("online","instore") then 1
          else 0
       END as purchase_yn,
       case
          when characteristic in ("online","instore") and
               characteristic in ("email",'account')   then 1
          else 0
       END as   purchaser_with_account
 FROM my_table
 GROUP BY user_name;
</code>```

Essentially the first is a flag where I check for the presence of either value for that user_name.
The Second field  is that they  meet this criteria AND that they meet the criteria for having either 'email' or 'account'

答:
If I correctly understand, if user have 'online' or 'instore', then for this user you want 1 as purchase_yn column, and if user also have  'email' or 'account', then 1 as purchaser_with_account column.

If this is correct, then one way is:

```<code>with your_table(user_name, characteristic) as(
    select 1, 'online' union all
    select 1, 'instore' union all
    select 1, 'account' union all
    select 1, 'email' union all
    select 2, 'account' union all
    select 2, 'email' union all
    select 3, 'online'
)

-- below is actual query:

select your_table.user_name, coalesce(max(t1.purchase_yn), 0) as purchase_yn, coalesce(max(t2.purchaser_with_account), 0) as purchaser_with_account
from your_table
left join (SELECT user_name, 1 as purchase_yn from your_table where characteristic in('online','instore') ) t1
on your_table.user_name = t1.user_name
left join (SELECT user_name, 1 as purchaser_with_account  from your_table where characteristic in('email', 'account') ) t2
on t1.user_name = t2.user_name
group by your_table.user_name
</code>```

Title: sql case statement IN with group by

Body:
I have a 2 column table with the columns : "user_name" and "characteristic".   Each user_name may appear multiple times with a different characteristic.

The values in characteristic are:

Online

Instore

Account

Email

I want to write a sql statement that goes like this - but obviously this isn't working:

SELECT user_name,
       case
          when characteristic in ("online","instore") then 1
          else 0
       END as purchase_yn,
       case
          when characteristic in ("online","instore") and
               characteristic in ("email",'account')   then 1
          else 0
       END as   purchaser_with_account
 FROM my_table
 GROUP BY user_name;

Essentially the first is a flag where I check for the presence of either value for that user_name.
The Second field  is that they  meet this criteria AND that they meet the criteria for having either 'email' or 'account'

Body:
If I correctly understand, if user have 'online' or 'instore', then for this user you want 1 as purchase_yn column, and if user also have  'email' or 'account', then 1 as purchaser_with_account column.

If this is correct, then one way is:

with your_table(user_name, characteristic) as(
    select 1, 'online' union all
    select 1, 'instore' union all
    select 1, 'account' union all
    select 1, 'email' union all
    select 2, 'account' union all
    select 2, 'email' union all
    select 3, 'online'
)

-- below is actual query:

select your_table.user_name, coalesce(max(t1.purchase_yn), 0) as purchase_yn, coalesce(max(t2.purchaser_with_account), 0) as purchaser_with_account
from your_table
left join (SELECT user_name, 1 as purchase_yn from your_table where characteristic in('online','instore') ) t1
on your_table.user_name = t1.user_name
left join (SELECT user_name, 1 as purchaser_with_account  from your_table where characteristic in('email', 'account') ) t2
on t1.user_name = t2.user_name
group by your_table.user_name


问:
Is there a standard function for "do this if Just x"?
I have the following code:

```<code>doIf :: (a -> IO ()) -> Maybe a -> IO ()
doIf f x = case x of
  Just i -> f i
  Nothing -> return ()

main = do
  mapM_ (doIf print) [Just 3, Nothing, Just 4]
</code>```

which outputs:

```<code>3
4
</code>```

In other words, the Just values are printed, but Nothing values cause no action.  (And do not interrupt computation.)

Is there a standard function like this in the Haskell libraries?  Also, can this be made more generic?  I tried replacing IO () with m b but then return () does not work.  How do you generically write return () for any monad? (If possible..)  Can even the Maybe be generalized here?

Lastly, can I do away with the doIf function entirely?  Can I have an operator <#> that applies an argument unless Nothing?

```<code>print <#> Just 3
print <#> Nothing
</code>```

would output

```<code>3
</code>```

But I don't know if this is possible.

答:
Your doIf is a special case of Data.Foldable.traverse_.

You can usually find this sort of thing through Hoogle, but it seems to be a little broken at the moment.  The command-line version I have installed on my system gives Data.Foldable.traverse_ as the first result for the query (a -> IO ()) -> Maybe a -> IO ().

And sure, you can define that operator, it's just (<#>) = doIf (or (<#>) = Data.Foldable.traverse_).

Body:
I have the following code:

doIf :: (a -> IO ()) -> Maybe a -> IO ()
doIf f x = case x of
  Just i -> f i
  Nothing -> return ()

main = do
  mapM_ (doIf print) [Just 3, Nothing, Just 4]

which outputs:

3
4

In other words, the Just values are printed, but Nothing values cause no action.  (And do not interrupt computation.)

Is there a standard function like this in the Haskell libraries?  Also, can this be made more generic?  I tried replacing IO () with m b but then return () does not work.  How do you generically write return () for any monad? (If possible..)  Can even the Maybe be generalized here?

Lastly, can I do away with the doIf function entirely?  Can I have an operator <#> that applies an argument unless Nothing?

print <#> Just 3
print <#> Nothing

would output

3

But I don't know if this is possible.