问:
C string arrays

Possible Duplicates:

  string literal in c

  Assigning strings to arrays of characters

I got the following code:

```<code>char result[3][4];

result[0] = "horse";
result[1] = "pig";
result[2] = "chicken";
</code>```

It won't compile saying Incompatible types in assignment. What am I doing wrong?

答: This will not work because result declared as char result[3][4] and used as result[0] will result in something similar with: char * const result. Constant pointer doesn't admit any assignment, it already contains pointer to the array of columns "[4]".

Title: C string arrays

Body:
Possible Duplicates:

  string literal in c

  Assigning strings to arrays of characters

I got the following code:

char result[3][4];

result[0] = "horse";
result[1] = "pig";
result[2] = "chicken";

It won't compile saying Incompatible types in assignment. What am I doing wrong?


来源: stackexchange

问:
fire fox 57.0.1 (64-bit) hangs when accessing paypal on windows 7
I am working on a charity website which receives donations via paypal. Just the standard donation form button. It works fine on chrome, IE, Safari, Opera, but seems to be hanging in Firefox latest version. You click the button get the revolving 'please wait' message but in FF it never takes you to the actual paypal donation screen. Just seems to be firefox with the issue.

I have used firefox for years but have to admit the latest version 57.0.1 on windows 7 seems really buggy. No paypal pages work on it. Even the w3c and other sites hang.

So I performed a firefox reset/refresh from inside firefox control panel. To my amazement after rebooting the donation page finally worked. Thought I had solved issue. But then I closed/re-opened FF to perform same test and again it freezes on 'Please wait' screen.

Then I uninstalled FF completely, re-downloaded/installed - again the donation screen worked first time but not the second. Can't really give exact URL because its private client work but any paypal checkout seems to hang in latest version of FF. My client gets same issue. Can anyone help?

答:
There does appear to be a clash with some anti-virus software and the latest release of Firefox: https://support.mozilla.org/en-US/kb/firefox-startup-crash-g-data-security-software

I would suggest whitelisting the Firefox application in your AV software if necessary until firefox address the issue.

ContentLicense: CC BY-SA 3.0


问:
Pandas dataframe.resample std on certain columns only?
I am trying to calculate monthly standard deviations for my data.

My data is loaded from a database into a dataframe with the following columns:

```<code>measurement_time, level, mixing_ratio, concentration
</code>```

To calculate the monthly standard deviations, I do the following:

```<code>    df_std = df_std.set_index('measurement_time')
    df_std = df_std.groupby(['level'], as_index=False)
    df_std = df_std.resample('M').std()
</code>```

The result is:

```<code>>> df_std.head()
                    level  mixing_ratio  concentration
  measurement_time
0 2016-01-31          0.0  3.435376e-11       0.000015
  2016-02-29          0.0  2.692636e-11       0.000012
  2016-03-31          0.0  6.709993e-11       0.000029
  2016-04-30          0.0  3.338249e-11       0.000014
  2016-05-31          0.0  3.916523e-11       0.000017
</code>```

The problem is that it is calculating the standard deviation on the level, too, while I only want the calculation performed on mixing_ratio & concentration

The result should be the monthly standard deviations at each level. If I had 7 levels, I would expect my dataframe to have 84 rows (7 * 12 months).

How can I fix this?

答:
When you resample you have to do something with the aggregated data.

Example of different functions for different columns:

```<code>df_resample = df_std.resample('M').agg({'level': np.mean, 'mixing_ratio': np.std, 'concentration':np.std})
</code>```

Other option is to groupby time and level.

Body:
I am trying to calculate monthly standard deviations for my data.

My data is loaded from a database into a dataframe with the following columns:

measurement_time, level, mixing_ratio, concentration

To calculate the monthly standard deviations, I do the following:

    df_std = df_std.set_index('measurement_time')
    df_std = df_std.groupby(['level'], as_index=False)
    df_std = df_std.resample('M').std()

The result is:

>> df_std.head()
                    level  mixing_ratio  concentration
  measurement_time
0 2016-01-31          0.0  3.435376e-11       0.000015
  2016-02-29          0.0  2.692636e-11       0.000012
  2016-03-31          0.0  6.709993e-11       0.000029
  2016-04-30          0.0  3.338249e-11       0.000014
  2016-05-31          0.0  3.916523e-11       0.000017

The problem is that it is calculating the standard deviation on the level, too, while I only want the calculation performed on mixing_ratio & concentration

The result should be the monthly standard deviations at each level. If I had 7 levels, I would expect my dataframe to have 84 rows (7 * 12 months).

How can I fix this?

Body:
When you resample you have to do something with the aggregated data.

Example of different functions for different columns:

df_resample = df_std.resample('M').agg({'level': np.mean, 'mixing_ratio': np.std, 'concentration':np.std})

Other option is to groupby time and level.


问:
How to set different permissions for directories and files using umask and fuse
I use fuse to mount some directories on Ubuntu. The user should have rwx on directories and rw- on files.

Now doing this with setfacl is quite easy. Doing setfacl -R -d -m u::rwX,g::rwX,o::--- dir/ does the job perfectly fine.

But how to do this with umask?

答:
What you should know about umask first is that umask is a mask; it is not a number to be subtracted.
It turns off permissions that would normally be granted.
Masking is not the same as subtracting, e.g. 666 masked with 001 is still 666 and 666 masked with 003 is 664.
The mask turns off permission bits. If they are already off, the umask makes no change.

Make sure you are in the directory you wanna assign permissions to and do the following:

this link answers exactly what you're looking for!

https://www.cyberciti.biz/tips/understanding-linux-unix-umask-value-usage.html

hope this helps.


问:
Rails 3, update linked model in controller on record creation
In my rails app I have the Posts Model, which has_many Comments.

Everytime a new comment is posted, I'd like the updated_at column in the Posts model to be updated.

I assume I need to do this in the create method of the Comments controller.

Does anyone have some idea of the specific way to do this?

```<code>   @post = Post.find_by_id(@comment.post_id)
   @post.save!
</code>```

Did not work.

Thanks!

-Elliot

答:
You can use the :touch awesomess to update the updated_at

So if you have

```<code>class Post
  has_many :comments
end

class Comment
  belongs_to :post, :touch=>true
end
</code>```

Then when you save a comment, it will touch the post and update the updated_at.

More infos:

SO Question

Rails Doc

Blog Post

ContentLicense: CC BY-SA 2.5

Body:
In my rails app I have the Posts Model, which has_many Comments.

Everytime a new comment is posted, I'd like the updated_at column in the Posts model to be updated.

I assume I need to do this in the create method of the Comments controller.

Does anyone have some idea of the specific way to do this?

   @post = Post.find_by_id(@comment.post_id)
   @post.save!

Did not work.

Thanks!

-Elliot

Body:
You can use the :touch awesomess to update the updated_at

So if you have

class Post
  has_many :comments
end

class Comment
  belongs_to :post, :touch=>true
end

Then when you save a comment, it will touch the post and update the updated_at.

More infos:

SO Question

Rails Doc

Blog Post


问:
Error bars in different colors with matplotlib
I have the following code, that produces a simple graph with both vertical and horizontal error bars:

```<code>#!/usr/bin/python
# -*- coding: utf-8 -*-

import pylab as pl
import matplotlib.pyplot as plt

x=[2,3]
error_x=[0.5,0.4]
y=[25,28]
error_y=[0.6,0.8]
lines={'linestyle': 'None'}
plt.rc('lines', **lines)
pl.plot(x, y, 'ro', markersize=6)
pl.errorbar(x, y, xerr=error_x, yerr=error_y, fmt='b')
pl.xlim(1.3,3.6)
pl.ylim(24.0,29.0)
pl.show()
</code>```

However, both error bars (vertical and horizontal) are blue, and I don't see how I could specify different colors for both of them. Is this possible? I would like, for example, for all horizontal error bars to be blue and for all vertical error bars to be green.

答:
Use ecolor keyword:

```<code>import pylab as pl
import matplotlib.pyplot as plt

x=[2,3]
error_x=[0.5,0.4]
y=[25,28]
error_y=[0.6,0.8]
lines={'linestyle': 'None'}
plt.rc('lines', **lines)
pl.plot(x, y, 'ro', markersize=6)
el = pl.errorbar(x, y, xerr=error_x, yerr=error_y, fmt='b', ecolor='yellow')
pl.xlim(1.3,3.6)
pl.ylim(24.0,29.0)
pl.show()
</code>```

Output:

Different color lines, per bar and per orientation:

```<code>import pylab as pl
import matplotlib.pyplot as plt

x=[2,3]
error_x=[0.5,0.4]
y=[25,28]
error_y=[0.6,0.8]
lines={'linestyle': 'None'}
plt.rc('lines', **lines)
pl.plot(x, y, 'ro', markersize=6)
el = pl.errorbar(x, y, xerr=error_x, yerr=error_y, fmt='b', ecolor=['yellow','blue'])
elines = el.get_children()
elines[1].set_color('green')
pl.xlim(1.3,3.6)
pl.ylim(24.0,29.0)
pl.show()
</code>```

Output:

Body:
I have the following code, that produces a simple graph with both vertical and horizontal error bars:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import pylab as pl
import matplotlib.pyplot as plt

x=[2,3]
error_x=[0.5,0.4]
y=[25,28]
error_y=[0.6,0.8]
lines={'linestyle': 'None'}
plt.rc('lines', **lines)
pl.plot(x, y, 'ro', markersize=6)
pl.errorbar(x, y, xerr=error_x, yerr=error_y, fmt='b')
pl.xlim(1.3,3.6)
pl.ylim(24.0,29.0)
pl.show()

However, both error bars (vertical and horizontal) are blue, and I don't see how I could specify different colors for both of them. Is this possible? I would like, for example, for all horizontal error bars to be blue and for all vertical error bars to be green.

Body:
Use ecolor keyword:

import pylab as pl
import matplotlib.pyplot as plt

x=[2,3]
error_x=[0.5,0.4]
y=[25,28]
error_y=[0.6,0.8]
lines={'linestyle': 'None'}
plt.rc('lines', **lines)
pl.plot(x, y, 'ro', markersize=6)
el = pl.errorbar(x, y, xerr=error_x, yerr=error_y, fmt='b', ecolor='yellow')
pl.xlim(1.3,3.6)
pl.ylim(24.0,29.0)
pl.show()

Output:

Different color lines, per bar and per orientation:

import pylab as pl
import matplotlib.pyplot as plt

x=[2,3]
error_x=[0.5,0.4]
y=[25,28]
error_y=[0.6,0.8]
lines={'linestyle': 'None'}
plt.rc('lines', **lines)
pl.plot(x, y, 'ro', markersize=6)
el = pl.errorbar(x, y, xerr=error_x, yerr=error_y, fmt='b', ecolor=['yellow','blue'])
elines = el.get_children()
elines[1].set_color('green')
pl.xlim(1.3,3.6)
pl.ylim(24.0,29.0)
pl.show()

Output:


问:
properties of :hover table rows don't revert to their pre-:hover state
I'm trying to highlight rows of a table on hover with a 2px border. To prevent cells from shifting they're given a 4px padding if not selected and not hovered, 2px border and 2px padding if hovered, and a 4px border if selected.

