问:
app engine standard environment call bigquery python
I am trying to deploy a simple standard app engine in python and from there to make bigquery queries through python bigquery client.

The code is as simple as these:

```<code>from __future__ import absolute_import
import webapp2
import os
from google.cloud import bigquery

class MainPage(webapp2.RequestHandler):
  def get(self):

  client = bigquery.Client(project = "ancient-ceiling-125223")
  project_name = str(client.project)

  query_job = client.query("select 1")

  assert query_job.state == 'RUNNING'

  iterator = query_job.result(timeout= 30)

  rows = list(iterator)

  self.response.write('nothing to see %s' % (project_name))

app = webapp2.WSGIApplication(
[('/', MainPage)], debug=True)
</code>```

The error log: The error appears in the dummy query request

```<code>*('Connection broken: IncompleteRead(209 bytes read)', IncompleteRead(209 bytes read)) (/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py:1528)
Traceback (most recent call last):
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1511, in __call__
    rv = self.handle_exception(request, response, e)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1505, in __call__
    rv = self.router.dispatch(request, response)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1253, in default_dispatcher
    return route.handler_adapter(request, response)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1077, in __call__
    return handler.dispatch()
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 547, in dispatch
    return self.handle_exception(e, self.app.debug)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 545, in dispatch
    return method(*args, **kwargs)
  File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/main.py", line 35, in get
    query_job = client.query("select 1")
  File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/google/cloud/bigquery/client.py", line 986, in query
    job._begin(retry=retry)
  File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/google/cloud/bigquery/job.py", line 397, in _begin
    method='POST', path=path, data=self._build_resource())
  File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/google/cloud/bigquery/client.py", line 271, in _call_api
    return call()
  File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/google/api_core/retry.py", line 260, in retry_wrapped_func
    on_error=on_error,
  File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/google/api_core/retry.py", line 177, in retry_target
    return target()
  File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/google/cloud/_http.py", line 290, in api_request
    headers=headers, target_object=_target_object)
  File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/google/cloud/_http.py", line 183, in _make_request
    return self._do_request(method, url, headers, data, target_object)
  File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/google/cloud/_http.py", line 212, in _do_request
    url=url, method=method, headers=headers, data=data)
  File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/google/auth/transport/requests.py", line 186, in request
    method, url, data=data, headers=request_headers, **kwargs)
  File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/requests/sessions.py", line 502, in request
    resp = self.send(prep, **send_kwargs)
  File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/requests/sessions.py", line 652, in send
    r.content
  File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/requests/models.py", line 825, in content
    self._content = bytes().join(self.iter_content(CONTENT_CHUNK_SIZE)) or bytes()
  File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/requests/models.py", line 750, in generate
    raise ChunkedEncodingError(e)
ChunkedEncodingError: ('Connection broken: IncompleteRead(209 bytes read)', IncompleteRead(209 bytes read))*
</code>```

答:
I could not make it work using python bigquery client library, Here is what I found working in standard app engine environment, </p>

```<code>from __future__ import absolute_import
import webapp2

from googleapiclient.discovery import build
from oauth2client.client import GoogleCredentials

class MainPage(webapp2.RequestHandler):
  def get(self):

    credentials = GoogleCredentials.get_application_default()
    service = build('bigquery', 'v2', credentials=credentials)

    datasets = service.datasets().list(projectId="ancient-ceiling-125223").execute()

    self.response.write('datasets: %s' % datasets)

app = webapp2.WSGIApplication(
    [('/', MainPage)], debug=True)
</code>```

Body:
I am trying to deploy a simple standard app engine in python and from there to make bigquery queries through python bigquery client.

The code is as simple as these:

from __future__ import absolute_import
import webapp2
import os
from google.cloud import bigquery

class MainPage(webapp2.RequestHandler):
  def get(self):

  client = bigquery.Client(project = "ancient-ceiling-125223")
  project_name = str(client.project)

  query_job = client.query("select 1")

  assert query_job.state == 'RUNNING'

  iterator = query_job.result(timeout= 30)

  rows = list(iterator)

  self.response.write('nothing to see %s' % (project_name))

app = webapp2.WSGIApplication(
[('/', MainPage)], debug=True)

The error log: The error appears in the dummy query request

*('Connection broken: IncompleteRead(209 bytes read)', IncompleteRead(209 bytes read)) (/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py:1528)
Traceback (most recent call last):
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1511, in __call__
    rv = self.handle_exception(request, response, e)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1505, in __call__
    rv = self.router.dispatch(request, response)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1253, in default_dispatcher
    return route.handler_adapter(request, response)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 1077, in __call__
    return handler.dispatch()
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 547, in dispatch
    return self.handle_exception(e, self.app.debug)
  File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.3/webapp2.py", line 545, in dispatch
    return method(*args, **kwargs)
  File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/main.py", line 35, in get
    query_job = client.query("select 1")
  File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/google/cloud/bigquery/client.py", line 986, in query
    job._begin(retry=retry)
  File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/google/cloud/bigquery/job.py", line 397, in _begin
    method='POST', path=path, data=self._build_resource())
  File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/google/cloud/bigquery/client.py", line 271, in _call_api
    return call()
  File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/google/api_core/retry.py", line 260, in retry_wrapped_func
    on_error=on_error,
  File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/google/api_core/retry.py", line 177, in retry_target
    return target()
  File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/google/cloud/_http.py", line 290, in api_request
    headers=headers, target_object=_target_object)
  File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/google/cloud/_http.py", line 183, in _make_request
    return self._do_request(method, url, headers, data, target_object)
  File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/google/cloud/_http.py", line 212, in _do_request
    url=url, method=method, headers=headers, data=data)
  File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/google/auth/transport/requests.py", line 186, in request
    method, url, data=data, headers=request_headers, **kwargs)
  File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/requests/sessions.py", line 502, in request
    resp = self.send(prep, **send_kwargs)
  File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/requests/sessions.py", line 652, in send
    r.content
  File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/requests/models.py", line 825, in content
    self._content = bytes().join(self.iter_content(CONTENT_CHUNK_SIZE)) or bytes()
  File "/base/data/home/apps/s~ancient-ceiling-125223/20171115t104156.405543624689752939/lib/requests/models.py", line 750, in generate
    raise ChunkedEncodingError(e)
ChunkedEncodingError: ('Connection broken: IncompleteRead(209 bytes read)', IncompleteRead(209 bytes read))*

Body:
I could not make it work using python bigquery client library, Here is what I found working in standard app engine environment,

from __future__ import absolute_import
import webapp2

from googleapiclient.discovery import build
from oauth2client.client import GoogleCredentials

class MainPage(webapp2.RequestHandler):
  def get(self):

    credentials = GoogleCredentials.get_application_default()
    service = build('bigquery', 'v2', credentials=credentials)

    datasets = service.datasets().list(projectId="ancient-ceiling-125223").execute()

    self.response.write('datasets: %s' % datasets)

app = webapp2.WSGIApplication(
    [('/', MainPage)], debug=True)


来源: stackexchange

问:
How to manage UIbutton in UItableViewCell without using sender.tag method?
I have a cell with a button inside. In my cellForRowAtIndexPath method i refeer to my uibutton in this way:

```<code>UIButton *Button= (UIButton *) [cell viewWithTag:3];
</code>```

I have found a solution, something like this:

```<code>Button.tag = indexPath.row;

[Button addTarget:self action:@selector(yourButtonClicked:) forControlEvents:UIControlEventTouchUpInside];

-(void)yourButtonClicked:(UIButton*)sender
{
     if (sender.tag == 0)
     {
         // Your code here
     }
}
</code>```

But my button.tag is already used to identify the UIbutton view from the others views inside the cell, i can't use it for the indexpath.row. How i can do in my case?

EDIT

Finally i have made a Category for the UIButton, it seems the faster ad reusable solutions but every answers here is a valid option

答: Create custom button subclass of UIButton and define property based on your need. Button.tag is a default identifier. In custom class you can give as many property as you want. Then user this Custom button class instead of UIButton. And user custom properties followed by dot(.) as like as tag.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have a cell with a button inside. In my cellForRowAtIndexPath method i refeer to my uibutton in this way:

UIButton *Button= (UIButton *) [cell viewWithTag:3];

I have found a solution, something like this:

Button.tag = indexPath.row;

[Button addTarget:self action:@selector(yourButtonClicked:) forControlEvents:UIControlEventTouchUpInside];

-(void)yourButtonClicked:(UIButton*)sender
{
     if (sender.tag == 0)
     {
         // Your code here
     }
}

But my button.tag is already used to identify the UIbutton view from the others views inside the cell, i can't use it for the indexpath.row. How i can do in my case?

EDIT

Finally i have made a Category for the UIButton, it seems the faster ad reusable solutions but every answers here is a valid option


问:
how to overwrite log file name in specified in log4j2.xml with new one?
I created separate simple log class: log.java)
e.g.,

```<code>import org.apache.log4j.LogManager;
public class Logs {
   private static final org.apache.log4j.Logger logger= LogManager.getLogger(Logs.class);
   public static org.apache.log4j.Logger Log() {
       return logger;
   }
}
</code>```

and using following log4j2.xml file

```<code><Configuration status="INFO">
    <Properties>
        <Property name="log-path">logs</Property>
    </Properties>

    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </Console>
        <File name="MyFile" fileName="${log-path}/Log${date:yyyy-MM-dd-HH-mm-ss}.log" immediateFlush="false" append="false">
            <PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </File>
    </Appenders>
    <Loggers>
        <Root level="INFO">
            <AppenderRef ref="Console" />
            <AppenderRef ref="MyFile" />
        </Root>
    </Loggers>
</Configuration>
</code>```

Question: I want to pass log file name say testbest.log to my log class so that when log is created the log file name would be testbest.log instead of Log${date:yyyy-MM-dd-HH-mm-ss}.log

How can I achieve this?

答:
log4j.xml

```<code><Configuration status="INFO">
    <Properties>
        <Property name="log-path">logs</Property>
    </Properties>

    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </Console>
        <File name="MyFile" fileName="${log-path}/${sys:log-file-name}" immediateFlush="false" append="false">
            <PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </File>
    </Appenders>
    <Loggers>
        <Root level="INFO">
            <AppenderRef ref="Console" />
            <AppenderRef ref="MyFile" />
        </Root>
    </Loggers>
</Configuration>
</code>```

You can specify file name as VM argument when starting

```<code>java -Dlog-file-name="testbest.log"
</code>```

Or you can define it programmatically as system property

```<code>System.setProperty("log-file-name", "testbest.log");
</code>```

Body:
I created separate simple log class: log.java)
e.g.,

import org.apache.log4j.LogManager;
public class Logs {
   private static final org.apache.log4j.Logger logger= LogManager.getLogger(Logs.class);
   public static org.apache.log4j.Logger Log() {
       return logger;
   }
}

