问:
retrieve json value by key
Below is success function for my ajax:

```<code>success: function(responseJson)
{
    var receivedData = [];

    $.each(responseJson.jsonArray, function(index)
    {
        $.each(responseJson.jsonArray[index], function(key, value)
        {
            var point = [];

            point.push(key);
            point.push(value);
            receivedData.push(point);
        });
    });

    if(receivedData["arrayData3"] === "data3")
    {
        alert("Edit Customer profile successfully!");
    }
},
</code>```

From code above, i push all data into receivedData variable, I can print all key and value out just by print the variable receivedData, but how can I get specific value by their key? receivedData["arrayData3"] will get undefined.
Below is code from my servlet:

```<code>JSONObject json = new JSONObject();
JSONArray array = new JSONArray();
JSONObject data =  new JSONObject();
data.put("arrayData1", "data1");
data.put("arrayData2", "data2");
data.put("arrayData3", "data3");
array.add(data);
json.put("jsonArray", array);
</code>```

答:
You mixed up the jsonarray with the jsonobject.

Actually,the resposeJson is like the code below.

```<code>resposeJson = {
    jsonArray:[
        {
            arrarData1: "data1"
        },
        {
            arrarData2: "data2"
        },
        {
            arrarData3: "data3"
        },
    ]
}
</code>```

So,you ajax code can be writed like below

```<code>success: function(responseJson)
{
var receivedData = [];

$.each(responseJson.jsonArray, function(index, elem)
{
    receivedData.push(elem);
});

if(receivedData["arrayData3"] === "data3")
{
    alert("Edit Customer profile successfully!");
}
},
</code>```

Title: retrieve json value by key

Body:
Below is success function for my ajax:

success: function(responseJson)
{
    var receivedData = [];

    $.each(responseJson.jsonArray, function(index)
    {
        $.each(responseJson.jsonArray[index], function(key, value)
        {
            var point = [];

            point.push(key);
            point.push(value);
            receivedData.push(point);
        });
    });

    if(receivedData["arrayData3"] === "data3")
    {
        alert("Edit Customer profile successfully!");
    }
},

From code above, i push all data into receivedData variable, I can print all key and value out just by print the variable receivedData, but how can I get specific value by their key? receivedData["arrayData3"] will get undefined.
Below is code from my servlet:

JSONObject json = new JSONObject();
JSONArray array = new JSONArray();
JSONObject data =  new JSONObject();
data.put("arrayData1", "data1");
data.put("arrayData2", "data2");
data.put("arrayData3", "data3");
array.add(data);
json.put("jsonArray", array);

Body:
You mixed up the jsonarray with the jsonobject.

Actually,the resposeJson is like the code below.

resposeJson = {
    jsonArray:[
        {
            arrarData1: "data1"
        },
        {
            arrarData2: "data2"
        },
        {
            arrarData3: "data3"
        },
    ]
}

So,you ajax code can be writed like below

success: function(responseJson)
{
var receivedData = [];

$.each(responseJson.jsonArray, function(index, elem)
{
    receivedData.push(elem);
});

if(receivedData["arrayData3"] === "data3")
{
    alert("Edit Customer profile successfully!");
}
},


来源: stackexchange

问:
How to extract boolean values from json file?
I am using jq parser to convert json to csv.

Input:

```<code>"abc":{
      "a_val":true
   },
"def":{
      "b_val":false
   },
"normaltext":{
      "c_val":"text_value"
   }
</code>```

I am getting below output.

```<code>,,"text_value"
</code>```

But my desire output is

```<code>"true", "false", "text_value"
</code>```

or

```<code>true, false, text_value
</code>```

Please help.
Thanks in advance.

答:
The input as shown is not quite valid JSON.  The following assumes that surrounding braces have been added so as to produce valid JSON.

The following jq query produces the desired CSV:

```<code>[.abc.a_val, .def.b_val, .normaltext.c_val] | @csv
</code>```

Typescript

```<code>$ jq -r '[.abc.a_val, .def.b_val, .normaltext.c_val] | @csv' input.json
true,false,"text_value"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using jq parser to convert json to csv.

Input:

"abc":{
      "a_val":true
   },
"def":{
      "b_val":false
   },
"normaltext":{
      "c_val":"text_value"
   }

I am getting below output.

,,"text_value"

But my desire output is

"true", "false", "text_value"

or

true, false, text_value

Please help.
Thanks in advance.

Body:
The input as shown is not quite valid JSON.  The following assumes that surrounding braces have been added so as to produce valid JSON.

The following jq query produces the desired CSV:

[.abc.a_val, .def.b_val, .normaltext.c_val] | @csv

Typescript

$ jq -r '[.abc.a_val, .def.b_val, .normaltext.c_val] | @csv' input.json
true,false,"text_value"


问:
How to call stored procedure and display what it returns in mvc 4 without using EF
I'm new to mvc and I'm trying to figure out how to connect to a database, call a stored procedure and display what it returns without using entity framework. I created a textbox and it suppose to filter the display based on user input (i.e. id number). There are a lot of columns in the db that needed to be displayed so if possible I prefer not creating a variable for each column in my Model. I've seen an example where they used model as strongly typed System.Data.DataTable, which works, but I ran into an issue since view doesn't allow two models and there for I couldn't use my textbox.

Does anyone know how can this be done, and would be able to shed some light into this?

Thank you!

答:
Hi my suggestion is you can use Ado.net entity data model for executing the stored procedures . Here is the complete example of how to do this: http://www.c-sharpcorner.com/UploadFile/vendettamit/calling-an-stored-procedure-using-ado-net-entity-model/

And for the problem view doesn't allow two models , we can use the concept of viewmodel and combine as many as model we want.

ex:

```<code>Public class sampleviewmodel
{
     public DataTable propertyname1{get;set;}
     public yourtype  propertyname2{get;set;}

}
</code>```

MoreInfo: http://www.dotnettricks.com/learn/mvc/understanding-viewmodel-in-aspnet-mvc

Hope the above information was helpful.

Thanks

Karthik

Body:
Hi my suggestion is you can use Ado.net entity data model for executing the stored procedures . Here is the complete example of how to do this: http://www.c-sharpcorner.com/UploadFile/vendettamit/calling-an-stored-procedure-using-ado-net-entity-model/

And for the problem view doesn't allow two models , we can use the concept of viewmodel and combine as many as model we want.

ex:

Public class sampleviewmodel
{
     public DataTable propertyname1{get;set;}
     public yourtype  propertyname2{get;set;}

}

MoreInfo: http://www.dotnettricks.com/learn/mvc/understanding-viewmodel-in-aspnet-mvc

Hope the above information was helpful.

Thanks

Karthik


问:
shell_exec not working
Here's my command:

```<code>sudo /usr/local/bin/jpegoptim --max=50 /home/someuser/public_html/reports/images/r121662.jpg
</code>```

This command is supposed to compress an image. I tried running this command using backtick operator and shell_exec, neither will work. The file doesn't compress.

But this command runs when I run it directly in the shell logged in as someuser. I've modified sudoers to accept the command without requiring a password. The file is compressed when I run it in the shell.

Apache is configured to run with suPHP, and the PHP files belong to someuser as well. I've further ensured this by writing a test php script just saying system(id); and running it in the browser. That tells me that the script is indeed being run by someuser.

Also, safe_mode is off.

EDIT: Ok, I got it to output the error

```<code>sudo: sorry, you must have a tty to run sudo
</code>```

Now, what does it mean?!

答: sudo typically requires terminal input (i.e., must have a tty) as it will attempt to ask the user for a password before allowing you to execute a command. Do you really need to use sudo to run the command?  Try removing the sudo.

ContentLicense: CC BY-SA 2.5

Title: shell_exec not working

Body:
Here's my command:

sudo /usr/local/bin/jpegoptim --max=50 /home/someuser/public_html/reports/images/r121662.jpg

This command is supposed to compress an image. I tried running this command using backtick operator and shell_exec, neither will work. The file doesn't compress.

But this command runs when I run it directly in the shell logged in as someuser. I've modified sudoers to accept the command without requiring a password. The file is compressed when I run it in the shell.

Apache is configured to run with suPHP, and the PHP files belong to someuser as well. I've further ensured this by writing a test php script just saying system(id); and running it in the browser. That tells me that the script is indeed being run by someuser.

Also, safe_mode is off.

EDIT: Ok, I got it to output the error

sudo: sorry, you must have a tty to run sudo

Now, what does it mean?!


问:
How to perform concurrent writes on a DynamoDB table?
I want to stream data from different sources- Twitter and reddit, specifically, and store it onto a DynamoDB table. I am quite new to this, so I am unsure if it is doable. I was thinking of using 2 different threads, one for Twitter and one for Reddit. Both the threads will fetch data from the corresponding stream and insert into the DynamoDB table.

Does this seem feasible? Would it be possible to do concurrent writes in DynamoDB? If not, what could be an alternative approach to simultaneously store data from different sources on a single DynamoDB table?

答:
It is highly-encouraged to perform concurrent writes to DynamoDB.

When an Amazon DynamoDB table is created, you can specify the Read and Write throughput per second. To fully utilize this capacity, you could use multiple threads on multiple servers.

To obtain the best throughput from DynamoDB, ensure that the writes employ wide-spread Partition Keys, since these identify how the data is partitioned across multiple DynamoDB servers. Each partition has a subset of the capacity. If many of the reads/writes use the same Partition Key, throughput will be reduced because the requests are hitting a hot partition.


问:
Exrin InjectionProxy InstanceType meaning and uses
When looking through the main app bootstrapper, the InjectionProxy is used to register instances and interfaces. I noticed that interfaces can be registered as InstanceType.SingleInstance (done for the database in the Tesla app) or InstanceType.EachResolve. Further delving of the InjectionProxy code shows that instances are always SingleInstance.

What is the difference between SingleInstance and EachResolve, why would I choose my interfaces to be one or the other, and why are instances always set to be SingleIstance?

答:
SingleInstance means that it will only ever create one copy of the class, for use in anything that requests it.

EachResolve, means that each class that has this interface injected into it, will get a new instance of the interface.

It depends on what you want for your app. In most cases, SingleInstance is what you want, but EachResolve is there incase your situation requires a new instance, instead of the same one used throughout your app.


问:
How to create a simple custom View?
I would like to create an custom View on Android. I have tried to do it as simple as possible and created an almost empty class MyView and used it in my LinearLayout but the application fails on start with "Force Close". How can I do a simple custom View? According to Building Custom Components the View gets the size 100x100 if I don't override onMeasure().

```<code>public class MyView extends View {

    public MyView(Context context) {
        super(context);
    }
}
</code>```

And I use it in a LinearLayout with:

```<code><view
    class="com.example.MyView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="0.0" />
