问:
Java beginner: convert an image to a binary array
this is what I've gone so far and I can't seem to go further because I don't understand bitwise operations on the RGB

```<code>// Read from a file
File file = new File("src/a.gif");
image = ImageO.read(file);
int[] rgbarr = image.getRGB(0, 0, 13, 15, null, 0, 13);// image is 13*15
System.out.println(rgbarr.length);
for (int i : rgbarr)
    {
        System.out.println(i);
    }
</code>```

Output: was values such as -16777216 and -1 Because I've already made an image black and white just to ease my understanding

But in our case here let's suppose it would be just random image , how do I get from normal RGB image to binary values (0 or 1) for each pixel.

答:
You can do some thing like this,

```<code>BufferedImage img = (BufferedImage) image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img , "jpg", baos);
byte[] previewByte = baos.toByteArray();
</code>```

Hope this helps!!

Body:
this is what I've gone so far and I can't seem to go further because I don't understand bitwise operations on the RGB

// Read from a file
File file = new File("src/a.gif");
image = ImageO.read(file);
int[] rgbarr = image.getRGB(0, 0, 13, 15, null, 0, 13);// image is 13*15
System.out.println(rgbarr.length);
for (int i : rgbarr)
    {
        System.out.println(i);
    }

Output: was values such as -16777216 and -1 Because I've already made an image black and white just to ease my understanding

But in our case here let's suppose it would be just random image , how do I get from normal RGB image to binary values (0 or 1) for each pixel.

Body:
You can do some thing like this,

BufferedImage img = (BufferedImage) image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img , "jpg", baos);
byte[] previewByte = baos.toByteArray();

Hope this helps!!


来源: stackexchange

问:
ElasticSearch - How to Aggregate the Geometric Mean?
I'm currently aggregating records to get the average (arithmetic average) of a field in the returned records. My use case requires me to get hold of the geometric average:

The geometric mean is defined as the nth root of the product of n

How could I go about getting this value? I don't even know where to start!

Thanks!

答:
It is not trivial, but it can be done. The idea is to use a sum of logs and then apply the n-th root:

```<code>pow(exp((sum of logs)), 1/n)
</code>```

In fact, GeometricMean aggregation of Elasticsearch Index Termlist Plugin does exactly that. (However, this is a third-party plugin, I can't tell if it is stable enough.)

Mapping and sample data

Let's assume we have the following mapping:

```<code>PUT geom_mean
{
  "mappings": {
    "nums": {
      "properties": {
        "x": {
          "type": "double"
        }
      }
    }
  }
}
</code>```

And we insert the following documents:

```<code>{"x":33}
{"x":324}
{"x":134}
{"x":0.1}
</code>```

Now we can try the query.

The ES query

Here is the query to calculate geometric mean:

```<code>POST geom_mean/nums/_search
{
  "size": 0,
  "aggs": {
    "aggs_root": {
      "terms": {
        "script": "'Bazinga!'"
      },
      "aggs": {
        "sum_log_x": {
          "sum": {
            "script": {
              "inline": "Math.log(doc.x.getValue())"
            }
          }
        },
        "geom_mean": {
          "bucket_script": {
            "buckets_path": {
              "sum_log_x": "sum_log_x",
              "x_cnt": "_count"
            },
            "script": "Math.pow(Math.exp(params.sum_log_x), 1 / params.x_cnt)"
          }
        }
      }
    }
  }
}
</code>```

The return value will be:

```<code>  "aggregations": {
    "aggs_root": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "Bazinga!",
          "doc_count": 4,
          "sum_log_x": {
            "value": 11.872505784215674
          },
          "geom_mean": {
            "value": 19.455434622111177
          }
        }
      ]
    }
  }
</code>```

Now a bit of explanation. Aggregation sum_log_x computes the sum of x. Aggregation named geom_mean is a sibling pipeline aggregation which is applied on the result of sum_log_x aggregation (its sibling). It uses special bucket path _count to get the number of elements. (Here you can read about bucket_script aggregation a bit more.)

The final trick is to wrap both of them with some aggregation, because, as explained in this issue, bucket_script cannot be a top-level aggregation. Here I do a terms aggregation on a script that always returns 'Bazinga!'

Thanks to anhzhi who proposed this hack.

Important considerations

Since the geometric mean is computed through logs, all x values should be greater than 0. However:

if any of values are < 0, the result is "NaN"

if all values are non-negative and less than "+Infinity", but at least one value is 0, the result is "-Infinity"

if both "+Infinity" and "-Infinity" are among the values, the result is "NaN".

The queries were tested with Elasticsearch 5.4. Performance on a large collection of documents was not tested, you might consider inserting x together with its log to make aggregations more efficient.

Hope that helps!

ContentLicense: CC BY-SA 3.0

Body:
It is not trivial, but it can be done. The idea is to use a sum of logs and then apply the n-th root:

pow(exp((sum of logs)), 1/n)

In fact, GeometricMean aggregation of Elasticsearch Index Termlist Plugin does exactly that. (However, this is a third-party plugin, I can't tell if it is stable enough.)

Mapping and sample data

Let's assume we have the following mapping:

PUT geom_mean
{
  "mappings": {
    "nums": {
      "properties": {
        "x": {
          "type": "double"
        }
      }
    }
  }
}

And we insert the following documents:

{"x":33}
{"x":324}
{"x":134}
{"x":0.1}

Now we can try the query.

The ES query

Here is the query to calculate geometric mean:

POST geom_mean/nums/_search
{
  "size": 0,
  "aggs": {
    "aggs_root": {
      "terms": {
        "script": "'Bazinga!'"
      },
      "aggs": {
        "sum_log_x": {
          "sum": {
            "script": {
              "inline": "Math.log(doc.x.getValue())"
            }
          }
        },
        "geom_mean": {
          "bucket_script": {
            "buckets_path": {
              "sum_log_x": "sum_log_x",
              "x_cnt": "_count"
            },
            "script": "Math.pow(Math.exp(params.sum_log_x), 1 / params.x_cnt)"
          }
        }
      }
    }
  }
}

The return value will be:

  "aggregations": {
    "aggs_root": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "Bazinga!",
          "doc_count": 4,
          "sum_log_x": {
            "value": 11.872505784215674
          },
          "geom_mean": {
            "value": 19.455434622111177
          }
        }
      ]
    }
  }

Now a bit of explanation. Aggregation sum_log_x computes the sum of x. Aggregation named geom_mean is a sibling pipeline aggregation which is applied on the result of sum_log_x aggregation (its sibling). It uses special bucket path _count to get the number of elements. (Here you can read about bucket_script aggregation a bit more.)

The final trick is to wrap both of them with some aggregation, because, as explained in this issue, bucket_script cannot be a top-level aggregation. Here I do a terms aggregation on a script that always returns 'Bazinga!'

Thanks to anhzhi who proposed this hack.

Important considerations

Since the geometric mean is computed through logs, all x values should be greater than 0. However:

if any of values are < 0, the result is "NaN"

if all values are non-negative and less than "+Infinity", but at least one value is 0, the result is "-Infinity"

if both "+Infinity" and "-Infinity" are among the values, the result is "NaN".

The queries were tested with Elasticsearch 5.4. Performance on a large collection of documents was not tested, you might consider inserting x together with its log to make aggregations more efficient.

Hope that helps!


问:
Appending a value in PowerShell
Goal: To identify elements with specific values in an attribute and append the value of identified values with user input.

I have an XML file which multiple resource elements, some of which has XML values and some not. Below is an example.

<resources>
  <resource identifier="i149" href="items/i149/qti.xml">
    <file href="items/i149/qti.xml" />
  </resource>
</resources>
```

<p>I am stuck as to how to append what I've identified. I'm currently using <code>SelectNodes()</code> to identify that any identifier value containing an <code>i</code> should be appended by with <code>$userInput</code>.   When I run it, though, I get this error:</p>

<blockquote>
  <p>Cannot convert argument "0", with value: "_01a", for "AppendChild" to type "System.Xml.XmlNode": "Cannot convert the "_01a" value of type "System.String" to type "System.Xml.XmlNode"."</p>
</blockquote>

<p>Instead of <code>SelectNodes()</code>, should I be getting the XML as a string?  Below is the code.</p>

<pre class="lang-bsh prettyprint-override"><code>#user prompt
$userInput = Read-Host -Prompt 'Insert 2 alpha-numeric'

#ims
$imsnodes = [xml](Get-Content $ims.FullName)
$identifier = $imsnodes.SelectNodes("//*[contains(@identifier,'i')]")
$identifier.AppendChild("_$userInput")
$imsnodes.Save($_.FullName)
</code>```

The outcome I would like to have is below, where XX = $userInput:

<resources>
  <resource identifier="i149_XX" href="items/i149/qti_XX.xml">
    <file href="items/i149/qti_XX.xml" />
  </resource>
</resources>
```

答:
You want to append a string to an attribute value, not an XML node to another XML node (which is what the AppendChild() method does).

Change this:

```<code>$identifier = $imsnodes.SelectNodes("//*[contains(@identifier,'i')]")
$identifier.AppendChild("_$userInput")
</code>```

into this:

```<code>$imsnodes.SelectNodes("//*[contains(@identifier,'i')]") | ForEach-Object {
    $_.identifier += "_$userInput"
}
</code>```

and the problem will disappear.

Title: Appending a value in PowerShell

Body:
Goal: To identify elements with specific values in an attribute and append the value of identified values with user input.

I have an XML file which multiple resource elements, some of which has XML values and some not. Below is an example.

<resources>
  <resource identifier="i149" href="items/i149/qti.xml">
    <file href="items/i149/qti.xml" />
  </resource>
</resources>

I am stuck as to how to append what I've identified. I'm currently using SelectNodes() to identify that any identifier value containing an i should be appended by with $userInput.   When I run it, though, I get this error:

Cannot convert argument "0", with value: "_01a", for "AppendChild" to type "System.Xml.XmlNode": "Cannot convert the "_01a" value of type "System.String" to type "System.Xml.XmlNode"."

Instead of SelectNodes(), should I be getting the XML as a string?  Below is the code.

#user prompt
$userInput = Read-Host -Prompt 'Insert 2 alpha-numeric'

#ims
$imsnodes = [xml](Get-Content $ims.FullName)
$identifier = $imsnodes.SelectNodes("//*[contains(@identifier,'i')]")
$identifier.AppendChild("_$userInput")
$imsnodes.Save($_.FullName)

The outcome I would like to have is below, where XX = $userInput:

<resources>
  <resource identifier="i149_XX" href="items/i149/qti_XX.xml">
    <file href="items/i149/qti_XX.xml" />
  </resource>
</resources>

Body:
You want to append a string to an attribute value, not an XML node to another XML node (which is what the AppendChild() method does).

Change this:

$identifier = $imsnodes.SelectNodes("//*[contains(@identifier,'i')]")
$identifier.AppendChild("_$userInput")

into this:

$imsnodes.SelectNodes("//*[contains(@identifier,'i')]") | ForEach-Object {
    $_.identifier += "_$userInput"
}

and the problem will disappear.


问:
CSS: Make it possible that element only have differnent :hover background after clicking (:active) on it
Hi there I try to make it possible that you first need to click on the element and after that it should chang the background everytime you hover over it. Important is that No JavaScript or JQuery should be used. It's not a link so :visited and href is not an option

```<code>*Pseudocode*

 *if* .lst-c:active *than* .lst-c:hover   {
       background: blue;
       border-radius: 20px 20px 0px 0px !important;
       }