and using following log4j2.xml file

<Configuration status="INFO">
    <Properties>
        <Property name="log-path">logs</Property>
    </Properties>

    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </Console>
        <File name="MyFile" fileName="${log-path}/Log${date:yyyy-MM-dd-HH-mm-ss}.log" immediateFlush="false" append="false">
            <PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </File>
    </Appenders>
    <Loggers>
        <Root level="INFO">
            <AppenderRef ref="Console" />
            <AppenderRef ref="MyFile" />
        </Root>
    </Loggers>
</Configuration>

Question: I want to pass log file name say testbest.log to my log class so that when log is created the log file name would be testbest.log instead of Log${date:yyyy-MM-dd-HH-mm-ss}.log

How can I achieve this?

Body:
log4j.xml

<Configuration status="INFO">
    <Properties>
        <Property name="log-path">logs</Property>
    </Properties>

    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </Console>
        <File name="MyFile" fileName="${log-path}/${sys:log-file-name}" immediateFlush="false" append="false">
            <PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </File>
    </Appenders>
    <Loggers>
        <Root level="INFO">
            <AppenderRef ref="Console" />
            <AppenderRef ref="MyFile" />
        </Root>
    </Loggers>
</Configuration>

You can specify file name as VM argument when starting

java -Dlog-file-name="testbest.log"

Or you can define it programmatically as system property

System.setProperty("log-file-name", "testbest.log");


问:
Adding and deleting content between two points on a document
I currently have a document, with help from StackOverflow users already, that randomly generates questions, adds it to the end of a document, and then has the ability to delete all the questions posted. This is based on deleting everything under a horizontal rule.

Link to GDrive containing example document & code: LINK TO GDRIVE

You can also see what it currently does here: https://imgur.com/QVrOZKu

However, I now want to only want to add content after a certain point in the document, as well as only delete content between two certain points. You can see the two horizontal rules in an image below in which I want to add/delete
content.

The first horizontal rule in the picture is the third horizontal rule in the document.

Has anyone got any ideas how I can delete and add content between those two points? I've tried using child index's but failed miserably.

答:
This is similar to Deleting all content down from the second horizontal line in a document so I adapt the solutions. First function deletes the paragraphs between the 3rd and 4th line. It counts horizontal lines as we loop through paragraphs. When the count reaches 3, start deleting subsequent paragraphs. When it exceeds 3, stop the loop.

```<code>function deleteFrom3to4() {
  var body = DocumentApp.getActiveDocument().getBody();
  body.appendParagraph('');
  var para = body.getParagraphs();
  var ruleCount = 0;
  for (var i = 0; i < para.length - 1; i++) {
    if (para[i].findElement(DocumentApp.ElementType.HORIZONTAL_RULE)) {
      ruleCount++;
    }
    else if (ruleCount == 3) {
      body.removeChild(para[i]);
    }
    if (ruleCount > 3) {
      break;
    }
  }
}
</code>```

And this one inserts a paragraph after the 3rd horizontal line. Again, it loops until the 3rd line is found; inserts a paragraph after it (expressed by body.getChildIndex(para[i]) + 1 child index) and stops.

```<code>function insertAfter3() {
  var body = DocumentApp.getActiveDocument().getBody();
  body.appendParagraph('');
  var para = body.getParagraphs();
  var ruleCount = 0;
  for (var i = 0; i < para.length - 1; i++) {
    if (para[i].findElement(DocumentApp.ElementType.HORIZONTAL_RULE)) {
      ruleCount++;
    }
    if (ruleCount == 3) {
      body.insertParagraph(body.getChildIndex(para[i]) + 1, "Here is a new paragraph");
      break;
    }
  }
}
</code>```

Body:
This is similar to Deleting all content down from the second horizontal line in a document so I adapt the solutions. First function deletes the paragraphs between the 3rd and 4th line. It counts horizontal lines as we loop through paragraphs. When the count reaches 3, start deleting subsequent paragraphs. When it exceeds 3, stop the loop.

function deleteFrom3to4() {
  var body = DocumentApp.getActiveDocument().getBody();
  body.appendParagraph('');
  var para = body.getParagraphs();
  var ruleCount = 0;
  for (var i = 0; i < para.length - 1; i++) {
    if (para[i].findElement(DocumentApp.ElementType.HORIZONTAL_RULE)) {
      ruleCount++;
    }
    else if (ruleCount == 3) {
      body.removeChild(para[i]);
    }
    if (ruleCount > 3) {
      break;
    }
  }
}

And this one inserts a paragraph after the 3rd horizontal line. Again, it loops until the 3rd line is found; inserts a paragraph after it (expressed by body.getChildIndex(para[i]) + 1 child index) and stops.

function insertAfter3() {
  var body = DocumentApp.getActiveDocument().getBody();
  body.appendParagraph('');
  var para = body.getParagraphs();
  var ruleCount = 0;
  for (var i = 0; i < para.length - 1; i++) {
    if (para[i].findElement(DocumentApp.ElementType.HORIZONTAL_RULE)) {
      ruleCount++;
    }
    if (ruleCount == 3) {
      body.insertParagraph(body.getChildIndex(para[i]) + 1, "Here is a new paragraph");
      break;
    }
  }
}


问:
Microsoft Graph OneDrive invite fails when inviting group alias
We are seeing what appears to be a change in the behavior of the Graph API. Our code, which grants access for an Excel workbook in OneDrive to a specific Security Group, is now failing where it used to succeed.

Request:

POST https://graph.microsoft.com/V1.0/groups/d4826b5d-4106-40a6-97e0-3826dff58e17/drive/root:/sageData/_verbs.xlsx:/invite HTTP/1.1
Accept: application/json
Authorization: Bearer <<token omitted>>
Content-Type: application/json; charset=utf-8
Host: graph.microsoft.com
Content-Length: 127
Expect: 100-continue
Connection: Keep-Alive

{
    "recipients": [{
        "alias": "d536e908-60cb-4558-8b3a-38f033d6508a"
    }],
    "requireSignIn": true,
    "sendInvitation": false,
    "roles": ["Write"]
}
```

<p>Response:</p>

<pre class="lang-http prettyprint-override"><code>HTTP/1.1 404 Not Found
Cache-Control: private
Content-Type: application/json
request-id: 48f148b6-0c15-410e-b29d-bef5880c7007
client-request-id: 48f148b6-0c15-410e-b29d-bef5880c7007
x-ms-ags-diagnostic: {"ServerInfo":{"DataCenter":"North Europe","Slice":"SliceB","Ring":"NA","ScaleUnit":"001","Host":"AGSFE_IN_14","ADSiteName":"DUB"}}
Duration: 981.5167
Date: Wed, 15 Nov 2017 13:05:50 GMT
Content-Length: 247

{
    "error": {
        "code": "itemNotFound",
        "message": "One of the provided recipients could not be found",
        "innerError": {
            "request-id": "48f148b6-0c15-410e-b29d-bef5880c7007",
            "date": "2017-11-15T13:05:51"
        }
    }
}
</code>```

However, we can see that "recipient"" (which is the Security Group id) does indeed exist:

GET https://graph.microsoft.com/v1.0/groups/d536e908-60cb-4558-8b3a-38f033d6508a
```

<p>Response</p>

<pre class="lang-json prettyprint-override"><code>{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#groups/$entity",
    "id": "d536e908-60cb-4558-8b3a-38f033d6508a",
    "deletedDateTime": null,
    "classification": null,
    "createdDateTime": "2017-11-15T12:42:01Z",
    "description": "{\"datasetIdentifier\":\"4122e61b-d5c1-4a58-9068-dfdeda9e8278\",\"roleIdentifier\":\"FullAccess\",\"isSageMetadata\":true,\"type\":\"Role\"}",
    "displayName": "Sage - Pete - All Apps & Add-Ins",
    "groupTypes": [],
    "mail": null,
    "mailEnabled": false,
    "mailNickname": "Sage-Pete-AllApps-Add-Ins",
    "onPremisesLastSyncDateTime": null,
    "onPremisesProvisioningErrors": [],
    "onPremisesSecurityIdentifier": null,
    "onPremisesSyncEnabled": null,
    "proxyAddresses": [],
    "renewedDateTime": "2017-11-15T12:42:01Z",
    "securityEnabled": true,
    "visibility": null
}
</code>```

The documentation states the recipient property we are posting should be "email" whereas we have used "alias" up to this point. If we change to "email" then it works.

However, that seems incorrect, according to the documentation we should use alias:

"The alias of the domain object, for cases where an email address is unavailable (e.g. security groups)."

Has anyone else encountered this behaviour?

答:
What you're submitting as an alias is actually an objectId. The alias in this case would be the object's mailNickname (i.e. Sage-Pete-AllApps-Add-Ins).

Either of these should work:

{
    "recipients": [{
        "objectId": "d536e908-60cb-4558-8b3a-38f033d6508a"
    }],
    "requireSignIn": true,
    "sendInvitation": false,
    "roles": ["Write"]
}
```

<p>or </p>

<pre class="lang-json prettyprint-override"><code>{
    "recipients": [{
        "alias": "Sage-Pete-AllApps-Add-Ins"
    }],
    "requireSignIn": true,
    "sendInvitation": false,
    "roles": ["Write"]
}
</code>```

Body:
We are seeing what appears to be a change in the behavior of the Graph API. Our code, which grants access for an Excel workbook in OneDrive to a specific Security Group, is now failing where it used to succeed.

Request:

POST https://graph.microsoft.com/V1.0/groups/d4826b5d-4106-40a6-97e0-3826dff58e17/drive/root:/sageData/_verbs.xlsx:/invite HTTP/1.1
Accept: application/json
Authorization: Bearer <<token omitted>>
Content-Type: application/json; charset=utf-8
Host: graph.microsoft.com
Content-Length: 127
Expect: 100-continue
Connection: Keep-Alive

{
    "recipients": [{
        "alias": "d536e908-60cb-4558-8b3a-38f033d6508a"
    }],
    "requireSignIn": true,
    "sendInvitation": false,
    "roles": ["Write"]
}

Response:

HTTP/1.1 404 Not Found
Cache-Control: private
Content-Type: application/json
request-id: 48f148b6-0c15-410e-b29d-bef5880c7007
client-request-id: 48f148b6-0c15-410e-b29d-bef5880c7007
x-ms-ags-diagnostic: {"ServerInfo":{"DataCenter":"North Europe","Slice":"SliceB","Ring":"NA","ScaleUnit":"001","Host":"AGSFE_IN_14","ADSiteName":"DUB"}}
Duration: 981.5167
Date: Wed, 15 Nov 2017 13:05:50 GMT
Content-Length: 247

{
    "error": {
        "code": "itemNotFound",
        "message": "One of the provided recipients could not be found",
        "innerError": {
            "request-id": "48f148b6-0c15-410e-b29d-bef5880c7007",
            "date": "2017-11-15T13:05:51"
        }
    }
}