</code>```

What am I doing wrong?

If I use the constructor that itemon suggest and the corresponding call to the superclass. Then the "Force Close" is gone, but my LinearLayout is broken, the components after MyView isn't shown.

Here is my main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    >
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="0.0"
    android:background="#f00"
    android:text="Hello"
/>
<view
    class="com.example.MyView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="0.0"
/>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="0.0"
    android:background="#00f"
    android:text="World"
/>
</LinearLayout>
</code>```

答:
may be you could define another constructor method like this:

```<code>public MyView(Context context, AttributeSet attrs)
</code>```

the android framework will try to build the UI with your view from the constructor above.

Title: How to create a simple custom View?

Body:
I would like to create an custom View on Android. I have tried to do it as simple as possible and created an almost empty class MyView and used it in my LinearLayout but the application fails on start with "Force Close". How can I do a simple custom View? According to Building Custom Components the View gets the size 100x100 if I don't override onMeasure().

public class MyView extends View {

    public MyView(Context context) {
        super(context);
    }
}

And I use it in a LinearLayout with:

<view
    class="com.example.MyView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="0.0" />

What am I doing wrong?

If I use the constructor that itemon suggest and the corresponding call to the superclass. Then the "Force Close" is gone, but my LinearLayout is broken, the components after MyView isn't shown.

Here is my main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    >
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="0.0"
    android:background="#f00"
    android:text="Hello"
/>
<view
    class="com.example.MyView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="0.0"
/>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="0.0"
    android:background="#00f"
    android:text="World"
/>
</LinearLayout>

Body:
may be you could define another constructor method like this:

public MyView(Context context, AttributeSet attrs)

the android framework will try to build the UI with your view from the constructor above.


问:
autocompletion pop up menu in sublime text 3 doesn't display
I have Sublime Text 3 on Ubuntu and the ctrl+space to bring the autocompletion menu does not work. I tried to set it in the user key binding but it still does not work.

I then installed the SublimeCodeIntel package, but I have the same issue. I can manually bring the pop-up menu up. Even with the ctrl+shift+space for SublimeCodeIntel nothing works.

any ideas?

答: First save your document as css or which ever format you want your browser to read it as. Sublime Text will recognize the type of markup/programming language you are using and auto complete accordingly. </p>


问:
I'm totally faint in using multer-s3 to upload image to aws s3 bucket
what does "upload.array('photos', 3) " in the following code denotes ....

My html code. (code reduced for brevity)

```<code> <form action="/upload" method="POST">
 <input type="file" name="pic" id="pic" accept="image/*">
 <input type="submit">
 </form>
</code>```

my expressjs code

```<code>AWS.config.update({
  accessKeyId: "xxxxxxxxxxxxx",
  secretAccessKey: "yyyyyyyyyy",
  "region": "zzzzzzzzz" ,
  signatureVersion: 'v4'
});

var s3=new AWS.S3();

var upload = multer({
  storage: multerS3({
    s3: s3,
    bucket: 'imgcontainer',
    metadata: function (req, file, cb) {
      cb(null, {fieldName: file.fieldname});
    },
    key: function (req, file, cb) {
      cb(null, Date.now().toString())
    }
  })
})

app.post('/upload', upload.array('photos', 3), function(req, res, next) {
  res.send('Successfully uploaded ' + req.files.length + ' files!')
})
</code>```

output:

```<code> Cannot read property 'length' of undefined
</code>```

答:
There are two issues:

The file field name is 'pic' and not 'photos' (which is the field name being used on the Express side). Change one name or the other.

The enctype="multipart/form-data" attribute needs to be explicitly set on the <form> tag, otherwise browsers will send the form as application/x-www-form-urlencoded which will not include file input data.

Make these changes and req.files should be populated as outlined in the multer documentation.

Body:
what does "upload.array('photos', 3) " in the following code denotes ....

My html code. (code reduced for brevity)

 <form action="/upload" method="POST">
 <input type="file" name="pic" id="pic" accept="image/*">
 <input type="submit">
 </form>

my expressjs code

AWS.config.update({
  accessKeyId: "xxxxxxxxxxxxx",
  secretAccessKey: "yyyyyyyyyy",
  "region": "zzzzzzzzz" ,
  signatureVersion: 'v4'
});

var s3=new AWS.S3();

var upload = multer({
  storage: multerS3({
    s3: s3,
    bucket: 'imgcontainer',
    metadata: function (req, file, cb) {
      cb(null, {fieldName: file.fieldname});
    },
    key: function (req, file, cb) {
      cb(null, Date.now().toString())
    }
  })
})

app.post('/upload', upload.array('photos', 3), function(req, res, next) {
  res.send('Successfully uploaded ' + req.files.length + ' files!')
})

output:

 Cannot read property 'length' of undefined