The code can be found in this JS Fiddle or pasted below.

```<code>td {
  padding: 6px 10px;
  text-align: center;
  border-bottom: 1px solid #E1E1E1;
  font-size: 1.3rem; }

table {
  border-collapse: collapse;
}

tr {
   padding: 4px;
}
tr.selected {
   border: 4px solid black; }
tr.selected td:first-child {
   padding-left : 8px; }
tr.selected td:last-child {
   padding-right : 8px; }

tr.notselected {
     border: 0px solid black;
     padding: 4px;}

tr.notselected:hover td:first-child {
   padding-left : 9px; }
tr.notselected:hover td:last-child {
   padding-right : 9px; }
tr.notselected:hover {
   border: 2px solid black;
   padding: 2px; }
</code>```

    Header 1
    Header 2

    Subheader 1.1
    Subheader 1.2
    Subheader 2.1
    Subheader 2.2

    Row 1
    10.1
    10.6
    9.1
    9.4

    Row 2
    12.9
    11.3
    10.1
    10.5

    Row 3

    8.7
    8.8

```

Instead of remaining static, the borders and contents of the rows below the hovered row shift down, remain shifted down after the row is un-hovered, but shift back up after a second hover on hover off.

答:
I would use CSS outlines instead of the borders/padding combination you have to prevent the rows shifting like in this fork of your Fiddle.</p>

```<code>outline: 2px solid black;
</code>```

Body:
I'm trying to highlight rows of a table on hover with a 2px border. To prevent cells from shifting they're given a 4px padding if not selected and not hovered, 2px border and 2px padding if hovered, and a 4px border if selected.

The code can be found in this JS Fiddle or pasted below.

td {
  padding: 6px 10px;
  text-align: center;
  border-bottom: 1px solid #E1E1E1;
  font-size: 1.3rem; }

table {
  border-collapse: collapse;
}

tr {
   padding: 4px;
}
tr.selected {
   border: 4px solid black; }
tr.selected td:first-child {
   padding-left : 8px; }
tr.selected td:last-child {
   padding-right : 8px; }

tr.notselected {
     border: 0px solid black;
     padding: 4px;}

tr.notselected:hover td:first-child {
   padding-left : 9px; }
tr.notselected:hover td:last-child {
   padding-right : 9px; }
tr.notselected:hover {
   border: 2px solid black;
   padding: 2px; }

    Header 1
    Header 2

    Subheader 1.1
    Subheader 1.2
    Subheader 2.1
    Subheader 2.2

    Row 1
    10.1
    10.6
    9.1
    9.4

    Row 2
    12.9
    11.3
    10.1
    10.5

    Row 3

    8.7
    8.8

Instead of remaining static, the borders and contents of the rows below the hovered row shift down, remain shifted down after the row is un-hovered, but shift back up after a second hover on hover off.

Body:
I would use CSS outlines instead of the borders/padding combination you have to prevent the rows shifting like in this fork of your Fiddle.

outline: 2px solid black;


问:
Updating / Replacing a deeply nested object in mongodb with spring data mongodb
I have a document of this kind.

{
  "id": "5a212b985735dd44089e4782",
  "people": [
    {
      "personId": "5a212b985735dd44089e4783",
      "name": "Ronaldo",
      "parents": [
        {
          "parentId": "5a212b985735dd44089e4784",
          "name": "Messi",
          "address": [
            {
              "addressId": "5a212b985735dd44089e4785",
              "country": "Argentina",
              "city": "Blah Blah"
            },
            {
              "addressId": "5a212b985735dd44089e4786",
              "country": "USA",
              "city": "New York"
            }
          ]
        }
      ]
    }
  ]
}
```
<p>I have to replace the exiting <strong>parent</strong> object inside the <strong>parents</strong> array with a new <strong>parent</strong> object.</p>
<p>The code I have written is:</p>
<pre class="lang-java prettyprint-override"><code>Query query = new Query(Criteria.where("id").is("5a212b985735dd44089e4782"));
Update update = new Update().push("people.$.parents", parent);
this.mongoTemplate.findAndModify(query, update, PeopleInfo.class);
</code>```

However, instead of replacing the existing parent object, it is creating a new one.

Does anyone know how to perform a query of this kind?

答:
Do read documentation for push here. What you should do in this case is set not push

```<code>Query query = new Query(Criteria.where("id").is("5a212b985735dd44089e4782"));
Update update = new Update().set("people.parents", parent);
this.mongoTemplate.findAndModify(query, update, PeopleInfo.class);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a document of this kind.

{
  "id": "5a212b985735dd44089e4782",
  "people": [
    {
      "personId": "5a212b985735dd44089e4783",
      "name": "Ronaldo",
      "parents": [
        {
          "parentId": "5a212b985735dd44089e4784",
          "name": "Messi",
          "address": [
            {
              "addressId": "5a212b985735dd44089e4785",
              "country": "Argentina",
              "city": "Blah Blah"
            },
            {
              "addressId": "5a212b985735dd44089e4786",
              "country": "USA",
              "city": "New York"
            }
          ]
        }
      ]
    }
  ]
}

I have to replace the exiting parent object inside the parents array with a new parent object.

The code I have written is:

Query query = new Query(Criteria.where("id").is("5a212b985735dd44089e4782"));
Update update = new Update().push("people.$.parents", parent);
this.mongoTemplate.findAndModify(query, update, PeopleInfo.class);

However, instead of replacing the existing parent object, it is creating a new one.

Does anyone know how to perform a query of this kind?

Body:
Do read documentation for push here. What you should do in this case is set not push

Query query = new Query(Criteria.where("id").is("5a212b985735dd44089e4782"));
Update update = new Update().set("people.parents", parent);
this.mongoTemplate.findAndModify(query, update, PeopleInfo.class);


问:
TotalVirtualMemory returns unrealistic number for my application

My application is returning a very large number for TotalVirtualMemory. I instantiate a ComputerInfo() object and call TotalVirtualMemory and the value returned is ~130TB. Creating a basic project to test this seems to return the correct value: ~4GB. What could be causing this? My Code is below:
</p>

```<code>using System;
using Microsoft.VisualBasic.Devices;

namespace ConsoleApp1
{
    public class Program
    {
        private static void Main(string[] args)
        {
            var test = new Program();
            Console.WriteLine($"Total Virtual Memory: {test.GetTotalVirtualMemory()}");
            Console.WriteLine($"Total Virtual Memory Readable: {test.GetTotalVirtualMemory() * (1.0 / 1024.0 / 1024.0 / 1024.0)}");
        }

        public ulong GetTotalVirtualMemory()
        {
            return new ComputerInfo().TotalVirtualMemory;
        }
    }
}
</code>```

答:
4GB is only expected for 32 bit processes, the number you got is the expected number for 64 bit processes

```<code>using System;
using Microsoft.VisualBasic.Devices;

namespace ConsoleApp1
{
    public class Program
    {
        private static void Main(string[] args)
        {
            var test = new Program();
            Console.WriteLine($"Is 64 Bit Process: {Environment.Is64BitProcess}");
            Console.WriteLine($"Total Virtual Memory: {test.GetTotalVirtualMemory()}");
            Console.WriteLine($"Total Virtual Memory Readable: {test.GetTotalVirtualMemory() * (1.0 / 1024.0 / 1024.0 / 1024.0)}");
        }

        public ulong GetTotalVirtualMemory()
        {
            return new ComputerInfo().TotalVirtualMemory;
        }
    }
}
</code>```

Change your "platform target" in the "project properties -> build tab", to be only run on x86 instead of being set to x64 or AnyCPU and you will see the 4GB number you expected.

Body:
My application is returning a very large number for TotalVirtualMemory. I instantiate a ComputerInfo() object and call TotalVirtualMemory and the value returned is ~130TB. Creating a basic project to test this seems to return the correct value: ~4GB. What could be causing this? My Code is below:

using System;
using Microsoft.VisualBasic.Devices;

namespace ConsoleApp1
{
    public class Program
    {
        private static void Main(string[] args)
        {
            var test = new Program();
            Console.WriteLine($"Total Virtual Memory: {test.GetTotalVirtualMemory()}");
            Console.WriteLine($"Total Virtual Memory Readable: {test.GetTotalVirtualMemory() * (1.0 / 1024.0 / 1024.0 / 1024.0)}");
        }

        public ulong GetTotalVirtualMemory()
        {
            return new ComputerInfo().TotalVirtualMemory;
        }
    }
}

Body:
4GB is only expected for 32 bit processes, the number you got is the expected number for 64 bit processes

using System;
using Microsoft.VisualBasic.Devices;

namespace ConsoleApp1
{
    public class Program
    {
        private static void Main(string[] args)
        {
            var test = new Program();
            Console.WriteLine($"Is 64 Bit Process: {Environment.Is64BitProcess}");
            Console.WriteLine($"Total Virtual Memory: {test.GetTotalVirtualMemory()}");
            Console.WriteLine($"Total Virtual Memory Readable: {test.GetTotalVirtualMemory() * (1.0 / 1024.0 / 1024.0 / 1024.0)}");
        }

        public ulong GetTotalVirtualMemory()
        {
            return new ComputerInfo().TotalVirtualMemory;
        }
    }
}

Change your "platform target" in the "project properties -> build tab", to be only run on x86 instead of being set to x64 or AnyCPU and you will see the 4GB number you expected.


问:
Android..error while finding address given location
I am an android beginner getting the error: cannot resolve the symbol isPresent, in my following code snippet. Experts, please help!</p>

```<code>Geocoder geo = new Geocoder(getApplicationContext(), Locale.getDefault());
    if(Geocoder.isPresent()){
        try {
            List<Address> addresses = geo.getFromLocation(l.getLatitude(),l.getLongitude(),1);
            if (addresses != null && addresses.size() >0){
                Address address = addresses.get(0);
                String addressText = String.format("%s,%s,%s", address.getLocality(),address.getCountryName());
                TextView place =(TextView)findViewById(R.id.place);
                place.setText(addressText);
            }

        }
        catch(IOException e){
            e.printStackTrace();
        }
</code>```

答: Well,the problem stands resolved. The error occurred because the snippet was appearing after a set of code, which were outside of the onCreate method.Sorry for the waste of time caused by this beginner.</p>

Body:
I am an android beginner getting the error: cannot resolve the symbol isPresent, in my following code snippet. Experts, please help!