However, we can see that "recipient"" (which is the Security Group id) does indeed exist:

GET https://graph.microsoft.com/v1.0/groups/d536e908-60cb-4558-8b3a-38f033d6508a

Response

{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#groups/$entity",
    "id": "d536e908-60cb-4558-8b3a-38f033d6508a",
    "deletedDateTime": null,
    "classification": null,
    "createdDateTime": "2017-11-15T12:42:01Z",
    "description": "{\"datasetIdentifier\":\"4122e61b-d5c1-4a58-9068-dfdeda9e8278\",\"roleIdentifier\":\"FullAccess\",\"isSageMetadata\":true,\"type\":\"Role\"}",
    "displayName": "Sage - Pete - All Apps & Add-Ins",
    "groupTypes": [],
    "mail": null,
    "mailEnabled": false,
    "mailNickname": "Sage-Pete-AllApps-Add-Ins",
    "onPremisesLastSyncDateTime": null,
    "onPremisesProvisioningErrors": [],
    "onPremisesSecurityIdentifier": null,
    "onPremisesSyncEnabled": null,
    "proxyAddresses": [],
    "renewedDateTime": "2017-11-15T12:42:01Z",
    "securityEnabled": true,
    "visibility": null
}

The documentation states the recipient property we are posting should be "email" whereas we have used "alias" up to this point. If we change to "email" then it works.

However, that seems incorrect, according to the documentation we should use alias:

"The alias of the domain object, for cases where an email address is unavailable (e.g. security groups)."

Has anyone else encountered this behaviour?

Body:
What you're submitting as an alias is actually an objectId. The alias in this case would be the object's mailNickname (i.e. Sage-Pete-AllApps-Add-Ins).

Either of these should work:

{
    "recipients": [{
        "objectId": "d536e908-60cb-4558-8b3a-38f033d6508a"
    }],
    "requireSignIn": true,
    "sendInvitation": false,
    "roles": ["Write"]
}

or

{
    "recipients": [{
        "alias": "Sage-Pete-AllApps-Add-Ins"
    }],
    "requireSignIn": true,
    "sendInvitation": false,
    "roles": ["Write"]
}


问:
Convert Long Date / Time to user friendly one PHP
well I have an api returning a date in this format

2010-10-22 07:00:00 Etc/GMT

how can I change that so it's

October 22, 2010

using php

Thanks! :D

答:
You need to use this functions :

strtotime() for getting the unixtimestamp,

strftime() for outputing a nice formatted time expression.

ContentLicense: CC BY-SA 2.5


问:
Chrome extension + webview
I'm struggling to find a definitive answer to this.

Chrome Apps are being deprecated across all OS except Chrome OS.

<webview> is only available in Chrome Apps?

This means I can't or shouldn't use <webview> in an extension (if possible)?

答:
As per further research, testing, and comments:

<webview> are definitely not useable in extensions, only in Apps.

Title: Chrome extension + webview


问:
What does booting and rebooting mean?
Could we use the word of booting to mean both start and restart?
What is the difference between booting and rebooting?

答:
booting comes from "pulling yourself up by your bootstraps". The computer starts itself based on a simple trigger.

re is a prefix meaning again. so rebooting is booting again after you booted, meaning booting a machine again after it was already running. Think shutdown into boot.

Title: What does booting and rebooting mean?


问:
automatic update date in sublime by save?
is there a way that sublime text automatically updates the date in a comment block on a file when I edit and save it?

like:

```<code>/**
 * @author yada yada
 * @date 2015-01-08
 */
</code>```

to:

```<code>/**
 * @author yada yada
 * @date 2015-01-19
 */
</code>```

答:
Awesome stuff! Small addition to the above solution:

Instead of

```<code>end = begin + 19
</code>```

This line will make it more dynamical, because it will get rid of everything until the end of the line.

```<code>end = content.find("\n", begin)
</code>```

Helps with versioning up, for example, where the line-length can vary.

Body:
is there a way that sublime text automatically updates the date in a comment block on a file when I edit and save it?

like:

/**
 * @author yada yada
 * @date 2015-01-08
 */

to:

/**
 * @author yada yada
 * @date 2015-01-19
 */

Body:
Awesome stuff! Small addition to the above solution:

Instead of

end = begin + 19

This line will make it more dynamical, because it will get rid of everything until the end of the line.

end = content.find("\n", begin)

Helps with versioning up, for example, where the line-length can vary.


问:
App Server not responding to Web server, need timeout parameter
When the web server gets an HTTP request, it serves the request by calling the app server. The app server is taking a long time to respond to the web server for a specific request.

Is there a configuration in the web server(Apache, Phusion Passenger) to set limit to the time that app server should take to respond for that particular request?

If yes,

If the web server terminates the connection to the app server, will the process/threads and other resources in the app server that were created to serve the request from the app server, get killed/recovered?

答: This is a feature of Passenger Enterprise, called PassengerMaxRequestTime. It allows you to limit the time that your webapp may spend processing a request. </p>


答:
Parse the date using strptime

Convert that to a timestamp using mktime

Format the timestamp using strftime

Title: Convert Long Date / Time to user friendly one PHP

Body:
well I have an api returning a date in this format

2010-10-22 07:00:00 Etc/GMT

how can I change that so it's

October 22, 2010

using php

Thanks! :D


问:
Convert row field names to a header csv
I have a python script that runs through a thousand csv files and extracts rows based on a date I specify and places them in a new csv. In this case where the DATE is equal to 10-15-2017. The resultant csv file looks like the attached image.

I want it to look like a proper csv with column header.

```<code>STATION, DATE, LATITUDE, LONGITUDE, ...
USW0003013, 10-15-2017, 36.7876, -105.6434, ...
USW0003016, 10-15-2017, 37.5456, -103.5671, ...
</code>```

I have done some searching but have only found information on transposing from rows to columns but since I have the field names in the rows I don't think this will work.

The following is the code I use to extract rows from each csv file (over one thousand) where the DATE is 10-15-2017.

```<code>path = "C:/py-testing/downloads/*.csv"

for fname in glob.glob(path):

     with open(fname, 'rb') as f:
         reader = csv.DictReader(f)
         rows = [
             row
             for row in reader
             if row['DATE'] == "2017-10-15"
         ]
     for row in rows:
         with open("C:/py-testing/output.csv", "ab") as f:
             writer = csv.writer(f, delimiter = ',')
             writer.writerow([row])
</code>```

答:
If you want to add custom headers just pass them as a second parameter to the DictWriter (in your case fieldnames equals to row.keys()).

Here is an example:

```<code>import csv

data = []
for i in range(10):
    data.append({'Date': '10-15-2017', 'LATITUDE': i+30})

with open('csv_with_headers.csv', 'wb') as outcsv:
    writer = csv.DictWriter(outcsv, fieldnames = ["Date", "LATITUDE"])
    writer.writeheader()
    writer.writerows(data)
</code>```

Output:

```<code>cat csv_with_headers.csv
Date,LATITUDE
10-15-2017,30
10-15-2017,31
10-15-2017,32
10-15-2017,33
10-15-2017,34
10-15-2017,35
10-15-2017,36
10-15-2017,37
10-15-2017,38
10-15-2017,39
</code>```

Title: Convert row field names to a header csv

Body:
I have a python script that runs through a thousand csv files and extracts rows based on a date I specify and places them in a new csv. In this case where the DATE is equal to 10-15-2017. The resultant csv file looks like the attached image.

I want it to look like a proper csv with column header.

STATION, DATE, LATITUDE, LONGITUDE, ...
USW0003013, 10-15-2017, 36.7876, -105.6434, ...
USW0003016, 10-15-2017, 37.5456, -103.5671, ...

I have done some searching but have only found information on transposing from rows to columns but since I have the field names in the rows I don't think this will work.

The following is the code I use to extract rows from each csv file (over one thousand) where the DATE is 10-15-2017.

path = "C:/py-testing/downloads/*.csv"

for fname in glob.glob(path):

     with open(fname, 'rb') as f:
         reader = csv.DictReader(f)
         rows = [
             row
             for row in reader
             if row['DATE'] == "2017-10-15"
         ]
     for row in rows:
         with open("C:/py-testing/output.csv", "ab") as f:
             writer = csv.writer(f, delimiter = ',')
             writer.writerow([row])

Body:
If you want to add custom headers just pass them as a second parameter to the DictWriter (in your case fieldnames equals to row.keys()).

Here is an example:

import csv

data = []
for i in range(10):
    data.append({'Date': '10-15-2017', 'LATITUDE': i+30})

with open('csv_with_headers.csv', 'wb') as outcsv:
    writer = csv.DictWriter(outcsv, fieldnames = ["Date", "LATITUDE"])
    writer.writeheader()
    writer.writerows(data)

Output:

cat csv_with_headers.csv
Date,LATITUDE
10-15-2017,30
10-15-2017,31
10-15-2017,32
10-15-2017,33
10-15-2017,34
10-15-2017,35
10-15-2017,36
10-15-2017,37
10-15-2017,38
10-15-2017,39


问:
Basic procedure in passing ORM object to tempate
I'm experimenting with https://github.com/hack4impact/flask-base and trying to pass a sqlalchemy orm object to a jinja2 template.

My property model is;

```<code>class Property(db.Model):
    __tablename__ = 'properties'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(140))
    body = db.Column(db.String(1400))
    img = db.Column(db.String(140))
    ....
</code>```

In my main/views.py I have:

```<code>from flask import render_template
from app import db
from app.models import Property

from . import main

@main.route('/')
def index():
    props = db.session.query(Property).all()
    return render_template('main/index.html')
</code>```

I understand that to pass a variable to a template you would do :

```<code>    return render_template('main/index.html', pr= props)
</code>```

However trying:

```<code>>>> type(props[0])
 <class 'app.models.property.Property'>
</code>```

This seems like the wrong type of object to pass. I would assume you would pass somthing more generic like a list of dicts. What is the best approach in passing a list of sqlalchemy objects into a jinja2 template?

答:
Jinja2 can handle any sort of Python object being passed to the template renderer, because it is written in Python and specifically is meant to work like that. So if you pass that props list to render_template, it will work just fine.

You can access object methods and attributes like normal, and even do iteration:

```<code>{% for prop in pr %}
  <p>Title: {{ prop.title }}</p>
  <p>Body: {{ prop.body }}</p>
  <img src="{{ prop.image }}" />
{% endfor %}
</code>```

Body:
I'm experimenting with https://github.com/hack4impact/flask-base and trying to pass a sqlalchemy orm object to a jinja2 template.

My property model is;

class Property(db.Model):
    __tablename__ = 'properties'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(140))
    body = db.Column(db.String(1400))
    img = db.Column(db.String(140))
    ....

In my main/views.py I have:

from flask import render_template
from app import db
from app.models import Property

from . import main