问:
Take certain parts from string, then use it to create one string variable
I'm trying to create a variable that's a string from a list
The list is just the alphabet (Don't ask why, it just has to for the program)

```<code>passwords = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
</code>```

Basically, I used to have a variable that took 4 random letters from it to create one string that looked like this:

```<code>correctPassword = random.sample(passwords,4)
</code>```

What I need is 4 specific characters from the list to create the same kind of string variable, the word "STOP".

An answer to this would be greatly appreciated, I'm trying to recreate the hacking minigame from Fallout, if any of you know what that is, thanks!

答:
You can use this for create a string variable from list:

```<code>import random
passwords = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
correctPassword = random.sample(passwords,4)
result = ""
result = result.join(correctPassword)
print(result)
</code>```

and get something like:STOP

The Python join() method is a string method. It merges a list of objects into a string.

Body:
I'm trying to create a variable that's a string from a list
The list is just the alphabet (Don't ask why, it just has to for the program)

passwords = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]

Basically, I used to have a variable that took 4 random letters from it to create one string that looked like this:

correctPassword = random.sample(passwords,4)

What I need is 4 specific characters from the list to create the same kind of string variable, the word "STOP".

An answer to this would be greatly appreciated, I'm trying to recreate the hacking minigame from Fallout, if any of you know what that is, thanks!

Body:
You can use this for create a string variable from list:

import random
passwords = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
correctPassword = random.sample(passwords,4)
result = ""
result = result.join(correctPassword)
print(result)

and get something like:STOP

The Python join() method is a string method. It merges a list of objects into a string.


问:
Horizontally align table-cells within table
How can I horizontally align the text within this table-cell? It looks like it's floating to the right, and I'm not sure why.
https://jsfiddle.net/o06e11o9/

HTML

```<code><div class="affil2">
  <div class="oval2"></div>
  <div class="contents">
    a lorem ipsum dolor sit amet. Donec facilisis tortor ut augue lacinia, at viverra est semper. Sed sapien metus, tempor a tortor.
    <br />
    <br /> Pellentesque non dignissim neque. Ut porta viverra est, ut dignissim elit elementum ut.
  </div>
</div>
</code>```

CSS

```<code>.affil2 {
  align-content: center;
  display: table;
  text-align: center;
  z-index: 20;
  border: 1px solid #705A1D;
  position: relative;
  height: 200px;
  width: 960px;
  background-color: #af9254;
  box-shadow: 0px 3px 10px 0px rgba(0, 0, 0, .35);
}

.contents {
  margin: 0 auto;
  text-align: left;
  width: 600px;
  display: table-cell;
  vertical-align: middle;
  color: #fff;
  font-size: 18px;
}

.oval2 {
  z-index: 1;
  position: absolute;
  top: -110px;
  width: 1200px;
  height: 250px;
  border-radius: 100%;
  background: radial-gradient(ellipse at center, rgba(255, 255, 255, 0.3) 0%, rgba(255, 0, 0, 0) 100%);
}
</code>```

答:
There are many strange things in your code, but for your solution you can change:

width: 100%; and text-align: center; of the class contents

```<code>.contents {
  margin: 0 auto;
  text-align: center;
  width: 100%;
  display: table-cell;
  vertical-align: middle;
  color: #fff;
  font-size: 18px;
}
</code>```

JsFiddle Link

Body:
How can I horizontally align the text within this table-cell? It looks like it's floating to the right, and I'm not sure why.
https://jsfiddle.net/o06e11o9/

HTML

    a lorem ipsum dolor sit amet. Donec facilisis tortor ut augue lacinia, at viverra est semper. Sed sapien metus, tempor a tortor.

 Pellentesque non dignissim neque. Ut porta viverra est, ut dignissim elit elementum ut.

CSS

.affil2 {
  align-content: center;
  display: table;
  text-align: center;
  z-index: 20;
  border: 1px solid #705A1D;
  position: relative;
  height: 200px;
  width: 960px;
  background-color: #af9254;
  box-shadow: 0px 3px 10px 0px rgba(0, 0, 0, .35);
}

.contents {
  margin: 0 auto;
  text-align: left;
  width: 600px;
  display: table-cell;
  vertical-align: middle;
  color: #fff;
  font-size: 18px;
}

.oval2 {
  z-index: 1;
  position: absolute;
  top: -110px;
  width: 1200px;
  height: 250px;
  border-radius: 100%;
  background: radial-gradient(ellipse at center, rgba(255, 255, 255, 0.3) 0%, rgba(255, 0, 0, 0) 100%);
}

Body:
There are many strange things in your code, but for your solution you can change:

width: 100%; and text-align: center; of the class contents

.contents {
  margin: 0 auto;
  text-align: center;
  width: 100%;
  display: table-cell;
  vertical-align: middle;
  color: #fff;
  font-size: 18px;
}

JsFiddle Link


问:
Target machine refused connection

```<code>from geopy.geocoders import Nominatim
import openpyxl
wb = openpyxl.load_workbook('#######.xlsx')
ws = wb.active
geolocator = Nominatim(timeout=60)

for i in range(2,1810):
    count1 = 0
    count2 = 1
    address = str(ws['B'+str(i)].value)
    city = str(ws['C'+str(i)].value)
    state = str(ws['D'+str(i)].value)
    zipc = str(ws['F'+str(i)].value)
    result = None
    iden1 = address + ' ' + city + ' ' + state
    iden2 = city + ' ' + zipc + ' ' + state
    iden3 = city + ' ' + state
    print(iden1, iden2, iden3)
    print(geolocator.geocode(iden2).address)
    try:
        location1 = geolocator.geocode(iden1)
    except:
        pass
    try:
        location2 = geolocator.geocode(iden2)
    except:
        pass
    try:
        location3 = geolocator.geocode(iden3)
    except:
        pass
    count = None
    try:
        county1 = str(location1.address)
        county1_list = county1.split(", ")
        #print(county1_list)
        for q in county1_list:
            if 'county' in q.lower():
                if count == None:
                    count = q
    except:
        pass
    try:
        county2 = str(location2.address)
        county2_list = county2.split(", ")
        #print(county2_list)
        for z in county2_list:
            if 'county' in z.lower():
                if count == None:
                    count = z
    except:
        pass
    try:
        county3 = str(location3.address)
        county3_list = county3.split(", ")
        #print(county3_list)
        for j in county3_list:
            if 'county' in j.lower():
                if count == None:
                    count = j
    except:
        pass
    print(i, count)
    #ws['E'+str(i)] = count
    if count == 50:
        #wb.save("#####" +str(count2) +".xlsx")
        count2 += 1
        count1 = 0
</code>```

Hello all, this code is pretty simple and uses geopy to extract county names using 3 different methods names iden1, iden2, and iden3 which are a combination of address, city, state, and zipcode. This ran fine for about 300 lines but began to repeat the same county, and after restarting the script, just spat out Nones. I put in the line print (geolocator.geocode(iden2).address) to find the error and got this error message.

Traceback (most recent call last):

File "C:/Users/#####/Downloads/Web content/#####/####_county.py",
  line 19, in
      print(geolocator.geocode(iden2).address)   File "C:\Users#####\AppData\Local\Programs\Python\Python36-32\lib\site-packages\geopy\geocoders\osm.py",
  line 193, in geocode
      self._call_geocoder(url, timeout=timeout), exactly_one   File "C:\Users#####\AppData\Local\Programs\Python\Python36-32\lib\site-packages\geopy\geocoders\base.py",
  line 171, in _call_geocoder
      raise GeocoderServiceError(message) geopy.exc.GeocoderServiceError: [WinError 10061] No connection could
  be made because the target machine actively refused it

This script was working before but now does not. Is my IP being blocked from using goepy's database or something? Thanks for your help!

答: It looks like you're hitting their ratelimiting. It seems that they ask that you limit your API requests to 1/second. You can take a look here for their usage  policy where they list alternatives to using their API as well as contraints.</p>

Title: Target machine refused connection

Body:
from geopy.geocoders import Nominatim
import openpyxl
wb = openpyxl.load_workbook('#######.xlsx')
ws = wb.active
geolocator = Nominatim(timeout=60)

for i in range(2,1810):
    count1 = 0
    count2 = 1
    address = str(ws['B'+str(i)].value)
    city = str(ws['C'+str(i)].value)
    state = str(ws['D'+str(i)].value)
    zipc = str(ws['F'+str(i)].value)
    result = None
    iden1 = address + ' ' + city + ' ' + state
    iden2 = city + ' ' + zipc + ' ' + state
    iden3 = city + ' ' + state
    print(iden1, iden2, iden3)
    print(geolocator.geocode(iden2).address)
    try:
        location1 = geolocator.geocode(iden1)
    except:
        pass
    try:
        location2 = geolocator.geocode(iden2)
    except:
        pass
    try:
        location3 = geolocator.geocode(iden3)
    except:
        pass
    count = None
    try:
        county1 = str(location1.address)
        county1_list = county1.split(", ")
        #print(county1_list)
        for q in county1_list:
            if 'county' in q.lower():
                if count == None:
                    count = q
    except:
        pass
    try:
        county2 = str(location2.address)
        county2_list = county2.split(", ")
        #print(county2_list)
        for z in county2_list:
            if 'county' in z.lower():
                if count == None:
                    count = z
    except:
        pass
    try:
        county3 = str(location3.address)
        county3_list = county3.split(", ")
        #print(county3_list)
        for j in county3_list:
            if 'county' in j.lower():
                if count == None:
                    count = j
    except:
        pass
    print(i, count)
    #ws['E'+str(i)] = count
    if count == 50:
        #wb.save("#####" +str(count2) +".xlsx")
        count2 += 1
        count1 = 0

Hello all, this code is pretty simple and uses geopy to extract county names using 3 different methods names iden1, iden2, and iden3 which are a combination of address, city, state, and zipcode. This ran fine for about 300 lines but began to repeat the same county, and after restarting the script, just spat out Nones. I put in the line print (geolocator.geocode(iden2).address) to find the error and got this error message.

Traceback (most recent call last):

File "C:/Users/#####/Downloads/Web content/#####/####_county.py",
  line 19, in
      print(geolocator.geocode(iden2).address)   File "C:\Users#####\AppData\Local\Programs\Python\Python36-32\lib\site-packages\geopy\geocoders\osm.py",
  line 193, in geocode
      self._call_geocoder(url, timeout=timeout), exactly_one   File "C:\Users#####\AppData\Local\Programs\Python\Python36-32\lib\site-packages\geopy\geocoders\base.py",
  line 171, in _call_geocoder
      raise GeocoderServiceError(message) geopy.exc.GeocoderServiceError: [WinError 10061] No connection could
  be made because the target machine actively refused it

This script was working before but now does not. Is my IP being blocked from using goepy's database or something? Thanks for your help!


问:
Ltac pattern matching: why does `forall x, ?P x` not match `forall x, x`?
```<code>Ltac checkForall H :=
  let T := type of H in
  match T with
  | forall x, ?P x =>
    idtac
  | _ =>
    fail 1 "not a forall"
  end.

Example test : (forall x, x) -> True.
Proof.
  intros H.
  Fail checkForall H. (* not a forall *)
Abort.
</code>```

I would naively expect checkForall H to succeed, but it doesn't.

In his book Certified Programming with Dependent Types, Adam Chlipala discusses a limitation of pattern matching on dependent types:

The problem is that unification variables may not contain locally bound variables.

Is this the reason for the behaviour I'm seeing here?

答:
As larsr explained, the pattern ?P x can only match a term that is syntactically an application, which does not cover the case you are considering. However, Ltac does provide features for the match you are looking for.  As the user manual says:

There is also a special notation for second-order pattern-matching problems: in an applicative pattern of the form @?id id1 …idn, the variable id matches any complex expression with (possible) dependencies in the variables id1 …idn and returns a functional term of the form fun id1 …idn => term.

Thus, we can write the following proof script:

```<code>Goal (forall x : Prop, x) -> False.
intros H.
match goal with
| H : forall x : Prop, @?P x |- _ => idtac P
end.
</code>```

which prints (fun x : Prop => x).

Body:
Ltac checkForall H :=
  let T := type of H in
  match T with
  | forall x, ?P x =>
    idtac
  | _ =>
    fail 1 "not a forall"
  end.

Example test : (forall x, x) -> True.
Proof.
  intros H.
  Fail checkForall H. (* not a forall *)
Abort.

I would naively expect checkForall H to succeed, but it doesn't.

In his book Certified Programming with Dependent Types, Adam Chlipala discusses a limitation of pattern matching on dependent types:

The problem is that unification variables may not contain locally bound variables.

Is this the reason for the behaviour I'm seeing here?

Body:
As larsr explained, the pattern ?P x can only match a term that is syntactically an application, which does not cover the case you are considering. However, Ltac does provide features for the match you are looking for.  As the user manual says:

There is also a special notation for second-order pattern-matching problems: in an applicative pattern of the form @?id id1 …idn, the variable id matches any complex expression with (possible) dependencies in the variables id1 …idn and returns a functional term of the form fun id1 …idn => term.

Thus, we can write the following proof script:

Goal (forall x : Prop, x) -> False.
intros H.
match goal with
| H : forall x : Prop, @?P x |- _ => idtac P
end.

which prints (fun x : Prop => x).

ContentLicense: CC BY-SA 4.0


问:
Excel Pivot table in ASP
Is there a way I can create Excel Pivot tables using ASP .NET 3.5 with C# ?</p>

答:
I have done this using a third party product: Gembox professional.

Create an Excel spreadsheet with a Pivot table based on a named range.
Export your data to the spreadsheet, update the name of the range and voila.

(I am not related to Gembox in any other way than being a happy customer)

Title: Excel Pivot table in ASP


问:
Parse csv data to create folders and record folder name
Hi I am trying to make a script that parses a csv and
Creates a folder for each line then Copies the item from a path specified in the csv to a location.  Currently I get an error saying Cannot bind argument to parameter 'Path' because it is null. Could someone please help

```<code>CSV Structure
FileLocation
K:\Folder\File
</code>```

Powershell Content

```<code>$csv = Import-Csv c:\export.csv

Foreach ($line in $csv){
    $inc = $i++
    mkdir $inc
    Copy-Item -Path $_.FileLocation -destination c:\users\bford.$inc -Recurse
    }
</code>```

答:
Mathias R. Jessen provided the crucial pointer in a comment on the question:

The foreach iteration variable is $line, yet an attempt is made to use $_ instead, which is undefined ($null) inside the loop body.

Therefore, replacing $_ with $line fixes the problem:

```<code>$csv = Import-Csv c:\export.csv

Foreach ($line in $csv){
    $inc = $i++
    mkdir $inc
    # $line is the iteration variable, not $_
    Copy-Item -Path $line.FileLocation -destination c:\users\bford.$inc -Recurse
}
</code>```

Automatic variable $_ (a.k.a. $PSItem) is defined by PowerShell only in specific contexts, such as in pipelines, usable in the script blocks passed to the ForEach-Object cmdlet.

Despite the unfortunately named foreach alias of the ForEach-Object cmdlet, it is distinct from the foreach statement: the former can - only - use $_ ($PSItem), whereas the latter must use whatever iteration variable is chosen (e.g., in the case above, $line).

Choosing between the foreach statement and the ForEach-Object cmdlet comes down to performance vs. memory use:

Use the pipeline and the ForEach-Object cmdlet to process one object at a time, keeping memory use constant, at the expense of performance.

Use the foreach statement to process a (typically) already-loaded-into-memory-as-a-whole collection quickly, at the expense of memory consumption.

The slower, but more memory-efficient and more concise equivalent of your solution is therefore:

```<code>Import-Csv c:\export.csv | ForEach-Object {
  mkdir ($inc = $i++); Copy-Item -Path $_.FileLocation -destination c:\users\bford.$inc -Recurse
}
</code>```

Note that $i is implicitly initialized to 0 when ++ is applied to it, but it's better to explicitly initialize it first, which you could do in a separate statement beforehand, or in a a -Begin block passed to ForEach-Object, for instance.

Optional reading: Unifying foreach and ForEach-Object with respect to $_

While it's important to understand the different use cases for the foreach statement vs. the ForEach-Object cmdlet, there is value in standardizing the use of $_:

This issue I've created on GitHub argues that the following should be possible - but currently (pre-v6) isn't:

```<code># WISHFUL THINKING: without an explicit iteration variable, define $_
# implicitly, as with the ForEach-Object *cmdlet*.
foreach ($csv) {
  mkdir ($inc = $i++)
  Copy-Item -Path $_.FileLocation -destination c:\users\bford.$inc -Recurse
}
</code>```

Body:
Hi I am trying to make a script that parses a csv and
Creates a folder for each line then Copies the item from a path specified in the csv to a location.  Currently I get an error saying Cannot bind argument to parameter 'Path' because it is null. Could someone please help

CSV Structure
FileLocation
K:\Folder\File

Powershell Content

$csv = Import-Csv c:\export.csv

Foreach ($line in $csv){
    $inc = $i++
    mkdir $inc
    Copy-Item -Path $_.FileLocation -destination c:\users\bford.$inc -Recurse
    }

Body:
Mathias R. Jessen provided the crucial pointer in a comment on the question:

The foreach iteration variable is $line, yet an attempt is made to use $_ instead, which is undefined ($null) inside the loop body.

Therefore, replacing $_ with $line fixes the problem:

$csv = Import-Csv c:\export.csv

Foreach ($line in $csv){
    $inc = $i++
    mkdir $inc
    # $line is the iteration variable, not $_
    Copy-Item -Path $line.FileLocation -destination c:\users\bford.$inc -Recurse
}

Automatic variable $_ (a.k.a. $PSItem) is defined by PowerShell only in specific contexts, such as in pipelines, usable in the script blocks passed to the ForEach-Object cmdlet.

Despite the unfortunately named foreach alias of the ForEach-Object cmdlet, it is distinct from the foreach statement: the former can - only - use $_ ($PSItem), whereas the latter must use whatever iteration variable is chosen (e.g., in the case above, $line).

Choosing between the foreach statement and the ForEach-Object cmdlet comes down to performance vs. memory use:

Use the pipeline and the ForEach-Object cmdlet to process one object at a time, keeping memory use constant, at the expense of performance.

Use the foreach statement to process a (typically) already-loaded-into-memory-as-a-whole collection quickly, at the expense of memory consumption.

The slower, but more memory-efficient and more concise equivalent of your solution is therefore:

Import-Csv c:\export.csv | ForEach-Object {
  mkdir ($inc = $i++); Copy-Item -Path $_.FileLocation -destination c:\users\bford.$inc -Recurse
}

Note that $i is implicitly initialized to 0 when ++ is applied to it, but it's better to explicitly initialize it first, which you could do in a separate statement beforehand, or in a a -Begin block passed to ForEach-Object, for instance.

Optional reading: Unifying foreach and ForEach-Object with respect to $_

While it's important to understand the different use cases for the foreach statement vs. the ForEach-Object cmdlet, there is value in standardizing the use of $_:

This issue I've created on GitHub argues that the following should be possible - but currently (pre-v6) isn't:

# WISHFUL THINKING: without an explicit iteration variable, define $_
# implicitly, as with the ForEach-Object *cmdlet*.
foreach ($csv) {
  mkdir ($inc = $i++)
  Copy-Item -Path $_.FileLocation -destination c:\users\bford.$inc -Recurse
}


问:
Regular expression for an email address not end with
I want to use regex in ruby to capture the plain text email address but NOT the email address surrounded by mailto link tags (like a@b.com), tried source.gsub(/(?!<$)[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/i) but this does not work

答:
/(\w+@[\w.-]+|\{(?:\w+, *)+\w+\}@[\w.-])(?!<\/a>)*$/i

So something like source.gsub(/(\w+@[\w.-]+|\{(?:\w+, *)+\w+\}@[\w.-])(?!<\/a>)*$/i)

Here's the regex statement, I took the liberty of using a different e-mail selector as well.

(?!<\/a>)*$ basically says ignore it if this ends in . It might be more efficient though to just filter out any  tags first if you're expecting multiple email addresses per line / document.

Title: Regular expression for an email address not end with </a>

Body:
/(\w+@[\w.-]+|\{(?:\w+, *)+\w+\}@[\w.-])(?!<\/a>)*$/i

So something like source.gsub(/(\w+@[\w.-]+|\{(?:\w+, *)+\w+\}@[\w.-])(?!<\/a>)*$/i)

Here's the regex statement, I took the liberty of using a different e-mail selector as well.

(?!<\/a>)*$ basically says ignore it if this ends in </a>. It might be more efficient though to just filter out any <a></a> tags first if you're expecting multiple email addresses per line / document.


答:
You can just create the variable as the following:

correctPassword = ["S", "T", "O", "P"]

Or, you can use the indexes of the letters:

correctPassword = [passwords[18], passwords[19], passwords[14], passwords[15]]

Title: Take certain parts from string, then use it to create one string variable


问:
How to set value for variable that refer to other class in constructor without parameter?
I have declared a list of variable including variable that refer to another class.

```<code>public class order {

    private int primaryid;
    private string desc;
    private int customerid;
    private Customer customer;

}
</code>```

And I already create the get and set methods. How can I assign value to variable customer in constructor without parameter?

```<code>public order(){
   primaryid = 0;
   desc = string.empty;
   customerid = 0;
   customer = ?
}
</code>```

答:
If you are just looking to instantiate a new customer try this:</p>

```<code>public order(){
   primaryid = 0;
   desc = string.empty;
   customerid = 0;
   customer = new Customer();
}
</code>```

Body:
I have declared a list of variable including variable that refer to another class.

public class order {

    private int primaryid;
    private string desc;
    private int customerid;
    private Customer customer;

}

And I already create the get and set methods. How can I assign value to variable customer in constructor without parameter?

public order(){
   primaryid = 0;
   desc = string.empty;
   customerid = 0;
   customer = ?
}

Body:
If you are just looking to instantiate a new customer try this:

public order(){
   primaryid = 0;
   desc = string.empty;
   customerid = 0;
   customer = new Customer();
}


答:
I'm not sure I understand what you're trying to do, but...
To create a string variable equal to "STOP":

```<code>x = "STOP"
</code>```

The line of code

```<code>correctPassword = random.sample(passwords,4)
</code>```

doesn't create a string variable but a list of strings 4 items long, each item being a 1-character string.  Using x as defined above, the expression x == correctPassword will always be false.

To consolidate those into a single string:

```<code>correctPasswordAsString = ''.join(correctPassword)
</code>```

A comparison x == correctPasswordAsString will be true if correctPasswordAsString is "STOP", false otherwise.

Body:
I'm not sure I understand what you're trying to do, but...
To create a string variable equal to "STOP":

x = "STOP"

The line of code

correctPassword = random.sample(passwords,4)

doesn't create a string variable but a list of strings 4 items long, each item being a 1-character string.  Using x as defined above, the expression x == correctPassword will always be false.

To consolidate those into a single string:

correctPasswordAsString = ''.join(correctPassword)

A comparison x == correctPasswordAsString will be true if correctPasswordAsString is "STOP", false otherwise.


问:
Why not fading out and fading in jquery?
I've been trying this for several hours

```<code>    $('#position-name').html('Successfuly Changed').fadeOut(1000);
    $('#position-name').html('New Name').fadeIn();
</code>```

I know its simple but, I don't know the reason why If I run those line within my code only New Name that keep showing up despite the given effect.

It fadeOut the New Name and then FadeIn the New Name again

why Is it not fading out or showing successfully changed?

答:
$( "#clickme" ).click(function() {
var message = $('#position-name');

message.html('Successfuly Changed').fadeOut(1000, function() {
  message.html('New Name').fadeIn("slow");
});

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#box {
  width: 200px;
  height: 50px;
  outline: 2px solid;
  line-height: 50px;
  text-align: center;
}</code>```

You can add the next animation in the callback funciton of fadeOut.
After 1 second of the fadeout animation the new fadeIn will start.

<button id="clickme">CLICK ME</button>```

Body:
I've been trying this for several hours

    $('#position-name').html('Successfuly Changed').fadeOut(1000);
    $('#position-name').html('New Name').fadeIn();

I know its simple but, I don't know the reason why If I run those line within my code only New Name that keep showing up despite the given effect.

It fadeOut the New Name and then FadeIn the New Name again

why Is it not fading out or showing successfully changed?

Body:
$( "#clickme" ).click(function() {
var message = $('#position-name');

message.html('Successfuly Changed').fadeOut(1000, function() {
  message.html('New Name').fadeIn("slow");
});

});

#box {
  width: 200px;
  height: 50px;
  outline: 2px solid;
  line-height: 50px;
  text-align: center;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

You can add the next animation in the callback funciton of fadeOut.
After 1 second of the fadeout animation the new fadeIn will start.

<div id="box">
  <div id="position-name"></div>
</div>

<button id="clickme">CLICK ME</button>


问:
Cannot find name 'google' - while using google maps on Ionic2
I wrote the following html/js code which is working fine.

```<code><!DOCTYPE html>
<html>

   <head>
      <script src = "https://maps.googleapis.com/maps/api/js"></script>

      <script>
        function loadMap() {
            var lat = 1;
            var lng = 0;
            var pos = "x";

            var mapOptions = {
               center:new google.maps.LatLng(45.10,20.10),
               zoom:5
            }
            var map = new google.maps.Map(document.getElementById("sample"),mapOptions);

            var marker = new google.maps.Marker({
               position: map.getCenter(),

               icon: {
                  path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW,
                  scale: 5,
                  strokeWeight:2,
                  strokeColor:"#B40404"
               },

               draggable:true,
               map: map,
            });

            google.maps.event.addListener(marker, 'dragend', function() {
                lat = marker.getPosition().lat();
                lng = marker.getPosition().lng();
                pos = " - " + lat + " - " + lng + " - ";
                infowindow = new google.maps.InfoWindow({
               content: pos
                });
               infowindow.open(map,marker);
            });

         }
      </script>
   </head>
   <body onload = "loadMap()">
      <div id = "sample" style = "width:580px; height:400px;"></div>
   </body>
</html>
</code>```

As you can see I did not use any API key
...

```

<p>Then in my related page (SearchPage) I just inserted the following content in the <code>html</code> file:</p>

```<ion-content>

</ion-content>
```

<p>and the <code>ts</code> file looks like this:</p>

```export class SearchPage {
    @ViewChild('map') mapElement: ElementRef;
    map: any;
    ...
    text: any;
    lat : any;
    lon : any;

    constructor(public navCtrl: NavController, public recoshService: Recosh, public alertCtrl: AlertController) {

        Geolocation.getCurrentPosition().then(
            pos => {
                this.lat = pos.coords.latitude;
                this.lon = pos.coords.longitude;
                this.loadMap();
                this.loadGuides();
            },
            err => {
        .....
loadMap(){
        let latLng = new google.maps.LatLng(this.lat, this.lon);
        let mapOptions = {
            center: latLng,
            zoom: 15,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
```

When Ionic2 is building errors are shown and the transpile fails. All of them are related the following error:

Cannot find name 'google'

It seems I'm using the js library in a wrong way. How can I fix it?

答:
I solved it by installing googlemaps:</p>

```<code>$npm install @types/googlemaps --save-dev
</code>```

Body:
I wrote the following html/js code which is working fine.

<!DOCTYPE html>

As you can see I did not use any API key
...

Then in my related page (SearchPage) I just inserted the following content in the html file:

<ion-content>

</ion-content>

and the ts file looks like this:

export class SearchPage {
    @ViewChild('map') mapElement: ElementRef;
    map: any;
    ...
    text: any;
    lat : any;
    lon : any;

    constructor(public navCtrl: NavController, public recoshService: Recosh, public alertCtrl: AlertController) {

        Geolocation.getCurrentPosition().then(
            pos => {
                this.lat = pos.coords.latitude;
                this.lon = pos.coords.longitude;
                this.loadMap();
                this.loadGuides();
            },
            err => {
        .....
loadMap(){
        let latLng = new google.maps.LatLng(this.lat, this.lon);
        let mapOptions = {
            center: latLng,
            zoom: 15,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);

When Ionic2 is building errors are shown and the transpile fails. All of them are related the following error:

Cannot find name 'google'

It seems I'm using the js library in a wrong way. How can I fix it?

Body:
I solved it by installing googlemaps:

$npm install @types/googlemaps --save-dev


问:
I want to open a program by JavaScript on the clients computer? (WScript.shell)
I tried to open a program using this code:

```<code><head>
<title></title>
<script language="javascript" type="text/javascript">
    function run() {
        var shell = new ActiveXObject("WScript.shell");
        if (shell) {
            shell.run('"C:\\Program Files (x86)\\BitTorrent\\BitTorrent.exe"', 1);
        }
        else
        { alert("BitTorrent is not installed on your system."); }
    }
</script>
</head>
<body onload="run()">

</body>
</html>
</code>```

But it doesn't work.
Any help, please?

答:
Check your browsers' configuration, it may block ActiveX.

Do you get any error message ?

Body:
I tried to open a program using this code:

<title></title>

But it doesn't work.
Any help, please?


问:
WKWebView upload file which name contains Chinese character results in garbled code
I am working on a Mac app, just a simple web application encapsulated in WKWebView.

Here is the code when I tring to upload a file which name contains special character:

```<code>-(void)webView:(WKWebView *)webView runOpenPanelWithParameters:(WKOpenPanelParameters *)parameters initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSArray<NSURL *> * _Nullable))completionHandler
{
     DEBUG_FUNC(@"");

     NSOpenPanel* openDlg = [NSOpenPanel openPanel];
    [openDlg setCanChooseFiles:YES];
    [openDlg setCanChooseDirectories:NO];
    [openDlg setPrompt:NSLocalizedString(@"Choose", nil)];
    openDlg.allowsMultipleSelection = YES;

    if ( [openDlg runModal] == NSOKButton )
    {
        if (completionHandler)
        {
            completionHandler([openDlg URLs]);
        }
    }
}
</code>```

When I was using WebView, this way can work, so it should not be a web problem.

But since the project used WKWebView,

 for example: file "证书.p12" would be changed to "è¯ä¹¦.p12" after uploaded via WKWebView.
Anyone know how to solve it?

Thanks!

答:
I've post this issue to https://bugs.webkit.org
So this is an WebKit bug confirmed by WebKit developers,
see more in https://bugs.webkit.org/show_bug.cgi?id=172849</p>

Body:
I am working on a Mac app, just a simple web application encapsulated in WKWebView.

Here is the code when I tring to upload a file which name contains special character:

-(void)webView:(WKWebView *)webView runOpenPanelWithParameters:(WKOpenPanelParameters *)parameters initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSArray<NSURL *> * _Nullable))completionHandler
{
     DEBUG_FUNC(@"");

     NSOpenPanel* openDlg = [NSOpenPanel openPanel];
    [openDlg setCanChooseFiles:YES];
    [openDlg setCanChooseDirectories:NO];
    [openDlg setPrompt:NSLocalizedString(@"Choose", nil)];
    openDlg.allowsMultipleSelection = YES;

    if ( [openDlg runModal] == NSOKButton )
    {
        if (completionHandler)
        {
            completionHandler([openDlg URLs]);
        }
    }
}

When I was using WebView, this way can work, so it should not be a web problem.

But since the project used WKWebView,

 for example: file "证书.p12" would be changed to "è¯ä¹¦.p12" after uploaded via WKWebView.
Anyone know how to solve it?

Thanks!


问:
Fixing Array out of index Error
Im working myself through the Android Programming 3rd edition book by The big nerd ranch. In Chapter 2 theres a challenge to add previous button to the app. I have added the previous button and it works fine as long as i dont try to previous the first question. I dont know exactly how to loop the button so whenever i previous the first question, it goes by default to the last question. The next button does loop through all the question, however the previous button does not. Im just learning the android environment so im sure this is a simple question. How can i fix my current error?

```<code>    mNextButton = (Button) findViewById(R.id.next_button);
    mNextButton.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();

            }
        });

    mPreviousButton = (Button) findViewById(R.id.previous_button);
    mPreviousButton.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
            updatePrevQuestion();

        }
    });

    updateQuestion();
    updatePrevQuestion();

}