</code>```

答:
Checkbox

/* Hide */
.is {  display: none  }

/* Is checked */
.is:checked + label .content:hover {  background: blue;  }

/* Not checked */
.content:hover {  background: red;  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" class="is" id="clicker">
<label for="clicker">
  <div class="content">Hello</div>
</label></code>```

Body:
Hi there I try to make it possible that you first need to click on the element and after that it should chang the background everytime you hover over it. Important is that No JavaScript or JQuery should be used. It's not a link so :visited and href is not an option

*Pseudocode*

 *if* .lst-c:active *than* .lst-c:hover   {
       background: blue;
       border-radius: 20px 20px 0px 0px !important;
       }

Body:
Checkbox

/* Hide */
.is {  display: none  }

/* Is checked */
.is:checked + label .content:hover {  background: blue;  }

/* Not checked */
.content:hover {  background: red;  }

<input type="checkbox" class="is" id="clicker">
<label for="clicker">
  <div class="content">Hello</div>
</label>


问:
Angular 2 ng2-redux and ngrx/store
I am new in Angular2, I know flux architecture and ng2 redux, ngrx/store but still confused which library is used for development of an application. Both of are provided the implementation of flux.
What is the difference between ng2-redux and ngrx/store?
What should be used in development?</p>

答:
From what I understand, the primary difference between the two is that ng2-redux uses Angular bindings for existing React/Redux implementation, whereas ngrx/store is an entire reimplementation of Redux concepts. As a result, some people will argue that ng2-redux has better compatibility with React/Redux libraries, middleware, and devtools.

hendrikswan on Github, who made a pretty good Pluralsight course on Angular with Redux, also claims that ng2-redux is a "more optimized way" to introduce Redux to an existing Angular application. (Source)

Despite all that, if you look and the ng2-redux Github vs the ngrx/store, looks like ngrx/store is a bit more popular. :)

Both are valid solutions to store management, so really it might just boil down to preference.

Title: Angular 2 ng2-redux and ngrx/store


问:
UIBezierPath on UiView doesn't update until scroll the tableview
I have added UIView to cell of Tableview and given the beizer path to bottom and right by following:

```<code>UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRect:CGRectMake(0,
                          0,
                          cell.bgView.frame.size.width -2+ shadowSize,
                          cell.bgView.frame.size.height+1 + shadowSize)];
    cell.bgView.layer.masksToBounds = NO;
    cell.bgView.layer.shadowColor = [[UIColor colorWithRed:186.0/255.0 green:0.0/255.0 blue:231.0/255.0 alpha:1.0f]CGColor];
    cell.bgView.layer.shadowOffset = CGSizeMake(0.0f, 0.0f);
    cell.bgView.layer.shadowOpacity = 0.7f;
    cell.bgView.layer.shadowPath = shadowPath.CGPath;
</code>```

First time, when tableview reload, bezier path doesn't load properly

but when I scroll up/down then it looks perfectly

.

I have tried with every possible solution i.e.

```<code>dispatch_async(dispatch_get_main_queue(), ^{
                [self.topRatedTable reloadData];
            });
</code>```

or

```<code> [cell layoutIfNeeded];
    [cell updateConstraintsIfNeeded];
</code>```

But nothing works.

答:
Your cell and its subviews (like, I assume, bgView) don't have their final frames until layout has run. If your path-creating code is in your tableView:cellForRowAtIndexPath: method, then you are accessing cell.bgView.frame before layout has run.

In your custom UITableViewCell subclass, override layoutSubviews and set the shadowPath after calling super:

```<code>// In your custom `UITableViewCell` subclass:
- (void)layoutSubviews {
    [super layoutSubviews];
    UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRect:CGRectMake(0,
                      0,
                      cell.bgView.frame.size.width -2+ shadowSize,
                      cell.bgView.frame.size.height+1 + shadowSize)];
    self.bgView.layer.shadowPath = shadowPath.CGPath;
}
</code>```

Body:
I have added UIView to cell of Tableview and given the beizer path to bottom and right by following:

UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRect:CGRectMake(0,
                          0,
                          cell.bgView.frame.size.width -2+ shadowSize,
                          cell.bgView.frame.size.height+1 + shadowSize)];
    cell.bgView.layer.masksToBounds = NO;
    cell.bgView.layer.shadowColor = [[UIColor colorWithRed:186.0/255.0 green:0.0/255.0 blue:231.0/255.0 alpha:1.0f]CGColor];
    cell.bgView.layer.shadowOffset = CGSizeMake(0.0f, 0.0f);
    cell.bgView.layer.shadowOpacity = 0.7f;
    cell.bgView.layer.shadowPath = shadowPath.CGPath;

First time, when tableview reload, bezier path doesn't load properly

but when I scroll up/down then it looks perfectly

.

I have tried with every possible solution i.e.

dispatch_async(dispatch_get_main_queue(), ^{
                [self.topRatedTable reloadData];
            });

or

 [cell layoutIfNeeded];
    [cell updateConstraintsIfNeeded];

But nothing works.

Body:
Your cell and its subviews (like, I assume, bgView) don't have their final frames until layout has run. If your path-creating code is in your tableView:cellForRowAtIndexPath: method, then you are accessing cell.bgView.frame before layout has run.

In your custom UITableViewCell subclass, override layoutSubviews and set the shadowPath after calling super:

// In your custom `UITableViewCell` subclass:
- (void)layoutSubviews {
    [super layoutSubviews];
    UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRect:CGRectMake(0,
                      0,
                      cell.bgView.frame.size.width -2+ shadowSize,
                      cell.bgView.frame.size.height+1 + shadowSize)];
    self.bgView.layer.shadowPath = shadowPath.CGPath;
}


答:
I think I got it.

The code above is for color images (3 channels) and it seems you are trying to run it over a B&W image (1 channel).

Either use a color image or replace the second line by:

```<code>b = Image@ArrayPad[ImageData@a, {{40, 0}, {40}}, 1];
</code>```

Here is the result for your image using the above replacement as:

```<code>a = Binarize[Image["path/file.png"]]
b = Image@ArrayPad[ImageData@a, {{40, 0}, {40}}, 1];
</code>```

ContentLicense: CC BY-SA 2.5

Title: Image manipulation with Mathematica

Body:
I've created this theme after my previous post. I can't run the following code (written by @belisarius):