@main.route('/')
def index():
    props = db.session.query(Property).all()
    return render_template('main/index.html')

I understand that to pass a variable to a template you would do :

    return render_template('main/index.html', pr= props)

However trying:

>>> type(props[0])
 <class 'app.models.property.Property'>

This seems like the wrong type of object to pass. I would assume you would pass somthing more generic like a list of dicts. What is the best approach in passing a list of sqlalchemy objects into a jinja2 template?

Body:
Jinja2 can handle any sort of Python object being passed to the template renderer, because it is written in Python and specifically is meant to work like that. So if you pass that props list to render_template, it will work just fine.

You can access object methods and attributes like normal, and even do iteration:

{% for prop in pr %}
  <p>Title: {{ prop.title }}</p>
  <p>Body: {{ prop.body }}</p>
  <img src="{{ prop.image }}" />
{% endfor %}


问:
UICollectionView: How do I implement auto-resizing of UICollectionViewCell in terms of its height?
Currently, I manually calculate the height of each cell depending upon how much height the labels and images would take. I have a square shaped image whose length is equal to width of the screen. But I am looking for other alternative where I don't have to do this manually. I want something like tableview where it is auto-calculated based on constraints. </p>

答:
Here's a little setup that will help you.

Apple gives several options for UICollectionView cell sizing:
1. Autolayout, 2. override sizeThatFits() or 3. override preferredLayoutAttributesFittingattributes()

You can watch WWDC 2016 video session 219 for more info.

Autolayout option below.

Created a UICollectionViewCell subclass, xib, with a text label.
In view controller created collectionView, added as subview, registered xib, set up UICollectionViewFlowLayout with estimated size 1x1. UICollectionView will calculate height out of the box.

```<code>class ViewController: UIViewController {
    var collectionView: UICollectionView? {
        didSet {
            let nib = UINib.init(nibName: "Cell", bundle: nil)
            collectionView?.register(nib, forCellWithReuseIdentifier: "Cell")
        }
    }

    let dataSource: [String] = ["test test test test test",
                                "test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test"]

    override func viewDidLoad() {
        super.viewDidLoad()
        let flowLayout = UICollectionViewFlowLayout()
        // Don't miss this line, or collectionView will use autosizing by default
        flowLayout.estimatedItemSize = CGSize(width: 1, height: 1)
        let collection = UICollectionView(frame: view.bounds, collectionViewLayout: flowLayout)
        view.addSubview(collection)
        collectionView = collection
        collectionView?.dataSource = self
    }
}

extension ViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSource.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! Cell
        cell.descriptionLabel.text = dataSource[indexPath.row]
        return cell
    }
}
</code>```

Cell setup:

```<code>@IBOutlet weak var widthLayoutConstraint: NSLayoutConstraint!

override func awakeFromNib() {
    super.awakeFromNib()
    // We dont need autolayout calculation for width and height of the cell so disabling it
    contentView.translatesAutoresizingMaskIntoConstraints = false
    // And adding a constant width constraint
    let width = UIScreen.main.bounds.size.width
    widthLayoutConstraint.constant = width - 24.0 // giving some offsets for the cell: 24 pt
}
</code>```

Also be aware that this setup will not work for iOS < 9.

Body:
Here's a little setup that will help you.

Apple gives several options for UICollectionView cell sizing:
1. Autolayout, 2. override sizeThatFits() or 3. override preferredLayoutAttributesFittingattributes()

You can watch WWDC 2016 video session 219 for more info.

Autolayout option below.

Created a UICollectionViewCell subclass, xib, with a text label.
In view controller created collectionView, added as subview, registered xib, set up UICollectionViewFlowLayout with estimated size 1x1. UICollectionView will calculate height out of the box.

class ViewController: UIViewController {
    var collectionView: UICollectionView? {
        didSet {
            let nib = UINib.init(nibName: "Cell", bundle: nil)
            collectionView?.register(nib, forCellWithReuseIdentifier: "Cell")
        }
    }

    let dataSource: [String] = ["test test test test test",
                                "test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test"]

    override func viewDidLoad() {
        super.viewDidLoad()
        let flowLayout = UICollectionViewFlowLayout()
        // Don't miss this line, or collectionView will use autosizing by default
        flowLayout.estimatedItemSize = CGSize(width: 1, height: 1)
        let collection = UICollectionView(frame: view.bounds, collectionViewLayout: flowLayout)
        view.addSubview(collection)
        collectionView = collection
        collectionView?.dataSource = self
    }
}

extension ViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSource.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! Cell
        cell.descriptionLabel.text = dataSource[indexPath.row]
        return cell
    }
}

Cell setup:

@IBOutlet weak var widthLayoutConstraint: NSLayoutConstraint!

override func awakeFromNib() {
    super.awakeFromNib()
    // We dont need autolayout calculation for width and height of the cell so disabling it
    contentView.translatesAutoresizingMaskIntoConstraints = false
    // And adding a constant width constraint
    let width = UIScreen.main.bounds.size.width
    widthLayoutConstraint.constant = width - 24.0 // giving some offsets for the cell: 24 pt
}

Also be aware that this setup will not work for iOS < 9.

ContentLicense: CC BY-SA 4.0


问:
In a multithreaded (Java or .Net) program, can I assume that copying a variable is atomic?
I was worrying about race conditions in an application I'm designing, when I was wondering about this question.

Let's say I have a large array or collection of some sort that is managed by one component of my program, let's call that component Monitor. Its job is to regularly check if the collection is "dirty", i. e. has changed recently, and if so, write a snapshot to disk (this is to checkpoint the application in case a crash occurs) and mark it as clean again.

Other components of the same program, running in a different thread, call the Monitor's methods to add data to or modify data in the array/collection. Those methods mark the collection as dirty.

Now, the altering methods run in the other components' threads, right? And if I'm not so lucky, they might be called while the snapshot is written to disk, change data that has already been written, set the dirty flag and the Monitor's thread unsets it just after that, without having saved the changes (it was already past the element when it changed). So I have a dirty collection that's marked as clean.

For a while, I thought that I could maybe solve the problem by making a temporary copy of the collection, mark it clean and then go and serialize the copy. But would the copying be atomic, i. e. can I be sure that the collection will not change while I'm copying it?

Meanwhile, I think I have found better solutions, like

setting a lock flag before beginning the write to disk and make the data altering methods wait until the flag is unset

have the data altering methods write to a "change queue" instead of directly to the collection and have the thread that does the disk writing process that queue

and I think the lock flag might be the best way to go. But I'm still curious: Is copying a variable atomic?

Follow-up: Maybe this should go in a question of its own, but actually it's very much the same. According to the answers below, my "lock flag" approach might also not work, right? Because the data altering method might check the lock flag while it is being set to the "locked" value and decide it's not locked. So I need a special construction like a mutex if I really want to do this right, correct?

Kudos to erickson for his very helpful answer on my follow-up. I really should have made this two questions so I could have accepted two answers. Please, vote him up, too.

答:
Depends very much on the hardware and JVM you are running

On some hardware and some JVMs some copies will be atomic
but it is safer to assume this is not the case even a simple integer to integer assignment can translate to four machine instructions on x856 hardware.

String and array copies can involve a sequence of thousands of instructions
and it is possible for two threads to update simultaniously.

OwnerDisplayName: Hanno

LastEditorDisplayName: Hanno

OwnerDisplayName: James Anderson


答:
```<code>echo date('F d, Y', strtotime($dt));
</code>```

Body: echo date('F d, Y', strtotime($dt));


问:
Creating selector menu from array of objects
I'm trying to create a selector menu from an array of ojbects. Here is a sample of the object:

```<code>let states = [
      {id: 1, state: "Alabama", district: "1st District", url:"Alabama_1st.pdf"},
      {id: 2, state: "Alabama", district: "2nd District", url:"Alabama_1st.pdf"},
      {id: 3, state: "Alabama", district: "3rd District", url:"Alabama_1st.pdf"},
      {id: 4, state: "Alabama", district: "4th District", url:"Alabama_1st.pdf"},
      {id: 5, state: "Alabama", district: "5th District", url:"Alabama_1st.pdf"},
      {id: 6, state: "Alabama", district: "6th District", url:"Alabama_1st.pdf"},
      {id: 7, state: "Alabama", district: "7th District", url:"Alabama_1st.pdf"},
      {id: 9, state: "Alaska", district: "Statewide District", url:"Alaska_1st.pdf"},
      {id: 10, state: "Arizona", district: "1st District", url:"Arizona_1st.pdf"},
      {id: 11, state: "Arizona", district: "2nd District", url:"Arizona.2nd.pdf"},
      {id: 12, state: "Arizona", district: "3rd District", url:"Arizona_3rd.pdf"},
</code>```

I have the following jQuery so far but am struggling to get the states.state and states.district to populate in my selector menu. My console log is coming back correct so I know I am accessing the data, just can't get it to append to my selector menu.

```<code><script>
        for(let i = 0; i < states.length; i++) {
           if(states[i].id > 0){
             $("#listed_states").append(states[i].state +" "+ states[i].district);
              console.log(states[i].state +" "+ states[i].district);
            }
          }
</script>

<body>

    <select>
      <option>Find Your District Here<option>
      <option id="listed_states"> <option>
    </select>
</body>
</code>```

I'll be adding an .change() function to this after it fires to load a url with a _target.

答:
Some issues:

The id should be on the select element, not on the option element, which you don't need.

The option tags do not have a closing tag: you actually open a second one each time

The code should execute when the document has loaded

You need to wrap the texts in option tags

You can use append once, and provide it an array:

let states = [ {id: 1, state: "Alabama", district: "1st District", url:"Alabama_1st.pdf"}, {id: 2, state: "Alabama", district: "2nd District", url:"Alabama_1st.pdf"}, {id: 3, state: "Alabama", district: "3rd District", url:"Alabama_1st.pdf"}, {id: 4, state: "Alabama", district: "4th District", url:"Alabama_1st.pdf"}, {id: 5, state: "Alabama", district: "5th District", url:"Alabama_1st.pdf"}, {id: 6, state: "Alabama", district: "6th District", url:"Alabama_1st.pdf"}, {id: 7, state: "Alabama", district: "7th District", url:"Alabama_1st.pdf"}, {id: 9, state: "Alaska", district: "Statewide District", url:"Alaska_1st.pdf"}, {id: 10, state: "Arizona", district: "1st District", url:"Arizona_1st.pdf"}, {id: 11, state: "Arizona", district: "2nd District", url:"Arizona.2nd.pdf"}, {id: 12, state: "Arizona", district: "3rd District", url:"Arizona_3rd.pdf"}];