private void updatePrevQuestion(){
    int question = mQuestionBank[mCurrentIndex].getTextResId();
    mQuestionTexView.setText(question);
}

private void updateQuestion(){
    int question = mQuestionBank[mCurrentIndex].getTextResId();
    mQuestionTexView.setText(question);
}
</code>```

Here is the error Im getting

```<code>6-06 19:18:09.158 14727-14727/com.example.dany_user.geo_quiz E/AndroidRuntime: FATAL EXCEPTION: main

Process: com.example.dany_user.geo_quiz, PID: 14727

java.lang.ArrayIndexOutOfBoundsException: length=6; index=-1

at com.example.dany_user.geo_quiz.QuizActivity.updatePrevQuestion(QuizActivity.java:98)
                                                                                at com.example.dany_user.geo_quiz.QuizActivity.access$400(QuizActivity.java:11)
                                                                                at com.example.dany_user.geo_quiz.QuizActivity$5.onClick(QuizActivity.java:87)
                                                                                at android.view.View.performClick(View.java:6205)
                                                                                at android.widget.TextView.performClick(TextView.java:11103)
                                                                                at android.view.View$PerformClick.run(View.java:23653)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6682)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
</code>```

答:
The problem is that (-1 % n) is -1 for any n in Java. To ensure that you wrap around to the end of the array, you can use this:

```<code>mCurrentIndex = (mCurrentIndex + mQuestionBank.length - 1) % mQuestionBank.length;
</code>```

That will result in mCurrentIndex always being in range after evaluation if it was already in range.

If you don't want to wrap around (and I'd suggest treating the "previous" and "next" buttons symmetrically), then you can do one or both of the following:

Do nothing in the event handler if mCurrentIndex is at an extreme value

Disable the relevant button if mCurrentIndex is at an extreme value, so the event handler cannot be triggered.

Title: Fixing Array out of index Error

Body:
Im working myself through the Android Programming 3rd edition book by The big nerd ranch. In Chapter 2 theres a challenge to add previous button to the app. I have added the previous button and it works fine as long as i dont try to previous the first question. I dont know exactly how to loop the button so whenever i previous the first question, it goes by default to the last question. The next button does loop through all the question, however the previous button does not. Im just learning the android environment so im sure this is a simple question. How can i fix my current error?

    mNextButton = (Button) findViewById(R.id.next_button);
    mNextButton.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
            updateQuestion();

            }
        });

    mPreviousButton = (Button) findViewById(R.id.previous_button);
    mPreviousButton.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
            updatePrevQuestion();

        }
    });

    updateQuestion();
    updatePrevQuestion();

}

private void updatePrevQuestion(){
    int question = mQuestionBank[mCurrentIndex].getTextResId();
    mQuestionTexView.setText(question);
}

private void updateQuestion(){
    int question = mQuestionBank[mCurrentIndex].getTextResId();
    mQuestionTexView.setText(question);
}

Here is the error Im getting

6-06 19:18:09.158 14727-14727/com.example.dany_user.geo_quiz E/AndroidRuntime: FATAL EXCEPTION: main

Process: com.example.dany_user.geo_quiz, PID: 14727

java.lang.ArrayIndexOutOfBoundsException: length=6; index=-1

at com.example.dany_user.geo_quiz.QuizActivity.updatePrevQuestion(QuizActivity.java:98)
                                                                                at com.example.dany_user.geo_quiz.QuizActivity.access$400(QuizActivity.java:11)
                                                                                at com.example.dany_user.geo_quiz.QuizActivity$5.onClick(QuizActivity.java:87)
                                                                                at android.view.View.performClick(View.java:6205)
                                                                                at android.widget.TextView.performClick(TextView.java:11103)
                                                                                at android.view.View$PerformClick.run(View.java:23653)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6682)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

Body:
The problem is that (-1 % n) is -1 for any n in Java. To ensure that you wrap around to the end of the array, you can use this:

mCurrentIndex = (mCurrentIndex + mQuestionBank.length - 1) % mQuestionBank.length;

That will result in mCurrentIndex always being in range after evaluation if it was already in range.

If you don't want to wrap around (and I'd suggest treating the "previous" and "next" buttons symmetrically), then you can do one or both of the following:

Do nothing in the event handler if mCurrentIndex is at an extreme value

Disable the relevant button if mCurrentIndex is at an extreme value, so the event handler cannot be triggered.


问:
Scala: short form of pattern matching that returns Boolean
I found myself writing something like this quite often:

```<code>a match {
  case `b` => // do stuff
  case _ => // do nothing
}
</code>```

Is there a shorter way to check if some value matches a pattern? I mean, in this case I could just write if (a == b) // do stuff, but what if the pattern is more complex? Like when matching against a list or any pattern of arbitrary complexity. I'd like to be able to write something like this:

```<code>if (a matches b) // do stuff
</code>```

I'm relatively new to Scala, so please pardon, if I'm missing something big :)

答:
This might help:

```<code>class Matches(m: Any) {
    def matches[R](f: PartialFunction[Any, R]) { if (f.isDefinedAt(m)) f(m) }
}
implicit def any2matches(m: Any) = new Matches(m)