Geocoder geo = new Geocoder(getApplicationContext(), Locale.getDefault());
    if(Geocoder.isPresent()){
        try {
            List<Address> addresses = geo.getFromLocation(l.getLatitude(),l.getLongitude(),1);
            if (addresses != null && addresses.size() >0){
                Address address = addresses.get(0);
                String addressText = String.format("%s,%s,%s", address.getLocality(),address.getCountryName());
                TextView place =(TextView)findViewById(R.id.place);
                place.setText(addressText);
            }

        }
        catch(IOException e){
            e.printStackTrace();
        }


问:
Constructor uses the mock object, how do I test a method in isolation?
I have a class that looks like this:

```<code>class MyClass {

  private IDependency dep;

  public MyClass(IDependency dep) {
    this.dep = dep;
    this.dep.Reset();
  }

  public void Clear() {
    this.dep.Reset();
  }
}
</code>```

How do I test that the Reset method gets called properly in the Clear method while ignoring what the constructor does?

My Moq test looks like this:

```<code>MockRepository mocks = new MockRepository(MockBehavior.Default);
var dep = mocks.Create<IDependency>();

dep.Setup(s => s.Reset());

MyClass myclass = new MyClass(dep.Object);
myclass.Clear():

state.Verify(s => s.Reset(), Times.Exactly(1));
</code>```

It fails because Reset has been called twice (once in the constructor, and once in the Clear method).

答:
I hoped there would be a better way of doing it, but the mock will record all calls to Reset so using a standard Verify call will always return 2. The following maintains a separate counter, which isn't very elegant. If there's a built-in way of doing this with Moq, I'd love to know.

```<code>int clearResetCount = 0;

Mock<IDependency> dep = new Mock<IDependency>();

MyClass myclass = new MyClass(dep.Object);

dep.Setup(s => s.Reset()).Callback(() => clearResetCount++);

Assert.AreEqual(0, clearResetCount, "Expected clear reset count - before.");

myclass.Clear();

Assert.AreEqual(1, clearResetCount, "Expected clear reset count - after.");
</code>```

Body:
I have a class that looks like this:

class MyClass {

  private IDependency dep;

  public MyClass(IDependency dep) {
    this.dep = dep;
    this.dep.Reset();
  }

  public void Clear() {
    this.dep.Reset();
  }
}

How do I test that the Reset method gets called properly in the Clear method while ignoring what the constructor does?

My Moq test looks like this:

MockRepository mocks = new MockRepository(MockBehavior.Default);
var dep = mocks.Create<IDependency>();

dep.Setup(s => s.Reset());

MyClass myclass = new MyClass(dep.Object);
myclass.Clear():

state.Verify(s => s.Reset(), Times.Exactly(1));

It fails because Reset has been called twice (once in the constructor, and once in the Clear method).

Body:
I hoped there would be a better way of doing it, but the mock will record all calls to Reset so using a standard Verify call will always return 2. The following maintains a separate counter, which isn't very elegant. If there's a built-in way of doing this with Moq, I'd love to know.

int clearResetCount = 0;

Mock<IDependency> dep = new Mock<IDependency>();

MyClass myclass = new MyClass(dep.Object);

dep.Setup(s => s.Reset()).Callback(() => clearResetCount++);

Assert.AreEqual(0, clearResetCount, "Expected clear reset count - before.");

myclass.Clear();

Assert.AreEqual(1, clearResetCount, "Expected clear reset count - after.");


问:
How to move node_modules folder to common location to access in all Angular2 apps
Is there a way to move node_modules folder to common location ex: C:\angular2 and access in different apps ex: C:\angular2\angular2-quickstart, C:\angular2\angular2-tour-of-heroes etc..

Only for learning angular2, I am creating applications. node_module folder is about 80mb. So instead of every time copy and pasting is there a way to place it in common location.

答:
Here is what you can do.

I have node_modules directory stored in C:\common folder

```<code>On windows:

Go to your project folder

    mklink /j node_modules C:\common\node_modules

    ng serve --preserve-symlinks

On Linux:

ln -s ~/common/node_modules node_modules
</code>```

Body:
Here is what you can do.

I have node_modules directory stored in C:\common folder

On windows:

Go to your project folder

    mklink /j node_modules C:\common\node_modules

    ng serve --preserve-symlinks

On Linux:

ln -s ~/common/node_modules node_modules


问:
Why can't programs be proven?
Why can't a computer program be proven just as a mathematical statement can?  A mathematical proof is built up on other proofs, which are built up from yet more proofs and on down to axioms - those truths truths we hold as self evident.

Computer programs don't seem to have such a structure.  If you write a computer program, how is it that you can take previous proven works and use them to show the truth of your program?  You can't since none exist.  Further, what are the axioms of programming?  The very atomic truths of the field?

I don't have good answers to the above.  But it seems software can't be proven because it is art and not science.  How do you prove a Picasso?

答:
If the program has a well defined objective and initial assumptions (ignoring Godel...) it can be proven.  Find all primes,x, for 6<=x<=10, your answer is 7 and that can be proven.  I wrote a program that plays NIM (the first Python program I ever wrote) and in theory the computer always wins after the game falls into a state in which the computer can win.  I haven't been able to prove it as true, but it IS true (mathematically by a digital binary sum proof)  I believe unless I made an error in the code.  Did I make an error, no seriously, can someone tell me if this program is beatable?

There are some mathematical theorems that have been "proven" with computer code like the four color theorem.  But there are objections, because like you said, can you prove the program?

Title: Why can't programs be proven?

OwnerDisplayName: Alex


问:
R - Change column name using get()

I have several data.frames in my Global Environment that I need to merge. Many of the data.frames have identical column names. I want to append a suffix to each column that marks its originating data.frame. Because I have many data.frames, I wanted to automate the process as in the following example.

```<code>df1 <-  data.frame(id = 1:5,x = LETTERS[1:5])
df2 <-  data.frame(id = 1:5,x = LETTERS[6:10])

obj <- ls()

for(o in obj){
  s <- sub('df','',eval(o))
  names(get(o))[-1] <- paste0(names(get(o))[-1],'.',s)
}

# Error in get(o) <- `*vtmp*` : could not find function "get<-"'
</code>```

But the individual pieces of the assignment work fine:

```<code>names(get(o))[-1]
# [1] "x"
paste0(names(get(o))[-1],'.',s)
# [1] "x.1"
</code>```

I've used get in a similar way to write.csveach object to a file.

```<code>for(o in obj){
  write.csv(get(o),file = paste0(o,'.csv'),row.names = F)
}
</code>```

Any ideas why it's not working in the assignment to change the column names?

答:
You can use eval which evaluate an R expression in a specified environment.

```<code>df1 <- data.frame(id = 1:5,x = LETTERS[1:5])
df2 <- data.frame(id = 1:5,x = LETTERS[6:10])

obj <- ls()

for(o in obj) {
  s <- sub('df', '', o)
  new_name <- paste0(names(get(o))[-1], '.', s)
  eval(parse(text = paste0('names(', o, ')[-1] <- ', substitute(new_name))))
}
</code>```

modify df1 and df2

```<code>  id x.1
1  1   A
2  2   B
3  3   C
4  4   D
5  5   E
</code>```

Title: R - Change column name using get()

Body:
I have several data.frames in my Global Environment that I need to merge. Many of the data.frames have identical column names. I want to append a suffix to each column that marks its originating data.frame. Because I have many data.frames, I wanted to automate the process as in the following example.

df1 <-  data.frame(id = 1:5,x = LETTERS[1:5])
df2 <-  data.frame(id = 1:5,x = LETTERS[6:10])

obj <- ls()

for(o in obj){
  s <- sub('df','',eval(o))
  names(get(o))[-1] <- paste0(names(get(o))[-1],'.',s)
}

# Error in get(o) <- `*vtmp*` : could not find function "get<-"'

But the individual pieces of the assignment work fine:

names(get(o))[-1]
# [1] "x"
paste0(names(get(o))[-1],'.',s)
# [1] "x.1"

I've used get in a similar way to write.csveach object to a file.

for(o in obj){
  write.csv(get(o),file = paste0(o,'.csv'),row.names = F)
}

Any ideas why it's not working in the assignment to change the column names?

Body:
You can use eval which evaluate an R expression in a specified environment.

df1 <- data.frame(id = 1:5,x = LETTERS[1:5])
df2 <- data.frame(id = 1:5,x = LETTERS[6:10])

obj <- ls()

for(o in obj) {
  s <- sub('df', '', o)
  new_name <- paste0(names(get(o))[-1], '.', s)
  eval(parse(text = paste0('names(', o, ')[-1] <- ', substitute(new_name))))
}

modify df1 and df2

  id x.1
1  1   A
2  2   B
3  3   C
4  4   D
5  5   E


问:
tf.assign on tf.concat tensor, drops Variable character of tensors?
I am trying to set specific values for the weights and values of a Tensorflow neural network using the Python API. To this end, I placed all weights and biases in a common collection with proper reshaping and using tf.concat on the tensors from each layer.

At a certain stage in my code, I retrieve said collection. However, when I then try to tf.assign (using tf.placeholder of the same shape) to these concatenated tensor in order to set all weights/biases from a single vector of values, e.g. sitting in the feed_dict, then I get the error

```<code>AttributeError: 'Tensor' object has no attribute 'assign'
</code>```

I have boiled my problem down to a minimum working example (MWE) as follows:

```<code>import tensorflow as tf

a=tf.Variable(tf.random_uniform([2], dtype=tf.float32))
b=tf.Variable(tf.random_uniform([2], dtype=tf.float32))
c=tf.concat([a,b], axis=0)

d_all=tf.placeholder(shape=[4], dtype=tf.float32)
d_single=tf.placeholder(shape=[2], dtype=tf.float32)

#e_all=tf.assign(c,d_all)
e_single=tf.assign(a,d_single)

sess=tf.Session()
sess.run(tf.global_variables_initializer())

print(a)
print(d_single)

sess.run(e_single, feed_dict={
    d_single: [1,2]
})

print(c)
print(d_all)

#sess.run(e_all, feed_dict={
#    d_all: [1,2,3,4]
#})
</code>```

The commented-out lines do not work and fail with the same error. It seems that the tensor resulting from tf.concat is not variable anymore and therefore does not have the assign property. I found a related issue here, but my problem is not solved by validate_shape as suggested there.

Any ideas? Is this desired behavior?

答:
Yes, it's a designed behavior, because c is an op, not a variable. Here's the simplest version of it:

c = a + b
tf.assign(c, a)  # Does not work!
```

Basically, this graph means that the node c depends on a and b through certain operation (concat, addition, whatever). Assigning other values to c conflicts with the values that are coming from a and b, in other words, it breaks the computational graph.

What you should do instead is split d_all into tensors of shape [2] and assign the underlying a and b. This way is perfectly valid.

Body:
I am trying to set specific values for the weights and values of a Tensorflow neural network using the Python API. To this end, I placed all weights and biases in a common collection with proper reshaping and using tf.concat on the tensors from each layer.

At a certain stage in my code, I retrieve said collection. However, when I then try to tf.assign (using tf.placeholder of the same shape) to these concatenated tensor in order to set all weights/biases from a single vector of values, e.g. sitting in the feed_dict, then I get the error

AttributeError: 'Tensor' object has no attribute 'assign'

I have boiled my problem down to a minimum working example (MWE) as follows:

import tensorflow as tf

a=tf.Variable(tf.random_uniform([2], dtype=tf.float32))
b=tf.Variable(tf.random_uniform([2], dtype=tf.float32))
c=tf.concat([a,b], axis=0)

d_all=tf.placeholder(shape=[4], dtype=tf.float32)
d_single=tf.placeholder(shape=[2], dtype=tf.float32)

#e_all=tf.assign(c,d_all)
e_single=tf.assign(a,d_single)

sess=tf.Session()
sess.run(tf.global_variables_initializer())

print(a)
print(d_single)

sess.run(e_single, feed_dict={
    d_single: [1,2]
})

print(c)
print(d_all)

#sess.run(e_all, feed_dict={
#    d_all: [1,2,3,4]
#})

The commented-out lines do not work and fail with the same error. It seems that the tensor resulting from tf.concat is not variable anymore and therefore does not have the assign property. I found a related issue here, but my problem is not solved by validate_shape as suggested there.

Any ideas? Is this desired behavior?

Body:
Yes, it's a designed behavior, because c is an op, not a variable. Here's the simplest version of it:

c = a + b
tf.assign(c, a)  # Does not work!

Basically, this graph means that the node c depends on a and b through certain operation (concat, addition, whatever). Assigning other values to c conflicts with the values that are coming from a and b, in other words, it breaks the computational graph.

What you should do instead is split d_all into tensors of shape [2] and assign the underlying a and b. This way is perfectly valid.


问:
Why is this std::vector being cleared when program enters main function?
The problem I'm having is that I am pushing an element into a vector at initialisation when all the static variables are initialised, and then when it enters the main function the vector resets to 0, as if it has cleared. In my case the vector was in a different CPP, but this also shows the problem:

```<code>#include <iostream>
#include <vector>

struct List
{
    static std::vector<int> listVector;
};

struct Foo
{
    Foo()
    {
        std::cout << List::listVector.size() << '\n';   // Prints 0
        List::listVector.push_back(1);
        std::cout << List::listVector.size() << '\n';   // Prints 1
    }
};
Foo fooObj;

std::vector<int> List::listVector;

int main()
{
    std::cout << List::listVector.size() << '\n';   // Prints 0
    List::listVector.push_back(2);
    std::cout << List::listVector.size() << '\n';   // Prints 1
}
</code>```

The first element I added to the vector has been lost. I know one has to be careful with initialisation order of static global variables, but I can't understand why the vector is being cleared. I'm tempted to think that when the Foo constructor runs it adds an element to the vector, but the vector hasn't been created yet, because it's written on the line after the Foo object is created. However, if this is the case, just what vector am I adding into when I do so in the constructor and it prints out a size of 1?

I'm kind of confused.

答:
I'm tempted to think that when the Foo constructor runs it adds an element to the vector, but the vector hasn't been created yet, because it's written on the line after the Foo object is created.

Yes, that's exactly right. The fooObj constructor just accesses the memory where the vector will be constructed, but it hasn't been constructed there yet. (So the program has undefined behaviour, and must be fixed)

However, if this is the case, just what vector am I adding into when I do so in the constructor and it prints out a size of 1?

The compiler simply interprets the memory as being a valid vector, because it has no way to know otherwise. That just happens to work, because the memory that the global will be constructed in is initially zero, because the execution environment ensures that all static objects' memory is initially zero, which happens to be the same as the default-constructed state (for your implementation's definition of std::vector). The program has no way to know that the memory location containing all-zeros is not a valid vector yet.

Later the constructor for the vector runs and re-initializes the memory, to the default-constructed state.

Here is an example showing what your program does: interpreting raw memory containing all zeros as a vector, and adding elements to that phantom vector (which doesn't really exist), then actually constructing a vector in that memory. Anything added to the phantom vector is lost once the real vector is created.

```<code>#include <iostream>
#include <vector>

int main()
{
    // initialize a block of memory to zero:
    alignas(std::vector<int>) char memory[sizeof(std::vector<int>)] = {};
    // use that memory as a vector, even though we haven't created any vector
    // (this is undefined behaviour! there is no vector yet!):
    std::vector<int>& vec = *reinterpret_cast<std::vector<int>*>(memory);
    vec.push_back(1);
    // the non-existent "phantom vector" has size 1:
    std::cout << vec.size() << std::endl;
    // now use "placement new" to construct an empty vector in that memory:
    new (memory) std::vector<int>();
    // the real vector is empty, the element in the phantom vector is lost:
    std::cout << vec.size() << std::endl;
}
</code>```

To fix your program you need to initialize the vector before anything refers to it (specifically, before the fooObj constructor tries to use it, by defining it before fooObj).

Body:
The problem I'm having is that I am pushing an element into a vector at initialisation when all the static variables are initialised, and then when it enters the main function the vector resets to 0, as if it has cleared. In my case the vector was in a different CPP, but this also shows the problem:

#include <iostream>
#include <vector>

struct List
{
    static std::vector<int> listVector;
};

struct Foo
{
    Foo()
    {
        std::cout << List::listVector.size() << '\n';   // Prints 0
        List::listVector.push_back(1);
        std::cout << List::listVector.size() << '\n';   // Prints 1
    }
};
Foo fooObj;

std::vector<int> List::listVector;

int main()
{
    std::cout << List::listVector.size() << '\n';   // Prints 0
    List::listVector.push_back(2);
    std::cout << List::listVector.size() << '\n';   // Prints 1
}

The first element I added to the vector has been lost. I know one has to be careful with initialisation order of static global variables, but I can't understand why the vector is being cleared. I'm tempted to think that when the Foo constructor runs it adds an element to the vector, but the vector hasn't been created yet, because it's written on the line after the Foo object is created. However, if this is the case, just what vector am I adding into when I do so in the constructor and it prints out a size of 1?

I'm kind of confused.

Body:
I'm tempted to think that when the Foo constructor runs it adds an element to the vector, but the vector hasn't been created yet, because it's written on the line after the Foo object is created.

Yes, that's exactly right. The fooObj constructor just accesses the memory where the vector will be constructed, but it hasn't been constructed there yet. (So the program has undefined behaviour, and must be fixed)

However, if this is the case, just what vector am I adding into when I do so in the constructor and it prints out a size of 1?

The compiler simply interprets the memory as being a valid vector, because it has no way to know otherwise. That just happens to work, because the memory that the global will be constructed in is initially zero, because the execution environment ensures that all static objects' memory is initially zero, which happens to be the same as the default-constructed state (for your implementation's definition of std::vector). The program has no way to know that the memory location containing all-zeros is not a valid vector yet.

Later the constructor for the vector runs and re-initializes the memory, to the default-constructed state.

Here is an example showing what your program does: interpreting raw memory containing all zeros as a vector, and adding elements to that phantom vector (which doesn't really exist), then actually constructing a vector in that memory. Anything added to the phantom vector is lost once the real vector is created.

#include <iostream>
#include <vector>

int main()
{
    // initialize a block of memory to zero:
    alignas(std::vector<int>) char memory[sizeof(std::vector<int>)] = {};
    // use that memory as a vector, even though we haven't created any vector
    // (this is undefined behaviour! there is no vector yet!):
    std::vector<int>& vec = *reinterpret_cast<std::vector<int>*>(memory);
    vec.push_back(1);
    // the non-existent "phantom vector" has size 1:
    std::cout << vec.size() << std::endl;
    // now use "placement new" to construct an empty vector in that memory:
    new (memory) std::vector<int>();
    // the real vector is empty, the element in the phantom vector is lost:
    std::cout << vec.size() << std::endl;
}

To fix your program you need to initialize the vector before anything refers to it (specifically, before the fooObj constructor tries to use it, by defining it before fooObj).


问:
CSS: Making two complementary diagonal divs
this is what I'm trying to do:

This is how I was trying to do it:
  The first div 'subCont1' works fine, even if it's getting out of the page. If I do the same thing with the second, this time scroll activates for the same reason.

.subCont1{

    background-color: blueviolet;
    position:absolute;
    left:-20%;
    top:0;

    width:70%;
    height:100%;
    transform: skew(-20deg);

    border:2px solid yellow;
}

.subCont2{

      width:50%;
      height:100%;

      border:2px solid grey;

      z-index:1000;

      overflow:hidden;
  }```

答:
I made this for one of my projects with a skewed handle which supported an animation using javascript but I took out those to make it raw and simple as per the design you mentioned. Hope, it helps.

#wrapper{
  position:relative;
  width:100%;
  min-height:300px;
  overflow:hidden;
  z-index: 100;
  border:2px solid black;
}

