问:
Is it normal to have regular model for GET and "flat" model for POST from Design REST point of view?
The questions about possibility to have different models for POST and GET methods in REST api have been asked several times but I would like to clarify one specific moment.
Suppose we are designing api about sport competition.

Models and corresponding resources:

```<code>1) Player
{  "id" : 2,
   "firstName" : "Nikolay",
   "lastName": "Grigoryan",
   .....
}
</code>```

/players/2

2) Tournament

```<code>{ "id" 1,
  "name": "Some tournament",
  "date" "01.02.2019",
  .......
}
</code>```

/tournaments/1

3) Participant

```<code>{
  "id": 2,
   "tournament": { "id" 1,
      "name": "Some tournament",
      "date" "01.02.2019",
      .......
    },
   "player": {  "id" : 2,
     "firstName" : "Nikolay",
     "lastName": "Grigoryan",
     .....
   }
}
</code>```

/tournament/1/participants/2

When I'm requesting the participants of the certain tournament it's convinient enough to have a separate field by name player containg full nested Player model whith all available fields. But when I'm creating a new participant the situation looks different for me. I would prefer to have just playerId to provide as POST body:

/tournament/1/participants

POST

```<code>{
  ....,
  playerId: 2,
  .....
}
</code>```

but not

```<code>{
  ....,
  "player": {
    "id": 2,
   ....
  }
}
</code>```

It seems no need to have nested model here but instead only playerId is enough and by this reason no need to have nested object only for holding id at all.

Is it ok to have such simplification of model for POST request or they should be of the same structure? Probably I miss something important by doing such conclusion. If so I would be grateful for explanation what exactly it is.

Thanks in advance.

答:
Is it ok to have such simplification of model for POST request or they should be of the same structure? Probably I miss something important by doing such conclusion. If so I would be grateful for explanation what exactly it is.

How would you do this as a web site?

You'd probably have some sort of form, with a drop down control that lists the identifiers that you might use.  The client would choose the identifier from the list, and submit the form.  The result would be an HTTP request message with the identifier in the request body.

Body:
The questions about possibility to have different models for POST and GET methods in REST api have been asked several times but I would like to clarify one specific moment.
Suppose we are designing api about sport competition.

Models and corresponding resources:

1) Player
{  "id" : 2,
   "firstName" : "Nikolay",
   "lastName": "Grigoryan",
   .....
}

/players/2

2) Tournament

{ "id" 1,
  "name": "Some tournament",
  "date" "01.02.2019",
  .......
}

/tournaments/1

3) Participant

{
  "id": 2,
   "tournament": { "id" 1,
      "name": "Some tournament",
      "date" "01.02.2019",
      .......
    },
   "player": {  "id" : 2,
     "firstName" : "Nikolay",
     "lastName": "Grigoryan",
     .....
   }
}

/tournament/1/participants/2

When I'm requesting the participants of the certain tournament it's convinient enough to have a separate field by name player containg full nested Player model whith all available fields. But when I'm creating a new participant the situation looks different for me. I would prefer to have just playerId to provide as POST body:

/tournament/1/participants

POST

{
  ....,
  playerId: 2,
  .....
}

but not

{
  ....,
  "player": {
    "id": 2,
   ....
  }
}

It seems no need to have nested model here but instead only playerId is enough and by this reason no need to have nested object only for holding id at all.

Is it ok to have such simplification of model for POST request or they should be of the same structure? Probably I miss something important by doing such conclusion. If so I would be grateful for explanation what exactly it is.

Thanks in advance.


来源: stackexchange

问:
how to filter out boolean fields in spark dataframe?
I have three columns in my data frame. In this second and third are boolean fields. I want to filter out the values which are true. i have tried this one nn.filter(col("col3")===true).show but it says invalid column name "true". what worng with my code? Does any help please?

my codes:

```<code>scala> nn.printSchema
root
 |-- ID: integer (nullable = true)
 |-- col2: boolean (nullable = true)
 |-- col3: boolean (nullable = true)

scala> nn.show
+---+-----+-----+
| ID| col2| col3|
+---+-----+-----+
|  4| true|false|
|  5|false|false|
|  6|false|false|
|  7|false|false|
| 12|false|false|
| 13|false|false|
| 14|false|false|
| 15|false| true|
| 16|false|false|
| 17|false|false|
| 18|false|false|
| 22|false|false|
| 36|false|false|
| 37|false|false|
| 38|false|false|
| 39|false|false|
| 40|false|false|
| 41| true|false|
| 42|false|false|
+---+-----+-----+

scala> nn.filter(col("col3")===true).show
[Stage 14:>                                                         (0 + 1) / 1]19/05/26 22:44:16 ERROR executor.Executor: Exception in task 0.0 in stage 14.0 (TID 14)
com.microsoft.sqlserver.jdbc.SQLServerException: Invalid column name 'true'.
        at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:217)
        at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1655)
        at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:440)
        at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:385)
        at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7505)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2445)
        at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:191)
        at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:166)
        at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeQuery(SQLServerPreparedStatement.java:297)
        at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD.compute(JDBCRDD.scala:301)
        at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
        at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
        at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
        at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
        at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
        at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
        at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
        at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
        at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
        at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
        at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
        at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
        at org.apache.spark.scheduler.Task.run(Task.scala:109)
        at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:345)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
</code>```

答:
You can apply directly filter on the boolean value. Why are you applying condition on it as col("col3")===true? Your column value is in boolean type and when we apply to a condition in the filter it returns value in boolean either true or false. When your column is boolean then why are you again trying the same?

```<code>scala> val someDf = Seq((1, true, false), (2, true, true)).toDF("col1", "col2", "col3")
someDf: org.apache.spark.sql.DataFrame = [col1: int, col2: boolean ... 1 more field]
</code>```

We have DF with the value:

```<code>scala> someDf.show
+----+----+-----+
|col1|col2| col3|
+----+----+-----+
|   1|true|false|
|   2|true| true|
+----+----+-----+
</code>```

Now apply the filter:

```<code>scala> someDf.filter(col("col3")).show
+----+----+----+
|col1|col2|col3|
+----+----+----+
|   2|true|true|
+----+----+----+
</code>```

Thanks.

ContentLicense: CC BY-SA 4.0

Body:
I have three columns in my data frame. In this second and third are boolean fields. I want to filter out the values which are true. i have tried this one nn.filter(col("col3")===true).show but it says invalid column name "true". what worng with my code? Does any help please?

my codes:

scala> nn.printSchema
root
 |-- ID: integer (nullable = true)
 |-- col2: boolean (nullable = true)
 |-- col3: boolean (nullable = true)

scala> nn.show
+---+-----+-----+
| ID| col2| col3|
+---+-----+-----+
|  4| true|false|
|  5|false|false|
|  6|false|false|
|  7|false|false|
| 12|false|false|
| 13|false|false|
| 14|false|false|
| 15|false| true|
| 16|false|false|
| 17|false|false|
| 18|false|false|
| 22|false|false|
| 36|false|false|
| 37|false|false|
| 38|false|false|
| 39|false|false|
| 40|false|false|
| 41| true|false|
| 42|false|false|
+---+-----+-----+

scala> nn.filter(col("col3")===true).show
[Stage 14:>                                                         (0 + 1) / 1]19/05/26 22:44:16 ERROR executor.Executor: Exception in task 0.0 in stage 14.0 (TID 14)
com.microsoft.sqlserver.jdbc.SQLServerException: Invalid column name 'true'.
        at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:217)
        at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1655)
        at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:440)
        at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:385)
        at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7505)
        at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2445)
        at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:191)
        at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:166)
        at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeQuery(SQLServerPreparedStatement.java:297)
        at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD.compute(JDBCRDD.scala:301)
        at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
        at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
        at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
        at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
        at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
        at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
        at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
        at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
        at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
        at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
        at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
        at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
        at org.apache.spark.scheduler.Task.run(Task.scala:109)
        at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:345)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)

Body:
You can apply directly filter on the boolean value. Why are you applying condition on it as col("col3")===true? Your column value is in boolean type and when we apply to a condition in the filter it returns value in boolean either true or false. When your column is boolean then why are you again trying the same?

scala> val someDf = Seq((1, true, false), (2, true, true)).toDF("col1", "col2", "col3")
someDf: org.apache.spark.sql.DataFrame = [col1: int, col2: boolean ... 1 more field]

We have DF with the value:

scala> someDf.show
+----+----+-----+
|col1|col2| col3|
+----+----+-----+
|   1|true|false|
|   2|true| true|
+----+----+-----+

Now apply the filter:

scala> someDf.filter(col("col3")).show
+----+----+----+
|col1|col2|col3|
+----+----+----+
|   2|true|true|
+----+----+----+

Thanks.


问:
Youtube Downloader Application
I am a computer science student and I want to make an application to automatically download the latest news from youtube and save it on my hdd.
I want to make an application that would download youtube videos that were uploaded on a particular day on a particular channel. I have the following programming skills: C#, JavaScript/Jquery, asp.net, Java.

This is what I want to do :

Search for the videos on that particular channel on a specific date

Extract & manipulate header info to generate the get_video token

Download the videos or feed it to a 3rd party download manager through a txt file

But I am not sure how to do this. Any ideas on how to proceed????
What technologies should I be looking at to make this possible....

答:
To make Youtube downloader application, you can use the following technologies:

Reactjs (for front end) . It is based on JavaScript.

'react-player' node module for embedding Youtube.

Google's Youtube API to get the list of videos based on the search.

"ReadableStream" object of JavaScript for downloading the stream and video files. (https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_streams)

Nodejs for back-end.

Example of a Youtube downloader is YTDownload. You can contact the website or youtube developer for more details.

ContentLicense: CC BY-SA 3.0

Title: Youtube Downloader Application


问:
glUniformMatrix4fv - INVALID OPERATION

Context:

OpenGL C API 4.1 ("modern" opengl)

Issue:

I am encoutering an INVALID OPERATION binding uniforms the wrong way with multiple shaders :

// Getting ids for each uniform
GLuint uniform1 = glGetUniformLocation(shader1_program.id, "mvp");
GLuint uniform2 = glGetUniformLocation(shader2_program.id, "mvp");

loop {
    // Print mesh 1 shader 1
    glUseProgram(shader1_program.id);
    glUniformMatrix4fv(uniform1 , 1, GL_FALSE, mvp1);
    check_gl_error(); // =============================> this one provides the error
    glBindVertexArray(vao1);
    glDrawArrays(GL_TRIANGLES, 0, vertex_number1);

    // Print mesh 2 with shader2
    glUseProgram(shader2_program.id);
    glUniformMatrix4fv(uniform2 , 1, GL_FALSE, mvp2);
    check_gl_error();
    glBindVertexArray(vao2);
    glDrawArrays(GL_TRIANGLES, 0, vertex_number2);
}
```

<p>Here is the <code>check_gl_error()</code> function that get error code from <code>glGetError</code> and print signification:</p>

```typedef struct glmaperror_s {
                            GLenum err;
                            char *string_error;
}                            glmaperror_t;

static const glmaperror_t glmaperror[] = {
    { GL_INVALID_OPERATION, "GL_INVALID_OPERATION", },
    { GL_INVALID_ENUM, "GL_INVALID_ENUM", },
    { GL_INVALID_VALUE, "GL_INVALID_VALUE", },
    { GL_OUT_OF_MEMORY, "GL_OUT_OF_MEMORY", },
    { GL_INVALID_FRAMEBUFFER_OPERATION, "GL_INVALID_FRAMEBUFFER_OPERATION", },
};