scala> 'c' matches { case x: Int => println("Int") }

scala> 2 matches { case x: Int => println("Int") }
Int
</code>```

Now, some explanation on the general nature of the problem.

Where may a match happen?

There are three places where pattern matching might happen: val, case and for. The rules for them are:

```<code>// throws an exception if it fails
val pattern = value

// filters for pattern, but pattern cannot be "identifier: Type",
// though that can be replaced by "id1 @ (id2: Type)" for the same effect
for (pattern <- object providing map/flatMap/filter/withFilter/foreach) ...

// throws an exception if none of the cases match
value match { case ... => ... }
</code>```

There is, however, another situation where case might appear, which is function and partial function literals. For example:

```<code>val f: Any => Unit = { case i: Int => println(i) }
val pf: PartialFunction[Any, Unit] = { case i: Int => println(i) }
</code>```

Both functions and partial functions will throw an exception if called with an argument that doesn't match any of the case statements. However, partial functions also provide a method called isDefinedAt which can test whether a match can be made or not, as well as a method called lift, which will turn a PartialFunction[T, R] into a Function[T, Option[R]], which means non-matching values will result in None instead of throwing an exception.

What is a match?

A match is a combination of many different tests:

```<code>// assign anything to x
case x

// only accepts values of type X
case x: X