.layer{
  position:absolute;
  width:100vw;
  min-height:300px;
  overflow:hidden;
  border:2px solid black;
}

.layer .content-wrap{
  position:absolute;
  width:100vw;
  min-height:300px;
}

.layer .content-body{
  width:25%;
  position:absolute;
  top:40%;
  text-align:center;
  transform: translateY(-50%);
}

.bottom{
  background: green;
  z-index:101;
}

.bottom .content-body{
  right:10%;
}

.top{
  background: red;
  color:#222;
  z-index:102;
  width:50vw;
}

.top .content-body{
  left:5%;
  color:#222;
}

.skewed .top{
  transform: skew(-20deg);
  margin-left:-1000px;
  width:calc(50vw + 1000px);
}

.skewed .top .content-wrap{
  transform: skew(20deg);
  margin-left:1000px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="wrapper" class="skewed">
  <div class="layer bottom">
    <div class="content-wrap">
      <div class="content-body">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et.</p>
      </div>
    </div>
  </div>

  <div class="layer top">
    <div class="content-wrap">
      <div class="content-body">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore . </p>
      </div>
    </div>
  </div>

</section></code>```

Body:
I made this for one of my projects with a skewed handle which supported an animation using javascript but I took out those to make it raw and simple as per the design you mentioned. Hope, it helps.

#wrapper{
  position:relative;
  width:100%;
  min-height:300px;
  overflow:hidden;
  z-index: 100;
  border:2px solid black;
}

.layer{
  position:absolute;
  width:100vw;
  min-height:300px;
  overflow:hidden;
  border:2px solid black;
}

.layer .content-wrap{
  position:absolute;
  width:100vw;
  min-height:300px;
}

.layer .content-body{
  width:25%;
  position:absolute;
  top:40%;
  text-align:center;
  transform: translateY(-50%);
}

.bottom{
  background: green;
  z-index:101;
}

.bottom .content-body{
  right:10%;
}

.top{
  background: red;
  color:#222;
  z-index:102;
  width:50vw;
}

.top .content-body{
  left:5%;
  color:#222;
}

.skewed .top{
  transform: skew(-20deg);
  margin-left:-1000px;
  width:calc(50vw + 1000px);
}

.skewed .top .content-wrap{
  transform: skew(20deg);
  margin-left:1000px;
}

<section id="wrapper" class="skewed">
  <div class="layer bottom">
    <div class="content-wrap">
      <div class="content-body">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et.</p>
      </div>
    </div>
  </div>

  <div class="layer top">
    <div class="content-wrap">
      <div class="content-body">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore . </p>
      </div>
    </div>
  </div>

</section>


问:
Getting screen coordinates based on triangles
If I have the length of the hypotenuse and its angle, how do I find the adjacent and opposite?

I'm writing this in JavaScript and I'm just trying to find the screen coordinates (x/y) where the hypotenuse ends given a length and angle. So, additionally, I need to know how to convert from a cartesian coordinates to screen coordinates.

Sorry, this is probably a pretty dumb question.

Here is a sketch if I'm being unclear:

So something like this:

```<code>function getLineEndCoords(originX, originY, hypotenuse, angle){
    // Probably something to do with tangents and cosines.
    return [x,y]
}
</code>```

Additionally, if anyone knows any good JS libraries for this sort of stuff (isometric drawings, display related math) that would be convenient.

答:
Using soh cah toa:

```<code>sin(A) = o/h
cos(A) = a/h
</code>```

therefore:

```<code>x = hypotenuse*sin(angle) + origionX
y = hypotenuse*cos(angle) + origionY
</code>```

It is usually easier to memorise that one axis is the sine of the angle multiplied by the length, and the other is the cosine of the angle times the length.

EDIT:

Sorry, I forgot to include adding the origin.

Body:
If I have the length of the hypotenuse and its angle, how do I find the adjacent and opposite?

I'm writing this in JavaScript and I'm just trying to find the screen coordinates (x/y) where the hypotenuse ends given a length and angle. So, additionally, I need to know how to convert from a cartesian coordinates to screen coordinates.

Sorry, this is probably a pretty dumb question.

Here is a sketch if I'm being unclear:

So something like this:

function getLineEndCoords(originX, originY, hypotenuse, angle){
    // Probably something to do with tangents and cosines.
    return [x,y]
}

Additionally, if anyone knows any good JS libraries for this sort of stuff (isometric drawings, display related math) that would be convenient.

Body:
Using soh cah toa:

sin(A) = o/h
cos(A) = a/h

therefore:

x = hypotenuse*sin(angle) + origionX
y = hypotenuse*cos(angle) + origionY

It is usually easier to memorise that one axis is the sine of the angle multiplied by the length, and the other is the cosine of the angle times the length.

EDIT:

Sorry, I forgot to include adding the origin.


问:
Argument unpacking with a Dict
I have a CSV file I'd like to parse as a Dict, so that the first item with the key of "key" can be unpacked to a variable, then the rest of the values as a list of keyed languages. Is there a nice, clean way of doing this?

My CSV is like so:

```<code>key,english,spanish
wanna_play_a_game,"Wanna play a game?","¿Quiero jugar a un juego?"
something_else,"Hello!","hola!"
</code>```

Dict object as such:

```<code>[{'key': 'wanna_play_a_game', 'english': 'Wanna play a game?', 'spanish': '¿Quiero jugar a un juego?'}, {'key': 'something_else', 'english': 'Hello', 'spanish': 'hola!'}]
</code>```

I did have a go but then realised that unpacking isn't the same with dicts (I assume) because they're not ordered like with lists. Am I overcomplicating things and should just saved the row['key'] to a variable and then remove it from the dict? Python isn't my bread & butter language so I'm not that knowledgable on the more magicky bits of the syntax.

This is what I was kinda getting at before realising I'm lost:

```<code>import csv
class Translate:

    def __init__(self):
        self.translations = self.readCSV('translations.csv')

    def readCSV(self, filename):
        with open(filename, 'rt') as csvfile:
            reader = csv.DictReader(csvfile)
            return [dict(d) for d in reader]

    def parse(self, line):
        # for t_key, *langs in self.translations:
        # for k, (t_key, *langs) in self.translations:
        # ... some magic function?
</code>```

The basic thing I'm trying to get is t_key to be "wanna_play_a_game" and langs to be ('english': 'Wanna play a game?', 'spanish': '¿Quiero jugar a un juego?')

答:
Unpacking is not what you want here. You should just pop t_key from the dict and then iterate over the rest.

```<code>t_key = langs.pop('key')
for key, value in langs.items():
    ...
</code>```

Title: Argument unpacking with a Dict

Body:
I have a CSV file I'd like to parse as a Dict, so that the first item with the key of "key" can be unpacked to a variable, then the rest of the values as a list of keyed languages. Is there a nice, clean way of doing this?

My CSV is like so:

key,english,spanish
wanna_play_a_game,"Wanna play a game?","¿Quiero jugar a un juego?"
something_else,"Hello!","hola!"

Dict object as such:

[{'key': 'wanna_play_a_game', 'english': 'Wanna play a game?', 'spanish': '¿Quiero jugar a un juego?'}, {'key': 'something_else', 'english': 'Hello', 'spanish': 'hola!'}]

I did have a go but then realised that unpacking isn't the same with dicts (I assume) because they're not ordered like with lists. Am I overcomplicating things and should just saved the row['key'] to a variable and then remove it from the dict? Python isn't my bread & butter language so I'm not that knowledgable on the more magicky bits of the syntax.

This is what I was kinda getting at before realising I'm lost:

import csv
class Translate:

    def __init__(self):
        self.translations = self.readCSV('translations.csv')

    def readCSV(self, filename):
        with open(filename, 'rt') as csvfile:
            reader = csv.DictReader(csvfile)
            return [dict(d) for d in reader]

    def parse(self, line):
        # for t_key, *langs in self.translations:
        # for k, (t_key, *langs) in self.translations:
        # ... some magic function?

The basic thing I'm trying to get is t_key to be "wanna_play_a_game" and langs to be ('english': 'Wanna play a game?', 'spanish': '¿Quiero jugar a un juego?')

Body:
Unpacking is not what you want here. You should just pop t_key from the dict and then iterate over the rest.

t_key = langs.pop('key')
for key, value in langs.items():
    ...


问:
Woocommerce: delete "additional information" tab
Two things I am trying to do on the product pages of this website: https://lovesometea.com/product/green-coconut/

1) Delete "additional information" tab
2) Add Attribute "Size" above the product description

To delete the "additional information" tab, I have been following this: https://idevie.com/tutorials/how-to-make-woocommerce-product-attributes-more-prominent

So this is what I did:
1) Added a custom plug-in and activated it - http://code.tutsplus.com/tutorials/making-woocommerce-product-attributes-more-prominent--cms-25438

2) Tried removing "additional information" by editing the tabs.php in /wp-content/plugins/woocommerce/templates/single-product/tabs

```<code>/**
 * Removes the "Additional Information" tab that displays the product attributes.
 *
 * @param array $tabs WooCommerce tabs to display.
 *
 * @return array WooCommerce tabs to display, minus "Additional Information".
 */
function tutsplus_remove_product_attributes_tab( $tabs ) {

    unset( $tabs['additional_information'] );

    return $tabs;

}

add_filter( 'woocommerce_product_tabs', 'tutsplus_remove_product_attributes_tab', 100 );
</code>```

This is where I'm stuck. I even tried deleting the additional-information.php file all together (in the same tabs folder) and additional information still displays!

I tried putting the above code in three different areas of the tabs.php file but no effect on the tab on the product page.

Any other suggestions? Perhaps there is a different/better method with the latest woocommerce version?

答:
Maybe you need to change the priority from 100 to 98 as in woocommerce documentation , put the code in functions.php file</p>

```<code>add_filter( 'woocommerce_product_tabs', 'woo_remove_product_tabs', 98 );

function woo_remove_product_tabs( $tabs ) {

    unset( $tabs['additional_information'] );   // Remove the additional information tab

    return $tabs;

}
</code>```

Body:
Two things I am trying to do on the product pages of this website: https://lovesometea.com/product/green-coconut/

1) Delete "additional information" tab
2) Add Attribute "Size" above the product description

To delete the "additional information" tab, I have been following this: https://idevie.com/tutorials/how-to-make-woocommerce-product-attributes-more-prominent

So this is what I did:
1) Added a custom plug-in and activated it - http://code.tutsplus.com/tutorials/making-woocommerce-product-attributes-more-prominent--cms-25438

2) Tried removing "additional information" by editing the tabs.php in /wp-content/plugins/woocommerce/templates/single-product/tabs

/**
 * Removes the "Additional Information" tab that displays the product attributes.
 *
 * @param array $tabs WooCommerce tabs to display.
 *
 * @return array WooCommerce tabs to display, minus "Additional Information".
 */
function tutsplus_remove_product_attributes_tab( $tabs ) {

    unset( $tabs['additional_information'] );

    return $tabs;

}

add_filter( 'woocommerce_product_tabs', 'tutsplus_remove_product_attributes_tab', 100 );

This is where I'm stuck. I even tried deleting the additional-information.php file all together (in the same tabs folder) and additional information still displays!

I tried putting the above code in three different areas of the tabs.php file but no effect on the tab on the product page.

Any other suggestions? Perhaps there is a different/better method with the latest woocommerce version?

Body:
Maybe you need to change the priority from 100 to 98 as in woocommerce documentation , put the code in functions.php file

add_filter( 'woocommerce_product_tabs', 'woo_remove_product_tabs', 98 );

function woo_remove_product_tabs( $tabs ) {

    unset( $tabs['additional_information'] );   // Remove the additional information tab

    return $tabs;

}


问:
Disable color and paging for mercurial
New versions of mercurial will apply colors to the output of most commands and will pipe commands with long output to a pager. How do I restore the old behavior to not color output and never use a pager?</p>

答:
When working with commandline, you can also add parameters or options to your commands. This is however not permanent. The hg --help --verbose  reveals:

```<code>--color TYPE        when to colorize (boolean, always, auto, never, or debug)
--pager TYPE        when to paginate (boolean, always, auto, or never)
                    (default: auto)
</code>```

So the next command disables your pager and does not show any colors:

```<code>hg incoming --pager never --color never
</code>```

Title: Disable color and paging for mercurial

Body:
When working with commandline, you can also add parameters or options to your commands. This is however not permanent. The hg --help --verbose  reveals:

--color TYPE        when to colorize (boolean, always, auto, never, or debug)
--pager TYPE        when to paginate (boolean, always, auto, or never)
                    (default: auto)

So the next command disables your pager and does not show any colors:

hg incoming --pager never --color never


问:
Adding to an Azure CosmosDB from inside an Azure Function
I've created a CosmosDB DB, with a single table, called MyTable.  My idea is that I want to insert into this table from an Azure function.  Having had a look around, I've come up with this function:

```<code>public static HttpResponseMessage Run(HttpRequestMessage req, TraceWriter log, out object tableOutput)
{
    log.Info("C# HTTP trigger function processed a request.");

    // parse query parameter
    string field1 = req.GetQueryNameValuePairs()
        .FirstOrDefault(q => string.Compare(q.Key, "field1", true) == 0)
        .Value;

    string field2 = req.GetQueryNameValuePairs()
        .FirstOrDefault(q => string.Compare(q.Key, "field2", true) == 0)
        .Value;

    var item = new
    {
        field1 = field1,
        field2 = field2
    };

    tableOutput = item;

    return req.CreateResponse(HttpStatusCode.OK);
}
</code>```

The error that I get is this:

2017-12-07T15:52:44.066 Exception while executing function:
  Functions.MyFunc. Microsoft.Azure.WebJobs.Host: Error while handling
  parameter tableOutput after function returned:.
  Microsoft.Azure.WebJobs.Extensions.DocumentDB: The collection
  'tableOutput' (in database 'myCosmosDB') does not exist. To
  automatically create the collection, set 'CreateIfNotExists' to
  'true'. Microsoft.Azure.Documents.Client: Message: {"Errors":["Owner
  resource does not exist"]}

I have set-up the output parameter, and I have seen the checkbox mentioned here (CreateIfNotExists); however, I have an existing Cosmos table set-up, and would like to write to that; so my question is, how can I access that table from within an Azure function?

The function.json is below:

```<code>{
  "bindings": [
    {
      "authLevel": "function",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in"
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "documentDB",
      "name": "outputDocument",
      "databaseName": "mycosmosdb",
      "collectionName": "tableOutput",
      "createIfNotExists": false,
      "connection": "mycostmosdb_DOCUMENTDB",
      "direction": "out"
    }
  ],
  "disabled": false
}
</code>```

EDIT:

Two people have implied that for the purposes of this question the terms Table and Collection are synonymous.  If I have understood correctly, then this appears to not be the case, as even when I change the collection name in the function.json to match the name of the table that I created, I get the same error.

To clarify the CosmosDB table configuration, I am seeing, inside data explorer, a node entitles TablesDB, which has a sub-node of the table that I've created.

答:
Make sure this is the value of your existing collection:
(you mention MyTable but it says tableOutput)

```<code>"collectionName": "tableOutput",
</code>```

Make sure the names are identical. Collection names are case sensitive. "mytable" and "myTable" are different collections

Body:
I've created a CosmosDB DB, with a single table, called MyTable.  My idea is that I want to insert into this table from an Azure function.  Having had a look around, I've come up with this function:

public static HttpResponseMessage Run(HttpRequestMessage req, TraceWriter log, out object tableOutput)
{
    log.Info("C# HTTP trigger function processed a request.");

    // parse query parameter
    string field1 = req.GetQueryNameValuePairs()
        .FirstOrDefault(q => string.Compare(q.Key, "field1", true) == 0)
        .Value;

    string field2 = req.GetQueryNameValuePairs()
        .FirstOrDefault(q => string.Compare(q.Key, "field2", true) == 0)
        .Value;

    var item = new
    {
        field1 = field1,
        field2 = field2
    };

    tableOutput = item;

    return req.CreateResponse(HttpStatusCode.OK);
}

The error that I get is this:

2017-12-07T15:52:44.066 Exception while executing function:
  Functions.MyFunc. Microsoft.Azure.WebJobs.Host: Error while handling
  parameter tableOutput after function returned:.
  Microsoft.Azure.WebJobs.Extensions.DocumentDB: The collection
  'tableOutput' (in database 'myCosmosDB') does not exist. To
  automatically create the collection, set 'CreateIfNotExists' to
  'true'. Microsoft.Azure.Documents.Client: Message: {"Errors":["Owner
  resource does not exist"]}

I have set-up the output parameter, and I have seen the checkbox mentioned here (CreateIfNotExists); however, I have an existing Cosmos table set-up, and would like to write to that; so my question is, how can I access that table from within an Azure function?

The function.json is below:

{
  "bindings": [
    {
      "authLevel": "function",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in"
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "documentDB",
      "name": "outputDocument",
      "databaseName": "mycosmosdb",
      "collectionName": "tableOutput",
      "createIfNotExists": false,
      "connection": "mycostmosdb_DOCUMENTDB",
      "direction": "out"
    }
  ],
  "disabled": false
}

EDIT:

Two people have implied that for the purposes of this question the terms Table and Collection are synonymous.  If I have understood correctly, then this appears to not be the case, as even when I change the collection name in the function.json to match the name of the table that I created, I get the same error.

To clarify the CosmosDB table configuration, I am seeing, inside data explorer, a node entitles TablesDB, which has a sub-node of the table that I've created.

Body:
Make sure this is the value of your existing collection:
(you mention MyTable but it says tableOutput)

"collectionName": "tableOutput",

Make sure the names are identical. Collection names are case sensitive. "mytable" and "myTable" are different collections


问:
Java equivalent of Perl's hash
I've been using a lot Perl hashes due to super flexibility and convenient.
for instance, in Perl I can do the following:

```<code>$hash{AREA_CODE}->{PHONE}->{STREET_ADDR}
</code>```

I wondering how can I accomplish the same thing with Java, I guess it has something to do with HashMap?

Thanks,

答: You're probably going to want to go with Groovy if you want this sort of flexibility but still run within the JVM. tchrist likes to ignore the point that Java is strong-typed as opposed to dynamic-typed languages like Perl or PHP - and also likes to ignore that Java is an order of magnitude faster at running, but that's just me being a "partisan", apparently.</p>

Title: Java equivalent of Perl's hash

Body:
I've been using a lot Perl hashes due to super flexibility and convenient.
for instance, in Perl I can do the following:

$hash{AREA_CODE}->{PHONE}->{STREET_ADDR}

I wondering how can I accomplish the same thing with Java, I guess it has something to do with HashMap?

Thanks,


答:
You need to update the Function.json with the correct "collectionName" value for your Cosmos DB Collection you're trying to save the new Document to. Currently, you do NOT have a Collection in your Cosmos DB Database ("mycosmosdb") with the name "tableOutput".

Also, if you'd wish for the Azure Function Output binding to automatically create the Collection if it doesn't exist, then set the Function.json property "createIfNotExists" to "true" and it'll create the Collection if it doesn't exist.

Either approach will get your code working without error, but you'll need to make sure the "collectionName" is set to the correct name of your Cosmos DB Collection you have set up.

For example, try changing your Function.json to the following:

```<code>{
  "bindings": [
    {
      "authLevel": "function",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in"
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "documentDB",
      "name": "outputDocument",
      "databaseName": "mycosmosdb",
      "collectionName": "MyTable",
      "createIfNotExists": true,
      "connection": "mycostmosdb_DOCUMENTDB",
      "direction": "out"
    }
  ],
  "disabled": false
}
</code>```

Title: Adding to an Azure CosmosDB from inside an Azure Function

Body:
You need to update the Function.json with the correct "collectionName" value for your Cosmos DB Collection you're trying to save the new Document to. Currently, you do NOT have a Collection in your Cosmos DB Database ("mycosmosdb") with the name "tableOutput".

Also, if you'd wish for the Azure Function Output binding to automatically create the Collection if it doesn't exist, then set the Function.json property "createIfNotExists" to "true" and it'll create the Collection if it doesn't exist.

Either approach will get your code working without error, but you'll need to make sure the "collectionName" is set to the correct name of your Cosmos DB Collection you have set up.

For example, try changing your Function.json to the following:

{
  "bindings": [
    {
      "authLevel": "function",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in"
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "documentDB",
      "name": "outputDocument",
      "databaseName": "mycosmosdb",
      "collectionName": "MyTable",
      "createIfNotExists": true,
      "connection": "mycostmosdb_DOCUMENTDB",
      "direction": "out"
    }
  ],
  "disabled": false
}


问:
How do I pad an IP address' octets and turn it into a unique int id in an Ansible playbook?
Given an IP address like 127.0.0.1 (as a string), I want to drop the dots, pad each octet (ideally except for the first one) with zeros to a length of three digits and turn the result into an integer, e.g. 127000000001. (Although I'm assuming that leading zeros would be dropped when converting from string to integer anyway.)

How do I go about doing that in Ansible?
I have the ip defined as ip: "127.0.0.1"

The octets can be obtained with octets: "{{ ip.split('.')}}"

I have found a post that shows how to format strings: {{'%03d'|format(item|int) }}

And I can join a list to a string using result: modified_octets.join()

What I'm struggling with is how to bring all that together. I know I can loop over the octets with an with_items: octets, and could thus apply the format to each item. But how would I join the result together into a list of items (i.e. modified_octets) again? (If I assign item to a variable using the register module, I'll only get the last octet's value; previous ones will be overridden by it...)

Update: It's not important whether I get a string or an int back, really, as long as the return value looks like an integer (i.e. no leading zeroes, no dots, numbers only, etc.)

答:
You could define an empty string before starting your loop

Add (concatenate) the result of every octet to the string

Then casting the string to integer

String =""
while loop
modified_octet=-------
String+=modified_octet   #string=string+modified_octet

An other effective way
for your example the output is integer number
which is summation of the next numbers:

12700000000001=12700000000000+00000000000001

**For other example **
127.10.23.1 ==> 127010023001 which is summation of the next numbers
0000000000001
0000000023000=23*10^3
0000100000000=10*10^6
1270000000000=10*10^9

you can split the octets and casting (convert) them to integer

and multiple

first octet from left in 10^9
   second                in 10^6
   3rd                   in 10^3
   Don't multiple  the last
   And sum the result

then return the result
if you tell me which language you use I could write code
Java or python


问:
Problems with Repast Model Launch
After a fresh install of Repast Symphony 2.5.0 (Win 64bit) and JDK 9.0.1 on a Windows 10 system, when importing a JZombies_Demo example, the model cannot be launched with the default configuration.

The error says:

```<code>    An internal error occurred during: "Launching JZombies_Demo Model".
    org.codehaus.groovy.eclipse.core.builder.GroovyClasspathContainer.<init>(Lorg/eclipse/core/resources/IProject;)V
</code>```

When I edit the default run configuration, in the Dependencies tab I see only the JRE System Library and nothing else. In the same tab, the Restore Default Entries is enabled - when I press it all the dependencies from Repast Symphony are added, and the previous error disappears. However, in this case when trying to launch another error is observed:

```<code>     saf.core.runtime.Boot - null
     java.lang.NullPointerException
     at saf.core.runtime.Boot.init(Boot.java:79)
     at saf.core.runtime.Boot.main(Boot.java:246)
     at repast.simphony.runtime.RepastMain.main(RepastMain.java:43)
</code>```

I also read about this problem on Repast Mailing List, and saw people talking about missing boot.properties file in the X\eclipse\plugins\repast.simphony.runtime_2.5.0 folder. However, the file is well in place there. So, I tried to link this to the previous error and saw that at (RepastMain.java:43) the pathInfo value was actually X\eclipse\plugins\repast.simphony.bin_and_src_2.5.0. Thus I tried to copy the boot.properties from the runtime directory to the bin_and_src - this removed the previous error, but brought a number of warnings related to UI initialization and an error:

```<code>     repast.simphony.ui.RSUIPlugin - Fatal error starting Repast
     java.lang.NoSuchMethodError: com.jgoodies.forms.layout.ColumnSpec.createGap(Lcom/jgoodies/forms/layout/ConstantSize;)Lcom/jgoodies/forms/layout/ColumnSpec;
at com.jgoodies.forms.layout.FormSpecs.<clinit>(FormSpecs.java:115)
at repast.simphony.ui.RunOptionsPanel.initComponents(RunOptionsPanel.java:114)
at repast.simphony.ui.RunOptionsPanel.<init>(RunOptionsPanel.java:39)
at repast.simphony.ui.RSGui.addRunOptionsView(RSGui.java:558)
at repast.simphony.ui.RSApplication.initGui(RSApplication.java:655)
at repast.simphony.ui.RSAppConfigurator.fillBars(RSAppConfigurator.java:52)
at saf.core.ui.GUICreatorDelegate.createDisplay(GUICreatorDelegate.java:160)
at saf.core.ui.GUICreator.createDisplay(GUICreator.java:12)
at repast.simphony.ui.RSUIPlugin$1.run(RSUIPlugin.java:102)
at java.desktop/java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.desktop/java.awt.EventQueue.access$500(Unknown Source)
at java.desktop/java.awt.EventQueue$3.run(Unknown Source)
at java.desktop/java.awt.EventQueue$3.run(Unknown Source)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.desktop/java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.desktop/java.awt.EventDispatchThread.run(Unknown Source)
</code>```

After seeing all that, enough frustration, and tries to reinstall the Repast and JDK the situation remained unchanged. Also need to note, that the same behavior is observed for other examples, and newly created Repast projects.

Would be very glad to hear your opinions on what can cause such Repast behavior.

答: It looks like this is an issue with Java 9 compatibility. Can you try a fresh install using the latest Java 8? In the meantime we'll follow up on what changes in Repast Simphony will be needed for Java 9 compatibility.</p>

Title: Problems with Repast Model Launch

Body:
After a fresh install of Repast Symphony 2.5.0 (Win 64bit) and JDK 9.0.1 on a Windows 10 system, when importing a JZombies_Demo example, the model cannot be launched with the default configuration.

The error says:

    An internal error occurred during: "Launching JZombies_Demo Model".
    org.codehaus.groovy.eclipse.core.builder.GroovyClasspathContainer.<init>(Lorg/eclipse/core/resources/IProject;)V

When I edit the default run configuration, in the Dependencies tab I see only the JRE System Library and nothing else. In the same tab, the Restore Default Entries is enabled - when I press it all the dependencies from Repast Symphony are added, and the previous error disappears. However, in this case when trying to launch another error is observed:

     saf.core.runtime.Boot - null
     java.lang.NullPointerException
     at saf.core.runtime.Boot.init(Boot.java:79)
     at saf.core.runtime.Boot.main(Boot.java:246)
     at repast.simphony.runtime.RepastMain.main(RepastMain.java:43)

I also read about this problem on Repast Mailing List, and saw people talking about missing boot.properties file in the X\eclipse\plugins\repast.simphony.runtime_2.5.0 folder. However, the file is well in place there. So, I tried to link this to the previous error and saw that at (RepastMain.java:43) the pathInfo value was actually X\eclipse\plugins\repast.simphony.bin_and_src_2.5.0. Thus I tried to copy the boot.properties from the runtime directory to the bin_and_src - this removed the previous error, but brought a number of warnings related to UI initialization and an error:

     repast.simphony.ui.RSUIPlugin - Fatal error starting Repast
     java.lang.NoSuchMethodError: com.jgoodies.forms.layout.ColumnSpec.createGap(Lcom/jgoodies/forms/layout/ConstantSize;)Lcom/jgoodies/forms/layout/ColumnSpec;
at com.jgoodies.forms.layout.FormSpecs.<clinit>(FormSpecs.java:115)
at repast.simphony.ui.RunOptionsPanel.initComponents(RunOptionsPanel.java:114)
at repast.simphony.ui.RunOptionsPanel.<init>(RunOptionsPanel.java:39)
at repast.simphony.ui.RSGui.addRunOptionsView(RSGui.java:558)
at repast.simphony.ui.RSApplication.initGui(RSApplication.java:655)
at repast.simphony.ui.RSAppConfigurator.fillBars(RSAppConfigurator.java:52)
at saf.core.ui.GUICreatorDelegate.createDisplay(GUICreatorDelegate.java:160)
at saf.core.ui.GUICreator.createDisplay(GUICreator.java:12)
at repast.simphony.ui.RSUIPlugin$1.run(RSUIPlugin.java:102)
at java.desktop/java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.desktop/java.awt.EventQueue.access$500(Unknown Source)
at java.desktop/java.awt.EventQueue$3.run(Unknown Source)
at java.desktop/java.awt.EventQueue$3.run(Unknown Source)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.desktop/java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.desktop/java.awt.EventDispatchThread.run(Unknown Source)

After seeing all that, enough frustration, and tries to reinstall the Repast and JDK the situation remained unchanged. Also need to note, that the same behavior is observed for other examples, and newly created Repast projects.

Would be very glad to hear your opinions on what can cause such Repast behavior.


问:
Change collor and texture in three.js
I'm trying to change the color and image of a material but I'm not getting it, I'm using the following code:

```<code>elf.material = new THREE.MeshPhongMaterial({map:THREE.ImageUtils.loadTexture('3d/caneca/e.jpg')});
</code>```

but it did not work.
In the object I have 3 materials, I wanted to change the color of one and replace the texture of another.

答:
You can change the material of an object at run time. All you need to do is, create a material by specifying the options and assign it to the object.
For example the following code will create a 'MeshStandardMaterial' with white color and other properties as specified. It will also have a texture which you have loaded. Consider 'box' as the object on which the material should be attached.

```<code>var material = new THREE.MeshStandardMaterial( { color: 0xffffff, side: THREE.FrontSide, opacity: 0.3, transparent: true, vertexColors: THREE.FaceColors, map : <THE TEXTURE YOU HAVE LOADED> } );
</code>```

As a better approach, you can load the texture using TextureLoader, and create a material when the texture is loaded. Following code explains that.

```<code>var loader = new THREE.TextureLoader();

function onLoad( texture ) {
    var material = new THREE.MeshPhongMaterial( { map : texture, color : 0xff0000 } );
    box.material = material;
}

function onProgress( xhr ) {
    console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
}

function onError( xhr ) {
    console.error( 'An error happened' );
}

loader.load( 'assets/img/crate.png', onLoad, onProgress, onError );
</code>```

You can also change the color and texture of the material without creating a new material,

to change only the color,

```<code>box.material.color.setHex( 0xff0000 );// will set red color for the box
</code>```

or to change the texture,

```<code>var loader = new THREE.TextureLoader();

function onLoad( texture ) {
    box.material.map = texture;
}

function onProgress( xhr ) {
    console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
}

function onError( xhr ) {
    console.error( 'An error happened' );
}

loader.load( 'assets/img/Dice-Blue-5.png', onLoad, onProgress, onError );
</code>```

Title: Change collor and texture in three.js

Body:
I'm trying to change the color and image of a material but I'm not getting it, I'm using the following code:

elf.material = new THREE.MeshPhongMaterial({map:THREE.ImageUtils.loadTexture('3d/caneca/e.jpg')});

but it did not work.
In the object I have 3 materials, I wanted to change the color of one and replace the texture of another.

Body:
You can change the material of an object at run time. All you need to do is, create a material by specifying the options and assign it to the object.
For example the following code will create a 'MeshStandardMaterial' with white color and other properties as specified. It will also have a texture which you have loaded. Consider 'box' as the object on which the material should be attached.

var material = new THREE.MeshStandardMaterial( { color: 0xffffff, side: THREE.FrontSide, opacity: 0.3, transparent: true, vertexColors: THREE.FaceColors, map : <THE TEXTURE YOU HAVE LOADED> } );

As a better approach, you can load the texture using TextureLoader, and create a material when the texture is loaded. Following code explains that.

var loader = new THREE.TextureLoader();

function onLoad( texture ) {
    var material = new THREE.MeshPhongMaterial( { map : texture, color : 0xff0000 } );
    box.material = material;
}

function onProgress( xhr ) {
    console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
}

function onError( xhr ) {
    console.error( 'An error happened' );
}

loader.load( 'assets/img/crate.png', onLoad, onProgress, onError );

You can also change the color and texture of the material without creating a new material,

to change only the color,

box.material.color.setHex( 0xff0000 );// will set red color for the box

or to change the texture,

var loader = new THREE.TextureLoader();

function onLoad( texture ) {
    box.material.map = texture;
}

function onProgress( xhr ) {
    console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
}

function onError( xhr ) {
    console.error( 'An error happened' );
}

loader.load( 'assets/img/Dice-Blue-5.png', onLoad, onProgress, onError );


问:
Cloudformation Init config files not writing the files
I am using AWS Cloudformation scripts to bring up a Auto-scaling Ec2 Instance - sample code provided below

```<code>    "GatewayLabAutoScalingGroup": {
  "Metadata": {
    "AWS::CloudFormation::Init": {
      "config": {
        "commands": {
          "a_install_pip": {
            "command": "pip install requests boto3"
          },
          "c_restart_cron": {
            "command": "service crond restart"
          },
          "d_restart_cfn_hup": {
            "command": "service cfn-hup restart"
          }
        },
        "files": {
          "/etc/cfn/cfn-hup.conf": {
            "content": {
              "Fn::Join": [
                "",
                [
                  "[main]\nstack=",
                  {
                    "Ref": "AWS::StackName"
                  },
                  "\nregion=",
                  {
                    "Ref": "AWS::Region"
                  },
                  "\nverbose=true\ninterval=1\n"
                ]
              ]
            },
            "group": "root",
            "mode": "000644",
            "owner": "root"
          },
          "/usr/local/sbin/join_ad_script.sh": {
            "content": {
              "Fn::Join": [
                "",
                [
                  "sudo yum -y update\nsudo yum -y install sssd realmd krb5-workstation\nsudo realm leave\n\nDOMAIN=\"",
                  {
                    "Ref": "SimpleADDomain"
                  },
                  "\"\n\ncat <<EOF > /etc/resolv.conf\nnameserver ",
                  {
                    "Fn::Select": [
                      0,
                      {
                        "Fn::GetAtt": [
                          "WorkspacesSimplead",
                          "DnsIpAddresses"
                        ]
                      }
                    ]
                  },
                  "\nnameserver ",
                  {
                    "Fn::Select": [
                      1,
                      {
                        "Fn::GetAtt": [
                          "WorkspacesSimplead",
                          "DnsIpAddresses"
                        ]
                      }
                    ]
                  },
                  "\nEOF\n\n# empty all current sssd cache\nsss_cache -E\n\necho ",
                  {
                    "Ref": "SimpleADPassword"
                  },
                  " | sudo realm join -U Administrator@${DOMAIN^^} ${DOMAIN^^} --verbose\nsudo sed -re 's/^(PasswordAuthentication)([[:space:]]+)no/\\1\\2yes/' -i.`date -I` /etc/ssh/sshd_config\necho \"enumerate=true\" >> /etc/sssd/sssd.conf\nsudo service sssd restart\nsudo service sshd restart\n\n# empty all current sssd cache\nsss_cache -E\n"
                ]
              ]
            },
            "group": "root",
            "mode": "000755",
            "owner": "root"
          }
        }
      }
    }
  },
  "Properties": {
    "AvailabilityZones": [
      {
        "Fn::Select": [
          0,
          {
            "Fn::GetAZs": ""
          }
        ]
      }
    ],
    "HealthCheckGracePeriod": 300,
    "HealthCheckType": "EC2",
    "LaunchConfigurationName": {
      "Ref": "GatewayLabLaunchConfiguration"
    },
    "LoadBalancerNames": [

    ],
    "MaxSize": 2,
    "MinSize": 1,
    "Tags": [
      {
        "Key": "Name",
        "PropagateAtLaunch": true,
        "Value": "hub-autoscaling"
        }
      }
    ],
    "VPCZoneIdentifier": [
      {
        "Ref": "EC2SubnetSubnet1"
      }
    ]
  },
  "Type": "AWS::AutoScaling::AutoScalingGroup",
  "UpdatePolicy": {
    "AutoScalingRollingUpdate": {
      "MaxBatchSize": 1,
      "MinInstancesInService": 1,
      "PauseTime": "PT60S"
    }
  }
}
</code>```

The files are not written to in the instance
The instance is coming up in a Private VPC
We have a proxy configured on port 8080

The works fine when the instance is connected to a NAT Gateway without a proxy

I do have ports 80, 22 & 443 opened up

答:
the userdata statements are run initially
They then call the cfn-init scripts

There were some errors in the scripts and they never completed; one of the problems as mentioned above was my instance behind a proxy

Getting the proxy configuration in as part of the UserData helped

Body:
I am using AWS Cloudformation scripts to bring up a Auto-scaling Ec2 Instance - sample code provided below

    "GatewayLabAutoScalingGroup": {
  "Metadata": {
    "AWS::CloudFormation::Init": {
      "config": {
        "commands": {
          "a_install_pip": {
            "command": "pip install requests boto3"
          },
          "c_restart_cron": {
            "command": "service crond restart"
          },
          "d_restart_cfn_hup": {
            "command": "service cfn-hup restart"
          }
        },
        "files": {
          "/etc/cfn/cfn-hup.conf": {
            "content": {
              "Fn::Join": [
                "",
                [
                  "[main]\nstack=",
                  {
                    "Ref": "AWS::StackName"
                  },
                  "\nregion=",
                  {
                    "Ref": "AWS::Region"
                  },
                  "\nverbose=true\ninterval=1\n"
                ]
              ]
            },
            "group": "root",
            "mode": "000644",
            "owner": "root"
          },
          "/usr/local/sbin/join_ad_script.sh": {
            "content": {
              "Fn::Join": [
                "",
                [
                  "sudo yum -y update\nsudo yum -y install sssd realmd krb5-workstation\nsudo realm leave\n\nDOMAIN=\"",
                  {
                    "Ref": "SimpleADDomain"
                  },
                  "\"\n\ncat <<EOF > /etc/resolv.conf\nnameserver ",
                  {
                    "Fn::Select": [
                      0,
                      {
                        "Fn::GetAtt": [
                          "WorkspacesSimplead",
                          "DnsIpAddresses"
                        ]
                      }
                    ]
                  },
                  "\nnameserver ",
                  {
                    "Fn::Select": [
                      1,
                      {
                        "Fn::GetAtt": [
                          "WorkspacesSimplead",
                          "DnsIpAddresses"
                        ]
                      }
                    ]
                  },
                  "\nEOF\n\n# empty all current sssd cache\nsss_cache -E\n\necho ",
                  {
                    "Ref": "SimpleADPassword"
                  },
                  " | sudo realm join -U Administrator@${DOMAIN^^} ${DOMAIN^^} --verbose\nsudo sed -re 's/^(PasswordAuthentication)([[:space:]]+)no/\\1\\2yes/' -i.`date -I` /etc/ssh/sshd_config\necho \"enumerate=true\" >> /etc/sssd/sssd.conf\nsudo service sssd restart\nsudo service sshd restart\n\n# empty all current sssd cache\nsss_cache -E\n"
                ]
              ]
            },
            "group": "root",
            "mode": "000755",
            "owner": "root"
          }
        }
      }
    }
  },
  "Properties": {
    "AvailabilityZones": [
      {
        "Fn::Select": [
          0,
          {
            "Fn::GetAZs": ""
          }
        ]
      }
    ],
    "HealthCheckGracePeriod": 300,
    "HealthCheckType": "EC2",
    "LaunchConfigurationName": {
      "Ref": "GatewayLabLaunchConfiguration"
    },
    "LoadBalancerNames": [

    ],
    "MaxSize": 2,
    "MinSize": 1,
    "Tags": [
      {
        "Key": "Name",
        "PropagateAtLaunch": true,
        "Value": "hub-autoscaling"
        }
      }
    ],
    "VPCZoneIdentifier": [
      {
        "Ref": "EC2SubnetSubnet1"
      }
    ]
  },
  "Type": "AWS::AutoScaling::AutoScalingGroup",
  "UpdatePolicy": {
    "AutoScalingRollingUpdate": {
      "MaxBatchSize": 1,
      "MinInstancesInService": 1,
      "PauseTime": "PT60S"
    }
  }
}

The files are not written to in the instance
The instance is coming up in a Private VPC
We have a proxy configured on port 8080

The works fine when the instance is connected to a NAT Gateway without a proxy

I do have ports 80, 22 & 443 opened up


问:
S/MIME Mail - signed or not signed - what's the standard procedure for sending to a known recipient
If you have already exchanged certificates with somebody and you already encrypt emails, do you sign the following emails anyway/again? What is the accepted standard procedure for this? Where is this described?</p>

答:
The purpose of a (cryptographic) signature on an email is to prove that the sender is who the sender claims to be, and not some one who found an open relay mail server to forge a From:.  Therefore one would sign any message that one wants to have proof of origin on, which one presumes would be all messages.

Encrypting means that only the intended recipient(s) can read it, but doesn't say anything about who sent it. So, great, an encrypted mail had an attachment... still throwing it in the trash. Or, I might have a policy to not decrypt it at all because it's bigger than 100kb and unsigned (I don't know of any client that has policies like that, but they're not unreasonable).


问:
FastText using pre-trained word vector for text classification
I am working on a text classification problem, that is, given some text, I need to assign to it certain given labels.

I have tried using fast-text library by Facebook, which has two utilities of interest to me:

A) Word Vectors with pre-trained models

B) Text Classification utilities

However, it seems that these are completely independent tools as I have been unable to find any tutorials that merge these two utilities.

What I want is to be able to classify some text, by taking advantage of the pre-trained models of the Word-Vectors. Is there any way to do this?

答:
FastText's native classification mode depends on you training the word-vectors yourself, using texts with known classes. The word-vectors thus become optimized to be useful for the specific classifications observed during training. So that mode typically wouldn't be used with pre-trained vectors.

If using pre-trained word-vectors, you'd then somehow compose those into a text-vector yourself (for example, by averaging all the words of a text together), then training a separate classifier (such as one of the many options from scikit-learn) using those features.


问:
Sql MAX DateTime and if clause?
My 2nd Sql question on SO today - I need to brush up my Sql skills!!!!

I have the following three tables....

Diary, Entry, and EntryType

A Diary can have many Entry(ies), each Entry is of a particular EntryType.

Entry has a created DateTime
EntryType has an Id, and SomeOtherValue (int)

EDIT

Sorry Chaps.  Thanks for response so far but I didn't explain it well enough; the requirements have changed a bit.....

I would like the Id of any Diary where its latest Entry that is greater than @lastDateTime AND EntryType.someOthervalue != 0 has a EntryType.someOthervalue == @someValue

Or to put it another way....For all those Entry rows with a created Date time > @lastDateTime, ignore the someOtherValues that equal 0, and if the top 1 left over has a someOtherValue = @someValue, return the Id of the diary!!!!

Does that make sense???  I'm not sure what I should be putting my MAX, WHERE, and HAVING (if anything at all!)

Thanks,

ETFairfax.

答:
If you want the last entry, and then with the last entry, test whether the entrytype of that last entry is @somevalue, then this should be the right query

```<code>select diaryid
from (
    select rn=row_number() over (partition by e.diaryid order by e.created desc),
        d.diaryid, et.someothervalue
    from entry e
    inner join entrytype et on e.entrytype = et.id
    where e.created > @lastDateTime
) X
where rn=1
  and SomeOtherValue = @someValue -- of the last record