int check_gl_error(void)
{
    GLenum  err;
    char    *error;

    error = 0;
    while ((err = glGetError()) != GL_NO_ERROR) {
        error = "Unhandled GL error";
        for (size_t i = 0; i * sizeof(glmaperror_t) < sizeof(glmaperror); i++) {
            if (glmaperror[i].err == err) {
                error = glmaperror[i].string_error;
            }
        }
        fprintf(stderr, "[GL Error]: %s\n", error);
        return (-1);
    }
    return (0);
}
```

<hr>

<p>Here are the two shaders :</p>

<p><strong>shader1</strong> :</p>

```#version 410
in vec3 position;
in vec3 color;

out vec4 _color;

uniform mat4 mvp;

void main() {
  gl_Position = mvp * vec4(position, 1.0);
  _color = vec4(color, 255.0);
}
```

<p><strong>shader2</strong></p>

```#version 410
in vec3 position;

uniform mat4 mvp;

void main() {
  gl_Position = mvp * vec4(position, 1.0);
}
```

Actually, only mesh 2 is rendered.

I have printed shader1_program.id and shader2_program.id, they are valid and have different values which is ok.

I have printed uniform1 and uniform2, they have the same numerical value.

Is it the right order to declare and bind uniform ?

答:
shader1_program.id is the result of the compiled shader1 code from the glCompileShader function. shader2_program.id is the result of the compiled shader2 code from the glCompileShader function.

  – Alrick 12 hours ago

So that's the problem then. glUseProgram expects a program object, not a shader object.

You create program objects by a call to glCreateProgram, followed by attaching your compiled shader stages with glAttachShader, and then calling glLinkProgram afterwards. You cannot call glUseProgram on a shader directly.

Title: glUniformMatrix4fv - INVALID OPERATION

Body:
Context:

OpenGL C API 4.1 ("modern" opengl)

Issue:

I am encoutering an INVALID OPERATION binding uniforms the wrong way with multiple shaders :

// Getting ids for each uniform
GLuint uniform1 = glGetUniformLocation(shader1_program.id, "mvp");
GLuint uniform2 = glGetUniformLocation(shader2_program.id, "mvp");

loop {
    // Print mesh 1 shader 1
    glUseProgram(shader1_program.id);
    glUniformMatrix4fv(uniform1 , 1, GL_FALSE, mvp1);
    check_gl_error(); // =============================> this one provides the error
    glBindVertexArray(vao1);
    glDrawArrays(GL_TRIANGLES, 0, vertex_number1);

    // Print mesh 2 with shader2
    glUseProgram(shader2_program.id);
    glUniformMatrix4fv(uniform2 , 1, GL_FALSE, mvp2);
    check_gl_error();
    glBindVertexArray(vao2);
    glDrawArrays(GL_TRIANGLES, 0, vertex_number2);
}

Here is the check_gl_error() function that get error code from glGetError and print signification:

typedef struct glmaperror_s {
                            GLenum err;
                            char *string_error;
}                            glmaperror_t;

static const glmaperror_t glmaperror[] = {
    { GL_INVALID_OPERATION, "GL_INVALID_OPERATION", },
    { GL_INVALID_ENUM, "GL_INVALID_ENUM", },
    { GL_INVALID_VALUE, "GL_INVALID_VALUE", },
    { GL_OUT_OF_MEMORY, "GL_OUT_OF_MEMORY", },
    { GL_INVALID_FRAMEBUFFER_OPERATION, "GL_INVALID_FRAMEBUFFER_OPERATION", },
};

int check_gl_error(void)
{
    GLenum  err;
    char    *error;

    error = 0;
    while ((err = glGetError()) != GL_NO_ERROR) {
        error = "Unhandled GL error";
        for (size_t i = 0; i * sizeof(glmaperror_t) < sizeof(glmaperror); i++) {
            if (glmaperror[i].err == err) {
                error = glmaperror[i].string_error;
            }
        }
        fprintf(stderr, "[GL Error]: %s\n", error);
        return (-1);
    }
    return (0);
}

Here are the two shaders :

shader1 :

#version 410
in vec3 position;
in vec3 color;

out vec4 _color;

uniform mat4 mvp;

void main() {
  gl_Position = mvp * vec4(position, 1.0);
  _color = vec4(color, 255.0);
}

shader2

#version 410
in vec3 position;

uniform mat4 mvp;

void main() {
  gl_Position = mvp * vec4(position, 1.0);
}

Actually, only mesh 2 is rendered.

I have printed shader1_program.id and shader2_program.id, they are valid and have different values which is ok.

I have printed uniform1 and uniform2, they have the same numerical value.

Is it the right order to declare and bind uniform ?


问:
bash. How to pick random line from a variable containing numerous lines?
```<code>a=$(find ./ -name "*-*.txt")
</code>```

Now I need to get random line from $a, but shuf yelling at me

```<code>b=$(shuf -n1 $a)
</code>```

shuf: extra operand

What's my issue?
Thank you!

答:
By default, shuf takes a single filename argument, and shuffles the contents of that file. You want it to shuffle its arguments instead; for that, use shuf -e:

```<code>b=$(shuf -e -n1 $a)
</code>```

BTW, there's a subtler problem with this: it'll get confused by filenames with spaces and/or wildcard characters. Maybe not going to happen in your environment, but I prefer to use scripting idioms that don't fall over due to funny filenames. To protect against that, store the filenames in an array rather than counting on word splitting to tell where one stops and the next begins:

```<code>readarray -d '' -t arr < <(find ./ -name "*-*.txt" -print0)
b=$(shuf -en1 "${arr[@]}")
</code>```

If you don't need to store the file list, things are even simpler:

```<code>b=$(find ./ -name "*-*.txt" -print0 | shuf -zn1 | tr -d '\0')
</code>```

Body:
a=$(find ./ -name "*-*.txt")

Now I need to get random line from $a, but shuf yelling at me

b=$(shuf -n1 $a)

shuf: extra operand

What's my issue?
Thank you!

Body:
By default, shuf takes a single filename argument, and shuffles the contents of that file. You want it to shuffle its arguments instead; for that, use shuf -e:

b=$(shuf -e -n1 $a)

BTW, there's a subtler problem with this: it'll get confused by filenames with spaces and/or wildcard characters. Maybe not going to happen in your environment, but I prefer to use scripting idioms that don't fall over due to funny filenames. To protect against that, store the filenames in an array rather than counting on word splitting to tell where one stops and the next begins:

readarray -d '' -t arr < <(find ./ -name "*-*.txt" -print0)
b=$(shuf -en1 "${arr[@]}")

If you don't need to store the file list, things are even simpler:

b=$(find ./ -name "*-*.txt" -print0 | shuf -zn1 | tr -d '\0')


问:
Inline functions are causing errors in unit test code coverage report
I'm writing some unit tests for my Android app written in Kotlin, and I'm getting errors from the included inlined collection functions, in this case specifically sortedBy

```<code> override fun onDaysSelected(dayOfWeekList: ArrayList<DayOfWeek>) {
        view.userRoutingRule.days = dayOfWeekList.sortedBy { it.dayOfWeek }
        renderRule()
 }