// only accepts values matches by pattern
case x @ pattern

// only accepts a value equal to the value X (upper case here makes a difference)
case X

// only accepts a value equal to the value of x
case `x`

// only accept a tuple of the same arity
case (x, y, ..., z)

// only accepts if extractor(value) returns true of Some(Seq()) (some empty sequence)
case extractor()

// only accepts if extractor(value) returns Some something
case extractor(x)

// only accepts if extractor(value) returns Some Seq or Tuple of the same arity
case extractor(x, y, ...,  z)

// only accepts if extractor(value) returns Some Tuple2 or Some Seq with arity 2
case x extractor y

// accepts if any of the patterns is accepted (patterns may not contain assignable identifiers)
case x | y | ... | z
</code>```

Now, extractors are the methods unapply or unapplySeq, the first returning Boolean or Option[T], and the second returning Option[Seq[T]], where None means no match is made, and Some(result) will try to match result as described above.

So there are all kinds of syntactic alternatives here, which just aren't possible without the use of one of the three constructions where pattern matches may happen. You may able to emulate some of the features, like value equality and extractors, but not all of them.

Body:
I found myself writing something like this quite often:

a match {
  case `b` => // do stuff
  case _ => // do nothing
}

Is there a shorter way to check if some value matches a pattern? I mean, in this case I could just write if (a == b) // do stuff, but what if the pattern is more complex? Like when matching against a list or any pattern of arbitrary complexity. I'd like to be able to write something like this:

if (a matches b) // do stuff

I'm relatively new to Scala, so please pardon, if I'm missing something big :)

Body:
This might help:

class Matches(m: Any) {
    def matches[R](f: PartialFunction[Any, R]) { if (f.isDefinedAt(m)) f(m) }
}
implicit def any2matches(m: Any) = new Matches(m)

scala> 'c' matches { case x: Int => println("Int") }

scala> 2 matches { case x: Int => println("Int") }
Int

Now, some explanation on the general nature of the problem.

Where may a match happen?

There are three places where pattern matching might happen: val, case and for. The rules for them are:

// throws an exception if it fails
val pattern = value

// filters for pattern, but pattern cannot be "identifier: Type",
// though that can be replaced by "id1 @ (id2: Type)" for the same effect
for (pattern <- object providing map/flatMap/filter/withFilter/foreach) ...

// throws an exception if none of the cases match
value match { case ... => ... }

There is, however, another situation where case might appear, which is function and partial function literals. For example:

val f: Any => Unit = { case i: Int => println(i) }
val pf: PartialFunction[Any, Unit] = { case i: Int => println(i) }

Both functions and partial functions will throw an exception if called with an argument that doesn't match any of the case statements. However, partial functions also provide a method called isDefinedAt which can test whether a match can be made or not, as well as a method called lift, which will turn a PartialFunction[T, R] into a Function[T, Option[R]], which means non-matching values will result in None instead of throwing an exception.

What is a match?

A match is a combination of many different tests:

// assign anything to x
case x

// only accepts values of type X
case x: X

// only accepts values matches by pattern
case x @ pattern

// only accepts a value equal to the value X (upper case here makes a difference)
case X

// only accepts a value equal to the value of x
case `x`

// only accept a tuple of the same arity
case (x, y, ..., z)

// only accepts if extractor(value) returns true of Some(Seq()) (some empty sequence)
case extractor()

// only accepts if extractor(value) returns Some something
case extractor(x)

// only accepts if extractor(value) returns Some Seq or Tuple of the same arity
case extractor(x, y, ...,  z)

// only accepts if extractor(value) returns Some Tuple2 or Some Seq with arity 2
case x extractor y

// accepts if any of the patterns is accepted (patterns may not contain assignable identifiers)
case x | y | ... | z

Now, extractors are the methods unapply or unapplySeq, the first returning Boolean or Option[T], and the second returning Option[Seq[T]], where None means no match is made, and Some(result) will try to match result as described above.

So there are all kinds of syntactic alternatives here, which just aren't possible without the use of one of the three constructions where pattern matches may happen. You may able to emulate some of the features, like value equality and extractors, but not all of them.


问:
How to make raycast ignore Trigger colliders?
I have a function that checks if a game object can see another game object without anything blocking its view:

```<code>public bool CheckVision(GameObject target)
{
    RaycastHit2D ray = (Physics2D.Raycast(transform.position, target.transform.position - transform.position, m_VisionRange));
    if(ray.collider.name == target.name)
    {
        Debug.DrawRay(transform.position, target.transform.position - transform.position);
        return true;
    }
    else
    {
        return false;
    }
}
</code>```

The only problem is that I don't want it to collide with colliders with the "isTrigger" flag set; I want the raycast to just ignore them. Any ideas?

答:
Change your triggered GameObjects layer on Ignore Raycast or use LayerMask
https://docs.unity3d.com/ScriptReference/LayerMask.html

```<code>int targetLayer = 1 << LayerMask.NameToLayer("Target Layer");
public bool CheckVision(GameObject target)
{
    RaycastHit2D ray = (Physics2D.Raycast(transform.position, target.transform.position - transform.position, m_VisionRange, targetLayer ));
    if(ray.collider.name == target.name)
    {
        Debug.DrawRay(transform.position, target.transform.position - transform.position);
        return true;
    }
    else
    {
        return false;
    }
}
</code>```

Body:
I have a function that checks if a game object can see another game object without anything blocking its view:

public bool CheckVision(GameObject target)
{
    RaycastHit2D ray = (Physics2D.Raycast(transform.position, target.transform.position - transform.position, m_VisionRange));
    if(ray.collider.name == target.name)
    {
        Debug.DrawRay(transform.position, target.transform.position - transform.position);
        return true;
    }
    else
    {
        return false;
    }
}

The only problem is that I don't want it to collide with colliders with the "isTrigger" flag set; I want the raycast to just ignore them. Any ideas?

Body:
Change your triggered GameObjects layer on Ignore Raycast or use LayerMask
https://docs.unity3d.com/ScriptReference/LayerMask.html

int targetLayer = 1 << LayerMask.NameToLayer("Target Layer");
public bool CheckVision(GameObject target)
{
    RaycastHit2D ray = (Physics2D.Raycast(transform.position, target.transform.position - transform.position, m_VisionRange, targetLayer ));
    if(ray.collider.name == target.name)
    {
        Debug.DrawRay(transform.position, target.transform.position - transform.position);
        return true;
    }
    else
    {
        return false;
    }
}


问:
How long does contract processing take?
I just uploaded my contact, bank and tax details to iTunes Connect; how long does this processing normally take? I can only find information from 5+ years ago.</p>

答: The contract review process is about 20 minutes.</p>

Title: How long does contract processing take?


问:
command line: how to copy files with the same name into one directory without overwriting
I have the next folder structure:

```<code>C:\My Test\
C:\My Test\Folder_1\activity[1].json
C:\My Test\Folder_N\...\activity[1].json
</code>```

My goal is to:

copy all activity*json files to D:\Output\ directory to have something like this:

```<code>D:\Output\activity[%unique_variable%].json
D:\Output\activity[%unique_variable%].json
</code>```

My code:

```<code>for /R "C:\My Test\" %%f in (activity*.json) do ( copy %%f D:\Output\activity%random%.json )
</code>```

答:
You could try something as follows:

```<code>setlocal enabledelayedexpansion
set "type=.json"
set "source=c:\my test"
set "dest=d:\output"

for /r "%source%" %%e in ("*%type%") do (
  for %%i in ("%dest%\%%~ne*") do (
    set /a count+=1
  )
  set "source=%%e"
  set "dest=%dest%\%%~ne"
  xcopy "!source!" "!dest!!count!%type%*"
  set count=
)
</code>```

If the file to be copied already exists in the destination folder, a numeric value will be added to the file name and incremented for every duplicate found.

Body:
I have the next folder structure:

C:\My Test\
C:\My Test\Folder_1\activity[1].json
C:\My Test\Folder_N\...\activity[1].json

My goal is to:

copy all activity*json files to D:\Output\ directory to have something like this:

D:\Output\activity[%unique_variable%].json
D:\Output\activity[%unique_variable%].json

My code:

for /R "C:\My Test\" %%f in (activity*.json) do ( copy %%f D:\Output\activity%random%.json )

Body:
You could try something as follows:

setlocal enabledelayedexpansion
set "type=.json"
set "source=c:\my test"
set "dest=d:\output"

for /r "%source%" %%e in ("*%type%") do (
  for %%i in ("%dest%\%%~ne*") do (
    set /a count+=1
  )
  set "source=%%e"
  set "dest=%dest%\%%~ne"
  xcopy "!source!" "!dest!!count!%type%*"
  set count=
)

If the file to be copied already exists in the destination folder, a numeric value will be added to the file name and incremented for every duplicate found.


答:
Without any parameters you can only initialize the customer with a new instance.

```<code>customer = new Customer();
</code>```

or if you are about to hard code the Customer properties, you can use

```<code>customer = new Customer{ *provide the initial values here* };
</code>```

for eg, if customer has FirstName and LastName as its properties,

```<code>customer = new Customer{ FirstName = "someName" , LastName = "someLastName" };
</code>```

Title: How to set value for variable that refer to other class in constructor without parameter?

Body:
I have declared a list of variable including variable that refer to another class.

public class order {

    private int primaryid;
    private string desc;
    private int customerid;
    private Customer customer;

}

And I already create the get and set methods. How can I assign value to variable customer in constructor without parameter?

public order(){
   primaryid = 0;
   desc = string.empty;
   customerid = 0;
   customer = ?
}

Body:
Without any parameters you can only initialize the customer with a new instance.

customer = new Customer();

or if you are about to hard code the Customer properties, you can use

customer = new Customer{ *provide the initial values here* };

for eg, if customer has FirstName and LastName as its properties,

customer = new Customer{ FirstName = "someName" , LastName = "someLastName" };


问:
Partial Specialization of Operator()
One of my classes declares a templated function:

```<code>template<class A, class B>
A do_something(const std::vector<B> &data)
</code>```

which I'd like to partially specialize on typename A. B is a family of types that implement a pretty minimal interface, and we use a lot of them, so I'd like my specialization to be generic on B. I suspect this is doubly vexing as typename A is used only as the return type.

From the internet, I've gleaned that I can't partially specialize a function, so I've created a class as follows:

```<code>template<class A, class B>
class do_something_implementation {
  public:
    do_something_implementation(const std::vector<B> &data_) {
      data = data_;
    }