</code>```

If however, you mean, among the entry types of @somevalue, is the latest one >@lastDateTime, then it is

```<code>select e.diaryid
from entry e
inner join entrytype et on e.entrytype = et.id
where et.SomeOtherValue = @someValue
group by e.diaryid
having max(e.created) > @lastDateTime
</code>```

Note: For a db with proper references, the diary_id can be derived from entry without going back to diary. The only reason for linking back to diary is if you need the full diary record, or if there is no foreign key and you need to validate that the diary_id exists.

For the 2nd type, there is another way to write this that is still ANSI compliant and may be faster.  This works by deducing that for the MAX e.created to be greater than @lastdatetime, ANY record

EDIT: As Andriy points out for the 2nd query (directly preceeding this statement), the HAVING clause can be moved to the WHERE clause based on the same fact, but I have left the query in that form to match the expression of the requirements (not using the deduced simplification).

```<code>select e.diaryid
from entry e
where exists (
    select *
    from entrytype et
    where e.entrytype = et.id
      and et.SomeOtherValue = @someValue)
  and e.created > @lastDateTime
GROUP BY e.diaryid
</code>```

This EXISTential test can stop inspecting entrytypes for an entry as soon as it finds one matching somevalue and created instead of fully processing the join and aggregating (max) before filtering it down in the HAVING clause.

Title: Sql MAX DateTime and if clause?

Body:
If you want the last entry, and then with the last entry, test whether the entrytype of that last entry is @somevalue, then this should be the right query

select diaryid
from (
    select rn=row_number() over (partition by e.diaryid order by e.created desc),
        d.diaryid, et.someothervalue
    from entry e
    inner join entrytype et on e.entrytype = et.id
    where e.created > @lastDateTime
) X
where rn=1
  and SomeOtherValue = @someValue -- of the last record

If however, you mean, among the entry types of @somevalue, is the latest one >@lastDateTime, then it is

select e.diaryid
from entry e
inner join entrytype et on e.entrytype = et.id
where et.SomeOtherValue = @someValue
group by e.diaryid
having max(e.created) > @lastDateTime

Note: For a db with proper references, the diary_id can be derived from entry without going back to diary. The only reason for linking back to diary is if you need the full diary record, or if there is no foreign key and you need to validate that the diary_id exists.

For the 2nd type, there is another way to write this that is still ANSI compliant and may be faster.  This works by deducing that for the MAX e.created to be greater than @lastdatetime, ANY record

EDIT: As Andriy points out for the 2nd query (directly preceeding this statement), the HAVING clause can be moved to the WHERE clause based on the same fact, but I have left the query in that form to match the expression of the requirements (not using the deduced simplification).

select e.diaryid
from entry e
where exists (
    select *
    from entrytype et
    where e.entrytype = et.id
      and et.SomeOtherValue = @someValue)
  and e.created > @lastDateTime
GROUP BY e.diaryid

This EXISTential test can stop inspecting entrytypes for an entry as soon as it finds one matching somevalue and created instead of fully processing the join and aggregating (max) before filtering it down in the HAVING clause.


问:
Run simple console application made with VS2010 framework 4.0 in a XP computer with framework 1.1
The application is quite simple, it just deletes some local files every configured time period, there is no linq no nothing "new" in the code. If I change the target framework to 2.0 it works well in my computer, but VS2010 doesnt have .net 1.1 as an available target framework.

Is it possible to have it run in an old xp computer that has framework 1.1 (I dont have acces to the computer, cant change its framework). The question is, is there something I can do (in the config file or sln file?) so that it can run in framework 1.1, or do I have to get VS2003 to recreate the console app using 1.1 framework?

Thanks in advance.

答:
No, there is nothing you can do to get 2.0 or 4.x .Net executable to run with 1.x framework.

You need to compile against 1.x. If you have old VS 2003 around you can use it to recompile solution. If you can't find it - you still can use command line tools (see Visual Studio 2005 and .Net framework 1.1 for some info). For simple project with just CS files using csc on target machine to compile the tool from sources may be the easiest route.