a = Image["path/file.png"]
b = Image@ArrayPad[ImageData@a, {{40, 0}, {40}, {0}}, {1, 1, 1}];
f[image_, angleMult_] := ImageForwardTransformation[image, (
    fi = ArcTan[Abs[#[[2]]/(#[[1]] - .5)]];
    fi1 = angleMult fi (#[[1]]^2 + #[[2]]^2)/2;
    {(1/2 - Sin[fi1] #[[2]] - Cos[fi1]/2 +
       Cos[fi1] #[[1]]), -Sin[fi1]/2 + Sin[fi1] #[[1]] +
      Cos[fi1] #[[2]]}) &]
t = Table[f[b, x], {x, 0, .2, .02}];
t1 = Reverse@t;
Export["anim.gif", Join[t, t1], "DisplayDurations" -> .15];
Import["anim.gif", "Animation"]

Here is a list of errors:

ArrayPad::depth: Padding amount {{40,0},{40},{0}} should specify padding in no more than the number of dimensions in array {{1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,0.996078,0.984314,<<142>>},<<49>>,<<145>>}. >>

Image::imgarray: The specified argument ArrayPad[{{1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,0.996078,0.984314,<<142>>},<<49>>,<<145>>},{{40,0},{40},{0}},{1,1,1}] should be an array of rank 2 or 3 with machine-sized numbers. >>

ImageForwardTransformation::imginv: Expecting an image or graphics instead of Image[ArrayPad[{{1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,0.996078,0.984314,<<142>>},<<49>>,<<145>>},{<<1>>},{1,1,1}]]. >>

General::stop: Further output of ImageForwardTransformation::imginv will be suppressed during this calculation. >>

Rasterize::bigraster: Not enough memory available to rasterize ImageForwardTransformation expression. >>

General::stop: Further output of Rasterize::bigraster will be suppressed during this calculation. >>

I'm using Mathematica 8 under Linux.

Body:
I think I got it.

The code above is for color images (3 channels) and it seems you are trying to run it over a B&W image (1 channel).

Either use a color image or replace the second line by:

b = Image@ArrayPad[ImageData@a, {{40, 0}, {40}}, 1];

Here is the result for your image using the above replacement as:

a = Binarize[Image["path/file.png"]]
b = Image@ArrayPad[ImageData@a, {{40, 0}, {40}}, 1];


问:
check List <int> A contains elements from list B, with repeated values

I'm trying to check if List<int> A contains all values available on List<int> B

But I need to be sure that not only values are correct but also their count, if A is real subset of B.

I found solution like this, but both gives wrong answer:

```<code>List <int> A = new List <int>(){1,1,2,3};
List <int> B = new List <int>(){1,2,3,5,6,7,8,9};

bool c = A.All(B.Contains);
bool d = !A.Except(B).Any();
Console.WriteLine(c); //True
Console.WriteLine(d); //True
</code>```

List A can't be subset of list B, because it contains double value 1;

How can I handle with repeated values?

More examples

```<code>A = {1,2,3};
B = {1,2,3,4,5};
A is a subset of B => True

A = {1,1,2,3,2};
B = {1,1,2,2,3,4,5};
A is a subset of B => True

A = {1,2,3};
B = {1,1,2,2,3,4,5};
A is a subset of B => True
</code>```

but:

```<code>A = {1,2,2,3};
B = {1,2,3,4,5};
A is not a subset of B => False
</code>```

答:
You could do the following to group the values and check the counts.</p>

```<code>var bCounts = B.GroupBy(x=>x).ToDictionary(g=>g.Key, g=>g.Count());
bool aIsSubsetOfB = A.GroupBy(x=>x)
    .All(g => bCounts.ContainsKey(g.Key) && bCounts[g.Key] > g.Count());
</code>```

Body:
I'm trying to check if List<int> A contains all values available on List<int> B

But I need to be sure that not only values are correct but also their count, if A is real subset of B.

I found solution like this, but both gives wrong answer:

List <int> A = new List <int>(){1,1,2,3};
List <int> B = new List <int>(){1,2,3,5,6,7,8,9};

bool c = A.All(B.Contains);
bool d = !A.Except(B).Any();
Console.WriteLine(c); //True
Console.WriteLine(d); //True

List A can't be subset of list B, because it contains double value 1;

How can I handle with repeated values?

More examples

A = {1,2,3};
B = {1,2,3,4,5};
A is a subset of B => True

A = {1,1,2,3,2};
B = {1,1,2,2,3,4,5};
A is a subset of B => True

A = {1,2,3};
B = {1,1,2,2,3,4,5};
A is a subset of B => True

but:

A = {1,2,2,3};
B = {1,2,3,4,5};
A is not a subset of B => False

Body:
You could do the following to group the values and check the counts.

var bCounts = B.GroupBy(x=>x).ToDictionary(g=>g.Key, g=>g.Count());
bool aIsSubsetOfB = A.GroupBy(x=>x)
    .All(g => bCounts.ContainsKey(g.Key) && bCounts[g.Key] > g.Count());


问:
efficient number generator for correlation studies
My goal is to generate 7 numbers within a min and max range that correspond to a Pearson correlation coefficient of greater than 0.95. I have been successful with 3 numbers (obviously because this isn't very computationally demanding).. however for 4 numbers, the computation required seems very large (i.e. on the order of 10k iterations). 7 numbers would be almost impossible with the current code.

Current code:

```<code>def pearson_def(x, y):
    assert len(x) == len(y)
    n = len(x)
    assert n > 0
    avg_x = average(x)
    avg_y = average(y)
    diffprod = 0
    xdiff2 = 0
    ydiff2 = 0
    for idx in range(n):
        xdiff = x[idx] - avg_x
        ydiff = y[idx] - avg_y
        diffprod += xdiff * ydiff
        xdiff2 += xdiff * xdiff
        ydiff2 += ydiff * ydiff

    return diffprod / math.sqrt(xdiff2 * ydiff2)

c1_high = 98
c1_low = 75

def corr_gen():
    container =[]
    x=0
    while True:
        c1 = c1_low
        c2 = np.random.uniform(c1_low, c1_high)
        c3 = c1_high
        container.append(c1)
        container.append(c2)
        container.append(c3)
        y = np.arange(len(container))

        if pearson_def(container,y) >0.95:
            c4 = np.random.uniform(c1_low, c1_high)
            container.append(c4)
            y = np.arange(len(container))
            if pearson_def(container,y) >0.95:
                return container
            else:
                continue
        else:
            x+=1
            print(x)
            continue

corrcheck = corr_gen()
print(corrcheck)
</code>```

Final objective:

*To have 4 columns with a linear distribution (with evenly spaced points)

*Each row corresponds to a group of items (C1,C2,C3,C4) and their sum must equal to 100.

```<code>       C1      C2    C3    C4   sum   range
 1     70      10    5     1    100    ^
 2     ..                              |
 3     ..                              |
 4     ..                              |
 5     ..                              |
 6     ..                              |
 7     90      20    15    3           _
</code>```

Example spread for two theoretical components:

答:
You can use np.random.multivariate_normal as follows:

```<code>import numpy as np

_corr = 0.95
n = 2
size = 7

corr = np.full((n, n), _corr)
np.fill_diagonal(corr, 1.)  # inplace op

# Change as you see fit; you can scale distr. later too
mu, sigma = 0., 1.
mu = np.repeat(mu, n)
sigma = np.repeat(sigma, n)

def corr2cov(corr, s):
    d = np.diag(s)
    return d.dot(corr).dot(d)

cov = corr2cov(corr, sigma)

# While we specified parameters, our draws are still psuedorandom.
# Loop till we meet the specified threshold for correl.
res = 0.
while res < _corr:
    dist = np.random.multivariate_normal(mean=mu, cov=cov, size=size)
    res = np.corrcoef(dist[:, 0], dist[:, 1])[0, 1]
</code>```

The result you're interested in is dist, in this case returned as a 2d array with 2 features and 7 samples each.

Walkthrough:

Create a correlation matrix with your specified correlation.

Specify a mean and standard deviation, ~N(0, 1) in this case, which you can scale later if wanted.

Convert the correlation to covariance using the standard deviation.  (They are the same in this particular case).

Draw random samples from a multivariate normal distribution.

Body:
My goal is to generate 7 numbers within a min and max range that correspond to a Pearson correlation coefficient of greater than 0.95. I have been successful with 3 numbers (obviously because this isn't very computationally demanding).. however for 4 numbers, the computation required seems very large (i.e. on the order of 10k iterations). 7 numbers would be almost impossible with the current code.

Current code:

def pearson_def(x, y):
    assert len(x) == len(y)
    n = len(x)
    assert n > 0
    avg_x = average(x)
    avg_y = average(y)
    diffprod = 0
    xdiff2 = 0
    ydiff2 = 0
    for idx in range(n):
        xdiff = x[idx] - avg_x
        ydiff = y[idx] - avg_y
        diffprod += xdiff * ydiff
        xdiff2 += xdiff * xdiff
        ydiff2 += ydiff * ydiff

    return diffprod / math.sqrt(xdiff2 * ydiff2)

c1_high = 98
c1_low = 75

def corr_gen():
    container =[]
    x=0
    while True:
        c1 = c1_low
        c2 = np.random.uniform(c1_low, c1_high)
        c3 = c1_high
        container.append(c1)
        container.append(c2)
        container.append(c3)
        y = np.arange(len(container))

        if pearson_def(container,y) >0.95:
            c4 = np.random.uniform(c1_low, c1_high)
            container.append(c4)
            y = np.arange(len(container))
            if pearson_def(container,y) >0.95:
                return container
            else:
                continue
        else:
            x+=1
            print(x)
            continue

corrcheck = corr_gen()
print(corrcheck)

Final objective:

*To have 4 columns with a linear distribution (with evenly spaced points)

*Each row corresponds to a group of items (C1,C2,C3,C4) and their sum must equal to 100.

       C1      C2    C3    C4   sum   range
 1     70      10    5     1    100    ^
 2     ..                              |
 3     ..                              |
 4     ..                              |
 5     ..                              |
 6     ..                              |
 7     90      20    15    3           _

Example spread for two theoretical components:

Body:
You can use np.random.multivariate_normal as follows:

import numpy as np

_corr = 0.95
n = 2
size = 7

corr = np.full((n, n), _corr)
np.fill_diagonal(corr, 1.)  # inplace op

# Change as you see fit; you can scale distr. later too
mu, sigma = 0., 1.
mu = np.repeat(mu, n)
sigma = np.repeat(sigma, n)

def corr2cov(corr, s):
    d = np.diag(s)
    return d.dot(corr).dot(d)

cov = corr2cov(corr, sigma)

# While we specified parameters, our draws are still psuedorandom.
# Loop till we meet the specified threshold for correl.
res = 0.
while res < _corr:
    dist = np.random.multivariate_normal(mean=mu, cov=cov, size=size)
    res = np.corrcoef(dist[:, 0], dist[:, 1])[0, 1]

The result you're interested in is dist, in this case returned as a 2d array with 2 features and 7 samples each.

Walkthrough:

Create a correlation matrix with your specified correlation.

Specify a mean and standard deviation, ~N(0, 1) in this case, which you can scale later if wanted.

Convert the correlation to covariance using the standard deviation.  (They are the same in this particular case).

Draw random samples from a multivariate normal distribution.


问:
Google Contacts feed is breaking gdata-contacts-3.0-1.47.1
This is for Google API folks.

Not sure when exactly the feed has changed but very recently (today or a couple of days ago). the GDATA library can't process Google Contacts feed anymore, failing with this:

com.yoxel.sync.core.exceptions.SyncException: com.google.gdata.util.ParseException: [Line 30, Column 86, element gContact:website] Invalid value for attribute : 'rel'

value=http://schemas.google.com/g/2005#profile

GDATA library seems to be expecting capital PROFILE but the feed started to send lowercase!

```<code>for (Enum enumValue : (Enum[])enumClass.getEnumConstants()) {
   if (enumToAttributeValue.getAttributeValue(enumValue).equals(value){
    return enumValue;
 }
}
</code>```

Is there more recent gdata library available?

Thank you.

10/9/20 Update:

For those migrating to the new People API check out our new unified API platform Aurinko.io

答: It appears that Google has now corrected the problem.</p>

ContentLicense: CC BY-SA 4.0

Body:
This is for Google API folks.

Not sure when exactly the feed has changed but very recently (today or a couple of days ago). the GDATA library can't process Google Contacts feed anymore, failing with this:

com.yoxel.sync.core.exceptions.SyncException: com.google.gdata.util.ParseException: [Line 30, Column 86, element gContact:website] Invalid value for attribute : 'rel'

value=http://schemas.google.com/g/2005#profile

GDATA library seems to be expecting capital PROFILE but the feed started to send lowercase!

for (Enum enumValue : (Enum[])enumClass.getEnumConstants()) {
   if (enumToAttributeValue.getAttributeValue(enumValue).equals(value){
    return enumValue;
 }
}

Is there more recent gdata library available?

Thank you.

10/9/20 Update:

For those migrating to the new People API check out our new unified API platform Aurinko.io


问:
New .Net Core 2 Site does not reconize Configuration.GetConnectionString
I am creating a new web site from an empty ASP.NET Core 2 template and following the Microsoft Entity Framework Tutorial to help me get setup. At one point it has you add the code:

```<code>services.AddDbContext<SchoolContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
</code>```

To the ConfigureServices() method of Startup.cs. I did this but in my project Visual Studio give me that little red line under Configuration in the Configuraiton.GetConnectionString

I had thought I was missing a using statement or even a package but the Visual Studio 2017 quick actions don't identify a using statement to use and I do have the Microsoft.AspNetCore.All package installed so I should have all the packages.

What am I missing that is making the Configuration not recognized?

Edit: The error is:

The name 'Configuration' does not exist in the current context

```<code>public void ConfigureServices(IServiceCollection services)
{
     services.AddDbContext<CollectionContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
     services.AddMvc();
}
</code>```

答:
You need to get the IConfiguration object via DI.

Add a IConfiguration argument to your Startup's constructor, and assign it to a Configuration property:

```<code>public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }
</code>```

I'm surprised how you don't have it though, because it's part of the template.

Body:
I am creating a new web site from an empty ASP.NET Core 2 template and following the Microsoft Entity Framework Tutorial to help me get setup. At one point it has you add the code:

services.AddDbContext<SchoolContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

To the ConfigureServices() method of Startup.cs. I did this but in my project Visual Studio give me that little red line under Configuration in the Configuraiton.GetConnectionString

I had thought I was missing a using statement or even a package but the Visual Studio 2017 quick actions don't identify a using statement to use and I do have the Microsoft.AspNetCore.All package installed so I should have all the packages.

What am I missing that is making the Configuration not recognized?

Edit: The error is:

The name 'Configuration' does not exist in the current context

public void ConfigureServices(IServiceCollection services)
{
     services.AddDbContext<CollectionContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
     services.AddMvc();
}

Body:
You need to get the IConfiguration object via DI.

Add a IConfiguration argument to your Startup's constructor, and assign it to a Configuration property:

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

I'm surprised how you don't have it though, because it's part of the template.


问:
Is it possible to load Bing Maps modules synchronously?
I have the following code in my page that loads the BingMap followed by a BingMap module asynchronously:

```<code>var MM = window.Microsoft.Maps;
var _map = new MM.Map(
MM.registerModule('HtmlPushpinLayerModule', '/include/js/mapsearch/HtmlPushpinLayerModule.js');
MM.loadModule('HtmlPushpinLayerModule', function loadHtmlPushpinLayer() {
    // do all sorts of things on the map.
});
</code>```

Is there anyway to load the module synchronously?

There is nothing that can be done until the module is loaded anyway, so it doesn't make sense for it to be async.  And there are so many indirections in the code already, I don't want to add anymore.

答:
No, modules have to load asynchronously, they are downloaded via AJAX, thus it is asynchronous. The ajax call could be forced to be synchronous, but that would mean all UI would be frozen until the module is loaded which would be a poor user experience.

Using the callback function is really simply an only adds 1 extra line of code to your application which consists of "});".

Body:
I have the following code in my page that loads the BingMap followed by a BingMap module asynchronously:

var MM = window.Microsoft.Maps;
var _map = new MM.Map(
MM.registerModule('HtmlPushpinLayerModule', '/include/js/mapsearch/HtmlPushpinLayerModule.js');
MM.loadModule('HtmlPushpinLayerModule', function loadHtmlPushpinLayer() {
    // do all sorts of things on the map.
});

Is there anyway to load the module synchronously?

There is nothing that can be done until the module is loaded anyway, so it doesn't make sense for it to be async.  And there are so many indirections in the code already, I don't want to add anymore.


问:
Multiple File Exists Checking? A Better way?
I have a script. It recieves a variable called $node, which is a string; for now, lets assume the variable value is "NODEVALUE". When the script is called, it takes the variable $node, and tries to find an image called NODEVALUE.png. If it cant find that image, it then checks for NODEVALUE.jpg, if it can't find that it looks for NODEVALUE.gif... and after all that, it still cant find, it returns RANDOM.png.

Right now I am doing this script as follows:

```<code>if (file_exists($img = $node.".png")) {  }
else if (file_exists($img = $node.".jpg")) {  }
else if (file_exists($img = $node.".gif")) {  }
else
{
    $img = 'RANDOM.png';
}
</code>```

There has to be a better way than this... anyone have any ideas?

答:
The most compact (and therefore not recommended) form would be:

```<code>if (array_sum(array_map("file_exists", array($fn1, $fn2, $fn3)))) {
</code>```

It could be adapted to also returning the found filename using array_search:

```<code>array_search(1, array_map("file_exists", array($fn1=>$fn1, $fn2=>$fn2)))
</code>```

Hardly readable. Note how it also requires a map like array("$node.png"=>"$node.png", "$node.gif"=>"$node.gif", ...). So it would not be that much shorter.

Body:
I have a script. It recieves a variable called $node, which is a string; for now, lets assume the variable value is "NODEVALUE". When the script is called, it takes the variable $node, and tries to find an image called NODEVALUE.png. If it cant find that image, it then checks for NODEVALUE.jpg, if it can't find that it looks for NODEVALUE.gif... and after all that, it still cant find, it returns RANDOM.png.

Right now I am doing this script as follows:

if (file_exists($img = $node.".png")) {  }
else if (file_exists($img = $node.".jpg")) {  }
else if (file_exists($img = $node.".gif")) {  }
else
{
    $img = 'RANDOM.png';
}

There has to be a better way than this... anyone have any ideas?

Body:
The most compact (and therefore not recommended) form would be:

if (array_sum(array_map("file_exists", array($fn1, $fn2, $fn3)))) {

It could be adapted to also returning the found filename using array_search:

array_search(1, array_map("file_exists", array($fn1=>$fn1, $fn2=>$fn2)))

Hardly readable. Note how it also requires a map like array("$node.png"=>"$node.png", "$node.gif"=>"$node.gif", ...). So it would not be that much shorter.


问:
how can I look up objective-c's property @synthesize getter setter code
in interview has a question "Could NSMutableArray property use copy why and why not " I have searched the answer but I want to see the auto generate's getter setter code how can I do?</p>

答:
You cannot see the Obj-C code for the setter only the assembler. To do this first select the source file containing the property in Xcode and then choose the menu item Produce > Perform Action > Assemble "File.m". This will open up a window containing the assembly code. Search for setPropertyName: where PropertyName is the capitalised name of your property.

This will show you the setter calls _objc_setProperty_nonatomic_copy or _objc_setProperty_atomic_copy. To see the code for those you will need to use the debugger and step into them. They essentially just call copyWithZone:.

More important is the reason behind the interview question. Either simple experimentation, or digging through the assembler as above, shows that the copy property attribute always does a copy and not a mutableCopy. So the declaration:

```<code>@property (nonatomic, copy) NSMutableArray *shouldBeInvalid;
</code>```

would in an ideal world generate a compiler error. If you assign a mutable array value to the property:

```<code>self.shouldBeInvalid = @[ @24 ].mutableCopy;
</code>```

then due to the copy the value actually assigned is an immutable array (NSArray), contradicting the NSMutableArray declared type. Trying to use the property value later as a mutable array:

```<code>[self.shouldBeInvalid addObject:@42];
</code>```

will produce a runtime error as the property's value is an immutable object contrary to its declared type...

You'll also find that the compiler happily allows you to assign an immutable array to the property:

```<code>self.shouldBeInvalid = @[ @24 ];
</code>```

without so much as a warning.

What the interviewer was probably seeking was for you to explain that for a property copy + mutable type makes no sense in Objective-C as the copy will produce an immutable object value. However a property with copy and an immutable object type (NSArray, NSDictionary, etc.) does make sense so that if a mutable object value is assigned an immutable copy of it is made, which prevents the property's value changing unexpectedly, e.g.:

```<code>@property (nonatomic) NSArray *shouldHaveCopy;

NSMutableArray *sample = @[ @"oops" ].mutableCopy;

self.shouldHaveCopy = sample;

[sample addObject:@"'immutable' property changed"];

// self.shouldHaveCopy now references a two element array despite
// its type being `NSArray`
</code>```

So the general rules are:

A property intended to have a mutable object value (NSMutableDictionary et al) should never specify copy; and

A property intended to have an immutable object value, when there is a corresponding mutable object subclass (e.g. NSArray has NSMutableArray etc.), should always specify copy.

HTH

Body:
You cannot see the Obj-C code for the setter only the assembler. To do this first select the source file containing the property in Xcode and then choose the menu item Produce > Perform Action > Assemble "File.m". This will open up a window containing the assembly code. Search for setPropertyName: where PropertyName is the capitalised name of your property.

This will show you the setter calls _objc_setProperty_nonatomic_copy or _objc_setProperty_atomic_copy. To see the code for those you will need to use the debugger and step into them. They essentially just call copyWithZone:.

More important is the reason behind the interview question. Either simple experimentation, or digging through the assembler as above, shows that the copy property attribute always does a copy and not a mutableCopy. So the declaration:

@property (nonatomic, copy) NSMutableArray *shouldBeInvalid;

would in an ideal world generate a compiler error. If you assign a mutable array value to the property:

self.shouldBeInvalid = @[ @24 ].mutableCopy;

then due to the copy the value actually assigned is an immutable array (NSArray), contradicting the NSMutableArray declared type. Trying to use the property value later as a mutable array:

[self.shouldBeInvalid addObject:@42];

will produce a runtime error as the property's value is an immutable object contrary to its declared type...

You'll also find that the compiler happily allows you to assign an immutable array to the property:

self.shouldBeInvalid = @[ @24 ];

without so much as a warning.

What the interviewer was probably seeking was for you to explain that for a property copy + mutable type makes no sense in Objective-C as the copy will produce an immutable object value. However a property with copy and an immutable object type (NSArray, NSDictionary, etc.) does make sense so that if a mutable object value is assigned an immutable copy of it is made, which prevents the property's value changing unexpectedly, e.g.:

@property (nonatomic) NSArray *shouldHaveCopy;

NSMutableArray *sample = @[ @"oops" ].mutableCopy;

self.shouldHaveCopy = sample;

[sample addObject:@"'immutable' property changed"];

// self.shouldHaveCopy now references a two element array despite
// its type being `NSArray`

So the general rules are:

A property intended to have a mutable object value (NSMutableDictionary et al) should never specify copy; and

A property intended to have an immutable object value, when there is a corresponding mutable object subclass (e.g. NSArray has NSMutableArray etc.), should always specify copy.

HTH


问:
Call Up FileMaker Record Based on Value of Javascript Variable in Web Viewer?
I am working on an app in FileMaker that includes a web map displayed through the web viewer.

I want the user to be able to select a feature within the web map and then call up the corresponding record in FileMaker. The web map features (GeoJSON) and the FileMaker records each have a corresponding ID column.

I already know how to pass the ID of a map feature to a js variable on a click event, but I do not know how to pass the value of this variable to FileMaker. Is this even possible? I hear FileMaker does not play well with others.

I have experience building interactive web maps but am relatively new to FileMaker.

Thanks!

答: This blog post (https://www.soliantconsulting.com/blog/getting-started-javascript-and-filemaker) has a free sample file that demonstrates how to get started using javascript and FileMaker.</p>


问:
Vba separate multiple dates in one cell
 I am trying to separate multiple dates from one cell into multiple cells containing one date in a transposed area and then paste them back over the original area as separate entries.

An example cell might have dates stored like 10/1110/1110/13 or 10/310/310/410/5.
The second scenario is what is causing the error as there is no leading zero for single digit days like 10/3, for example.

Ideally, the code would separate the dates into separate cells like: 10/11,10/11,10/13 and 10/3,10/4,10/5. When single digits days are present ,however, it comes out completely jumbled up and inaccurate.

Admittedly, I had help from another coworker with this code who is on vacation currently, which is why I am having such trouble understanding this. Is there something I could change to account for single digit days or should I approach this process differently?

Thanks!

```<code>'separate column J by "/" and store in transpose area

  dim h as variant
  dim i as variant
  dim j as variant
  dim counter as variant
  dim stringcheck as variant
  dim strInput as variant
  dim strCurrent as variant

 strInput = Cells(j, 10)
 h = 0

For counter = 1 To Len(strInput) - 2
    stringcheck = InStr(strInput, "/")
    Debug.Print j & stringcheck
    If stringcheck <> 0 Then

        If Mid(strInput, counter, 1) = "/" Then
            Cells(17, i + h) = strCurrent & Mid(strInput, counter, 3)
            counter = counter + 2
            h = h + 1
            strCurrent = vbNullString
        Else
            Cells(17, i + h) = Cells(j, 10)
            strCurrent = strCurrent & Mid(strInput, counter, 1)

        End If

    'else just paste the value
    Else
        Cells(17, i) = strInput
    End If

Next counter
</code>```

答:
If all of the months within one cell's mashed up dates can be reasonably assumed to be the same then that could be used as a delimiter to split the mash-up and reassemble it.

```<code>Function splitMashUp(str As String, _
                     Optional splitchr As String = "/", _
                     Optional delim As String = ", ")
    Dim i As Long, tmp As Variant

    tmp = Split(str, Left(str, InStr(1, str, splitchr)))
    For i = LBound(tmp) + 1 To UBound(tmp)
        tmp(i) = Left(str, InStr(1, str, splitchr)) & tmp(i)
    Next i
    splitMashUp = Mid(Join(tmp, delim), Len(delim) + 1)
End Function
</code>```

Title: Vba separate multiple dates in one cell

Body:
 I am trying to separate multiple dates from one cell into multiple cells containing one date in a transposed area and then paste them back over the original area as separate entries.

An example cell might have dates stored like 10/1110/1110/13 or 10/310/310/410/5.
The second scenario is what is causing the error as there is no leading zero for single digit days like 10/3, for example.

Ideally, the code would separate the dates into separate cells like: 10/11,10/11,10/13 and 10/3,10/4,10/5. When single digits days are present ,however, it comes out completely jumbled up and inaccurate.

Admittedly, I had help from another coworker with this code who is on vacation currently, which is why I am having such trouble understanding this. Is there something I could change to account for single digit days or should I approach this process differently?

Thanks!

'separate column J by "/" and store in transpose area

  dim h as variant
  dim i as variant
  dim j as variant
  dim counter as variant
  dim stringcheck as variant
  dim strInput as variant
  dim strCurrent as variant

 strInput = Cells(j, 10)
 h = 0

For counter = 1 To Len(strInput) - 2
    stringcheck = InStr(strInput, "/")
    Debug.Print j & stringcheck
    If stringcheck <> 0 Then

        If Mid(strInput, counter, 1) = "/" Then
            Cells(17, i + h) = strCurrent & Mid(strInput, counter, 3)
            counter = counter + 2
            h = h + 1
            strCurrent = vbNullString
        Else
            Cells(17, i + h) = Cells(j, 10)
            strCurrent = strCurrent & Mid(strInput, counter, 1)

        End If

    'else just paste the value
    Else
        Cells(17, i) = strInput
    End If

Next counter

Body:
If all of the months within one cell's mashed up dates can be reasonably assumed to be the same then that could be used as a delimiter to split the mash-up and reassemble it.

Function splitMashUp(str As String, _
                     Optional splitchr As String = "/", _
                     Optional delim As String = ", ")
    Dim i As Long, tmp As Variant

    tmp = Split(str, Left(str, InStr(1, str, splitchr)))
    For i = LBound(tmp) + 1 To UBound(tmp)
        tmp(i) = Left(str, InStr(1, str, splitchr)) & tmp(i)
    Next i
    splitMashUp = Mid(Join(tmp, delim), Len(delim) + 1)
End Function


问:
Html.DropDownListFor set selected value
I create a @Html.DropDownListFor and populate it from the database. How can I set a selected value to the drop down?

My View:

```<code>@Html.DropDownListFor(m => m.Forms, new SelectList(Model.Forms, "FormsCreatorID", "FormName"),
            "Select a Form", new { @class = "form-control" })
</code>```

My Controller:

```<code>var forms = db.formscreators.Where(fp => fp.PropertyID == id || fp.PropertyID == 0)
            .OrderByDescending(x => x.PropertyID).GroupBy(x => x.FormName).Select(x => x.FirstOrDefault()).ToList();
var viewModel = new ListFormsCreator { Forms = forms };
</code>```

My ViewModel:

```<code>public class ListFormsCreator
{
    public List<formscreator> Forms { get; set; }
}
</code>```

My Database Model:

```<code>public partial class formscreator
{
    public int FormsCreatorID { get; set; }
    public string FormName { get; set; }
    public int PropertyID { get; set; }
}
</code>```

Thanks

答:
You should generate a 'SelectListItem' list on the controller with setting 'Selected' value and pass it via ViewBag or ViewModel. In my sample, for simplicity, I used ViewBag.
Here is the shortened Controller:

```<code>public ActionResult Edit(int? id)
{
    if (id == null)
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

    Album album = context.Albums.Find(id);

    if (album == null)
    {
        return HttpNotFound();
    }

    ViewBag.GenreId = context.Genres.Select(
        g => new SelectListItem()
        {
            Value = g.GenreId.ToString(),
            Text = g.Name,
            Selected = g.GenreId == album.GenreId ? true : false
        }).ToList();

    return View(album);
}
</code>```

Here is the shortened View Code

```<code>@using MvcMusicStore2017.Models;
@model Album
@Html.DropDownList("GenreId", null, new { @class = "form-control" })
</code>```

Title: Html.DropDownListFor set selected value

Body:
I create a @Html.DropDownListFor and populate it from the database. How can I set a selected value to the drop down?

My View:

@Html.DropDownListFor(m => m.Forms, new SelectList(Model.Forms, "FormsCreatorID", "FormName"),
            "Select a Form", new { @class = "form-control" })

My Controller:

var forms = db.formscreators.Where(fp => fp.PropertyID == id || fp.PropertyID == 0)
            .OrderByDescending(x => x.PropertyID).GroupBy(x => x.FormName).Select(x => x.FirstOrDefault()).ToList();
var viewModel = new ListFormsCreator { Forms = forms };

My ViewModel:

public class ListFormsCreator
{
    public List<formscreator> Forms { get; set; }
}

My Database Model:

public partial class formscreator
{
    public int FormsCreatorID { get; set; }
    public string FormName { get; set; }
    public int PropertyID { get; set; }
}

Thanks

Body:
You should generate a 'SelectListItem' list on the controller with setting 'Selected' value and pass it via ViewBag or ViewModel. In my sample, for simplicity, I used ViewBag.
Here is the shortened Controller:

public ActionResult Edit(int? id)
{
    if (id == null)
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

    Album album = context.Albums.Find(id);

    if (album == null)
    {
        return HttpNotFound();
    }

    ViewBag.GenreId = context.Genres.Select(
        g => new SelectListItem()
        {
            Value = g.GenreId.ToString(),
            Text = g.Name,
            Selected = g.GenreId == album.GenreId ? true : false
        }).ToList();

    return View(album);
}

Here is the shortened View Code

@using MvcMusicStore2017.Models;
@model Album
@Html.DropDownList("GenreId", null, new { @class = "form-control" })


问:
pygame spritesheet sprite animation

I am trying to make a walking animation for my sprite (4 directional) by using 4 different sprite sheets (Movement up, down, left and right). As well as this, I would like to replace the coloured square with the image/s but am unsure as how I am supposed to do this. Below is the main.py game file:

```<code>import pygame as pg
import sys
from settings import *
from os import path
from sprites import *
from tilemap import *

class Spritesheet:
    def __init__(self, filename, cols, rows):
        self.sheet = pg.image.load(filename)

        self.cols = cols  #no. of columns in spritesheet
        self.rows = rows  #no. of rows
        self.totalCellCount = cols*rows
        self.rect=self.sheet.get_rect()
        w = self.cellWidth = self.rect.width / cols
        h = self.cellHeight = self.rect.height / rows
        hw, hh = self.cellCenter = (w / 2, h / 2)

        self.cells = list([(index % cols * w, index // cols * h, w, h) for index in range(self.totalCellCount)])
        self.handle = list([
            (0, 0), (-hw, 0), (-w, 0),
            (0, -hh), (-hw, -hh), (-w, -hh),
            (0, -h), (-hw, -h), (-w, -h),])

    def draw(self, surface, cellIndex, x, y, handle = 0):
        surface.blit(self.sheet, (x + self.handle[handle][0], y + self.handle[handle][1]), self.cells[cellIndex])

CENTER_HANDLE = 4
index = 0

class Game:
    def __init__(self):
        pg.init()
        self.screen=pg.display.set_mode((WIDTH, HEIGHT))
        pg.display.set_caption(TITLE)
        self.clock = pg.time.Clock()
        pg.key.set_repeat(500, 100)
        self.load_data()

    def load_data(self):
        game_folder = path.dirname(__file__)
        img_folder = path.join(game_folder, 'img')
        self.map= Map(path.join(game_folder, 'map.txt'))

    def new(self):
        # initialize all variables and do all the setup for a new game
        self.all_sprites = pg.sprite.Group()
        self.walls = pg.sprite.Group()
        self.player1group = pg.sprite.Group()
        self.player2group = pg.sprite.Group()
        for row, tiles in enumerate(self.map.data):
            for col, tile in enumerate(tiles):
                if tile == '1':
                    Wall(self, col, row)
                if tile =='P':
                    self.player = Civilian(self, col, row)
                if tile =='T':
                    self.player2 = Thief(self, col, row)

    def run(self):
        # game loop - set self.playing = False to end the game
        self.playing = True
        while self.playing:
            self.dt = self.clock.tick(FPS) / 1000
            self.events()
            self.update()
            self.draw()

    def quit(self):
        pg.quit()   #Calls the quit function, game window closes
        sys.exit()

    def update(self):
        # update portion of the game loop
        self.all_sprites.update()   #All sprite attributes, position etc are updated

    def draw_grid(self):
        for x in range(0, WIDTH, TILESIZE):
            pg.draw.line(self.screen, LIGHTGREY, (x, 0), (x, HEIGHT))
        for y in range(0, HEIGHT, TILESIZE):
            pg.draw.line(self.screen, LIGHTGREY, (0, y), (WIDTH, y))

    def draw(self):
        self.screen.fill(BGCOLOR)
        self.draw_grid()
        self.all_sprites.draw(self.screen)
        pg.display.flip()

    def events(self):
        # catch all events here
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.quit()
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_ESCAPE:
                    self.quit()

    def show_start_screen(self):
        pass

    def show_go_screen(self):
        pass

# create the game object
g = Game()
g.show_start_screen()
while True:
    g.new()
    g.run()
    g.show_go_screen()
</code>```

Here is the sprites.py file, cont. sprite classes

```<code>import pygame as pg
from settings import *
vec = pg.math.Vector2

class Civilian(pg.sprite.Sprite):
    def __init__(self, game, x, y):
        self.groups = game.all_sprites, game.player1group
        pg.sprite.Sprite.__init__(self, self.groups)
        self.game = game
        self.image = pg.Surface((TILESIZE, TILESIZE))
        self.image.fill(YELLOW)
        self.rect = self.image.get_rect()
        self.vel = vec(0, 0)
        self.pos = vec(x, y) * TILESIZE

    def get_keys(self):
        self.vel= vec(0, 0)
        keys = pg.key.get_pressed()
        if keys[pg.K_a]:    # Const. subtracts player speed from velocity (E.g. Moves sprite to the left)
            self.vel.x= -PLAYER_SPEED
        if keys[pg.K_d]:    # Const. adds player speed value to velocity (E.g. Moves sprite to the right)
            self.vel.x= PLAYER_SPEED
        if keys[pg.K_w]:    # Const. subtracts player speed value from y velocity (Moves player upwards; opposite)
            self.vel.y= -PLAYER_SPEED
        if keys[pg.K_s]: # Const. adds player speed value to y velocity (Moves player downwards; opposite)
            self.vel.y= PLAYER_SPEED
        if self.vel.x != 0 and self.vel.y != 0:   # Offsetting increased vecocity when moving diagonally (Has both x and y velocity)
            self.vel *= 0.7071

    def collide_with_player2(self, dir, ifColliding):
        if dir == 'x':
            collides = pg.sprite.spritecollide(self, self.game.player2group, False)
            if collides:
                if self.vel.x > 0:
                    self.pos.x = collides[0].rect.left - self.rect.width
                if self.vel.x < 0:
                    self.pos.x = collides[0].rect.right
                self.vel.x = 0
                self.rect.x = self.pos.x
                print("collide x")
                self.ifColliding = True

        if dir == 'y':
            collides = pg.sprite.spritecollide(self, self.game.player2group, False)
            if collides:
                if self.vel.y > 0:
                    self.pos.y = collides[0].rect.top - self.rect.height
                if self.vel.y < 0:
                    self.pos.y = collides[0].rect.bottom
                self.vel.y = 0
                self.rect.y = self.pos.y
                print("collide y")
                self.ifColliding = True

    def collide_with_walls(self, dir):
        if dir == 'x':
            collides = pg.sprite.spritecollide(self, self.game.walls, False)
            if collides:
                if self.vel.x > 0:
                    self.pos.x = collides[0].rect.left - self.rect.width
                if self.vel.x < 0:
                    self.pos.x = collides[0].rect.right
                self.vel.x = 0
                self.rect.x = self.pos.x
        if dir == 'y':
            collides = pg.sprite.spritecollide(self, self.game.walls, False)
            if collides:
                if self.vel.y > 0:
                    self.pos.y = collides[0].rect.top - self.rect.height
                if self.vel.y < 0:
                    self.pos.y = collides[0].rect.bottom
                self.vel.y = 0
                self.rect.y = self.pos.y

    def update(self):
        self.ifColliding = False
        self.get_keys()
        self.pos += self.vel * self.game.dt
        self.rect.x = self.pos.x
        self.collide_with_walls('x'), self.collide_with_player2('x', self.ifColliding)
        self.rect.y = self.pos.y
        self.collide_with_walls('y'), self.collide_with_player2('y', self.ifColliding)
        if self.ifColliding == True:
            Thief.health -= COL_DAMAGE
            print(Thief.health)

class Thief(pg.sprite.Sprite):
    health = 100
    def __init__(self, game, x, y):
        self.groups = game.all_sprites, game.player2group
        pg.sprite.Sprite.__init__(self, self.groups)
        self.game = game
        self.image = pg.Surface((TILESIZE, TILESIZE))
        self.image.fill(RED)
        self.rect = self.image.get_rect()
        self.vel = vec(0, 0)
        self.pos = vec(x, y) * TILESIZE
        s = Spritesheet("spritesheet_thief.png", 9, 4)

    def get_keys(self):
        self.vel = vec(0, 0)
        keys = pg.key.get_pressed()
        if keys[pg.K_LEFT]:    # Const. subtracts player speed from velocity (E.g. Moves sprite to the left)
            self.vel.x= -PLAYER_SPEED
        elif keys[pg.K_RIGHT]:    # Const. adds player speed value to velocity (E.g. Moves sprite to the right)
            self.vel.x= PLAYER_SPEED
        elif keys[pg.K_UP]:    # Const. subtracts player speed value from y velocity (Moves player upwards; opposite)
            self.vel.y= -PLAYER_SPEED
        elif keys[pg.K_DOWN]: # Const. adds player speed value to y velocity (Moves player downwards; opposite)
            self.vel.y= PLAYER_SPEED
        elif self.vel.x != 0 and self.vel.y != 0:   # Offsetting increased vecocity when moving diagonally (Has both x and y velocity)
            self.vel *= 0.7071

    def collide_with_player1(self, dir, ifColliding):
        if dir == 'x':
            collides = pg.sprite.spritecollide(self, self.game.player1group, False)
            if collides:
                if self.vel.x > 0:
                    self.pos.x = collides[0].rect.left - self.rect.width
                if self.vel.x < 0:
                    self.pos.x = collides[0].rect.right
                self.vel.x = 0
                self.rect.x = self.pos.x
                print("collide x")
                self.ifColliding = True

        if dir == 'y':
            collides = pg.sprite.spritecollide(self, self.game.player1group, False)
            if collides:
                if self.vel.y > 0:
                    self.pos.y = collides[0].rect.top - self.rect.height
                if self.vel.y < 0:
                    self.pos.y = collides[0].rect.bottom
                self.vel.y = 0
                self.rect.y = self.pos.y
                print("collide y")
                self.ifColliding = True

    def collide_with_walls(self, dir):
        if dir == 'x':
            collides = pg.sprite.spritecollide(self, self.game.walls, False)
            if collides:
                if self.vel.x > 0:
                    self.pos.x = collides[0].rect.left - self.rect.width
                if self.vel.x < 0:
                    self.pos.x = collides[0].rect.right
                self.vel.x = 0
                self.rect.x = self.pos.x
        if dir == 'y':
            collides = pg.sprite.spritecollide(self, self.game.walls, False)
            if collides:
                if self.vel.y > 0:
                    self.pos.y = collides[0].rect.top - self.rect.height
                if self.vel.y < 0:
                    self.pos.y = collides[0].rect.bottom
                self.vel.y = 0
                self.rect.y = self.pos.y

    def update(self):
        s.draw(self.game.screen, index % s.totalCellCount, HW, HH, CENTER_HANDLE)
        index += 1
        self.ifColliding = False
        self.get_keys()
        self.pos += self.vel * self.game.dt
        self.rect.x = self.pos.x
        self.collide_with_walls('x'), self.collide_with_player1('x', self.ifColliding)
        self.rect.y = self.pos.y
        self.collide_with_walls('y'), self.collide_with_player1('y', self.ifColliding)
        if Thief.health <= 0:
            self.kill()

class Wall(pg.sprite.Sprite):
    def __init__(self, game, x, y):
        self.groups = game.all_sprites, game.walls
        pg.sprite.Sprite.__init__(self, self.groups)
        self.game = game
        self.image = pg.Surface((TILESIZE, TILESIZE))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.x = x
        self.y = y
        self.rect.x = x * TILESIZE
        self.rect.y = y * TILESIZE
</code>```

Hoping to run through a row of cells within the sprite sheet depending on the direction the sprite is moving in and set that as the sprite image (Giving the illusion that the player sprite is animated)

Any help would be appreciated, sorry if the Question is confusing, first time using the site and not too good at coding at the current stage.

答:
Load four images as

```<code>self.image_up = pygame.image.load(...)
self.image_down = pygame.image.load(...)
self.image_left = pygame.image.load(...)
self.image_right = pygame.image.load(...)
</code>```

and later when you need it replace

```<code>self.image = self.image_up
</code>```

or

```<code>self.image = self.image_down
</code>```

etc.

If you have all positions in one file then you can use pygame.Surface.subsurface to cut off part of image and create new one

```<code>spritesheet = pygame.image.load(...)

self.image_up = spritesheet.subsurface( Rect(0,0,10,10) )
self.image_down = spritesheet.subsurface( Rect(...) )
self.image_left = spritesheet.subsurface( Rect(...) )
self.image_right = spritesheet.subsurface( Rect(...) )
</code>```

My simple example (with all positions in one file) on GitHub: pygame-spritesheet

Use left/right arrows to move object and it will use different image.

Title: pygame spritesheet sprite animation

Body:
I am trying to make a walking animation for my sprite (4 directional) by using 4 different sprite sheets (Movement up, down, left and right). As well as this, I would like to replace the coloured square with the image/s but am unsure as how I am supposed to do this. Below is the main.py game file:

import pygame as pg
import sys
from settings import *
from os import path
from sprites import *
from tilemap import *

class Spritesheet:
    def __init__(self, filename, cols, rows):
        self.sheet = pg.image.load(filename)

        self.cols = cols  #no. of columns in spritesheet
        self.rows = rows  #no. of rows
        self.totalCellCount = cols*rows
        self.rect=self.sheet.get_rect()
        w = self.cellWidth = self.rect.width / cols
        h = self.cellHeight = self.rect.height / rows
        hw, hh = self.cellCenter = (w / 2, h / 2)

        self.cells = list([(index % cols * w, index // cols * h, w, h) for index in range(self.totalCellCount)])
        self.handle = list([
            (0, 0), (-hw, 0), (-w, 0),
            (0, -hh), (-hw, -hh), (-w, -hh),
            (0, -h), (-hw, -h), (-w, -h),])

    def draw(self, surface, cellIndex, x, y, handle = 0):
        surface.blit(self.sheet, (x + self.handle[handle][0], y + self.handle[handle][1]), self.cells[cellIndex])

CENTER_HANDLE = 4
index = 0

class Game:
    def __init__(self):
        pg.init()
        self.screen=pg.display.set_mode((WIDTH, HEIGHT))
        pg.display.set_caption(TITLE)
        self.clock = pg.time.Clock()
        pg.key.set_repeat(500, 100)
        self.load_data()

    def load_data(self):
        game_folder = path.dirname(__file__)
        img_folder = path.join(game_folder, 'img')
        self.map= Map(path.join(game_folder, 'map.txt'))

    def new(self):
        # initialize all variables and do all the setup for a new game
        self.all_sprites = pg.sprite.Group()
        self.walls = pg.sprite.Group()
        self.player1group = pg.sprite.Group()
        self.player2group = pg.sprite.Group()
        for row, tiles in enumerate(self.map.data):
            for col, tile in enumerate(tiles):
                if tile == '1':
                    Wall(self, col, row)
                if tile =='P':
                    self.player = Civilian(self, col, row)
                if tile =='T':
                    self.player2 = Thief(self, col, row)

    def run(self):
        # game loop - set self.playing = False to end the game
        self.playing = True
        while self.playing:
            self.dt = self.clock.tick(FPS) / 1000
            self.events()
            self.update()
            self.draw()

    def quit(self):
        pg.quit()   #Calls the quit function, game window closes
        sys.exit()

    def update(self):
        # update portion of the game loop
        self.all_sprites.update()   #All sprite attributes, position etc are updated

    def draw_grid(self):
        for x in range(0, WIDTH, TILESIZE):
            pg.draw.line(self.screen, LIGHTGREY, (x, 0), (x, HEIGHT))
        for y in range(0, HEIGHT, TILESIZE):
            pg.draw.line(self.screen, LIGHTGREY, (0, y), (WIDTH, y))

    def draw(self):
        self.screen.fill(BGCOLOR)
        self.draw_grid()
        self.all_sprites.draw(self.screen)
        pg.display.flip()

    def events(self):
        # catch all events here
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.quit()
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_ESCAPE:
                    self.quit()

    def show_start_screen(self):
        pass

    def show_go_screen(self):
        pass

# create the game object
g = Game()
g.show_start_screen()
while True:
    g.new()
    g.run()
    g.show_go_screen()

Here is the sprites.py file, cont. sprite classes

import pygame as pg
from settings import *
vec = pg.math.Vector2

class Civilian(pg.sprite.Sprite):
    def __init__(self, game, x, y):
        self.groups = game.all_sprites, game.player1group
        pg.sprite.Sprite.__init__(self, self.groups)
        self.game = game
        self.image = pg.Surface((TILESIZE, TILESIZE))
        self.image.fill(YELLOW)
        self.rect = self.image.get_rect()
        self.vel = vec(0, 0)
        self.pos = vec(x, y) * TILESIZE

    def get_keys(self):
        self.vel= vec(0, 0)
        keys = pg.key.get_pressed()
        if keys[pg.K_a]:    # Const. subtracts player speed from velocity (E.g. Moves sprite to the left)
            self.vel.x= -PLAYER_SPEED
        if keys[pg.K_d]:    # Const. adds player speed value to velocity (E.g. Moves sprite to the right)
            self.vel.x= PLAYER_SPEED
        if keys[pg.K_w]:    # Const. subtracts player speed value from y velocity (Moves player upwards; opposite)
            self.vel.y= -PLAYER_SPEED
        if keys[pg.K_s]: # Const. adds player speed value to y velocity (Moves player downwards; opposite)
            self.vel.y= PLAYER_SPEED
        if self.vel.x != 0 and self.vel.y != 0:   # Offsetting increased vecocity when moving diagonally (Has both x and y velocity)
            self.vel *= 0.7071

    def collide_with_player2(self, dir, ifColliding):
        if dir == 'x':
            collides = pg.sprite.spritecollide(self, self.game.player2group, False)
            if collides:
                if self.vel.x > 0:
                    self.pos.x = collides[0].rect.left - self.rect.width
                if self.vel.x < 0:
                    self.pos.x = collides[0].rect.right
                self.vel.x = 0
                self.rect.x = self.pos.x
                print("collide x")
                self.ifColliding = True

        if dir == 'y':
            collides = pg.sprite.spritecollide(self, self.game.player2group, False)
            if collides:
                if self.vel.y > 0:
                    self.pos.y = collides[0].rect.top - self.rect.height
                if self.vel.y < 0:
                    self.pos.y = collides[0].rect.bottom
                self.vel.y = 0
                self.rect.y = self.pos.y
                print("collide y")
                self.ifColliding = True

    def collide_with_walls(self, dir):
        if dir == 'x':
            collides = pg.sprite.spritecollide(self, self.game.walls, False)
            if collides:
                if self.vel.x > 0:
                    self.pos.x = collides[0].rect.left - self.rect.width
                if self.vel.x < 0:
                    self.pos.x = collides[0].rect.right
                self.vel.x = 0
                self.rect.x = self.pos.x
        if dir == 'y':
            collides = pg.sprite.spritecollide(self, self.game.walls, False)
            if collides:
                if self.vel.y > 0:
                    self.pos.y = collides[0].rect.top - self.rect.height
                if self.vel.y < 0:
                    self.pos.y = collides[0].rect.bottom
                self.vel.y = 0
                self.rect.y = self.pos.y

    def update(self):
        self.ifColliding = False
        self.get_keys()
        self.pos += self.vel * self.game.dt
        self.rect.x = self.pos.x
        self.collide_with_walls('x'), self.collide_with_player2('x', self.ifColliding)
        self.rect.y = self.pos.y
        self.collide_with_walls('y'), self.collide_with_player2('y', self.ifColliding)
        if self.ifColliding == True:
            Thief.health -= COL_DAMAGE
            print(Thief.health)

class Thief(pg.sprite.Sprite):
    health = 100
    def __init__(self, game, x, y):
        self.groups = game.all_sprites, game.player2group
        pg.sprite.Sprite.__init__(self, self.groups)
        self.game = game
        self.image = pg.Surface((TILESIZE, TILESIZE))
        self.image.fill(RED)
        self.rect = self.image.get_rect()
        self.vel = vec(0, 0)
        self.pos = vec(x, y) * TILESIZE
        s = Spritesheet("spritesheet_thief.png", 9, 4)

    def get_keys(self):
        self.vel = vec(0, 0)
        keys = pg.key.get_pressed()
        if keys[pg.K_LEFT]:    # Const. subtracts player speed from velocity (E.g. Moves sprite to the left)
            self.vel.x= -PLAYER_SPEED
        elif keys[pg.K_RIGHT]:    # Const. adds player speed value to velocity (E.g. Moves sprite to the right)
            self.vel.x= PLAYER_SPEED
        elif keys[pg.K_UP]:    # Const. subtracts player speed value from y velocity (Moves player upwards; opposite)
            self.vel.y= -PLAYER_SPEED
        elif keys[pg.K_DOWN]: # Const. adds player speed value to y velocity (Moves player downwards; opposite)
            self.vel.y= PLAYER_SPEED
        elif self.vel.x != 0 and self.vel.y != 0:   # Offsetting increased vecocity when moving diagonally (Has both x and y velocity)
            self.vel *= 0.7071

    def collide_with_player1(self, dir, ifColliding):
        if dir == 'x':
            collides = pg.sprite.spritecollide(self, self.game.player1group, False)
            if collides:
                if self.vel.x > 0:
                    self.pos.x = collides[0].rect.left - self.rect.width
                if self.vel.x < 0:
                    self.pos.x = collides[0].rect.right
                self.vel.x = 0
                self.rect.x = self.pos.x
                print("collide x")
                self.ifColliding = True

        if dir == 'y':
            collides = pg.sprite.spritecollide(self, self.game.player1group, False)
            if collides:
                if self.vel.y > 0:
                    self.pos.y = collides[0].rect.top - self.rect.height
                if self.vel.y < 0:
                    self.pos.y = collides[0].rect.bottom
                self.vel.y = 0
                self.rect.y = self.pos.y
                print("collide y")
                self.ifColliding = True

    def collide_with_walls(self, dir):
        if dir == 'x':
            collides = pg.sprite.spritecollide(self, self.game.walls, False)
            if collides:
                if self.vel.x > 0:
                    self.pos.x = collides[0].rect.left - self.rect.width
                if self.vel.x < 0:
                    self.pos.x = collides[0].rect.right
                self.vel.x = 0
                self.rect.x = self.pos.x
        if dir == 'y':
            collides = pg.sprite.spritecollide(self, self.game.walls, False)
            if collides:
                if self.vel.y > 0:
                    self.pos.y = collides[0].rect.top - self.rect.height
                if self.vel.y < 0:
                    self.pos.y = collides[0].rect.bottom
                self.vel.y = 0
                self.rect.y = self.pos.y

    def update(self):
        s.draw(self.game.screen, index % s.totalCellCount, HW, HH, CENTER_HANDLE)
        index += 1
        self.ifColliding = False
        self.get_keys()
        self.pos += self.vel * self.game.dt
        self.rect.x = self.pos.x
        self.collide_with_walls('x'), self.collide_with_player1('x', self.ifColliding)
        self.rect.y = self.pos.y
        self.collide_with_walls('y'), self.collide_with_player1('y', self.ifColliding)
        if Thief.health <= 0:
            self.kill()

class Wall(pg.sprite.Sprite):
    def __init__(self, game, x, y):
        self.groups = game.all_sprites, game.walls
        pg.sprite.Sprite.__init__(self, self.groups)
        self.game = game
        self.image = pg.Surface((TILESIZE, TILESIZE))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.x = x
        self.y = y
        self.rect.x = x * TILESIZE
        self.rect.y = y * TILESIZE

Hoping to run through a row of cells within the sprite sheet depending on the direction the sprite is moving in and set that as the sprite image (Giving the illusion that the player sprite is animated)

Any help would be appreciated, sorry if the Question is confusing, first time using the site and not too good at coding at the current stage.

Body:
Load four images as

self.image_up = pygame.image.load(...)
self.image_down = pygame.image.load(...)
self.image_left = pygame.image.load(...)
self.image_right = pygame.image.load(...)

and later when you need it replace

self.image = self.image_up

or

self.image = self.image_down

etc.

If you have all positions in one file then you can use pygame.Surface.subsurface to cut off part of image and create new one

spritesheet = pygame.image.load(...)

self.image_up = spritesheet.subsurface( Rect(0,0,10,10) )
self.image_down = spritesheet.subsurface( Rect(...) )
self.image_left = spritesheet.subsurface( Rect(...) )
self.image_right = spritesheet.subsurface( Rect(...) )

My simple example (with all positions in one file) on GitHub: pygame-spritesheet

Use left/right arrows to move object and it will use different image.


问:
How to Match Using sed a Multi-Line Range Defined by More Than Two Bounds?
How do I...

...USE sed to match not just the standard 2-bound range, but a range characterized by a "multi-range" -- multiple (>2) submatches in some specific order...

...WHILE containing paired internal matches (e.g. ( / )) that might overlap a pair of the multi-range's bounding patterns?

The Working Simple Range Match

Say I have a pattern whose content resembles something like this in a given formatting:

```<code>           someVar: SomeObj.someFunct
                        ("name1", "name2",
                         SomeConst)
</code>```

In most cases like above, regardless of formatting for some constant SomeObj.someFunct, I could capture w/ the range pattern:

cat $file | sed -ne '/^[ \t]*[a-zA-Z0-9_\: ]*SomeObj.someFunct/,/)/ {p}'

where the dual range bounds are:

/^[ \t]*[a-zA-Z0-9_\: ]*SomeObj.someFunct/

and

/)/

So basically it's looking for the opening bit, then the closing parantheses.

Fail Cases

But this will occasionally fail  if there's stuff in between w/ ).  A simple example might be:

```<code>           someVar: SomeObj.someFunct
                        (thisTimeImCallingTheFunction(), "name2",
                         SomeConst)
</code>```

It also fails if SomeObj.someFunct is on the next line, i.e.:

```<code>           someVar:
              SomeObj.someFunct("name1", "name2",
                         SomeConst)
</code>```

A Multiply Bounded Range?

My idea is that I would like a "multi-range", or the equivalent of:

/^[ \t]*[a-zA-Z0-9_\: ]*/

and

/SomeObj.someFunct/

and

/(/

| and (optional)

|

| some arbitrary # of intermediary ( and ))

and

/)/

...so the range would have to check through at least the 4 bounds, with the final two checking for an optional intermediate to guard against interior ( / ) pairs.

What I got

Unfortunately the naive version of this w/ out even considering the optional interior matches....

cat $file | sed -ne '/^[ \t]*[a-zA-Z0-9_\: ]*/,/SomeObj.someFunct/,/(/,/)/ {p}'

does not work.

It appears that the pattern /check1/,/check2/,/check3/,/check4/ is not valid and some more complex strategy must be employed.

Summary of the Question

check a contiguous range defined by two end patterns and interior patterns in some specific order (but not necessarily on the same line)

for each additional ( encountered, skip one ) before the final match of the range ).

Note/Disclaimer

I searched for previous questions like this, figuring it was asked, but only found questions asking about multiple ranges with standard dual bounds, not a "multi range" in the sense of a single contiguous range defined by more than two bounding matches.

BONUS QUESTION:

Once I have such a multi-bound match, how can I multi-capture the following patterns:

the whitespace before someVar.

The three argument (including interiror ( / ) in the complex case.

答: Your first fail case with the nested function call cannot be handled in proper "regular" expressions. Some extensions like Perl's REs can deal with finding matching pairs of arbitrary nested things, but really you want an actual parser at this point. </p>

Body:
How do I...

...USE sed to match not just the standard 2-bound range, but a range characterized by a "multi-range" -- multiple (>2) submatches in some specific order...

...WHILE containing paired internal matches (e.g. ( / )) that might overlap a pair of the multi-range's bounding patterns?

The Working Simple Range Match

Say I have a pattern whose content resembles something like this in a given formatting:

           someVar: SomeObj.someFunct
                        ("name1", "name2",
                         SomeConst)

In most cases like above, regardless of formatting for some constant SomeObj.someFunct, I could capture w/ the range pattern:

cat $file | sed -ne '/^[ \t]*[a-zA-Z0-9_\: ]*SomeObj.someFunct/,/)/ {p}'

where the dual range bounds are:

/^[ \t]*[a-zA-Z0-9_\: ]*SomeObj.someFunct/

and

/)/

So basically it's looking for the opening bit, then the closing parantheses.

Fail Cases

But this will occasionally fail  if there's stuff in between w/ ).  A simple example might be:

           someVar: SomeObj.someFunct
                        (thisTimeImCallingTheFunction(), "name2",
                         SomeConst)

It also fails if SomeObj.someFunct is on the next line, i.e.:

           someVar:
              SomeObj.someFunct("name1", "name2",
                         SomeConst)

A Multiply Bounded Range?

My idea is that I would like a "multi-range", or the equivalent of:

/^[ \t]*[a-zA-Z0-9_\: ]*/

and

/SomeObj.someFunct/

and

/(/

| and (optional)

|

| some arbitrary # of intermediary ( and ))

and

/)/

...so the range would have to check through at least the 4 bounds, with the final two checking for an optional intermediate to guard against interior ( / ) pairs.

What I got

Unfortunately the naive version of this w/ out even considering the optional interior matches....

cat $file | sed -ne '/^[ \t]*[a-zA-Z0-9_\: ]*/,/SomeObj.someFunct/,/(/,/)/ {p}'

does not work.

It appears that the pattern /check1/,/check2/,/check3/,/check4/ is not valid and some more complex strategy must be employed.

Summary of the Question

check a contiguous range defined by two end patterns and interior patterns in some specific order (but not necessarily on the same line)

for each additional ( encountered, skip one ) before the final match of the range ).

Note/Disclaimer

I searched for previous questions like this, figuring it was asked, but only found questions asking about multiple ranges with standard dual bounds, not a "multi range" in the sense of a single contiguous range defined by more than two bounding matches.

BONUS QUESTION:

Once I have such a multi-bound match, how can I multi-capture the following patterns:

the whitespace before someVar.

The three argument (including interiror ( / ) in the complex case.


问:
http service not starting error 1009
I was trying to print a document for one of my games but the page viewer couldn't see the printer so I checked the print spooler service

```<code>C:\WINDOWS\system32>sc qc spooler
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: spooler
        TYPE               : 110  WIN32_OWN_PROCESS (interactive)
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\WINDOWS\System32\spoolsv.exe
        LOAD_ORDER_GROUP   : SpoolerGroup
        TAG                : 0
        DISPLAY_NAME       : Print Spooler
        DEPENDENCIES       : RPCSS
                           : http
        SERVICE_START_NAME : LocalSystem

C:\WINDOWS\system32>sc query spooler

SERVICE_NAME: spooler
        TYPE               : 110  WIN32_OWN_PROCESS  (interactive)
        STATE              : 1  STOPPED
        WIN32_EXIT_CODE    : 1068  (0x42c)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x0
        WAIT_HINT          : 0x0

C:\WINDOWS\system32>
</code>```

And tried to start it, then this happened

```<code>C:\WINDOWS\system32>net start spooler
System error 1068 has occurred.

The dependency service or group failed to start.

C:\WINDOWS\system32>
</code>```

Ok so I checked the dependencies

```<code>C:\WINDOWS\system32>sc qc rpcss
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: rpcss
        TYPE               : 20  WIN32_SHARE_PROCESS
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\WINDOWS\system32\svchost.exe -k rpcss
        LOAD_ORDER_GROUP   : COM Infrastructure
        TAG                : 0
        DISPLAY_NAME       : Remote Procedure Call (RPC)
        DEPENDENCIES       : RpcEptMapper
                           : DcomLaunch
        SERVICE_START_NAME : NT AUTHORITY\NetworkService

C:\WINDOWS\system32>sc query rpcss

SERVICE_NAME: rpcss
        TYPE               : 20  WIN32_SHARE_PROCESS
        STATE              : 4  RUNNING
                                (NOT_STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN)
        WIN32_EXIT_CODE    : 0  (0x0)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x0
        WAIT_HINT          : 0x0

C:\WINDOWS\system32>
</code>```

Ok RPCSS is good, next one

```<code>C:\WINDOWS\system32>sc qc http && sc query http
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: http
        TYPE               : 1  KERNEL_DRIVER
        START_TYPE         : 3   DEMAND_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : system32\drivers\HTTP.sys
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : HTTP Service
        DEPENDENCIES       :
        SERVICE_START_NAME :

SERVICE_NAME: http
        TYPE               : 1  KERNEL_DRIVER
        STATE              : 1  STOPPED
        WIN32_EXIT_CODE    : 1009  (0x3f1)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x0
        WAIT_HINT          : 0x0

C:\WINDOWS\system32>
</code>```

OK seeing it stopped I tried to start it again

```<code>C:\WINDOWS\system32>net start http
System error 1009 has occurred.

The configuration registry database is corrupt.

C:\WINDOWS\system32>
</code>```

So I run SFC to try and fix this BUT...

```<code>C:\WINDOWS\system32>sfc /scannow

Beginning system scan.  This process will take some time.

Beginning verification phase of system scan.
Verification 100% complete.

Windows Resource Protection did not find any integrity violations.

C:\WINDOWS\system32>
</code>```

A fat lot of help this is, it can't even fix something so inherently wrong...

So this is where I ask the community for help, I don't know what to do past this point. Help is very much appreciated.

答:
In my case, I had a sub-key under
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\HTTP\Parameters\SslBindingInfo that was missing information. i.e. all the keys such as 0.0.0.0:40015 have values like "AppId","DefaultFlags", etc.
I had one that had no values under this key. I deleted that "empty" key and HTTP was able to start up.

Title: http service not starting error 1009

Body:
I was trying to print a document for one of my games but the page viewer couldn't see the printer so I checked the print spooler service

C:\WINDOWS\system32>sc qc spooler
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: spooler
        TYPE               : 110  WIN32_OWN_PROCESS (interactive)
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\WINDOWS\System32\spoolsv.exe
        LOAD_ORDER_GROUP   : SpoolerGroup
        TAG                : 0
        DISPLAY_NAME       : Print Spooler
        DEPENDENCIES       : RPCSS
                           : http
        SERVICE_START_NAME : LocalSystem

C:\WINDOWS\system32>sc query spooler

SERVICE_NAME: spooler
        TYPE               : 110  WIN32_OWN_PROCESS  (interactive)
        STATE              : 1  STOPPED
        WIN32_EXIT_CODE    : 1068  (0x42c)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x0
        WAIT_HINT          : 0x0

C:\WINDOWS\system32>

And tried to start it, then this happened

C:\WINDOWS\system32>net start spooler
System error 1068 has occurred.

The dependency service or group failed to start.

C:\WINDOWS\system32>

Ok so I checked the dependencies

C:\WINDOWS\system32>sc qc rpcss
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: rpcss
        TYPE               : 20  WIN32_SHARE_PROCESS
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\WINDOWS\system32\svchost.exe -k rpcss
        LOAD_ORDER_GROUP   : COM Infrastructure
        TAG                : 0
        DISPLAY_NAME       : Remote Procedure Call (RPC)
        DEPENDENCIES       : RpcEptMapper
                           : DcomLaunch
        SERVICE_START_NAME : NT AUTHORITY\NetworkService

C:\WINDOWS\system32>sc query rpcss

SERVICE_NAME: rpcss
        TYPE               : 20  WIN32_SHARE_PROCESS
        STATE              : 4  RUNNING
                                (NOT_STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN)
        WIN32_EXIT_CODE    : 0  (0x0)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x0
        WAIT_HINT          : 0x0

C:\WINDOWS\system32>

Ok RPCSS is good, next one

C:\WINDOWS\system32>sc qc http && sc query http
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: http
        TYPE               : 1  KERNEL_DRIVER
        START_TYPE         : 3   DEMAND_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : system32\drivers\HTTP.sys
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : HTTP Service
        DEPENDENCIES       :
        SERVICE_START_NAME :

SERVICE_NAME: http
        TYPE               : 1  KERNEL_DRIVER
        STATE              : 1  STOPPED
        WIN32_EXIT_CODE    : 1009  (0x3f1)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x0
        WAIT_HINT          : 0x0

C:\WINDOWS\system32>

OK seeing it stopped I tried to start it again

C:\WINDOWS\system32>net start http
System error 1009 has occurred.

The configuration registry database is corrupt.

C:\WINDOWS\system32>

So I run SFC to try and fix this BUT...

C:\WINDOWS\system32>sfc /scannow

Beginning system scan.  This process will take some time.

Beginning verification phase of system scan.
Verification 100% complete.

Windows Resource Protection did not find any integrity violations.

C:\WINDOWS\system32>

A fat lot of help this is, it can't even fix something so inherently wrong...

So this is where I ask the community for help, I don't know what to do past this point. Help is very much appreciated.


问:
Rails 3 i need some help with making a FAQ page
first off ive tried google and cant seem to find an answer i can understand what i would like to do is list my questions from an active record witch i have that much working then make the question its self a link so her is my page so far!

```<code>   <h1>Listing faqs</h1>

<table>

<% @faqs.each do |faq| %>
  <tr><td width="90px"><div id="right">Question : </div></td><td><%= faq.question %></td></tr>

<% end %>
</table>

<br />

<table>

<% @faqs.each do |faq| %>
  <tr><td width="90px"><div id="right">Question : </div></td><td><%= faq.question %></td></tr>
  <tr><td valign="top"><div id="right">Answer : </div></td><td><%= faq.answer %></td></tr>
<% end %>
</table>

<br />

<%= link_to 'New Faq', new_faq_path %>
</code>```

im amusingenter code here i can stick something in before faq.question like a link_to or something or something but im not shure what

答:
First of all, in Rails 3 forms should start with <%=, not <%.

```<code><%= @faqs.each do |faq| %>
  <tr>
    <td width="90px">
      <div id="right">Question : </div>
    </td>
    <td>
      <%= link_to(faq.question, faq_path(faq.id) %>
    </td>
  </tr>
<% end %>
</code>```

Body:
first off ive tried google and cant seem to find an answer i can understand what i would like to do is list my questions from an active record witch i have that much working then make the question its self a link so her is my page so far!

Listing faqs

<% @faqs.each do |faq| %>

Question :
	<%= faq.question %>

<% end %>

<% @faqs.each do |faq| %>

Question :
	<%= faq.question %>

Answer :
	<%= faq.answer %>

<% end %>

<%= link_to 'New Faq', new_faq_path %>

im amusingenter code here i can stick something in before faq.question like a link_to or something or something but im not shure what

Body:
First of all, in Rails 3 forms should start with <%=, not <%.

<%= @faqs.each do |faq| %>
  <tr>
    <td width="90px">
      <div id="right">Question : </div>
    </td>
    <td>
      <%= link_to(faq.question, faq_path(faq.id) %>
    </td>
  </tr>
<% end %>


问:
Redirect with arguments and message
I want to do a redirect with arguments and at the same time send a message to the redirected page.

Where to redirect:

```<code>path('companies/<int:pk>/', AccountCompanyDetailView.as_view(), name='detail_company')

from django.shortcuts import redirect

def post_view(request, id):
    return redirect('detail_company', pk=id)
</code>```

I want to send to the page to which will be redirected a 'message' to show to the user why it was redirected.

It is possible?

答:
A very simple solution is to modify your urls.py in this way:

```<code>  url(r'^'desired_url_to_redirect/(?:(?P<error_key>[0-9]+)/)?$', views.'name_of_your_view', name='name_of_your_view'),
</code>```

The second parameter is optional and would act as a key for the type error. The only thing left would be to update your template to present the desired message based on the type of error.

For defining your view don't forget to insert as a second parameter 'error_key=None'

Title: Redirect with arguments and message

Body:
I want to do a redirect with arguments and at the same time send a message to the redirected page.

Where to redirect:

path('companies/<int:pk>/', AccountCompanyDetailView.as_view(), name='detail_company')

from django.shortcuts import redirect

def post_view(request, id):
    return redirect('detail_company', pk=id)

I want to send to the page to which will be redirected a 'message' to show to the user why it was redirected.

It is possible?

Body:
A very simple solution is to modify your urls.py in this way:

  url(r'^'desired_url_to_redirect/(?:(?P<error_key>[0-9]+)/)?$', views.'name_of_your_view', name='name_of_your_view'),

The second parameter is optional and would act as a key for the type error. The only thing left would be to update your template to present the desired message based on the type of error.

For defining your view don't forget to insert as a second parameter 'error_key=None'


问:
VBA Replace not working for numbers over 1.0
I'm trying to make a macro that takes the selected cells, replace the "." with ",", then changes it to double, divides it by 2 and rounds it off.

Examples of cells:

0.910   1.000

```<code>For Each Cell In Selection
    Cell.Value = Replace(Cell, ".", ",")
    Cell = CDbl(Cell.Value)
    Cell = Cell / 2
    Cell = Round(Cell, 4)
Next Cell
</code>```

I'm expecting to get:

0.4550  0.5000

The problem is that if I have a number greater than 1.0 it just removes the "." and doesn't replace it with anything and since the cells have 3 decimals, I suddenly get 1000 instead of 1.

So I get:

0.4550  500

Any suggestions of what goes wrong?

答:
A little simpler; credited to @njimack</p>

```<code>For Each cell In Selection
    If IsNumeric(cell) Then cell.Formula = Round(cell.Value, 1)
Next cell
</code>```

Body:
I'm trying to make a macro that takes the selected cells, replace the "." with ",", then changes it to double, divides it by 2 and rounds it off.

Examples of cells:

0.910   1.000

For Each Cell In Selection
    Cell.Value = Replace(Cell, ".", ",")
    Cell = CDbl(Cell.Value)
    Cell = Cell / 2
    Cell = Round(Cell, 4)
Next Cell

I'm expecting to get:

0.4550  0.5000

The problem is that if I have a number greater than 1.0 it just removes the "." and doesn't replace it with anything and since the cells have 3 decimals, I suddenly get 1000 instead of 1.

So I get:

0.4550  500

Any suggestions of what goes wrong?

Body:
A little simpler; credited to @njimack

For Each cell In Selection
    If IsNumeric(cell) Then cell.Formula = Round(cell.Value, 1)
Next cell