  int do_something_implementation<int, B>::operator()() {
    /* Complicated algorithm goes here... */
  }

  double do_something_implementation<double, B>::operator()() {
    /* Different complicated algorithm goes here... */
  }

  private:
      std::vector<B> data;
}
</code>```

When I try to compile that (using Visual Studio 2008), the compiler crashes (!) and I get the following error:

```<code>fatal error C1001: An internal error has occurred in the compiler.
</code>```

I assume this is my problem and not the compiler's. Is there a better way to express the partial specialization I'm aiming for?

答:
People typically just forward to a static implementation.</p>

```<code>template<class A, class B> class X;
template<class A, class B> friend class X;
template<class A, class B> class X {
public:
    static A do_something(class_type* not_this, const std::vector<B>& data) {
        //...
    }
};
// partially specialize
template<class A, class B>
A do_something(const std::vector<B> &data) {
    return X<A, B>::do_something(this, data);
};
</code>```

Title: Partial Specialization of Operator()

Body:
One of my classes declares a templated function:

template<class A, class B>
A do_something(const std::vector &data)

which I'd like to partially specialize on typename A. B is a family of types that implement a pretty minimal interface, and we use a lot of them, so I'd like my specialization to be generic on B. I suspect this is doubly vexing as typename A is used only as the return type.

From the internet, I've gleaned that I can't partially specialize a function, so I've created a class as follows:

template<class A, class B>
class do_something_implementation {
  public:
    do_something_implementation(const std::vector &data_) {
      data = data_;
    }

  int do_something_implementation<int, B>::operator()() {
    /* Complicated algorithm goes here... */
  }

  double do_something_implementation<double, B>::operator()() {
    /* Different complicated algorithm goes here... */
  }

  private:
      std::vector data;
}

When I try to compile that (using Visual Studio 2008), the compiler crashes (!) and I get the following error:

fatal error C1001: An internal error has occurred in the compiler.

I assume this is my problem and not the compiler's. Is there a better way to express the partial specialization I'm aiming for?

Body:
People typically just forward to a static implementation.

template<class A, class B> class X;
template<class A, class B> friend class X;
template<class A, class B> class X {
public:
    static A do_something(class_type* not_this, const std::vector<B>& data) {
        //...
    }
};
// partially specialize
template<class A, class B>
A do_something(const std::vector<B> &data) {
    return X<A, B>::do_something(this, data);
};


问:
jQuery Datepicker is not being executed
I have the following in my main php file:

```<code><script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
    $( function() {
        $( "#datepicker" ).datepicker();
    } );
</script>
</code>```

The input box that contains the input box is being written by innerHTML.

For example, this is how the input box is being written.

echo $api->get_add_number(); calls PHP code. There is a select box that will call the following:

```<code>function fetch_select(val)
{
    $.ajax({
        type: 'post',
        url: 'fetch_data.php',
        data: {
            get_option:val
        },
        success: function (response) {
            document.getElementById("new_select").innerHTML=response;
        }
    });
}
</code>```

From there the input box will be written and returned as innerHTML.

The issue is when I try and click the input box:

```<code><input type="text" id="datepicker"/>
</code>```

I get no date pick popup. Is this because it is in innerHTML and can't be reached by javascript?

答:
No, there is nothing to do with innerHTML, the problem here is timing. All jquery plugins are built when you call its function.

So you just need to call it after include your new html

```<code>success: function (response) {
            document.getElementById("new_select").innerHTML=response;
            $( "#datepicker" ).datepicker();
         }
</code>```

Title: jQuery Datepicker is not being executed

Body:
I have the following in my main php file:

The input box that contains the input box is being written by innerHTML.

For example, this is how the input box is being written.

echo $api->get_add_number(); calls PHP code. There is a select box that will call the following:

function fetch_select(val)
{
    $.ajax({
        type: 'post',
        url: 'fetch_data.php',
        data: {
            get_option:val
        },
        success: function (response) {
            document.getElementById("new_select").innerHTML=response;
        }
    });
}

From there the input box will be written and returned as innerHTML.

The issue is when I try and click the input box:

<input type="text" id="datepicker"/>

I get no date pick popup. Is this because it is in innerHTML and can't be reached by javascript?

Body:
No, there is nothing to do with innerHTML, the problem here is timing. All jquery plugins are built when you call its function.

So you just need to call it after include your new html

success: function (response) {
            document.getElementById("new_select").innerHTML=response;
            $( "#datepicker" ).datepicker();
         }


问:
chrome app client certificate for authentication
I am trying to find more information/documentation on submitting client certificates using a chrome application (chrome.sockets.tcp). We currently are using chrome sockets and are communicating fine using TLS 1.1. However, we have new requirements that specify using a client certificate for authentication.  I am looking for any documentation or examples that will demonstrate the implementation using chrome.sockets.tcp API. Any suggestions are greatly appreciated.

Thanks,
Tom

答:
I believe you will need to use forge, a JavaScript TLS implementation.

You can see an example in that project's examples folder of using getCertificate


问:
Simple Yahtzee simulation not giving proper result?
I am working through the MIT OpenCourseWare intro to computer programming course and I am not sure if I am solving a simple simulation the right way.

What is the probability of rolling a Yahtzee! on the first roll? That is, what is the
  probability of rolling five 6-sided dice, and having them all display the same number?

Write a Monte Carlo simulation to solve the above problem (the Yahtzee problem), and
  submit your code as

So the probability of rolling a Yahtzee is 1/1296 or about .077%

Here is my code to run the simulation:

```<code>import random

def runYahtzee(numTrials):
    """Runs the classes version of the yahtzee simulation"""

    success = 0
    for i in range(numTrials):

        dices = []
        for i in range(6):
            dices.append(random.randrange(1,7))
        #print dices

        state = True
        for dice in dices:
            if dice != dices[0]:
                state = False
        if state == True:
            print "You got a Yahtzee"
            print dices
            success += 1

    print "numTrials is: " + str(numTrials)
    print "Success is: " + str(success)
    rate = float(success)/numTrials
    return rate

runYahtzee(10000000)
</code>```

Running the program multiple times, I get around .0001258 each time.  This is .012%, but the actual probability is around .077%. Is there something that I am doing wrong here?

答:
Here's how I'd write it (Python 3):

```<code>from collections import Counter
from random import randint

def roll():
    return randint(1, 6)

def is_yahtzee(num_dice = 5):
    first = roll()
    return all(roll() == first for _ in range(1, num_dice))

def montecarlo(fn, num_trials):
    return Counter(fn() for _ in range(num_trials))

def main():
    num_trials = 10000000
    result = montecarlo(is_yahtzee, num_trials)
    prob = result[True] / num_trials
    print(
        "After {} trials, probability of Yahtzee is {:0.5f}%"
        .format(num_trials, 100. * prob)
    )

if __name__ == "__main__":
    main()
</code>```

which runs like

```<code>After 10000000 trials, probability of Yahtzee is 0.07605%
</code>```

Note that keeping your functions short generally makes them easier to understand and test.

Body:
I am working through the MIT OpenCourseWare intro to computer programming course and I am not sure if I am solving a simple simulation the right way.

What is the probability of rolling a Yahtzee! on the first roll? That is, what is the
  probability of rolling five 6-sided dice, and having them all display the same number?

Write a Monte Carlo simulation to solve the above problem (the Yahtzee problem), and
  submit your code as

So the probability of rolling a Yahtzee is 1/1296 or about .077%

Here is my code to run the simulation:

import random

def runYahtzee(numTrials):
    """Runs the classes version of the yahtzee simulation"""

    success = 0
    for i in range(numTrials):

        dices = []
        for i in range(6):
            dices.append(random.randrange(1,7))
        #print dices

        state = True
        for dice in dices:
            if dice != dices[0]:
                state = False
        if state == True:
            print "You got a Yahtzee"
            print dices
            success += 1

    print "numTrials is: " + str(numTrials)
    print "Success is: " + str(success)
    rate = float(success)/numTrials
    return rate

runYahtzee(10000000)

Running the program multiple times, I get around .0001258 each time.  This is .012%, but the actual probability is around .077%. Is there something that I am doing wrong here?

Body:
Here's how I'd write it (Python 3):

from collections import Counter
from random import randint

def roll():
    return randint(1, 6)

def is_yahtzee(num_dice = 5):
    first = roll()
    return all(roll() == first for _ in range(1, num_dice))

def montecarlo(fn, num_trials):
    return Counter(fn() for _ in range(num_trials))

def main():
    num_trials = 10000000
    result = montecarlo(is_yahtzee, num_trials)
    prob = result[True] / num_trials
    print(
        "After {} trials, probability of Yahtzee is {:0.5f}%"
        .format(num_trials, 100. * prob)
    )

if __name__ == "__main__":
    main()

which runs like

After 10000000 trials, probability of Yahtzee is 0.07605%

Note that keeping your functions short generally makes them easier to understand and test.


问:
Meteor template won't reference event or method
In meteor.js, I've having trouble connecting the HTML and the JS.  There's no reaction on the button click, and I don't see why not.  Therefore the meteor method in server isn't called, and no email is sent.
HTML:

```<code><template name='confirmation'>
    <div class = "container" >
    <form role = "form" id = "email-form">
        <div class = "form-group">
            <label for="inputEmail">Email address</label>
            <input type= "email" class = "form-control" id = "inputEmail" placeholder = "Enter email">
        </div>
        <button type = "submit" class = "btn btn-primary"> Send mail</button>
    </form>
    </div>
</template>
</code>```

This code runs on the client:

```<code> Template.confirmation.events({
  'submit #confirmation-form': function (e,t) {
    e.preventDefault();
    var toAddr=t.find('#inputEmail').value;
    var subject = ("Booked");
    var body = ("Thanks for booking")
    Meteor.call('sendEmail', toAddr, subj, text)
  }
  })