$(function () {
    $("#listed_states").append(
        $.map(states, function (state) {
            return $('<option>').text(state.state + " " + state.district);
        })
    );
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="listed_states">
    <option>Find Your District Here</option>
</select></code>```

Body:
I'm trying to create a selector menu from an array of ojbects. Here is a sample of the object:

let states = [
      {id: 1, state: "Alabama", district: "1st District", url:"Alabama_1st.pdf"},
      {id: 2, state: "Alabama", district: "2nd District", url:"Alabama_1st.pdf"},
      {id: 3, state: "Alabama", district: "3rd District", url:"Alabama_1st.pdf"},
      {id: 4, state: "Alabama", district: "4th District", url:"Alabama_1st.pdf"},
      {id: 5, state: "Alabama", district: "5th District", url:"Alabama_1st.pdf"},
      {id: 6, state: "Alabama", district: "6th District", url:"Alabama_1st.pdf"},
      {id: 7, state: "Alabama", district: "7th District", url:"Alabama_1st.pdf"},
      {id: 9, state: "Alaska", district: "Statewide District", url:"Alaska_1st.pdf"},
      {id: 10, state: "Arizona", district: "1st District", url:"Arizona_1st.pdf"},
      {id: 11, state: "Arizona", district: "2nd District", url:"Arizona.2nd.pdf"},
      {id: 12, state: "Arizona", district: "3rd District", url:"Arizona_3rd.pdf"},

I have the following jQuery so far but am struggling to get the states.state and states.district to populate in my selector menu. My console log is coming back correct so I know I am accessing the data, just can't get it to append to my selector menu.

    <select>
      <option>Find Your District Here<option>
      <option id="listed_states"> <option>
    </select>

I'll be adding an .change() function to this after it fires to load a url with a _target.

Body:
Some issues:

The id should be on the select element, not on the option element, which you don't need.

The option tags do not have a closing tag: you actually open a second one each time

The code should execute when the document has loaded

You need to wrap the texts in option tags

You can use append once, and provide it an array:

let states = [ {id: 1, state: "Alabama", district: "1st District", url:"Alabama_1st.pdf"}, {id: 2, state: "Alabama", district: "2nd District", url:"Alabama_1st.pdf"}, {id: 3, state: "Alabama", district: "3rd District", url:"Alabama_1st.pdf"}, {id: 4, state: "Alabama", district: "4th District", url:"Alabama_1st.pdf"}, {id: 5, state: "Alabama", district: "5th District", url:"Alabama_1st.pdf"}, {id: 6, state: "Alabama", district: "6th District", url:"Alabama_1st.pdf"}, {id: 7, state: "Alabama", district: "7th District", url:"Alabama_1st.pdf"}, {id: 9, state: "Alaska", district: "Statewide District", url:"Alaska_1st.pdf"}, {id: 10, state: "Arizona", district: "1st District", url:"Arizona_1st.pdf"}, {id: 11, state: "Arizona", district: "2nd District", url:"Arizona.2nd.pdf"}, {id: 12, state: "Arizona", district: "3rd District", url:"Arizona_3rd.pdf"}];

$(function () {
    $("#listed_states").append(
        $.map(states, function (state) {
            return $('<option>').text(state.state + " " + state.district);
        })
    );
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="listed_states">
    <option>Find Your District Here</option>
</select>


问:
Expression must have same datatype error while executing a query
Need your help in resolving the error which I'm getting. I'm using a union to join two queries and is giving me an error. Below is the query along with the error message.

Query:

```<code>SELECT 'Firewall Rules' as Platform
       , 'TestCount' TestCount
       , 'TestPassCount' TestPassCount
       , percentage as percentage
       , firewall_name as Server
from(
    SELECT round(avg(replace(PER_OF_VIOLATING_RULES, '%', ''))* 1 , 2)||'%'  as percentage
           , firewall_name
    from table1
    group by firewall_name
)
union
select 'Database' as Platform
       , count( *) TestCount
       , count(case when result_status = 'Not A Finding' then 1 end) TestPassCount
       , Round(  count(case when result_status = 'Not A Finding' then 1 end) / count(*) * 100 , 2) percentage
       , asset as Server
FROM table2
group by asset
</code>```

Error message:

```<code>ORA-01790: expression must have the same datatype as corresponding expression
01790. 00000 -  "expression must have the same datatype as the corresponding expression"
*Cause:
*Action:
Error at Line: 1 Column: 37
</code>```

Can someone help in modifying the query?

答:
'TestCount' TestCount and TestPassCount' TestPassCount are string in first query and you are fetching numeric values in second query for the respective fields.

You can typecast using TO_CHAR Function in the second query to overcome this.

Body:
Need your help in resolving the error which I'm getting. I'm using a union to join two queries and is giving me an error. Below is the query along with the error message.

Query:

SELECT 'Firewall Rules' as Platform
       , 'TestCount' TestCount
       , 'TestPassCount' TestPassCount
       , percentage as percentage
       , firewall_name as Server
from(
    SELECT round(avg(replace(PER_OF_VIOLATING_RULES, '%', ''))* 1 , 2)||'%'  as percentage
           , firewall_name
    from table1
    group by firewall_name
)
union
select 'Database' as Platform
       , count( *) TestCount
       , count(case when result_status = 'Not A Finding' then 1 end) TestPassCount
       , Round(  count(case when result_status = 'Not A Finding' then 1 end) / count(*) * 100 , 2) percentage
       , asset as Server
FROM table2
group by asset

Error message:

ORA-01790: expression must have the same datatype as corresponding expression
01790. 00000 -  "expression must have the same datatype as the corresponding expression"
*Cause:
*Action:
Error at Line: 1 Column: 37

Can someone help in modifying the query?


问:
How to change Attributes on a Pop Up to equal to the Attributes of the Buttons that opened said Pop Up?
My project is a card game. Each Card is also a Button. When you click on a card in play, a Pop Up opens with a Card Image, a Scrollable Label of Card Text, and various Buttons.

My current problem is trying to change the Image and Text in the Pop Up to match that of the actual Card Button information. I currently have the ability to change the information that shows up but only as the most recent definition of it. From what I understand this is because I'm redefining the class attribute, not an instance of the class attribute.

I've tried to do a def__init__(self, parameters): in the Card (Button Image) file, however this would crash anytime I tried to perform the draw method of the PlayMatWidget.

I think this may have something to do with Kivy Object Properties but I'm not entirely sure on how to use them for this exactly (largely since the buttons aren't created at runtime)

Thank you for reading!

Python File:

```<code>from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.image import Image
from kivy.uix.popup import Popup
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView
from kivy.properties import StringProperty
from kivy.properties import ObjectProperty
from kivy.lang import Builder
import random

Builder.load_string('''
<ScrollableLabel>:
    Label:
        size_hint_y: None
        height: self.texture_size[1]
        text_size: self.width, None
        text: root.text
''')

class ScrollableLabel(ScrollView):
    text = StringProperty('')

# Visual Representation of a Card or Deck
class ImageButton(ButtonBehavior, Image):
    pass

class CardBackend:
    def __init__(self, name, card_art, effect_one):
        self.name = name
        self.card_art = card_art
        self.effect = effect_one

class Card(ImageButton):
    # Defining the Popup Window
    main_pop = Popup()
    main_pop.title = 'Inspect Card'
    main_pop.title_align = 'center'
    main_pop.size_hint = None, None
    main_pop.size = 400, 400
    main_pop.auto_dismiss = False
    main_pop.opacity = 0.8

    # Variables or Variables to Be
    card_text = 'ABCDEFGHIJK1234567890' * 100
    card_art = Image(source='test.png', size_hint=(.9, .85), pos_hint={'x': -0.18, 'y': .125})

    # Primary Child Widget
    main_box = FloatLayout()

    # Buttons
    play_button = Button(text='Play', size_hint=(0.32, 0.1), pos_hint={'x': 0.01, 'y': 0.0})
    discard_button = Button(text='Discard', size_hint=(0.32, 0.1), pos_hint={'x': 0.34, 'y': 0.0})
    close_button = Button(text='Close', size_hint=(0.32, 0.1), pos_hint={'x': 0.67, 'y': 0.0})
    close_button.bind(on_press=main_pop.dismiss)

    # Scrolling Card Text Viewer
    card_info = ScrollableLabel(text=card_text, size_hint=(0.45, .8), pos_hint={'x': .55, 'y': .15})

    # Building main_pop.content
    main_box.add_widget(play_button)
    main_box.add_widget(discard_button)
    main_box.add_widget(close_button)
    main_box.add_widget(card_info)
    main_box.add_widget(card_art)
    main_pop.content = main_box

class PlayMatWidget(FloatLayout):
    def draw(self):
        # Create Backend
        # Draw Backend
        # Create Card() using Backend

        # Defining Card Data (Removed for imported Decks)
        backend_bewd = CardBackend('Blue Eyes White Dragon', 'bewd.png', 'One')
        backend_dragon = CardBackend('Dragon Egg', 'test.png', 'Two')
        backend_lava = CardBackend('Lava Golem', 'lavagolem.png', 'Three')

        # Creating Card Button Objects
        card_zero = Card()
        card_one = Card()
        card_two = Card()

        # Defining Card Title
        card_zero.main_pop.title = backend_lava.name
        card_one.main_pop.title = backend_dragon.name
        card_two.main_pop.title = backend_bewd.name

        # Defining Card Text for Scrollview
        card_zero.card_info.text = backend_bewd.effect

        # Defining Card Art
        card_zero.source = backend_bewd.card_art
        card_one.source = backend_dragon.card_art
        card_two.source = backend_lava.card_art

        deck_dictionary = {
            0: card_zero,
            1: card_one,
            2: card_two,
        }

        # Prototype Shuffle for top card
        # drawing = random.choice(deck_list)

        # Creating a Physical Card Object
        # drawn_card = Card()

        # OLD
        # Applying Card Data from backend to front end Card Object
        # drawn_card.main_pop.title = drawing.name
        # drawn_card.source = drawing.card_art
        # drawn_card.card_art.source = drawing.card_art
        # drawn_card.card_info.text = drawing.effect

        # Used to check somethings
        for x in range(0, 3):
            print(deck_dictionary[x].source)
            print(deck_dictionary[x].main_pop.title)

        self.ids.PlayerField.add_widget(random.choice(deck_dictionary), index=int(len(self.ids.PlayerField.children)/2))

class CardGameApp(App):
    def build(self):
        return PlayMatWidget()

if __name__ == "__main__":
    CardGameApp().run()
</code>```

Kivy File:

```<code><Card@ImageButton>:
    size_hint: 0.8,0.8
    pos_hint: {'x':0, 'y':0.1}
    on_press: print('confirming press')
    on_press: root.main_pop.open()

<PlayMatWidget>:
    id: PlayMat
    canvas:
        Rectangle:
            size: self.size
            pos: self.pos
            source: 'tron1.png'
    StackLayout:
        id: OppHand
        size_hint: 0.6, 0.1
        pos_hint: {'x':0.2,'y': 0.9}
        canvas:
            Rectangle:
                size: self.size
                pos: self.pos
                source: 'background.png'
    StackLayout:
        id: OppField
        size_hint: 0.6, 0.4
        pos_hint: {'x':0.2, 'y':0.5}
        canvas:
            Rectangle:
                size: self.size
                pos: self.pos
                source: 'background.png'
    StackLayout:
        id: cards
        size_hint: 0.6,0.4
        pos_hint: {'x':0.2, 'y':0.1}
        canvas:
            Rectangle:
                size: self.size
                pos: self.pos
                source: 'background.png'
    AnchorLayout:
        id: PlayerFieldAnchor
        anchor_x: 'center'
        anchor_y: 'center'
        size_hint: 0.6,0.4
        pos_hint: {'x':0.2, 'y':0.1}
        canvas.before:
            Rectangle:
                size: self.size
                pos: self.pos
                source: 'background.png'
        BoxLayout:
            id: PlayerField
            orientation: 'horizontal'
    StackLayout:
        id: PlayerHand
        orientation: 'lr-tb'
        size_hint: 0.6,0.1
        pos_hint: {'x': 0.2, 'y':0}
        canvas:
            Rectangle:
                size: self.size
                pos: self.pos
                source: 'background.png'
    ImageButton:
        id: PlayerDeck
        source: 'cardback.png'
        size_hint: 0.15, 0.15
        pos_hint: {'x':0.025,'y':0.05}
        on_press: root.draw()
</code>```

答:
1/ everytime you override an __init__ method, you need to call the super() method, if you don't do so for kivy widgets, they will crash, because they won't be initialised correctly, for python 3 i believe you want to do

```<code>def __init__(self, **kwargs):
    super().__init__(**kwargs)
    …
</code>```

2/ usually in kivy, it's easier to create a property and pass it by name, instead of passing parameters to init, this way you don't even need to override __init__, avoiding the error in 1/.

```<code>class CardBackend:
    name = StringProperty()
    card_art = StringProperty()
    effect = stringProperty()

…

card = CardBackend(
    name='Blue Eyes White Dragon',
    card_art='bewd.png',
    effect='One')
</code>```

or, to use that in kv

```<code>CardBackend:
    name: 'Blue Eyes White Dragon'
    card_art: 'bewd.png'
    effect: 'One'
</code>```

3/ in Card you define indeed everything in the class instead of the __init__, which means this code will be ran when the class is defined, not when an instance is created, maybe you actually want a function, not a class? or maybe you want to override the on_press method of your ImageButton, and put all of this code in it, using the properties of the card instead of the hardcoded values you use currently.

Body:
My project is a card game. Each Card is also a Button. When you click on a card in play, a Pop Up opens with a Card Image, a Scrollable Label of Card Text, and various Buttons.

My current problem is trying to change the Image and Text in the Pop Up to match that of the actual Card Button information. I currently have the ability to change the information that shows up but only as the most recent definition of it. From what I understand this is because I'm redefining the class attribute, not an instance of the class attribute.

I've tried to do a def__init__(self, parameters): in the Card (Button Image) file, however this would crash anytime I tried to perform the draw method of the PlayMatWidget.

I think this may have something to do with Kivy Object Properties but I'm not entirely sure on how to use them for this exactly (largely since the buttons aren't created at runtime)

Thank you for reading!

Python File:

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.image import Image
from kivy.uix.popup import Popup
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView
from kivy.properties import StringProperty
from kivy.properties import ObjectProperty
from kivy.lang import Builder
import random

Builder.load_string('''
<ScrollableLabel>:
    Label:
        size_hint_y: None
        height: self.texture_size[1]
        text_size: self.width, None
        text: root.text
''')

class ScrollableLabel(ScrollView):
    text = StringProperty('')

# Visual Representation of a Card or Deck
class ImageButton(ButtonBehavior, Image):
    pass

class CardBackend:
    def __init__(self, name, card_art, effect_one):
        self.name = name
        self.card_art = card_art
        self.effect = effect_one

class Card(ImageButton):
    # Defining the Popup Window
    main_pop = Popup()
    main_pop.title = 'Inspect Card'
    main_pop.title_align = 'center'
    main_pop.size_hint = None, None
    main_pop.size = 400, 400
    main_pop.auto_dismiss = False
    main_pop.opacity = 0.8

    # Variables or Variables to Be
    card_text = 'ABCDEFGHIJK1234567890' * 100
    card_art = Image(source='test.png', size_hint=(.9, .85), pos_hint={'x': -0.18, 'y': .125})

    # Primary Child Widget
    main_box = FloatLayout()

    # Buttons
    play_button = Button(text='Play', size_hint=(0.32, 0.1), pos_hint={'x': 0.01, 'y': 0.0})
    discard_button = Button(text='Discard', size_hint=(0.32, 0.1), pos_hint={'x': 0.34, 'y': 0.0})
    close_button = Button(text='Close', size_hint=(0.32, 0.1), pos_hint={'x': 0.67, 'y': 0.0})
    close_button.bind(on_press=main_pop.dismiss)

    # Scrolling Card Text Viewer
    card_info = ScrollableLabel(text=card_text, size_hint=(0.45, .8), pos_hint={'x': .55, 'y': .15})

    # Building main_pop.content
    main_box.add_widget(play_button)
    main_box.add_widget(discard_button)
    main_box.add_widget(close_button)
    main_box.add_widget(card_info)
    main_box.add_widget(card_art)
    main_pop.content = main_box

class PlayMatWidget(FloatLayout):
    def draw(self):
        # Create Backend
        # Draw Backend
        # Create Card() using Backend

        # Defining Card Data (Removed for imported Decks)
        backend_bewd = CardBackend('Blue Eyes White Dragon', 'bewd.png', 'One')
        backend_dragon = CardBackend('Dragon Egg', 'test.png', 'Two')
        backend_lava = CardBackend('Lava Golem', 'lavagolem.png', 'Three')

        # Creating Card Button Objects
        card_zero = Card()
        card_one = Card()
        card_two = Card()

        # Defining Card Title
        card_zero.main_pop.title = backend_lava.name
        card_one.main_pop.title = backend_dragon.name
        card_two.main_pop.title = backend_bewd.name

        # Defining Card Text for Scrollview
        card_zero.card_info.text = backend_bewd.effect

        # Defining Card Art
        card_zero.source = backend_bewd.card_art
        card_one.source = backend_dragon.card_art
        card_two.source = backend_lava.card_art

        deck_dictionary = {
            0: card_zero,
            1: card_one,
            2: card_two,
        }

        # Prototype Shuffle for top card
        # drawing = random.choice(deck_list)

        # Creating a Physical Card Object
        # drawn_card = Card()

        # OLD
        # Applying Card Data from backend to front end Card Object
        # drawn_card.main_pop.title = drawing.name
        # drawn_card.source = drawing.card_art
        # drawn_card.card_art.source = drawing.card_art
        # drawn_card.card_info.text = drawing.effect

        # Used to check somethings
        for x in range(0, 3):
            print(deck_dictionary[x].source)
            print(deck_dictionary[x].main_pop.title)

        self.ids.PlayerField.add_widget(random.choice(deck_dictionary), index=int(len(self.ids.PlayerField.children)/2))

class CardGameApp(App):
    def build(self):
        return PlayMatWidget()

if __name__ == "__main__":
    CardGameApp().run()

Kivy File:

<Card@ImageButton>:
    size_hint: 0.8,0.8
    pos_hint: {'x':0, 'y':0.1}
    on_press: print('confirming press')
    on_press: root.main_pop.open()

<PlayMatWidget>:
    id: PlayMat
    canvas:
        Rectangle:
            size: self.size
            pos: self.pos
            source: 'tron1.png'
    StackLayout:
        id: OppHand
        size_hint: 0.6, 0.1
        pos_hint: {'x':0.2,'y': 0.9}
        canvas:
            Rectangle:
                size: self.size
                pos: self.pos
                source: 'background.png'
    StackLayout:
        id: OppField
        size_hint: 0.6, 0.4
        pos_hint: {'x':0.2, 'y':0.5}
        canvas:
            Rectangle:
                size: self.size
                pos: self.pos
                source: 'background.png'
    StackLayout:
        id: cards
        size_hint: 0.6,0.4
        pos_hint: {'x':0.2, 'y':0.1}
        canvas:
            Rectangle:
                size: self.size
                pos: self.pos
                source: 'background.png'
    AnchorLayout:
        id: PlayerFieldAnchor
        anchor_x: 'center'
        anchor_y: 'center'
        size_hint: 0.6,0.4
        pos_hint: {'x':0.2, 'y':0.1}
        canvas.before:
            Rectangle:
                size: self.size
                pos: self.pos
                source: 'background.png'
        BoxLayout:
            id: PlayerField
            orientation: 'horizontal'
    StackLayout:
        id: PlayerHand
        orientation: 'lr-tb'
        size_hint: 0.6,0.1
        pos_hint: {'x': 0.2, 'y':0}
        canvas:
            Rectangle:
                size: self.size
                pos: self.pos
                source: 'background.png'
    ImageButton:
        id: PlayerDeck
        source: 'cardback.png'
        size_hint: 0.15, 0.15
        pos_hint: {'x':0.025,'y':0.05}
        on_press: root.draw()

Body:
1/ everytime you override an __init__ method, you need to call the super() method, if you don't do so for kivy widgets, they will crash, because they won't be initialised correctly, for python 3 i believe you want to do

def __init__(self, **kwargs):
    super().__init__(**kwargs)
    …

2/ usually in kivy, it's easier to create a property and pass it by name, instead of passing parameters to init, this way you don't even need to override __init__, avoiding the error in 1/.

class CardBackend:
    name = StringProperty()
    card_art = StringProperty()
    effect = stringProperty()

…

card = CardBackend(
    name='Blue Eyes White Dragon',
    card_art='bewd.png',
    effect='One')

or, to use that in kv

CardBackend:
    name: 'Blue Eyes White Dragon'
    card_art: 'bewd.png'
    effect: 'One'

3/ in Card you define indeed everything in the class instead of the __init__, which means this code will be ran when the class is defined, not when an instance is created, maybe you actually want a function, not a class? or maybe you want to override the on_press method of your ImageButton, and put all of this code in it, using the properties of the card instead of the hardcoded values you use currently.


问:
Angular Firestore filter docs based on permissions
I'm having trouble querying a collection where the documents have differing permissions on them.

Is there anyway to perform a query on a collection to prevent getting permissions denied on documents I can't read. I'm able to achieve this if I query them one at a time.I need to query the collection to return multiple docs where I might not have permissions for some? I could keep a list of document Ids a specific user has access to query, but I can't find any documentation on specifying an array of documents.

Collection:

```<code>Library > { libraryID } > {
   Users:{ uid, uid, uid },
   title: 'Title of library'
}
</code>```

Rules:

```<code>match /Library/{libraryID} {
  allow read: if get(/databases/$(database)/documents/Library/$(libraryID)).data.Users[(request.auth.uid)] == true;
}
</code>```

Permission are limited if the users id is in the data.

This works fine:

```<code>this.afs.collection<Library('Library').doc({libraryID}); // Everything works great
</code>```

But I need multiple items from the collection, so when I try something like the example below if fails as I do not have permissions to all the documents in the collection:

```<code>this.afs.collection<Library('Library'); //PERMISSION DENIED
</code>```

I was hoping I could use query to fix this, but because it is looking into the document it also fails:

```<code>this.afs.collection<Library('Library',ref => ref.where('Users/'+this._uid, '==', 'true')); // PERMISSION DENIED
</code>```

So I wish I could just specify the docs I have access to ( this is what I need ) and return them in a collection

```<code>this.afs.collection<Library('Library').doc([{libraryID},{libraryID2},{libraryID3}])
</code>```

If anyone knows a solution to achieve this, or a refactor of the structure to achieve this it would be a huge help.

答:
Try this rule

```<code>match /Library/{libraryID} {
  allow read: if exists(/databases/$(database)/documents/Library/$(libraryID)/Users/$(request.auth.uid));
}
</code>```

Which says, allow read if the current users id is present in the Users node.

Body:
I'm having trouble querying a collection where the documents have differing permissions on them.

Is there anyway to perform a query on a collection to prevent getting permissions denied on documents I can't read. I'm able to achieve this if I query them one at a time.I need to query the collection to return multiple docs where I might not have permissions for some? I could keep a list of document Ids a specific user has access to query, but I can't find any documentation on specifying an array of documents.

Collection:

Library > { libraryID } > {
   Users:{ uid, uid, uid },
   title: 'Title of library'
}

Rules:

match /Library/{libraryID} {
  allow read: if get(/databases/$(database)/documents/Library/$(libraryID)).data.Users[(request.auth.uid)] == true;
}

Permission are limited if the users id is in the data.

This works fine:

this.afs.collection<Library('Library').doc({libraryID}); // Everything works great

But I need multiple items from the collection, so when I try something like the example below if fails as I do not have permissions to all the documents in the collection:

this.afs.collection<Library('Library'); //PERMISSION DENIED

I was hoping I could use query to fix this, but because it is looking into the document it also fails:

this.afs.collection<Library('Library',ref => ref.where('Users/'+this._uid, '==', 'true')); // PERMISSION DENIED

So I wish I could just specify the docs I have access to ( this is what I need ) and return them in a collection

this.afs.collection<Library('Library').doc([{libraryID},{libraryID2},{libraryID3}])

If anyone knows a solution to achieve this, or a refactor of the structure to achieve this it would be a huge help.

Body:
Try this rule

match /Library/{libraryID} {
  allow read: if exists(/databases/$(database)/documents/Library/$(libraryID)/Users/$(request.auth.uid));
}

Which says, allow read if the current users id is present in the Users node.


问:
How to make jquery to php code?
I am trying to make jquery code to php code. But i don't understand, my code structure is correct or not.

Here is jQuery code:

```<code>let params = {
    locale: 'en_US',
    client_country_code: 'US',
    fb_api_req_friendly_name: 'save_core_profile_info',
    access_token: token_user
};

params.work = JSON.stringify([{
    "id": 123456789,
    "privacy": '{"value":"EVERYONE"}',
    "ref": "nux_android"
}]);
</code>```

And here is my trying php code:

```<code>$params = array(
    "locale" => 'en_US',
    "client_country_code" => 'US',
    "fb_api_req_friendly_name" => 'save_core_profile_info',
    "access_token" => $token_user);

$params->work = json_encode(array(array(
    "id" => 12345678,
    "privacy" => '{"value":"EVERYONE"}',
    "ref" => "nux_android"
    )));
</code>```

If my php coding is not correct, how to i coding php code for making jQuery to php? thanks.

答:
If you want it to be a PHP array:

```<code>$params = array(
    "locale" => 'en_US',
    "client_country_code" => 'US',
    "fb_api_req_friendly_name" => 'save_core_profile_info',
    "access_token" => $token_user);

$params["work"] = json_encode(array(array(
    "id" => 12345678,
    "privacy" => '{"value":"EVERYONE"}',
    "ref" => "nux_android"
    )));
</code>```

If you want it to be a PHP object:

```<code>$params = (object)array(
    "locale" => 'en_US',
    "client_country_code" => 'US',
    "fb_api_req_friendly_name" => 'save_core_profile_info',
    "access_token" => $token_user);

$params->work = json_encode(array(array(
    "id" => 12345678,
    "privacy" => '{"value":"EVERYONE"}',
    "ref" => "nux_android"
    )));
</code>```

Title: How to make jquery to php code?

Body:
I am trying to make jquery code to php code. But i don't understand, my code structure is correct or not.

Here is jQuery code:

let params = {
    locale: 'en_US',
    client_country_code: 'US',
    fb_api_req_friendly_name: 'save_core_profile_info',
    access_token: token_user
};

params.work = JSON.stringify([{
    "id": 123456789,
    "privacy": '{"value":"EVERYONE"}',
    "ref": "nux_android"
}]);

And here is my trying php code:

$params = array(
    "locale" => 'en_US',
    "client_country_code" => 'US',
    "fb_api_req_friendly_name" => 'save_core_profile_info',
    "access_token" => $token_user);

$params->work = json_encode(array(array(
    "id" => 12345678,
    "privacy" => '{"value":"EVERYONE"}',
    "ref" => "nux_android"
    )));

If my php coding is not correct, how to i coding php code for making jQuery to php? thanks.

Body:
If you want it to be a PHP array:

$params = array(
    "locale" => 'en_US',
    "client_country_code" => 'US',
    "fb_api_req_friendly_name" => 'save_core_profile_info',
    "access_token" => $token_user);

$params["work"] = json_encode(array(array(
    "id" => 12345678,
    "privacy" => '{"value":"EVERYONE"}',
    "ref" => "nux_android"
    )));

If you want it to be a PHP object:

$params = (object)array(
    "locale" => 'en_US',
    "client_country_code" => 'US',
    "fb_api_req_friendly_name" => 'save_core_profile_info',
    "access_token" => $token_user);

$params->work = json_encode(array(array(
    "id" => 12345678,
    "privacy" => '{"value":"EVERYONE"}',
    "ref" => "nux_android"
    )));


问:
Spark SQL 2.0: NullPointerException with a valid PostgreSQL query
I have a valid PostgreSQL query : when I copy/paste it in PSQL, I get the desired result.

But when I run with Spark SQL it leads to a NullPointerException.

Here is the snippet of code causing the error:

```<code>extractDataFrame().show()

private def extractDataFrame(): DataFrame = {
  val query =
    """(
      SELECT events.event_facebook_id, events.name, events.tariffrange,
        eventscounts.attending_count, eventscounts.declined_count, eventscounts.interested_count,
        eventscounts.noreply_count,
        artists.facebookid as artist_facebook_id, artists.likes as artistlikes,
        organizers.organizerid, organizers.likes as organizerlikes,
        places.placeid, places.capacity, places.likes as placelikes
      FROM events
        LEFT JOIN eventscounts on eventscounts.event_facebook_id = events.event_facebook_id
        LEFT JOIN eventsartists on eventsartists.event_id = events.event_facebook_id
          LEFT JOIN artists on eventsartists.artistid = artists.facebookid
        LEFT JOIN eventsorganizers on eventsorganizers.event_id = events.event_facebook_id
          LEFT JOIN organizers on eventsorganizers.organizerurl = organizers.facebookurl
        LEFT JOIN eventsplaces on eventsplaces.event_id = events.event_facebook_id
          LEFT JOIN places on eventsplaces.placefacebookurl = places.facebookurl
      ) df"""

  spark.sqlContext.read.jdbc(databaseURL, query, connectionProperties)
}
</code>```

The SparkSession is defined as follows:

```<code>val databaseURL = "jdbc:postgresql://dbHost:5432/ticketapp"
val spark = SparkSession
  .builder
  .master("local[*]")
  .appName("tariffPrediction")
  .getOrCreate()

val connectionProperties = new Properties
connectionProperties.put("user", "simon")
connectionProperties.put("password", "root")
</code>```

And here is the complete stacktrace:

```<code>[SparkException: Job aborted due to stage failure: Task 0 in stage 27.0 failed 1 times, most recent failure: Lost task 0.0 in stage 27.0 (TID 27, localhost): java.lang.NullPointerException
    at org.apache.spark.sql.catalyst.expressions.codegen.UnsafeRowWriter.write(UnsafeRowWriter.java:210)
    at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIterator.processNext(Unknown Source)
    at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43)
    at org.apache.spark.sql.execution.WholeStageCodegenExec$$anonfun$8$$anon$1.hasNext(WholeStageCodegenExec.scala:370)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$4.apply(SparkPlan.scala:246)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$4.apply(SparkPlan.scala:240)
    at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$24.apply(RDD.scala:784)
    at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$24.apply(RDD.scala:784)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:319)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:283)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:70)
    at org.apache.spark.scheduler.Task.run(Task.scala:85)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:274)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Driver stacktrace:]