</code>```

This is the error I'm getting when I run my unit tests with coverage

---- IntelliJ IDEA coverage runner ----  sampling ... include patterns:
  com.mypackage..*
  exclude patterns:[2019.02.02 14:49:40] (Coverage): Class data was not
  extracted:
  com.mypackage\myfile$onDaysSelected$$inlined$sortedBy$1:
  java.lang.Throwable

Process finished with exit code 0

My unit tests all pass accordingly, but when I go to look at the coverage report, it's almost completely bare as this error stopped it from completing.

Is there any solution to this at this point? It's hard to know if I missed some condition if I can't just look at the report.

答:
It's a known issue with calculating coverage of imline methods that use lambdas. (see No coverage report for inlined Kotlin methods and https://discuss.kotlinlang.org/t/inline-functions-coverage/5366)

If you want to run coverage in the current state, you'll need to use other approaches, for example implementing Comparable interface in your DayOfWeek and using .sorted() method.

Body:
I'm writing some unit tests for my Android app written in Kotlin, and I'm getting errors from the included inlined collection functions, in this case specifically sortedBy

 override fun onDaysSelected(dayOfWeekList: ArrayList<DayOfWeek>) {
        view.userRoutingRule.days = dayOfWeekList.sortedBy { it.dayOfWeek }
        renderRule()
 }

This is the error I'm getting when I run my unit tests with coverage

---- IntelliJ IDEA coverage runner ----  sampling ... include patterns:
  com.mypackage..*
  exclude patterns:[2019.02.02 14:49:40] (Coverage): Class data was not
  extracted:
  com.mypackage\myfile$onDaysSelected$$inlined$sortedBy$1:
  java.lang.Throwable

Process finished with exit code 0

My unit tests all pass accordingly, but when I go to look at the coverage report, it's almost completely bare as this error stopped it from completing.

Is there any solution to this at this point? It's hard to know if I missed some condition if I can't just look at the report.


问:
iPhone- application crashes on click of menu action button in QLPreviewController ios 4.2
```<code> When I try to click the menu action button in QLPreviewController the application crashes.
</code>```

This is what I'm doing in delegate method

```<code>- (id)previewController:(QLPreviewController *)previewController previewItemAtIndex:(NSInteger)index
{

    NSMutableString*Url = [[NSMutableString alloc] initWithFormat:@"http://10.30.24.21/Documents/abc.doc];

    NSURL *fileURL;
    fileURL = [NSURL URLWithString:Url];// the url of the file which is present in NAS device
    [Url release];
    return fileURL;
}
</code>```

This is the crash report

```<code>2011-01-11 12:21:36.717 iLink[5548:207] *** Assertion failure in -[UIDocumentInteractionController setURL:], /SourceCache/UIKit_Sim/UIKit-1447.6.4/UIDocumentInteractionController.m:1060
2011-01-11 12:21:36.720 iLink[5548:207] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UIDocumentInteractionController: invalid scheme https.  Only the file scheme is supported.'
</code>```

When I try to preview file present locally menu action button click is not crashing.

there I'll be using

```<code> NSURL *fileURL;
    fileURL = [NSURL fileURLWithPath:filePath];// filePath is local file path.
</code>```

I understood that when we preview local files ([NSURL fileURLWithPath:filePath]) menu action button click is not crashing ,, when we preview files from server ([NSURL URLWithString:Url]) menu action button click crashes.

I have two questions,
1. Can we disable the menu action button?
2. Is there any way to avoid the crash using [NSURL URLWithString:Url]?

Thanks

答:
Need to use</p>

```<code>[NSURL fileURLWithPath:urPath]
</code>```

Body:
 When I try to click the menu action button in QLPreviewController the application crashes.

This is what I'm doing in delegate method

- (id)previewController:(QLPreviewController *)previewController previewItemAtIndex:(NSInteger)index
{

    NSMutableString*Url = [[NSMutableString alloc] initWithFormat:@"http://10.30.24.21/Documents/abc.doc];

    NSURL *fileURL;
    fileURL = [NSURL URLWithString:Url];// the url of the file which is present in NAS device
    [Url release];
    return fileURL;
}

This is the crash report

2011-01-11 12:21:36.717 iLink[5548:207] *** Assertion failure in -[UIDocumentInteractionController setURL:], /SourceCache/UIKit_Sim/UIKit-1447.6.4/UIDocumentInteractionController.m:1060
2011-01-11 12:21:36.720 iLink[5548:207] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UIDocumentInteractionController: invalid scheme https.  Only the file scheme is supported.'

When I try to preview file present locally menu action button click is not crashing.

there I'll be using

 NSURL *fileURL;
    fileURL = [NSURL fileURLWithPath:filePath];// filePath is local file path.

I understood that when we preview local files ([NSURL fileURLWithPath:filePath]) menu action button click is not crashing ,, when we preview files from server ([NSURL URLWithString:Url]) menu action button click crashes.

I have two questions,
1. Can we disable the menu action button?
2. Is there any way to avoid the crash using [NSURL URLWithString:Url]?

Thanks

Body:
Need to use

[NSURL fileURLWithPath:urPath]


问:
error: conversion from 'fundamental type' to non-scalar type 'NamedType<fundamental type>' requested
I have the following structure (simplified enough to replicate the issue):

```<code>template < class T, class P = struct NamedTypeDefaultTag > struct NamedType
{
    //static_assert(std::is_fundamental_v< T >, "Template parameter is not a fundamental type.");

    using ValueType = T;

    ValueType m{};

    constexpr NamedType() noexcept = default;
    constexpr NamedType(const NamedType & value) noexcept = default;
    constexpr NamedType(NamedType && value) noexcept = default;

    constexpr explicit NamedType(const T & value) noexcept : m{value} { }

    constexpr NamedType & operator = (const T & value) { m = value; return *this; }
};
</code>```

And then I attempt to use the assignment operator like this:

```<code>int main() {
    using NT_t = NamedType< int >;

    // generates error
    int t = 1;
    NT_t a = t;
    const NT_t b = 2;
    // works fine
    NT_t c;
    c = 2;

    return 0;
}
</code>```

I suspect that because I declare it and assign it at the same time it somehow attempts to use a constructor (which is explicit).

But I don't understand what's causing it and how to get around it.

答:
NT_t a = t; attempts an implicit conversion from int to NT_t. But the constructor capable of performing such a conversion is marked explicit, thus precluding its use in implicit conversions. Make it

```<code>NT_t a{t};
const NT_t b{2};
</code>```

Body:
I have the following structure (simplified enough to replicate the issue):

template < class T, class P = struct NamedTypeDefaultTag > struct NamedType
{
    //static_assert(std::is_fundamental_v< T >, "Template parameter is not a fundamental type.");

    using ValueType = T;

    ValueType m{};

    constexpr NamedType() noexcept = default;
    constexpr NamedType(const NamedType & value) noexcept = default;
    constexpr NamedType(NamedType && value) noexcept = default;

    constexpr explicit NamedType(const T & value) noexcept : m{value} { }

    constexpr NamedType & operator = (const T & value) { m = value; return *this; }
};

And then I attempt to use the assignment operator like this:

int main() {
    using NT_t = NamedType< int >;

    // generates error
    int t = 1;
    NT_t a = t;
    const NT_t b = 2;
    // works fine
    NT_t c;
    c = 2;

    return 0;
}

I suspect that because I declare it and assign it at the same time it somehow attempts to use a constructor (which is explicit).

But I don't understand what's causing it and how to get around it.

Body:
NT_t a = t; attempts an implicit conversion from int to NT_t. But the constructor capable of performing such a conversion is marked explicit, thus precluding its use in implicit conversions. Make it

NT_t a{t};
const NT_t b{2};


问:
How to make an input variable global in python 3.7?
I'm making a basic dice game and have created a process in which the the player can confirm their name or redo it. and the p1 variable i've used to store the players name only works within the function but I want to use it in the whole program

I've already tried define the variable before the function, which isn't working, and have tried writing Global before it in the function but it says "invalid syntax"

#Functions
p1 = ""

def P1Start():
   print("Player 1 type your name")
   p1 =  str(input())
   print("Are you sure this is your name", p1)
   time.sleep(timesleep)
   print("Type YES to confirm")
   time.sleep(timesleep)
   print("Type NO to decline")

def P1Creation():
   P1confirmation = str(input())
   if P1confirmation =="yes":
        print("carry on")
        #elif P1confirmation == "NO" or "no":
        #P1Start()
        print(p1)
   else:
        print("Restarting the Player 1 Name Collection")
        time.sleep(1)
        P1Start()
#End of Functions

print("Welcome to the Dice game")
time.sleep(timesleep)
P1Start()
time.sleep(timesleep)
P1Creation()

print(p1)
```

<p>or</p>

<pre class="lang-py prettyprint-override"><code>#Functions
p1 = ""

def P1Start():
   print("Player 1 type your name")
   global p1 =  str(input())
   print("Are you sure this is your name", p1)
   time.sleep(timesleep)
   print("Type YES to confirm")
   time.sleep(timesleep)
   print("Type NO to decline")

def P1Creation():
   P1confirmation = str(input())
   if P1confirmation =="yes":
        print("carry on")
        #elif P1confirmation == "NO" or "no":
        #P1Start()
        print(p1)
   else:
        print("Restarting the Player 1 Name Collection")
        time.sleep(1)
        P1Start()
#End of Functions

print("Welcome to the Dice game")
time.sleep(timesleep)
P1Start()
time.sleep(timesleep)
P1Creation()

print(p1)
</code>```

Putting Global in front just shows "invalid syntax"
What should I do to make this work?

答:
You can't do a global and an assignment in one. Instead of this:

```<code>global p1 =  str(input())
</code>```

Do this:

```<code>global p1
p1 =  str(input())
</code>```

Body:
I'm making a basic dice game and have created a process in which the the player can confirm their name or redo it. and the p1 variable i've used to store the players name only works within the function but I want to use it in the whole program

I've already tried define the variable before the function, which isn't working, and have tried writing Global before it in the function but it says "invalid syntax"

#Functions
p1 = ""

def P1Start():
   print("Player 1 type your name")
   p1 =  str(input())
   print("Are you sure this is your name", p1)
   time.sleep(timesleep)
   print("Type YES to confirm")
   time.sleep(timesleep)
   print("Type NO to decline")

def P1Creation():
   P1confirmation = str(input())
   if P1confirmation =="yes":
        print("carry on")
        #elif P1confirmation == "NO" or "no":
        #P1Start()
        print(p1)
   else:
        print("Restarting the Player 1 Name Collection")
        time.sleep(1)
        P1Start()
#End of Functions

print("Welcome to the Dice game")
time.sleep(timesleep)
P1Start()
time.sleep(timesleep)
P1Creation()

print(p1)

or

#Functions
p1 = ""

def P1Start():
   print("Player 1 type your name")
   global p1 =  str(input())
   print("Are you sure this is your name", p1)
   time.sleep(timesleep)
   print("Type YES to confirm")
   time.sleep(timesleep)
   print("Type NO to decline")

def P1Creation():
   P1confirmation = str(input())
   if P1confirmation =="yes":
        print("carry on")
        #elif P1confirmation == "NO" or "no":
        #P1Start()
        print(p1)
   else:
        print("Restarting the Player 1 Name Collection")
        time.sleep(1)
        P1Start()
#End of Functions

print("Welcome to the Dice game")
time.sleep(timesleep)
P1Start()
time.sleep(timesleep)
P1Creation()

print(p1)

Putting Global in front just shows "invalid syntax"
What should I do to make this work?

Body:
You can't do a global and an assignment in one. Instead of this:

global p1 =  str(input())

Do this:

global p1
p1 =  str(input())


问:
file handling using structured array
I want to store string and char data into a .dat file.. program is running correctly.But after open the .dat file the same name is written twise.Why is that ? I can't find the problem.

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

struct patients{
        char name[8];
        char appType[1];
};

int main(void)
{

    FILE *F1;
    F1 = fopen("appointment.dat","a");

    int i = 0;
    struct patients detailsArr[5];

    for( i = 0 ; i < 5 ; i++ )
    {
        printf("Enter Patient Name : ");
        scanf("%s",detailsArr[i].name);

        printf("Enter Appointment Type :");
        scanf(" %c",detailsArr[i].appType);

    }

    if ( F1 == NULL )
    {
        printf("Error in File Reading !");
        return -1;
    }

    for( i = 0 ; i < 5 ; i++ )
    {
        fprintf(F1 ,"%s\t",detailsArr[i].name);
        fprintf(F1 ,"%s",detailsArr[i].appType);
        fprintf(F1 ,"\n");

    }

    fclose(F1);

    return 0;
}
</code>```

This is my Output :

```<code>Dilshan CRuwan
Ruwan   TMangala
Mangala SGanesh
Ganesh  CJithen
Jithen  SV
</code>```

答:
You need to change this line:

```<code>char appType[1];
</code>```

to this:

```<code>char appType;
</code>```

if you want to use the %c scanf format specifier.

To avoid overflow (and non-null-terminated strings), you should also use %7s instead of %s in this line:

```<code> scanf("%s",detailsArr[i].name);
</code>```

You also need to change this line:

```<code> fprintf(F1 ,"%s",detailsArr[i].appType);
</code>```

to this:

```<code> fprintf(F1 ,"%c",detailsArr[i].appType);
</code>```

It's just a matter of type changes.

Title: file handling using structured array

Body:
I want to store string and char data into a .dat file.. program is running correctly.But after open the .dat file the same name is written twise.Why is that ? I can't find the problem.

#include<stdio.h>

struct patients{
        char name[8];
        char appType[1];
};

int main(void)
{

    FILE *F1;
    F1 = fopen("appointment.dat","a");

    int i = 0;
    struct patients detailsArr[5];

    for( i = 0 ; i < 5 ; i++ )
    {
        printf("Enter Patient Name : ");
        scanf("%s",detailsArr[i].name);

        printf("Enter Appointment Type :");
        scanf(" %c",detailsArr[i].appType);

    }

    if ( F1 == NULL )
    {
        printf("Error in File Reading !");
        return -1;
    }

    for( i = 0 ; i < 5 ; i++ )
    {
        fprintf(F1 ,"%s\t",detailsArr[i].name);
        fprintf(F1 ,"%s",detailsArr[i].appType);
        fprintf(F1 ,"\n");

    }

    fclose(F1);

    return 0;
}

This is my Output :

Dilshan CRuwan
Ruwan   TMangala
Mangala SGanesh
Ganesh  CJithen
Jithen  SV

Body:
You need to change this line:

char appType[1];

to this:

char appType;

if you want to use the %c scanf format specifier.

To avoid overflow (and non-null-terminated strings), you should also use %7s instead of %s in this line:

 scanf("%s",detailsArr[i].name);

You also need to change this line:

 fprintf(F1 ,"%s",detailsArr[i].appType);

to this:

 fprintf(F1 ,"%c",detailsArr[i].appType);

It's just a matter of type changes.


问:
Set up Python 3 build system with Sublime Text 3
I want to configure Sublime Text 3 to build Python 3, but I don't seem to understand how the builds work. Many tutorials have told me to make a build file containing code such as:

```<code>{
    'cmd': ['/usr/bin/python3', '-u', '$file'],
    'file_regex': '^[ ]*File "(…*?)", line ([0-9]*)',
    'selector': 'source.python'
}
</code>```

and save it as a file called Python.sublime-build or python3.sublime-build (much of the information I found was conflicting). One tutorial suggested creating a new folder in the ST3 Packages folder called Python and add the build file in there, whilst other tutorials suggested leaving it in the folder called User.

One tutorial explained how I had to change the Environment Variable path on my operating system to get it to work. That didn't seem to help either.

I added a folder Python to Packages (since it wasn't there already) and added in a build file with the name Python.sublime_build which featured only the code I posted above in it. Now when I attempt to run Sublime Text it gives me this error:

```<code>Error trying to parse build system:
Expected value in Packages\Python\Python.sublime-build:2:5
</code>```

答:
And to add on to the already solved problem, I had installed Portable Scientific Python on my flash drive E: which on another computer changed to D:, I would get the error "The system cannot find the file specified". So I used parent directory to define the path, like this:

From this:

```<code>{
    "cmd": ["E:/WPy64-3720/python-3.7.2.amd64/python.exe", "$file"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "selector": "source.python"
}
</code>```

To this:

```<code>{
    "cmd": ["../../../../WPy64-3720/python-3.7.2.amd64/python.exe","$file"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "selector": "source.python"
}
</code>```

You can modify depending on where your python is installed your python.

Body:
I want to configure Sublime Text 3 to build Python 3, but I don't seem to understand how the builds work. Many tutorials have told me to make a build file containing code such as:

{
    'cmd': ['/usr/bin/python3', '-u', '$file'],
    'file_regex': '^[ ]*File "(…*?)", line ([0-9]*)',
    'selector': 'source.python'
}

and save it as a file called Python.sublime-build or python3.sublime-build (much of the information I found was conflicting). One tutorial suggested creating a new folder in the ST3 Packages folder called Python and add the build file in there, whilst other tutorials suggested leaving it in the folder called User.

One tutorial explained how I had to change the Environment Variable path on my operating system to get it to work. That didn't seem to help either.

I added a folder Python to Packages (since it wasn't there already) and added in a build file with the name Python.sublime_build which featured only the code I posted above in it. Now when I attempt to run Sublime Text it gives me this error:

Error trying to parse build system:
Expected value in Packages\Python\Python.sublime-build:2:5

Body:
And to add on to the already solved problem, I had installed Portable Scientific Python on my flash drive E: which on another computer changed to D:, I would get the error "The system cannot find the file specified". So I used parent directory to define the path, like this:

From this:

{
    "cmd": ["E:/WPy64-3720/python-3.7.2.amd64/python.exe", "$file"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "selector": "source.python"
}

To this:

{
    "cmd": ["../../../../WPy64-3720/python-3.7.2.amd64/python.exe","$file"],
    "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
    "selector": "source.python"
}

You can modify depending on where your python is installed your python.


问:
Session no longer exists when resend WWW Unity3d and PHP
I created a system that sends the user id by Unity3D and on the server creates a session and sends the session back to the client (on Unity3D), so it all works! But when I send back from Unity3D to the server the session is simply gone! I already checked the browser and it works, it just does not work on Unity3D!
Does anyone have any idea what it is?

C# on Unity3d

```<code>void Start () {
   WWW w = new WWW (url+ "?id=" + userId);
   StartCoroutine (SessionWWW (w));
}

private IEnumerator SessionWWW (WWW _w){
    yield return _w;

    PlayerPrefs.SetString("cookie", _w.text);

    Debug.Log (PlayerPrefs.GetString("cookie"));
    Debug.Log (_w.text);
}

void Update(){
    if (Input.GetKeyDown (KeyCode.P)) {
        string session= PlayerPrefs.GetString("cookie");
        WWW w = new WWW (url "?sessionid=" + session);
        StartCoroutine (GetSessionWWW (w));
    }
}

private IEnumerator GetSessionWWW (WWW _w){
    yield return _w;
    if (_w.text == "ok") {
        Debug.Log ("received!");
    } else {
        Debug.Log (_w.text);
    }
}
</code>```

PHP script:

```<code><?PHP
session_start();

if(isset($_GET['id'])){
    $id = $_GET['id'];
    $_SESSION['session'] = $id;
    echo $_SESSION['session'];
}
if(isset($_GET['sessionid'])){
    if(isset($_SESSION['session'])){
        echo $_SESSION['session'];
    }

}
?>
</code>```

答:
If your wanting to set the session id of the current session in PHP use the function session_id($id) BEFORE session_start.
https://www.php.net/manual/en/function.session-id.php

```<code><?php

//do you need both of these?
if(isset($_GET['id'])){
    $id = $_GET['id'];
    session_id($id);
}
if(isset($_GET['sessionid'])){
    $sessionid = $_GET['sessionid'];
    session_id($sessionid);
}

session_start();

print_r($_SESSION)
?>
</code>```

session_id ([ string $id ] ) : string

If id is specified, it will
  replace the current session id. session_id() needs to be called before
  session_start() for that purpose. Depending on the session handler,
  not all characters are allowed within the session id. For example, the
  file session handler only allows characters in the range a-z A-Z 0-9 ,
  (comma) and - (minus)

you might also want to validate before setting the session id to prevent mistakes from your code and if this is on the internet other people can find it too.

(from the link above)

```<code>function session_valid_id($session_id)
{
    return preg_match('/^[-,a-zA-Z0-9]{1,128}$/', $session_id) > 0;
}

$id = $_GET['id'];
if (session_valid_id($id)) {
    session_id($id);
}
</code>```

Body:
I created a system that sends the user id by Unity3D and on the server creates a session and sends the session back to the client (on Unity3D), so it all works! But when I send back from Unity3D to the server the session is simply gone! I already checked the browser and it works, it just does not work on Unity3D!
Does anyone have any idea what it is?

C# on Unity3d

void Start () {
   WWW w = new WWW (url+ "?id=" + userId);
   StartCoroutine (SessionWWW (w));
}

private IEnumerator SessionWWW (WWW _w){
    yield return _w;

    PlayerPrefs.SetString("cookie", _w.text);

    Debug.Log (PlayerPrefs.GetString("cookie"));
    Debug.Log (_w.text);
}

void Update(){
    if (Input.GetKeyDown (KeyCode.P)) {
        string session= PlayerPrefs.GetString("cookie");
        WWW w = new WWW (url "?sessionid=" + session);
        StartCoroutine (GetSessionWWW (w));
    }
}

private IEnumerator GetSessionWWW (WWW _w){
    yield return _w;
    if (_w.text == "ok") {
        Debug.Log ("received!");
    } else {
        Debug.Log (_w.text);
    }
}

PHP script:

<?PHP
session_start();

if(isset($_GET['id'])){
    $id = $_GET['id'];
    $_SESSION['session'] = $id;
    echo $_SESSION['session'];
}
if(isset($_GET['sessionid'])){
    if(isset($_SESSION['session'])){
        echo $_SESSION['session'];
    }

}
?>

Body:
If your wanting to set the session id of the current session in PHP use the function session_id($id) BEFORE session_start.
https://www.php.net/manual/en/function.session-id.php

<?php

//do you need both of these?
if(isset($_GET['id'])){
    $id = $_GET['id'];
    session_id($id);
}
if(isset($_GET['sessionid'])){
    $sessionid = $_GET['sessionid'];
    session_id($sessionid);
}

session_start();

print_r($_SESSION)
?>

session_id ([ string $id ] ) : string

If id is specified, it will
  replace the current session id. session_id() needs to be called before
  session_start() for that purpose. Depending on the session handler,
  not all characters are allowed within the session id. For example, the
  file session handler only allows characters in the range a-z A-Z 0-9 ,
  (comma) and - (minus)

you might also want to validate before setting the session id to prevent mistakes from your code and if this is on the internet other people can find it too.

(from the link above)

function session_valid_id($session_id)
{
    return preg_match('/^[-,a-zA-Z0-9]{1,128}$/', $session_id) > 0;
}

$id = $_GET['id'];
if (session_valid_id($id)) {
    session_id($id);
}


答:
I am able to decode the data myself with the code below:</p>

```<code>// joint values
double q1 = 0, q2=0, q3=0, q4=0, q5=0, q6=0;
// pose values
double x = 0, y=0, z=0, rX=0, rY=0, rZ=0;

QByteArray array;
array = p_socket->readAll();

// decoding length data
int length = 0;
memcpy(&length, array.constData(), 4);
length = qToBigEndian(length);
qDebug() << length;

int byteLength = 8;

// decoding joint 1 value
QByteArray jointArray1 = array.mid(252,byteLength).toHex();
long long currentJointPosition1=jointArray1.toLongLong(0,16);
q1 = reinterpret_cast<double&>(currentJointPosition1);

// decoding joint 2 value
QByteArray jointArray2 = array.mid(252+1*byteLength,byteLength).toHex();
long long currentJointPosition2=jointArray2.toLongLong(0,16);
q2 = reinterpret_cast<double&>(currentJointPosition2);
</code>```

Title: QTcpSocket: decoding received data

Body:
I am able to decode the data myself with the code below:

// joint values
double q1 = 0, q2=0, q3=0, q4=0, q5=0, q6=0;
// pose values
double x = 0, y=0, z=0, rX=0, rY=0, rZ=0;

QByteArray array;
array = p_socket->readAll();

// decoding length data
int length = 0;
memcpy(&length, array.constData(), 4);
length = qToBigEndian(length);
qDebug() << length;

int byteLength = 8;

// decoding joint 1 value
QByteArray jointArray1 = array.mid(252,byteLength).toHex();
long long currentJointPosition1=jointArray1.toLongLong(0,16);
q1 = reinterpret_cast<double&>(currentJointPosition1);

// decoding joint 2 value
QByteArray jointArray2 = array.mid(252+1*byteLength,byteLength).toHex();
long long currentJointPosition2=jointArray2.toLongLong(0,16);
q2 = reinterpret_cast<double&>(currentJointPosition2);


问:
How to update the time every second using "setInterval()" without the time flashing in and out every second?
I'm using a dropdown list that displays different timezones onclick using moment-timezone. For example when you click the dropdown labeled "est" it will display the time in eastern time, when you click "cst" the cst time will display and so on.

Anyways the problem I'm running into is this... I use setInterval(updateTime, 1000); to show the seconds tick up every second, now by doing this when a user clicks on "est" and then another time zone in the dropdown list like "cst" both of those times will appear and disappear every second on top of each other. I want it so when you click on an li element the previous one that was on screen will have the property of display=none. So when u click est for example est time will display and then when u click on cst the est will be display=none and the cst time will display. Man that was a mouthful.

Is there a way to accomplish this and still use the setInterval of 1second?

Here is my code...

```<code><div>
    <li>
        <ul>
        <li id="tmz1">est</li>
        <li id="tmz2">central</li>
        <li>pacific</li>
        </ul>
   </li>

   <div id="output1"></div>
   <div id="output2"></div>
</div>

$(document).ready(function(){

    var output1 = document.getElementById('output1');
    var output2 = document.getElementById('output2');

    document.getElementById('tmz1').onclick = function updateTime(){

        output2.style.display = "none";
        output1.style.display = "block";

        var now = moment();
        var humanReadable = now.tz("America/Los_Angeles").format('hh:mm:ssA');

        output1.textContent = humanReadable;
        setInterval(updateTime, 1000);

    }

    updateTime();

});

$(document).ready(function(){

    var output2 = document.getElementById('output2');
    var output1 = document.getElementById('output1');

    document.getElementById('tmz2').onclick = function updateTimeX(){

        output1.style.display = "none";
        output2.style.display = "block";

        var now = moment();
        var humanReadable =
        now.tz("America/New_York").format('hh:mm:ssA');

        output2.textContent = humanReadable;
        setInterval(updateTimeX, 1000);

    }

    updateTimeX();

});
</code>```

答:
Assign your setInterval to a variable and clear it when a user selects the new value form dropdown and restart the interval with new value </p>

```<code>var interval = setInterval(updateTime, 1000);
if(oldValue !== newValue){
  clearInterval(interval)
}
</code>```

Body:
I'm using a dropdown list that displays different timezones onclick using moment-timezone. For example when you click the dropdown labeled "est" it will display the time in eastern time, when you click "cst" the cst time will display and so on.

Anyways the problem I'm running into is this... I use setInterval(updateTime, 1000); to show the seconds tick up every second, now by doing this when a user clicks on "est" and then another time zone in the dropdown list like "cst" both of those times will appear and disappear every second on top of each other. I want it so when you click on an li element the previous one that was on screen will have the property of display=none. So when u click est for example est time will display and then when u click on cst the est will be display=none and the cst time will display. Man that was a mouthful.

Is there a way to accomplish this and still use the setInterval of 1second?

Here is my code...

est

central

pacific

$(document).ready(function(){

    var output1 = document.getElementById('output1');
    var output2 = document.getElementById('output2');

    document.getElementById('tmz1').onclick = function updateTime(){

        output2.style.display = "none";
        output1.style.display = "block";

        var now = moment();
        var humanReadable = now.tz("America/Los_Angeles").format('hh:mm:ssA');

        output1.textContent = humanReadable;
        setInterval(updateTime, 1000);

    }

    updateTime();

});

$(document).ready(function(){

    var output2 = document.getElementById('output2');
    var output1 = document.getElementById('output1');

    document.getElementById('tmz2').onclick = function updateTimeX(){

        output1.style.display = "none";
        output2.style.display = "block";

        var now = moment();
        var humanReadable =
        now.tz("America/New_York").format('hh:mm:ssA');

        output2.textContent = humanReadable;
        setInterval(updateTimeX, 1000);

    }

    updateTimeX();

});

Body:
Assign your setInterval to a variable and clear it when a user selects the new value form dropdown and restart the interval with new value

var interval = setInterval(updateTime, 1000);
if(oldValue !== newValue){
  clearInterval(interval)
}


问:
Value of type AuthDataResult has no member providerID
I am expierencing this frustrating problem. This is beyond irritating that they make updates like this for Firebase with little to no specific documentation. I am getting the same error: Value of type 'AuthDataResult' has no member 'providerID' . and here is my code:</p>

```<code>                if let user = user {
                    if self.segmentedControl.selectedSegmentIndex == 0 {
                        let userData = ["provider": user.providerID] as [String: Any]
                        DataService.instance.createFirebaseDBUser(uid: user.uid, userData: userData, isDriver: false)
                    } else {
                        let userData = ["provider": user.providerID, USER_IS_DRIVER: true, ACCOUNT_PICKUP_MODE_ENABLED: false, DRIVER_IS_ON_TRIP: false] as [String: Any]
                        DataService.instance.createFirebaseDBUser(uid: user.uid, userData: userData, isDriver: true)
                    }
                }
</code>```

答:
I just had to add another "user" after the first user. Not sure why Google made this change in the most recent Firebase update.</p>

```<code>let userData = ["provider": user.user.providerID, "email": user.user.email]
DataService.instance.createDBUser(uid: user.user.uid, userData: userData as Dictionary<String, Any>)
userCreationComplete(true, nil)
</code>```

Body:
I am expierencing this frustrating problem. This is beyond irritating that they make updates like this for Firebase with little to no specific documentation. I am getting the same error: Value of type 'AuthDataResult' has no member 'providerID' . and here is my code:

                if let user = user {
                    if self.segmentedControl.selectedSegmentIndex == 0 {
                        let userData = ["provider": user.providerID] as [String: Any]
                        DataService.instance.createFirebaseDBUser(uid: user.uid, userData: userData, isDriver: false)
                    } else {
                        let userData = ["provider": user.providerID, USER_IS_DRIVER: true, ACCOUNT_PICKUP_MODE_ENABLED: false, DRIVER_IS_ON_TRIP: false] as [String: Any]
                        DataService.instance.createFirebaseDBUser(uid: user.uid, userData: userData, isDriver: true)
                    }
                }

Body:
I just had to add another "user" after the first user. Not sure why Google made this change in the most recent Firebase update.

let userData = ["provider": user.user.providerID, "email": user.user.email]
DataService.instance.createDBUser(uid: user.user.uid, userData: userData as Dictionary<String, Any>)
userCreationComplete(true, nil)


问:
How can I code a matrix within a matrix using a loop?
So I have this 3x3 G matrix (not shown here, it's irrelevant to my problem) that I created using the two variables u (a vector, x - y) and the scalar k. x_j = (x_1 (j), x_2 (j), x_3 (j)) and  y_j = (y_1 (j), y_2 (j), y_3 (j)). alpha_j is a 3x3 matrix. The A matrix is block diagonal matrix of size 3nx3n. I am having trouble with the W matrix. How do I code a matrix of size 3nx3n, where the (i,j)th block is the 3x3 matrix given by alpha_i*G_[ij]*alpha_j?? I am lost.

My alpha_j matrix also seems to be having some trouble. The loop keeps throwing me the error, "only length-1 arrays can be converted to Python scalars." pls help :/

```<code>def W(x, y, k, alpha, A):
    u = x - y
    n = x.shape[0]
    W = np.zeros((3*n, 3*n))

    for i in range(0, n-1):
        for j in range(0, n-1):
                #u = -np.array([[x[i,0] - x[j,0]], [x[i,1] -               x[j,1]], [0]]) ??
                W[i][j] = (alpha_j(alpha, A) * G(u, k) * alpha_j(alpha, A))
        W[i][i] = np.zeros((n, n))

    return W

def alpha_j(a, A):
    alph = np.array([[0,0,0],[0,0,0],[0,0,0]],complex)
    rho = np.random.rand(3,1)
    for i in range(0, 2):
        for j in range(0, 2):
            alph[i][j] = (rho[i] * a * A[i][j])
    return alph

#-------------------------------------------------------------------

x1 = np.array([[1], [2], [0]])
y1 = np.array([[4], [5], [0]])

# SYSTEM PARAMETERS

# incoming Wave angle
theta = 0 # can range from [0, 2pi)

# susceptibility
chi = 10 + 1j

# wavelength
lam = 0.5 # microns (values between .4-.7)

# frequency
k = (2 * np.pi)/lam # 1/microns

# volume
V_0 = (0.05)**3 # microns^3

# incoming wave vector
K = k * np.array([[0], [np.sin(theta)], [np.cos(theta)]])

# polarization vector
vecinc = np.array([[1], [0], [0]]) # (can choose any vector perpendicular to K)

# for the fixed alpha case
alpha = (V_0 * 3 * chi)/(chi + 3)

# 3 x 3 matrix
A = np.matlib.identity(3) # could be any symmetric matrix,

#-------------------------------------------------------------------

# TEST FUNCTIONS

test = G((x1-y1), k)
print(test)

w = W(x1, y1, k, alpha, A)
print(w)
</code>```

Sometimes my W loops throws me the error, "can't set an array element with a sequence." But I need to set each array element in this arbitrary matrix W to the 3x3 matrix created by multiplying alpha by G...

答:
To your question of how to create a new array with a block for each element, the following should do the trick:

G = np.random.random([3,3])
result = np.zeros([9,9])
num_blocks = 3
a = np.random.random([3,3])
b = np.random.random([3,3])
for i in range(G.shape[0]):
    for j in range(G.shape[1]):
        block_result = a*G[i,j]*b
        for k in range(num_blocks):
            for l in range(num_blocks):
                result[3*i + k, 3*j + l] = block_result[i, j]
```

<p>You should be able to generalize from there. I hope I've understood correctly. </p>

<p>EDIT: It looks like I haven't understood correctly. I'm leaving it in hopes it spurs you to an answer. The general idea is to generate ranges of indices to operate on, and then just operate on them directly. Slicing might be helpful, too.</p>

<p>Ah, you asked how to create a diagonal filled with blocks. In that case:</p>

<pre class="lang-py prettyprint-override"><code>num_diagonal_blocks = 3 # for example

for block_dim in range(num_diagonal_blocks)
    # do your block calculation...
    for k in range(G.shape[0]):
        for l in range(G.shape[1]):
            result[3*block_dim + k, 3*block_dim + l] = # assign to element of block
</code>```

I think that's nearly it.

Body:
So I have this 3x3 G matrix (not shown here, it's irrelevant to my problem) that I created using the two variables u (a vector, x - y) and the scalar k. x_j = (x_1 (j), x_2 (j), x_3 (j)) and  y_j = (y_1 (j), y_2 (j), y_3 (j)). alpha_j is a 3x3 matrix. The A matrix is block diagonal matrix of size 3nx3n. I am having trouble with the W matrix. How do I code a matrix of size 3nx3n, where the (i,j)th block is the 3x3 matrix given by alpha_i*G_[ij]*alpha_j?? I am lost.

My alpha_j matrix also seems to be having some trouble. The loop keeps throwing me the error, "only length-1 arrays can be converted to Python scalars." pls help :/

def W(x, y, k, alpha, A):
    u = x - y
    n = x.shape[0]
    W = np.zeros((3*n, 3*n))

    for i in range(0, n-1):
        for j in range(0, n-1):
                #u = -np.array([[x[i,0] - x[j,0]], [x[i,1] -               x[j,1]], [0]]) ??
                W[i][j] = (alpha_j(alpha, A) * G(u, k) * alpha_j(alpha, A))
        W[i][i] = np.zeros((n, n))

    return W

def alpha_j(a, A):
    alph = np.array([[0,0,0],[0,0,0],[0,0,0]],complex)
    rho = np.random.rand(3,1)
    for i in range(0, 2):
        for j in range(0, 2):
            alph[i][j] = (rho[i] * a * A[i][j])
    return alph

#-------------------------------------------------------------------

x1 = np.array([[1], [2], [0]])
y1 = np.array([[4], [5], [0]])

# SYSTEM PARAMETERS

# incoming Wave angle
theta = 0 # can range from [0, 2pi)

# susceptibility
chi = 10 + 1j

# wavelength
lam = 0.5 # microns (values between .4-.7)

# frequency
k = (2 * np.pi)/lam # 1/microns

# volume
V_0 = (0.05)**3 # microns^3

# incoming wave vector
K = k * np.array([[0], [np.sin(theta)], [np.cos(theta)]])

# polarization vector
vecinc = np.array([[1], [0], [0]]) # (can choose any vector perpendicular to K)

# for the fixed alpha case
alpha = (V_0 * 3 * chi)/(chi + 3)

# 3 x 3 matrix
A = np.matlib.identity(3) # could be any symmetric matrix,

#-------------------------------------------------------------------

# TEST FUNCTIONS

test = G((x1-y1), k)
print(test)

w = W(x1, y1, k, alpha, A)
print(w)

Sometimes my W loops throws me the error, "can't set an array element with a sequence." But I need to set each array element in this arbitrary matrix W to the 3x3 matrix created by multiplying alpha by G...

Body:
To your question of how to create a new array with a block for each element, the following should do the trick:

G = np.random.random([3,3])
result = np.zeros([9,9])
num_blocks = 3
a = np.random.random([3,3])
b = np.random.random([3,3])
for i in range(G.shape[0]):
    for j in range(G.shape[1]):
        block_result = a*G[i,j]*b
        for k in range(num_blocks):
            for l in range(num_blocks):
                result[3*i + k, 3*j + l] = block_result[i, j]

You should be able to generalize from there. I hope I've understood correctly.

EDIT: It looks like I haven't understood correctly. I'm leaving it in hopes it spurs you to an answer. The general idea is to generate ranges of indices to operate on, and then just operate on them directly. Slicing might be helpful, too.

Ah, you asked how to create a diagonal filled with blocks. In that case:

num_diagonal_blocks = 3 # for example

for block_dim in range(num_diagonal_blocks)
    # do your block calculation...
    for k in range(G.shape[0]):
        for l in range(G.shape[1]):
            result[3*block_dim + k, 3*block_dim + l] = # assign to element of block

I think that's nearly it.


问:
What is the use of typescript when it is eventually transpiled into javascript?
I read that typescript introduces the concept of assigning the variable "a type" so that we can avoid type errors at runtime.

I tried implementing the "type" concept in VS_CODE.

This is the code i tried

```<code>//main.ts

let message = "Hello all of you!!"

console.log(message);

let message2 : string = "Welcome typescript with the concept of
'type' ";

console.log(message2);

message2 = 233;

console.log(message2);
</code>```

This is the error i got in the console.

```<code>main.ts:9:1 - error TS2322: Type '233' is not assignable to type
'string'.

9 message2 = 233;

[00:30:56] Found 1 error. Watching for file changes.
</code>```

Transpiled JS Code

```<code>//main.js
"use strict";
var message = "Hello all of you!!";
console.log(message);
var message2 = "Welcome typescript with the concept of 'type' ";
console.log(message2);
message2 = 233;
console.log(message2);
</code>```

JS Output

```<code>venkat-6805:Typescript-basics venkat-6805$ node main
Hello all of you!!
Welcome typescript with the concept of 'type'
venkat-6805:Typescript-basics venkat-6805$ node main
Hello all of you!!
Welcome typescript with the concept of 'type'
233
venkat-6805:Typescript-basics venkat-6805$ ;
</code>```

So my question is

Won't typescript stop transpilation when it finds an error?

Eventually, every typescript code is converted into JS code. Then what is the use of typescript?

答:
1) Won't typescript stop transpilation when it finds an error

If you want to prevent Typescript from transpiling when there's such an error, you should set noEmitOnError to true, in your tsconfig.json, eg:

```<code>{
  "compilerOptions": {
    "noEmitOnError": true
  }
}
</code>```

Otherwise, typing errors will not prevent the code from being transpiled.

2) Eventually, every typescript code is converted into JS code. Then what is the use of typescript

Because it's relatively easy to fix compile-time errors, but it can be much more difficult to fix runtime errors. For a particularly bad case, consider a section of code which only gets run rarely, and you forget to cast a string to a number before using + on it. So, instead of someVariable + 5 resulting in a number which gets 5 added to it, it results in a string which gets 5 concatenated to it, which is unexpected, and may eventually cause a bug later down the line. If this eventually results in an error, the ultimate source of the error may be difficult to track down. This could waste a lot of programmer's time in a large codebase, especially if the person who wrote the original code isn't the one debugging.

With Typescript, this rare runtime error is turned into a compile-time error, when you try to use a string where a number is required. This is an easy 5-second fix, which is quite an improvement.

Of course, there are other opinion-based advantages and disadvantages of Typescript (it takes some time to learn, and everyone working on the code needs to know it to use it), but this is one sort of advantage to keep in mind.

Body:
I read that typescript introduces the concept of assigning the variable "a type" so that we can avoid type errors at runtime.

I tried implementing the "type" concept in VS_CODE.

This is the code i tried

//main.ts

let message = "Hello all of you!!"

console.log(message);

let message2 : string = "Welcome typescript with the concept of
'type' ";

console.log(message2);

message2 = 233;

console.log(message2);

This is the error i got in the console.

main.ts:9:1 - error TS2322: Type '233' is not assignable to type
'string'.

9 message2 = 233;

[00:30:56] Found 1 error. Watching for file changes.

Transpiled JS Code

//main.js
"use strict";
var message = "Hello all of you!!";
console.log(message);
var message2 = "Welcome typescript with the concept of 'type' ";
console.log(message2);
message2 = 233;
console.log(message2);

JS Output

venkat-6805:Typescript-basics venkat-6805$ node main
Hello all of you!!
Welcome typescript with the concept of 'type'
venkat-6805:Typescript-basics venkat-6805$ node main
Hello all of you!!
Welcome typescript with the concept of 'type'
233
venkat-6805:Typescript-basics venkat-6805$ ;

So my question is

Won't typescript stop transpilation when it finds an error?

Eventually, every typescript code is converted into JS code. Then what is the use of typescript?

Body:
1) Won't typescript stop transpilation when it finds an error

If you want to prevent Typescript from transpiling when there's such an error, you should set noEmitOnError to true, in your tsconfig.json, eg:

{
  "compilerOptions": {
    "noEmitOnError": true
  }
}

Otherwise, typing errors will not prevent the code from being transpiled.

2) Eventually, every typescript code is converted into JS code. Then what is the use of typescript

Because it's relatively easy to fix compile-time errors, but it can be much more difficult to fix runtime errors. For a particularly bad case, consider a section of code which only gets run rarely, and you forget to cast a string to a number before using + on it. So, instead of someVariable + 5 resulting in a number which gets 5 added to it, it results in a string which gets 5 concatenated to it, which is unexpected, and may eventually cause a bug later down the line. If this eventually results in an error, the ultimate source of the error may be difficult to track down. This could waste a lot of programmer's time in a large codebase, especially if the person who wrote the original code isn't the one debugging.

With Typescript, this rare runtime error is turned into a compile-time error, when you try to use a string where a number is required. This is an easy 5-second fix, which is quite an improvement.

Of course, there are other opinion-based advantages and disadvantages of Typescript (it takes some time to learn, and everyone working on the code needs to know it to use it), but this is one sort of advantage to keep in mind.


问:
Replacing images on mouseover with only childnodes and javascript
I have to place three images side by side, and onmouseover function, when the user moves the mouse over an image , that particular image will be duplicate on the other two images. When the use moves the mouse out from the image, the image will restore as in initial page.
But I have to use childnodes for this. I'm not able to figure this out.

I've tried this following code, but it doesn't do anything.
I tried to paste the code here, but it was getting out onto the body of the message so I made this codepen where you can see it.
So far I'm only to get index[1] and index[2] pic to show up on index[0], but no other changes are happening.
https://codepen.io/anon/pen/xNjezN

```<code>function heroes(q){
    if(q.src == imgArray[0])
    {
        for(var index=0; index<images.length; index++)
        {
            images[index] = document.getElementById("legends").childNodes[index];
            images[index].src = imgArray[0];
        }
    }
    else if(q.src == imgArray[1])
    {
        for(var index=0; index<images.length; index++)
        {
            images[index] = document.getElementById("legends").childNodes[index];
            images[index].src = imgArray[1];
        }
    }
    else if(q.src == imgArray[2])
    {
        for(var index=0; index<images.length; index++)
        {
            images[index] = document.getElementById("legends").childNodes[index];
            images[index].src = imgArray[2];
        }
    }
}
</code>```

If someone can please suggest something.

答:
If this is what you want, I've just selected all img tag that you want take src from on onmouseout event. onmouseout callback function I've just replaced the mnImg.src value to current image src.

If you want replace img src on mouse over you can replace onmouseout with onmouseover.

On mouse out

let images = document.querySelectorAll('.img');
let mnImg = document.querySelector('#mnImg');

images.forEach(img => {
  img.onmouseout = function() {
    mnImg.src = this.src;
  };
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>img {
  height: 100px;
  width: 100px;
}</code>```

```
</div>
</div>
</p>

<p><strong>On mouse over</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let images = document.querySelectorAll('.img');
let mnImg = document.querySelector('#mnImg');

images.forEach(img => {
  img.onmouseover = function() {
    mnImg.src = this.src;
  };
})</code>```

img {
  height: 100px;
  width: 100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div id="legends">
    <img src="https://imagizer.imageshack.com/img921/9646/HCBvlG.jpg" id="mnImg">
    <img src="https://imagizer.imageshack.com/img924/3295/Fb6gMO.jpg" class='img'>
    <img src="https://imagizer.imageshack.com/img923/6089/01GQK7.jpg" class='img'>
  </div>
</body></code>```

Body:
I have to place three images side by side, and onmouseover function, when the user moves the mouse over an image , that particular image will be duplicate on the other two images. When the use moves the mouse out from the image, the image will restore as in initial page.
But I have to use childnodes for this. I'm not able to figure this out.

I've tried this following code, but it doesn't do anything.
I tried to paste the code here, but it was getting out onto the body of the message so I made this codepen where you can see it.
So far I'm only to get index[1] and index[2] pic to show up on index[0], but no other changes are happening.
https://codepen.io/anon/pen/xNjezN

function heroes(q){
    if(q.src == imgArray[0])
    {
        for(var index=0; index<images.length; index++)
        {
            images[index] = document.getElementById("legends").childNodes[index];
            images[index].src = imgArray[0];
        }
    }
    else if(q.src == imgArray[1])
    {
        for(var index=0; index<images.length; index++)
        {
            images[index] = document.getElementById("legends").childNodes[index];
            images[index].src = imgArray[1];
        }
    }
    else if(q.src == imgArray[2])
    {
        for(var index=0; index<images.length; index++)
        {
            images[index] = document.getElementById("legends").childNodes[index];
            images[index].src = imgArray[2];
        }
    }
}

If someone can please suggest something.

Body:
If this is what you want, I've just selected all img tag that you want take src from on onmouseout event. onmouseout callback function I've just replaced the mnImg.src value to current image src.

If you want replace img src on mouse over you can replace onmouseout with onmouseover.

On mouse out

let images = document.querySelectorAll('.img');
let mnImg = document.querySelector('#mnImg');

images.forEach(img => {
  img.onmouseout = function() {
    mnImg.src = this.src;
  };
})

img {
  height: 100px;
  width: 100px;
}

<body>
  <div id="legends">
    <img src="https://imagizer.imageshack.com/img921/9646/HCBvlG.jpg" id="mnImg">
    <img src="https://imagizer.imageshack.com/img924/3295/Fb6gMO.jpg" class='img'>
    <img src="https://imagizer.imageshack.com/img923/6089/01GQK7.jpg" class='img'>
  </div>
</body>

On mouse over

let images = document.querySelectorAll('.img');
let mnImg = document.querySelector('#mnImg');

images.forEach(img => {
  img.onmouseover = function() {
    mnImg.src = this.src;
  };
})

img {
  height: 100px;
  width: 100px;
}

<body>
  <div id="legends">
    <img src="https://imagizer.imageshack.com/img921/9646/HCBvlG.jpg" id="mnImg">
    <img src="https://imagizer.imageshack.com/img924/3295/Fb6gMO.jpg" class='img'>
    <img src="https://imagizer.imageshack.com/img923/6089/01GQK7.jpg" class='img'>
  </div>
</body>


问:
How to add customized cell in tableview when user selects cell
I want to add my customized tableviewcell in my tableview when user selects a cell I have some buttons on that customized cell and want to give user option as soon he selects a cell.

Any suggestions and guidance to move on from here?

答: Create two custom cells, one for the normal rows and other for the required row. When the user touches a particular cell, you can record it's indexPath and reload the tableView. When the cellForRowAtIndexPath is called the second time after tableView reload, you can identify the row with the flag set earlier. You can then create a new cell for it.</p>

ContentLicense: CC BY-SA 2.5


问:
Need a regex for URL check?
I need a regex for a URL string.

My URL string goes like

https colon // string dot string / string (It does not contain any space in between)

答:
Below example for BigQuery Standard SQL    </p>

```<code>#standardSQL
WITH `project.dataset.table` AS (
  SELECT 'check this link http://www.example.com/products?id=1&page=2' tweet UNION ALL
  SELECT 'http://www.example.com/products?id=1&page=2 this link is awesome' tweet UNION ALL
  SELECT 'the link http://www.example.com/products?id=1&page=2 is awesome' tweet

)
SELECT REGEXP_REPLACE(tweet, r"(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+", '') clean_tweet
FROM `project.dataset.table`
</code>```

<p>with result   </p>

```<code>Row clean_tweet
1   check this link
2   this link is awesome
3   the link is awesome
</code>```

Title: Need a regex for URL check?

Body:
Below example for BigQuery Standard SQL

#standardSQL
WITH `project.dataset.table` AS (
  SELECT 'check this link http://www.example.com/products?id=1&page=2' tweet UNION ALL
  SELECT 'http://www.example.com/products?id=1&page=2 this link is awesome' tweet UNION ALL
  SELECT 'the link http://www.example.com/products?id=1&page=2 is awesome' tweet

)
SELECT REGEXP_REPLACE(tweet, r"(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+", '') clean_tweet
FROM `project.dataset.table`

with result

Row clean_tweet
1   check this link
2   this link is awesome
3   the link is awesome


问:
Unsupported operand type error while using class variable and class method for counting instance creation
I defined my class variable "count_instance", so as to count the number of instances created with my class "Person". After initialization, I wrote the command "Person.count_instance +=1". This is so that my count_instance will increase by 1 with each new instance creation.

But when I am creating my instances (object) of my class it results in an error saying- "unsupported operand type(s) for +=: 'method' and 'int'".

Can someone please help me why is this happening? and How to fix this. I am using python 3.6

I tried to check the semantic and syntactic errors. But I couldn't fix this problem.

    class Person:
        count_instance = 0
        def __init__(self, first_name, last_name, age): # These are attributes in the bracket and init is the initialization method.
    #Instance Variable declaration
            Person.count_instance +=1
            self.first_name = first_name
            self.Last_name = last_name
            self.age = age
        @classmethod
        def count_instance(cls):
            return f"You have created {cls.count_instance} of Person Class"

        def full_name(self):
            return(f"{self.first_name} {self.last_name}")

        def is_above_18(self):
            return self.age>18

    #Creating the instances
    p1 = Person("Sara", "Kat", 18)
    p2 = Person("Pankaj", "Mishra", 26)

```

enter image description here
TypeError: unsupported operand type(s) for +=: 'method' and 'int'

答:
count_instance is both a variable and a method in your code. Use unique names for both. For instance by changing the method to print_count_instance:

```<code>class Person:
    count_instance = 0
    def __init__(self, first_name, last_name, age): # These are attributes in the bracket and init is the initialization method.
#Instance Variable declaration
        Person.count_instance +=1
        self.first_name = first_name
        self.Last_name = last_name
        self.age = age
    @classmethod
    def print_count_instance(cls):
        return f"You have created {cls.count_instance} of Person Class"

    def full_name(self):
        return(f"{self.first_name} {self.last_name}")

    def is_above_18(self):
        return self.age>18

#Creating the instances
p1 = Person("Sara", "Kat", 18)
p2 = Person("Pankaj", "Mishra", 26)

p1.print_count_instance()
</code>```

Body:
I defined my class variable "count_instance", so as to count the number of instances created with my class "Person". After initialization, I wrote the command "Person.count_instance +=1". This is so that my count_instance will increase by 1 with each new instance creation.

But when I am creating my instances (object) of my class it results in an error saying- "unsupported operand type(s) for +=: 'method' and 'int'".

Can someone please help me why is this happening? and How to fix this. I am using python 3.6

I tried to check the semantic and syntactic errors. But I couldn't fix this problem.

    class Person:
        count_instance = 0
        def __init__(self, first_name, last_name, age): # These are attributes in the bracket and init is the initialization method.
    #Instance Variable declaration
            Person.count_instance +=1
            self.first_name = first_name
            self.Last_name = last_name
            self.age = age
        @classmethod
        def count_instance(cls):
            return f"You have created {cls.count_instance} of Person Class"

        def full_name(self):
            return(f"{self.first_name} {self.last_name}")

        def is_above_18(self):
            return self.age>18

    #Creating the instances
    p1 = Person("Sara", "Kat", 18)
    p2 = Person("Pankaj", "Mishra", 26)

enter image description here
TypeError: unsupported operand type(s) for +=: 'method' and 'int'

Body:
count_instance is both a variable and a method in your code. Use unique names for both. For instance by changing the method to print_count_instance:

class Person:
    count_instance = 0
    def __init__(self, first_name, last_name, age): # These are attributes in the bracket and init is the initialization method.
#Instance Variable declaration
        Person.count_instance +=1
        self.first_name = first_name
        self.Last_name = last_name
        self.age = age
    @classmethod
    def print_count_instance(cls):
        return f"You have created {cls.count_instance} of Person Class"

    def full_name(self):
        return(f"{self.first_name} {self.last_name}")

    def is_above_18(self):
        return self.age>18

#Creating the instances
p1 = Person("Sara", "Kat", 18)
p2 = Person("Pankaj", "Mishra", 26)

p1.print_count_instance()


问:
Fit image inside as background button when button is clicked
When input type file is clicked, I want to show the selected image as background of the button.

But the following code doesn't fit(cover) the image inside the button after the image is selected.

Html

input#file {
  display: inline-block;
  box-shadow: 0 0 5px rgb(0, 0, 0, 0.3);
  width: 100%;
  padding: 400px 0 0 0;
  overflow: hidden;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  border-radius: 20px;
  background-size: 60px 60px;
  cursor: pointer;
  border: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type='file' id="file" (change)="onSelectFile($event)" class="form-control btn btn-primary" [ngStyle]="{'background': 'url(' + imageURL + ') center center no-repeat #e4e4e4'}"></code>```

Component

```<code>onSelectFile(event) {
  if (event.target.files && event.target.files[0]) {
    var reader = new FileReader();

    reader.readAsDataURL(event.target.files[0]);

    reader.onload = (event) => {
      this.imageURL = event.target.result;
    }
  }
}
</code>```

答:
background style you used in input overwrote the background-size as center center.
You should use the following code to set the background-size: cover.

```<code>[ngStyle]="{'background': 'url(' + imageURL + ') center center / cover no-repeat #e4e4e4'}"
</code>```

Body:
When input type file is clicked, I want to show the selected image as background of the button.

But the following code doesn't fit(cover) the image inside the button after the image is selected.

Html

input#file {
  display: inline-block;
  box-shadow: 0 0 5px rgb(0, 0, 0, 0.3);
  width: 100%;
  padding: 400px 0 0 0;
  overflow: hidden;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  border-radius: 20px;
  background-size: 60px 60px;
  cursor: pointer;
  border: none;
}

<input type='file' id="file" (change)="onSelectFile($event)" class="form-control btn btn-primary" [ngStyle]="{'background': 'url(' + imageURL + ') center center no-repeat #e4e4e4'}">

Component

onSelectFile(event) {
  if (event.target.files && event.target.files[0]) {
    var reader = new FileReader();

    reader.readAsDataURL(event.target.files[0]);

    reader.onload = (event) => {
      this.imageURL = event.target.result;
    }
  }
}

Body:
background style you used in input overwrote the background-size as center center.
You should use the following code to set the background-size: cover.

[ngStyle]="{'background': 'url(' + imageURL + ') center center / cover no-repeat #e4e4e4'}"


问:
Detect Enter key is pressed with jQuery
I have a text field which is showing a value. What I want is when the user writes a new value in that text field and presses enter, an ajax function is triggered to do a pagination operation. I have a text field like this:

```<code><input type="text" id="page" name="page" value="<?php echo($this->pn);?> />
</code>```

And when a user writes any new value and presses enter, I want the following ajax function triggered:

```
update_ajax2({rpp:<?php echo($this->rpp);?>,pn:document.page.paged.value,filter:'<?php echo($this->filter);?>',orderby:'<?php echo($this->orderby);?>'});
```

I tried using the keypress event to detect if(e.which===13) but this doesn't solve the problem. Can anyone guide me?

答:
Key pressed event should work try it</p>

```<code>function keyPressedTest(a)
{
    a=(a)?a:window.event;
    input=(a.target)?a.target:a.srcElement;
    if(a.keyCode==13)
    {
        your_function()
    }
}
</code>```

Title: Detect Enter key is pressed with jQuery

Body:
I have a text field which is showing a value. What I want is when the user writes a new value in that text field and presses enter, an ajax function is triggered to do a pagination operation. I have a text field like this:

<input type="text" id="page" name="page" value="<?php echo($this->pn);?> />

And when a user writes any new value and presses enter, I want the following ajax function triggered:

update_ajax2({rpp:<?php echo($this->rpp);?>,pn:document.page.paged.value,filter:'<?php echo($this->filter);?>',orderby:'<?php echo($this->orderby);?>'});

I tried using the keypress event to detect if(e.which===13) but this doesn't solve the problem. Can anyone guide me?

Body:
Key pressed event should work try it

function keyPressedTest(a)
{
    a=(a)?a:window.event;
    input=(a.target)?a.target:a.srcElement;
    if(a.keyCode==13)
    {
        your_function()
    }
}


问:
What does the following vector declaration means vector<vector<int>>v(100)?
How can I assign single size to a 2d vector?
Also what does this imply?</p>

答:
v is declared to be a vector whose element type is vector<int>, and initialized to contain 100 such elements - all empty vectors. In other words, v.size() == 100, v[i].size() == 0 (for i from 0 through 99).

If you want to initialize v to contain 100 vectors, each of which contains 100 ints, you can do it this way:

```<code>std::vector<std::vector<int>> v{100, std::vector<int>{100}};
</code>```

Body:
v is declared to be a vector whose element type is vector<int>, and initialized to contain 100 such elements - all empty vectors. In other words, v.size() == 100, v[i].size() == 0 (for i from 0 through 99).

If you want to initialize v to contain 100 vectors, each of which contains 100 ints, you can do it this way:

std::vector<std::vector<int>> v{100, std::vector<int>{100}};


问:
Get 2 parameters from a returning fuction (tuple) in python
I'm having difficulty getting two parameters returned from a function as a tuple:

```<code>>>> ir7(41,7)

(966, 1023, 571, 396, 105, 2, 3)
</code>```

If I want to get specified tuple I use this:

```<code> >>> ir7(41,7)[0]

966
</code>```

but what if I want to get 1st, 3rd and 4th element from the tuple. What is the correct syntax? Something like:

```<code>a,b,c= ir7(41,7)[1][3][4]
</code>```

答:
You could introduce slicing to slim the result down before assigning values as well:

```<code>a, _, b, c = ir7(41, 7)[1:4]
</code>```

Even better you could use operator.itemgetter

```<code>from operator import itemgetter

a, b, c = itemgetter(1,3,4)(ir7(41, 7))
</code>```

Body:
I'm having difficulty getting two parameters returned from a function as a tuple:

>>> ir7(41,7)

(966, 1023, 571, 396, 105, 2, 3)

If I want to get specified tuple I use this:

 >>> ir7(41,7)[0]

966

but what if I want to get 1st, 3rd and 4th element from the tuple. What is the correct syntax? Something like:

a,b,c= ir7(41,7)[1][3][4]

Body:
You could introduce slicing to slim the result down before assigning values as well:

a, _, b, c = ir7(41, 7)[1:4]

Even better you could use operator.itemgetter

from operator import itemgetter

a, b, c = itemgetter(1,3,4)(ir7(41, 7))


问:
Replace '-' with space if the next charcter is a letter not a digit and remove when it is at the start
I have a list of string i.e.

```<code>slist = ["-args", "-111111", "20-args", "20 - 20", "20-10", "args-deep"]
</code>```

I want to remove the '-' from string where it is the first character and is followed by strings but not numbers or if before the '-' there is number/alphabet but after it is alphabets, then it should replace the '-' with space

So for the list slist I want the output as

```<code>["args", "-111111", "20 args", "20 - 20", "20-10", "args deep"]
</code>```

I have tried

```<code>slist = ["-args", "-111111", "20-args", "20 - 20", "20-10", "args-deep"]
nlist = list()
for estr in slist:
    nlist.append(re.sub("((^-[a-zA-Z])|([0-9]*-[a-zA-Z]))", "", estr))
print (nlist)
</code>```

and i get the output

```<code>['rgs', '-111111', 'rgs', '20 - 20', '20-10', 'argseep']
</code>```

答:
You may use

```<code>nlist.append(re.sub(r"-(?=[a-zA-Z])", " ", estr).lstrip())
</code>```

or

```<code>nlist.append(re.sub(r"-(?=[^\W\d_])", " ", estr).lstrip())
</code>```

Result: ['args', '-111111', '20 args', '20 - 20', '20-10', 'args deep']

See the Python demo.

The -(?=[a-zA-Z]) pattern matches a hyphen before an ASCII letter (-(?=[^\W\d_]) matches a hyphen before any letter), and replaces the match with a space. Since - may be matched at the start of a string, the space may appear at that position, so .lstrip() is used to remove the space(s) there.

Body:
I have a list of string i.e.

slist = ["-args", "-111111", "20-args", "20 - 20", "20-10", "args-deep"]

I want to remove the '-' from string where it is the first character and is followed by strings but not numbers or if before the '-' there is number/alphabet but after it is alphabets, then it should replace the '-' with space

So for the list slist I want the output as

["args", "-111111", "20 args", "20 - 20", "20-10", "args deep"]

I have tried

slist = ["-args", "-111111", "20-args", "20 - 20", "20-10", "args-deep"]
nlist = list()
for estr in slist:
    nlist.append(re.sub("((^-[a-zA-Z])|([0-9]*-[a-zA-Z]))", "", estr))
print (nlist)

and i get the output

['rgs', '-111111', 'rgs', '20 - 20', '20-10', 'argseep']

Body:
You may use

nlist.append(re.sub(r"-(?=[a-zA-Z])", " ", estr).lstrip())

or

nlist.append(re.sub(r"-(?=[^\W\d_])", " ", estr).lstrip())

Result: ['args', '-111111', '20 args', '20 - 20', '20-10', 'args deep']

See the Python demo.

The -(?=[a-zA-Z]) pattern matches a hyphen before an ASCII letter (-(?=[^\W\d_]) matches a hyphen before any letter), and replaces the match with a space. Since - may be matched at the start of a string, the space may appear at that position, so .lstrip() is used to remove the space(s) there.


问:
How can I do an SQL pivot putting all results in 1 row per record?
I have a table with a list of Customers (just their IDs) in one column, and then a list of Artists they like in another column, for example;

```<code>12345 Creed
12345 Evanescence
12345 Linkin Park
22556 Creed
22556 Foo Fighters
33485 Foo Fighters
</code>```

I have created a Pivot using dynamic column headers (for the Artist) as although there is a set list for them to pick from, this could change and I don't want to have to keep updating the code every time there is a change (I want an easy life like the rest of us!)

What I want the Pivot to display is 1 row per Customer, to show which Artists they like.

However when I run the below PIVOT the results return more than 1 row per Customer for those Customers that have listed more than 1 Artist, like this:

```<code>CustomerID  Creed  Evanescence  Foo Fighters  Linkin Park
12345       Creed
12345              Evanescence
12345                                         Linkin Park
22556       Creed
22556                           Foo Fighters
33485                           Foo Fighters
</code>```

What I want:

```<code>CustomerID  Creed  Evanescence  Foo Fighters  Linkin Park
12345       Creed  Evanescence                Linkin Park
22556       Creed               Foo Fighters
33485                           Foo Fighters
</code>```

T-SQL

```<code>--Declare variables
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)

--Get distinct values of the PIVOT Column
SELECT @ColumnName= ISNULL(@ColumnName + ',','')
       + QUOTENAME([Artist])
FROM (SELECT DISTINCT [Artist] FROM ##TEMP_CustomerWithArtists) AS Artists

--Prepare the PIVOT query using the dynamic
SET @DynamicPivotQuery =
  N'SELECT DISTINCT CustomerID, ' + @ColumnName + '
    FROM ##TEMP_CustomerWithArtists
    PIVOT(MAX(Artist)
          FOR [Artist] IN (' + @ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery
</code>```

答:
The SELECT DISTINCT is not needed in the outer query.

This problem occurs when the underlying table has additional columns.  You don't mention any, but try this:

```<code>SET @DynamicPivotQuery = N'
SELECT CustomerID, ' + @ColumnName + '
FROM (SELECT DISTINCT CustomerID, Artist
      FROM ##TEMP_CustomerWithArtists cwa
     ) cwa
PIVOT(MAX(Artist)
      FOR [Artist] IN (' + @ColumnName + ')
     ) AS PVTTable';
</code>```

This behavior is one of the reasons I don't like the PIVOT syntax.

Body:
I have a table with a list of Customers (just their IDs) in one column, and then a list of Artists they like in another column, for example;

12345 Creed
12345 Evanescence
12345 Linkin Park
22556 Creed
22556 Foo Fighters
33485 Foo Fighters

I have created a Pivot using dynamic column headers (for the Artist) as although there is a set list for them to pick from, this could change and I don't want to have to keep updating the code every time there is a change (I want an easy life like the rest of us!)

What I want the Pivot to display is 1 row per Customer, to show which Artists they like.

However when I run the below PIVOT the results return more than 1 row per Customer for those Customers that have listed more than 1 Artist, like this:

CustomerID  Creed  Evanescence  Foo Fighters  Linkin Park
12345       Creed
12345              Evanescence
12345                                         Linkin Park
22556       Creed
22556                           Foo Fighters
33485                           Foo Fighters

What I want:

CustomerID  Creed  Evanescence  Foo Fighters  Linkin Park
12345       Creed  Evanescence                Linkin Park
22556       Creed               Foo Fighters
33485                           Foo Fighters

T-SQL

--Declare variables
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)

--Get distinct values of the PIVOT Column
SELECT @ColumnName= ISNULL(@ColumnName + ',','')
       + QUOTENAME([Artist])
FROM (SELECT DISTINCT [Artist] FROM ##TEMP_CustomerWithArtists) AS Artists

--Prepare the PIVOT query using the dynamic
SET @DynamicPivotQuery =
  N'SELECT DISTINCT CustomerID, ' + @ColumnName + '
    FROM ##TEMP_CustomerWithArtists
    PIVOT(MAX(Artist)
          FOR [Artist] IN (' + @ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery

Body:
The SELECT DISTINCT is not needed in the outer query.

This problem occurs when the underlying table has additional columns.  You don't mention any, but try this:

SET @DynamicPivotQuery = N'
SELECT CustomerID, ' + @ColumnName + '
FROM (SELECT DISTINCT CustomerID, Artist
      FROM ##TEMP_CustomerWithArtists cwa
     ) cwa
PIVOT(MAX(Artist)
      FOR [Artist] IN (' + @ColumnName + ')
     ) AS PVTTable';

This behavior is one of the reasons I don't like the PIVOT syntax.


问:
display files and dir in linux as graphic mode
how to display the directories and files in graphic way

I forget the command in linux but some linux command can displayed from root directories the recursive directories like this

root

```<code>|
</code>```

sbin  etc   var ...

```<code>|   |     |

dir dir dir dir ........

|   |   |   |
|   |   |   |
</code>```

答:
For an output like

```<code>|-root
|---dir00
|-----dir01
|---dir01
</code>```

Try this

Body:
how to display the directories and files in graphic way

I forget the command in linux but some linux command can displayed from root directories the recursive directories like this

root

|

sbin  etc   var ...

|   |     |

dir dir dir dir ........

|   |   |   |
|   |   |   |

Body:
For an output like

|-root
|---dir00
|-----dir01
|---dir01

Try this


问:
Access JSP file Inside Fat Jar
I have spring boot app which creates fat jar and the exploded version of the fat as below,

/META-INF/resources/index.jsp as per the below,

Spring Boot Executable jar structure

i tried to access the prefix in application.properties,

```<code>spring.mvc.view.prefix = /WEB-INF/resources/ - No luck
spring.mvc.view.prefix = /META-INF/resources/  - No luck
spring.mvc.view.prefix = /resources/ - No luck
</code>```

So what could be the correct prefix for this one? Thanks in advance!

答:
Make sure you have maven plugin configured to be executable.

```<code><plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <executable>true</executable>
    </configuration>
</plugin>
</code>```

And to run this war file in a docker container, just run it like it's just a jar file. In your Dockerfile, use your war's name:

```<code>ENTRYPOINT exec java -jar /my_project.war
</code>```

Title: Access JSP file Inside Fat Jar

Body:
I have spring boot app which creates fat jar and the exploded version of the fat as below,

/META-INF/resources/index.jsp as per the below,

Spring Boot Executable jar structure

i tried to access the prefix in application.properties,

spring.mvc.view.prefix = /WEB-INF/resources/ - No luck
spring.mvc.view.prefix = /META-INF/resources/  - No luck
spring.mvc.view.prefix = /resources/ - No luck

So what could be the correct prefix for this one? Thanks in advance!

Body:
Make sure you have maven plugin configured to be executable.

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <executable>true</executable>
    </configuration>
</plugin>

And to run this war file in a docker container, just run it like it's just a jar file. In your Dockerfile, use your war's name:

ENTRYPOINT exec java -jar /my_project.war