</code>```

This code runs on the server:

```<code>    if (Meteor.isServer){
  Meteor.startup(function(){

  process.env.MAIL_URL = "mailgun"
  Accounts.config({
    sendVerificationEmail: true
  })

  })
  Meteor.methods({
    'sendEmail': function(toAddr,subj,text){
      this.unblock();
      Email.Send({
        from: "booking@timesharewebapp.com",
        to:Meteor.toAddr,
        subject : subj,
        text: text
      })
    }
  })
}
</code>```

The problem is that nothing will react when I press the button.  Nothing comes up in the console, or in the cmd prompt.  I don't know if it's the way I'm calling my events, or if it's the email function.

答:
You are using the wrong selector on the event. Try the below code.</p>

```<code>Template.confirmation.events({
  'submit #email-form': function (e,t) {
    e.preventDefault();
    var toAddr=t.find('#inputEmail').value;
    var subject = ("Booked");
    var body = ("Thanks for booking")
    Meteor.call('sendEmail', toAddr, subj, text)
  }
})
</code>```

Body:
In meteor.js, I've having trouble connecting the HTML and the JS.  There's no reaction on the button click, and I don't see why not.  Therefore the meteor method in server isn't called, and no email is sent.
HTML:

<template name='confirmation'>

    <form role = "form" id = "email-form">

            Email address
            <input type= "email" class = "form-control" id = "inputEmail" placeholder = "Enter email">

        <button type = "submit" class = "btn btn-primary"> Send mail</button>
    </form>

</template>

This code runs on the client:

 Template.confirmation.events({
  'submit #confirmation-form': function (e,t) {
    e.preventDefault();
    var toAddr=t.find('#inputEmail').value;
    var subject = ("Booked");
    var body = ("Thanks for booking")
    Meteor.call('sendEmail', toAddr, subj, text)
  }
  })

This code runs on the server:

    if (Meteor.isServer){
  Meteor.startup(function(){

  process.env.MAIL_URL = "mailgun"
  Accounts.config({
    sendVerificationEmail: true
  })

  })
  Meteor.methods({
    'sendEmail': function(toAddr,subj,text){
      this.unblock();
      Email.Send({
        from: "booking@timesharewebapp.com",
        to:Meteor.toAddr,
        subject : subj,
        text: text
      })
    }
  })
}

The problem is that nothing will react when I press the button.  Nothing comes up in the console, or in the cmd prompt.  I don't know if it's the way I'm calling my events, or if it's the email function.

Body:
You are using the wrong selector on the event. Try the below code.

Template.confirmation.events({
  'submit #email-form': function (e,t) {
    e.preventDefault();
    var toAddr=t.find('#inputEmail').value;
    var subject = ("Booked");
    var body = ("Thanks for booking")
    Meteor.call('sendEmail', toAddr, subj, text)
  }
})


问:
SQL: how to select text with the shortest, longest and average length text message in one query?
Question: Find the tweet(s) with the shortest, longest and average length text message.

My sql query:

```<code>SELECT *
FROM Tweet
WHERE text = ANY (SELECT max(length(text)), min(length(text)), avg(length(text))
                  FROM Tweet
                 )
</code>```

But the result shows:

OperationalError: near "SELECT": syntax error

答:
You are close.  But a JOIN is a better approach:

```<code>SELECT t.*
FROM Tweet t JOIN
     (SELECT max(length(text)) as maxt, min(length(text)) as mint,
             avg(length(text)) as avt
      FROM Tweet
     ) tt
     on length(t.text) in (tt.maxt, tt.mint, tt.avgt);
</code>```

I don't think avg(length(text)) makes sense unless you take the floor or convert it to an integer somehow.  That said, some databases will return an integer for an avg(), so it might work in your database.

Your query doesn't work because the subquery returns three columns; however, it is only being compared to one.  Some databases allow tuples with in.  Even so, the length of the operands don't match.

Body:
Question: Find the tweet(s) with the shortest, longest and average length text message.

My sql query:

SELECT *
FROM Tweet
WHERE text = ANY (SELECT max(length(text)), min(length(text)), avg(length(text))
                  FROM Tweet
                 )

But the result shows:

OperationalError: near "SELECT": syntax error

Body:
You are close.  But a JOIN is a better approach:

SELECT t.*
FROM Tweet t JOIN
     (SELECT max(length(text)) as maxt, min(length(text)) as mint,
             avg(length(text)) as avt
      FROM Tweet
     ) tt
     on length(t.text) in (tt.maxt, tt.mint, tt.avgt);

I don't think avg(length(text)) makes sense unless you take the floor or convert it to an integer somehow.  That said, some databases will return an integer for an avg(), so it might work in your database.

Your query doesn't work because the subquery returns three columns; however, it is only being compared to one.  Some databases allow tuples with in.  Even so, the length of the operands don't match.


问:
Neo4j / Cypher - Conditional set/create/etc statement based on count (or any previous query statement)
How do you conditionally do a SET (or anything else) based on the result of a previous line? So for example the query below (which doesn't work atm), where I'm trying to update something based on if the count is 1 (and not do it otherwise). Query doesn't like statements after THEN so that's where the error is occurring. I've tried also using WHERE clauses but no luck as of yet.

Is there any other way to accomplish what I'm trying to do below in a single query?

```<code>MATCH (n:Thing { name: 'asdf' })
OPTIONAL MATCH (p:Thing)-[:HAS_CHILD]->(n)
OPTIONAL MATCH (c)<-[:HAS_CHILD]-(p:Thing)
WITH c, p, n,
CASE count(c)
WHEN 1
THEN SET p.btogstate = 'closed'
DETACH DELETE n
</code>```

Update

Tried the following based on a similar post but still no luck:

```<code>MATCH (n:Thing { name: 'asdf' })
OPTIONAL MATCH (p:Thing)-[:HAS_CHILD]->(n)
OPTIONAL MATCH (c)<-[:HAS_CHILD]-(p:Thing)
WITH c, p, n,
CASE WHEN count(c) = 1 then [1] else [] end as countOne
FOREACH (x in countOne | SET p.btogstate = 'closed'
DETACH DELETE n
</code>```

Update 2 (final)

While cybersam's solution worked in a particular situation, the following was the only thing that ended up working for my particular situation for reasons that I still don't understand, so here it is for anyone that might run into similar weirdness. The main difference is that instead of using count to see if there was more than one child for the parent node, I just did another match to see if there was anything else that was a child of the parent node that wasn't the originally matched child (i.e. where n<>y). If there was not (i.e. y is null) then update the property, if there was (i.e. y is not null) then don't do anything other than delete n:

```<code>MATCH (n:Thing { name: 'asdf' })
OPTIONAL MATCH (p:Thing)-[:HAS_CHILD]->(n)
with p, n
OPTIONAL MATCH (p)-[:HAS_CHILD]->(y)
WHERE n<>y
WITH n, y, p,
CASE WHEN y IS NULL then [1] else [] end as countOne
FOREACH (x in countOne | SET p.btogstate = 'closed')
DETACH DELETE n;
</code>```

答:
Try this:

```<code>MATCH (n:Thing { name: 'asdf' })
OPTIONAL MATCH (p:Thing)-[:HAS_CHILD]->(n)
OPTIONAL MATCH (c)<-[:HAS_CHILD]-(p:Thing)
WITH c, p, n
FOREACH(x IN (CASE WHEN c IS NULL THEN [] else [1] END) |
  DETACH DELETE n
)
</code>```

Based on this Mark Needham post (Neo4j: LOAD CSV – Handling conditionals).

Body:
How do you conditionally do a SET (or anything else) based on the result of a previous line? So for example the query below (which doesn't work atm), where I'm trying to update something based on if the count is 1 (and not do it otherwise). Query doesn't like statements after THEN so that's where the error is occurring. I've tried also using WHERE clauses but no luck as of yet.

Is there any other way to accomplish what I'm trying to do below in a single query?

MATCH (n:Thing { name: 'asdf' })
OPTIONAL MATCH (p:Thing)-[:HAS_CHILD]->(n)
OPTIONAL MATCH (c)<-[:HAS_CHILD]-(p:Thing)
WITH c, p, n,
CASE count(c)
WHEN 1
THEN SET p.btogstate = 'closed'
DETACH DELETE n

Update

Tried the following based on a similar post but still no luck:

MATCH (n:Thing { name: 'asdf' })
OPTIONAL MATCH (p:Thing)-[:HAS_CHILD]->(n)
OPTIONAL MATCH (c)<-[:HAS_CHILD]-(p:Thing)
WITH c, p, n,
CASE WHEN count(c) = 1 then [1] else [] end as countOne
FOREACH (x in countOne | SET p.btogstate = 'closed'
DETACH DELETE n

Update 2 (final)

While cybersam's solution worked in a particular situation, the following was the only thing that ended up working for my particular situation for reasons that I still don't understand, so here it is for anyone that might run into similar weirdness. The main difference is that instead of using count to see if there was more than one child for the parent node, I just did another match to see if there was anything else that was a child of the parent node that wasn't the originally matched child (i.e. where n<>y). If there was not (i.e. y is null) then update the property, if there was (i.e. y is not null) then don't do anything other than delete n:

MATCH (n:Thing { name: 'asdf' })
OPTIONAL MATCH (p:Thing)-[:HAS_CHILD]->(n)
with p, n
OPTIONAL MATCH (p)-[:HAS_CHILD]->(y)
WHERE n<>y
WITH n, y, p,
CASE WHEN y IS NULL then [1] else [] end as countOne
FOREACH (x in countOne | SET p.btogstate = 'closed')
DETACH DELETE n;

Body:
Try this:

MATCH (n:Thing { name: 'asdf' })
OPTIONAL MATCH (p:Thing)-[:HAS_CHILD]->(n)
OPTIONAL MATCH (c)<-[:HAS_CHILD]-(p:Thing)
WITH c, p, n
FOREACH(x IN (CASE WHEN c IS NULL THEN [] else [1] END) |
  DETACH DELETE n
)

Based on this Mark Needham post (Neo4j: LOAD CSV – Handling conditionals).


答:
This should work:

```<code>MATCH (n:Thing { name: 'asdf' })
OPTIONAL MATCH (c)<-[:HAS_CHILD]-(p:Thing)-[:HAS_CHILD]->(n)
WITH p, n,
  CASE WHEN COUNT(c) = 1 then [1] else [] end as countOne
FOREACH (x in countOne | SET p.btogstate = 'closed')
DETACH DELETE n;
</code>```

Notice that, unlike your original query, the WITH clause does not include c by itself, as that would prevent the aggregation function COUNT from working as expected (in that case, the count would always have a value of 1 if the optional match found any matches).

Title: Neo4j / Cypher - Conditional set/create/etc statement based on count (or any previous query statement)

Body:
This should work:

MATCH (n:Thing { name: 'asdf' })
OPTIONAL MATCH (c)<-[:HAS_CHILD]-(p:Thing)-[:HAS_CHILD]->(n)
WITH p, n,
  CASE WHEN COUNT(c) = 1 then [1] else [] end as countOne
FOREACH (x in countOne | SET p.btogstate = 'closed')
DETACH DELETE n;

Notice that, unlike your original query, the WITH clause does not include c by itself, as that would prevent the aggregation function COUNT from working as expected (in that case, the count would always have a value of 1 if the optional match found any matches).