</code>```

The most surprising part is that if I remove one (whichever one) of the LEFT JOIN clauses in the SQL query, I don't get any errors...

答:
This issue is related to Teradata JDBC driver. This problem is discussed at https://community.teradata.com/t5/Connectivity/Teradata-JDBC-Driver-returns-the-wrong-schema-column-nullability/m-p/76667/highlight/true#M3798.

The root cause is discussed on the first page. And the solution is on the third page.

People from Teradata said they fixed the issue in the 16.10.* driver with a MAYBENULL parameter, but I am still seeing an undeterministic behaviour.

Here is a similar discussion https://issues.apache.org/jira/browse/SPARK-17195

Body:
I have a valid PostgreSQL query : when I copy/paste it in PSQL, I get the desired result.

But when I run with Spark SQL it leads to a NullPointerException.

Here is the snippet of code causing the error:

extractDataFrame().show()

private def extractDataFrame(): DataFrame = {
  val query =
    """(
      SELECT events.event_facebook_id, events.name, events.tariffrange,
        eventscounts.attending_count, eventscounts.declined_count, eventscounts.interested_count,
        eventscounts.noreply_count,
        artists.facebookid as artist_facebook_id, artists.likes as artistlikes,
        organizers.organizerid, organizers.likes as organizerlikes,
        places.placeid, places.capacity, places.likes as placelikes
      FROM events
        LEFT JOIN eventscounts on eventscounts.event_facebook_id = events.event_facebook_id
        LEFT JOIN eventsartists on eventsartists.event_id = events.event_facebook_id
          LEFT JOIN artists on eventsartists.artistid = artists.facebookid
        LEFT JOIN eventsorganizers on eventsorganizers.event_id = events.event_facebook_id
          LEFT JOIN organizers on eventsorganizers.organizerurl = organizers.facebookurl
        LEFT JOIN eventsplaces on eventsplaces.event_id = events.event_facebook_id
          LEFT JOIN places on eventsplaces.placefacebookurl = places.facebookurl
      ) df"""

  spark.sqlContext.read.jdbc(databaseURL, query, connectionProperties)
}

The SparkSession is defined as follows:

val databaseURL = "jdbc:postgresql://dbHost:5432/ticketapp"
val spark = SparkSession
  .builder
  .master("local[*]")
  .appName("tariffPrediction")
  .getOrCreate()

val connectionProperties = new Properties
connectionProperties.put("user", "simon")
connectionProperties.put("password", "root")

And here is the complete stacktrace:

[SparkException: Job aborted due to stage failure: Task 0 in stage 27.0 failed 1 times, most recent failure: Lost task 0.0 in stage 27.0 (TID 27, localhost): java.lang.NullPointerException
    at org.apache.spark.sql.catalyst.expressions.codegen.UnsafeRowWriter.write(UnsafeRowWriter.java:210)
    at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIterator.processNext(Unknown Source)
    at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43)
    at org.apache.spark.sql.execution.WholeStageCodegenExec$$anonfun$8$$anon$1.hasNext(WholeStageCodegenExec.scala:370)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$4.apply(SparkPlan.scala:246)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$4.apply(SparkPlan.scala:240)
    at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$24.apply(RDD.scala:784)
    at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$24.apply(RDD.scala:784)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:319)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:283)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:70)
    at org.apache.spark.scheduler.Task.run(Task.scala:85)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:274)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Driver stacktrace:]

The most surprising part is that if I remove one (whichever one) of the LEFT JOIN clauses in the SQL query, I don't get any errors...


答:
This should work:</p>

```<code>date("F j, Y", strtotime($date))
</code>```

Body:
This should work:

date("F j, Y", strtotime($date))


问:
Print ArrayLists that are HashMap values
I have a HashMap that contains ArrayList of subjects. Every student has different notes. How can I print those notes from the HashMap? At the end of my code I have println, if I want to print every average specific to a subject, how can I do that?

```<code>Student student1 = new Apprentice("Jack", "Morgan");
Subject english = new Subject("English", Arrays.asList(2, 3, 2, 2));
Subject japanese = new Subject("japanese", Arrays.asList(2, 2, 2, 4));

HashMap<Student, List<Subject>> studentGrade = new HashMap<>();
studentGrade.put(student1, Arrays.asList(english, japanese));

for (Map.Entry<Apprentice, List<Subject> > entry : apprenticeGrades.entrySet()) {
    System.out.println("Student " + entry.getKey());

    for (Subject subject : entry.getValue()) {
        System.out.println("Average from subject:" + subject.getAvg());
    }
</code>```

答:
```<code> final List<Subject> subjectList = studentGrade
                // get a Collection<List<Subject>>
                .values()
                // make a stream from the collection
                .stream()
                // turn each List<Subject> into a Stream<Subject> and merge these streams
                .flatMap(List::stream)
                // accumulate the result into a List
                .collect(Collectors.toList());

        for(Subject subject : subjectList){
            System.out.println("Average from subject:" + subject.getAvg());
        }
</code>```

<p>Put all the subjects (values) in a list first and iterate through it to calculate and print the average. </p>

Body:
I have a HashMap that contains ArrayList of subjects. Every student has different notes. How can I print those notes from the HashMap? At the end of my code I have println, if I want to print every average specific to a subject, how can I do that?

Student student1 = new Apprentice("Jack", "Morgan");
Subject english = new Subject("English", Arrays.asList(2, 3, 2, 2));
Subject japanese = new Subject("japanese", Arrays.asList(2, 2, 2, 4));

HashMap<Student, List<Subject>> studentGrade = new HashMap<>();
studentGrade.put(student1, Arrays.asList(english, japanese));

for (Map.Entry<Apprentice, List<Subject> > entry : apprenticeGrades.entrySet()) {
    System.out.println("Student " + entry.getKey());

    for (Subject subject : entry.getValue()) {
        System.out.println("Average from subject:" + subject.getAvg());
    }

Body:
 final List<Subject> subjectList = studentGrade
                // get a Collection<List<Subject>>
                .values()
                // make a stream from the collection
                .stream()
                // turn each List<Subject> into a Stream<Subject> and merge these streams
                .flatMap(List::stream)
                // accumulate the result into a List
                .collect(Collectors.toList());

        for(Subject subject : subjectList){
            System.out.println("Average from subject:" + subject.getAvg());
        }

Put all the subjects (values) in a list first and iterate through it to calculate and print the average.


问:
How to assert url was called from javascript using rspec and capybara

Scenario:

We use capybara integration tests to test that our frontend plumbing (javascript) is connected properly.

Sometimes all we need to validate the test is:

has content rendered properly on the page

has the js called the correct url open interaction

Problem:

Item 1 above is easy. However, with item 2 I can't seem to find an easy way to say:

Assert that url was called from js in browser.

Example:

```<code>it "should call coorect url with correct query string" do
  visit widgets_path

  # THIS IS WHAT I NEED TO KNOW
  expect(something).to receive(:some_method).with(url: "my/test/url", params: {per_page: 2})

  # In other words, I don't want the controller action to run. I don't care about the result since the controller is being tested elsewhere.
  # I just need to know that the correct URL was called with the correct params.

  within 'ul.pagination' do
    click_on '2'
  end
end
</code>```

I've tried mocking the controller action, but there's no way to inspect the params. Or is there? Without inspecting the params, how can I know if the correct stuff was sent? All I know it's the correct route, which isn't enough.

If I could inspect the params then this would be solved... but otherwise?

答:
If you are looking for the Rails solution, here it is! Tested with Rails 5.1.3.

1) Create a request params matcher spec/support/matchers/request_with_params.rb

RSpec::Matchers.define :request_with_params do |params|
  match { |request| request.params.symbolize_keys.slice(*params.keys) == params }
end

2) Create a helper method for your acceptance tests (you can use some logics to pass symbol instead of class UsersController -> :users if needed)

def expect_request(controller, action, params = {})
  expect_any_instance_of(ActionDispatch::Routing::RouteSet::Dispatcher)
    .to receive(:dispatch)
    .with(controller, action.to_s, request_with_params(params), anything)
  end
end

3) Use it!

expect_request(UsersController, :index)

or with params

expect_request(UsersController, :show, { id: 1 })

OR

4) There is another way in using https://github.com/oesmith/puffing-billy Check this gem for intercepting requests sent by your browser. But it can be an overkill if you need to mock only certain requests to your backend app.

Body:
Scenario:

We use capybara integration tests to test that our frontend plumbing (javascript) is connected properly.

Sometimes all we need to validate the test is:

has content rendered properly on the page

has the js called the correct url open interaction

Problem:

Item 1 above is easy. However, with item 2 I can't seem to find an easy way to say:

Assert that url was called from js in browser.

Example:

it "should call coorect url with correct query string" do
  visit widgets_path

  # THIS IS WHAT I NEED TO KNOW
  expect(something).to receive(:some_method).with(url: "my/test/url", params: {per_page: 2})

  # In other words, I don't want the controller action to run. I don't care about the result since the controller is being tested elsewhere.
  # I just need to know that the correct URL was called with the correct params.

  within 'ul.pagination' do
    click_on '2'
  end
end

I've tried mocking the controller action, but there's no way to inspect the params. Or is there? Without inspecting the params, how can I know if the correct stuff was sent? All I know it's the correct route, which isn't enough.

If I could inspect the params then this would be solved... but otherwise?


问:
Can Apache beam support Parallel Sorting?
Could you please tell me if I can achieve parallel sorting using Apache beam? For the documentation it is given that Apache Beam can sort using a single machine. Is there any way to achieve parallel sorting?</p>

答: Ah, so you're doing merely a per-key sort, not a global sort. Please use the SortValues transform. Each individual key will be sorted using a single machine, but I presume that the amount of data you have per key is not that big. Please let me know if that's not the case and if after trying this transform you find that it performs unacceptably.


问:
jQuery div.html() update does not update on browser after first change
I have a div on a page that is updated via a form and changed via an AJAX call.
When the form is edited and saved, the $('#element').html(new_html) works fine in the success call and changes on the browser.
However, if I change the data again and call the AJAX script more than once, it will return the changed data to the success function, and updates the va new_html correctly, but the $('#element').html(new_html) does NOT update the DOM or browser. Only on the first call, after that an entire page refresh is required.

Why would $('#element).html(new_html) change the display on the browser on the first call, but not on any subsequent calls?

Is this a caching issue?

答: This is resolved and was a programming error. I'd delete the question, but since some have tried to help already just wanted to leave it here with my answer.</p>


答:
This can be done easily using pandas module as follows:

```<code>import pandas as pd

path = "C:/py-testing/downloads/*.csv"

csv_all = []
for fname in glob.glob(path):
    csv_all.append(pd.read_csv(fname))

df = pd.concat(csv_all)
df = df.loc[df['DATE'] == "2017-10-15"]
#Choose the columns you need
df = df[['STATION', 'DATE', 'LATITUDE', 'LONGITUDE']]
df.to_csv('./csv_merged.csv')
</code>```

Title: Convert row field names to a header csv

Body:
I have a python script that runs through a thousand csv files and extracts rows based on a date I specify and places them in a new csv. In this case where the DATE is equal to 10-15-2017. The resultant csv file looks like the attached image.

I want it to look like a proper csv with column header.

STATION, DATE, LATITUDE, LONGITUDE, ...
USW0003013, 10-15-2017, 36.7876, -105.6434, ...
USW0003016, 10-15-2017, 37.5456, -103.5671, ...

I have done some searching but have only found information on transposing from rows to columns but since I have the field names in the rows I don't think this will work.

The following is the code I use to extract rows from each csv file (over one thousand) where the DATE is 10-15-2017.

path = "C:/py-testing/downloads/*.csv"

for fname in glob.glob(path):

     with open(fname, 'rb') as f:
         reader = csv.DictReader(f)
         rows = [
             row
             for row in reader
             if row['DATE'] == "2017-10-15"
         ]
     for row in rows:
         with open("C:/py-testing/output.csv", "ab") as f:
             writer = csv.writer(f, delimiter = ',')
             writer.writerow([row])

Body:
This can be done easily using pandas module as follows:

import pandas as pd

path = "C:/py-testing/downloads/*.csv"

csv_all = []
for fname in glob.glob(path):
    csv_all.append(pd.read_csv(fname))

df = pd.concat(csv_all)
df = df.loc[df['DATE'] == "2017-10-15"]
#Choose the columns you need
df = df[['STATION', 'DATE', 'LATITUDE', 'LONGITUDE']]
df.to_csv('./csv_merged.csv')