问:
Oracle error at dbms_utility
The problem occurred when I tried to create a database user with more than 30 characters and then to create a trigger in that (within one script). The user wasn't created as it had more than 30 chars, but somehow the trigger got created. Now I'm not able to login to the database anymore and throws the below exception when my java application tries to connect to this database.

```<code> Caused by: java.sql.SQLException: Cannot create PoolableConnectionFactory
 (ORA-00604: error occurred at recursive SQL level 1
 ORA-00972: identifier is too long
ORA-06512: at "SYS.DBMS_UTILITY", line 833
ORA-06512: at "SYS.DBMS_SESSION", line 230
ORA-06512: at line 2
)
    at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:2303)
    at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2043)
    at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1543)
    at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:139)
    at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:380)
    at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:228)
    ... 95 more
Caused by: java.sql.SQLException: ORA-00604: error occurred at recursive SQL
level 1
ORA-00972: identifier is too long
ORA-06512: at "SYS.DBMS_UTILITY", line 833
ORA-06512: at "SYS.DBMS_SESSION", line 230
ORA-06512: at line 2

    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:445)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:389)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:382)
    at oracle.jdbc.driver.T4CTTIfun.processError(T4CTTIfun.java:600)
    at oracle.jdbc.driver.T4CTTIoauthenticate.processError(T4CTTIoauthenticate.java:445)
    at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:450)
    at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:192)
    at oracle.jdbc.driver.T4CTTIoauthenticate.doOAUTH(T4CTTIoauthenticate.java:380)
    at oracle.jdbc.driver.T4CTTIoauthenticate.doOAUTH(T4CTTIoauthenticate.java:760)
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:401)
    at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:546)
    at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:236)
    at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
    at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:521)
    at org.apache.tomcat.dbcp.dbcp2.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:38)
    at org.apache.tomcat.dbcp.dbcp2.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:257)
    at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.validateConnectionFactory(BasicDataSource.java:2313)
    at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:2299)
</code>```

How can this trigger can be deleted or any other ways to rectify this problem?

Script that I executed: (but instead of TESTDB, I previously had more than 30 chars)

```<code>-- USER SQL
CREATE USER TESTDB IDENTIFIED BY nodba ;

-- ROLES

GRANT "CONNECT" TO TESTDB ;

-- SYSTEM PRIVILEGES
GRANT SELECT ANY TABLE TO TESTDB ;
GRANT SELECT ANY SEQUENCE TO TESTDB ;
GRANT SELECT ANY TRANSACTION TO TESTDB ;
GRANT UPDATE ANY TABLE TO TESTDB ;
GRANT INSERT ANY TABLE TO TESTDB ;
GRANT DELETE ANY TABLE TO TESTDB ;

create role TestRole;

grant TestRole to TESTDB;

ALTER SESSION SET CURRENT_SCHEMA = TESTDB;

create or replace trigger readonly_logon_trigger
after logon on database
begin
if (dbms_session.is_role_enabled('TestRole')) then
 execute immediate 'alter session set current_schema = MAINDB';
end if;
end;
</code>```

答: The trigger was added at the system level with more than 30 characters that was causing this problem. It's resolved now.</p>

Title: Oracle error at dbms_utility

Body:
The problem occurred when I tried to create a database user with more than 30 characters and then to create a trigger in that (within one script). The user wasn't created as it had more than 30 chars, but somehow the trigger got created. Now I'm not able to login to the database anymore and throws the below exception when my java application tries to connect to this database.

 Caused by: java.sql.SQLException: Cannot create PoolableConnectionFactory
 (ORA-00604: error occurred at recursive SQL level 1
 ORA-00972: identifier is too long
ORA-06512: at "SYS.DBMS_UTILITY", line 833
ORA-06512: at "SYS.DBMS_SESSION", line 230
ORA-06512: at line 2
)
    at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:2303)
    at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2043)
    at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1543)
    at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:139)
    at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:380)
    at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:228)
    ... 95 more
Caused by: java.sql.SQLException: ORA-00604: error occurred at recursive SQL
level 1
ORA-00972: identifier is too long
ORA-06512: at "SYS.DBMS_UTILITY", line 833
ORA-06512: at "SYS.DBMS_SESSION", line 230
ORA-06512: at line 2

    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:445)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:389)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:382)
    at oracle.jdbc.driver.T4CTTIfun.processError(T4CTTIfun.java:600)
    at oracle.jdbc.driver.T4CTTIoauthenticate.processError(T4CTTIoauthenticate.java:445)
    at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:450)
    at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:192)
    at oracle.jdbc.driver.T4CTTIoauthenticate.doOAUTH(T4CTTIoauthenticate.java:380)
    at oracle.jdbc.driver.T4CTTIoauthenticate.doOAUTH(T4CTTIoauthenticate.java:760)
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:401)
    at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:546)
    at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:236)
    at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
    at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:521)
    at org.apache.tomcat.dbcp.dbcp2.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:38)
    at org.apache.tomcat.dbcp.dbcp2.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:257)
    at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.validateConnectionFactory(BasicDataSource.java:2313)
    at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:2299)

How can this trigger can be deleted or any other ways to rectify this problem?

Script that I executed: (but instead of TESTDB, I previously had more than 30 chars)

-- USER SQL
CREATE USER TESTDB IDENTIFIED BY nodba ;

-- ROLES

GRANT "CONNECT" TO TESTDB ;

-- SYSTEM PRIVILEGES
GRANT SELECT ANY TABLE TO TESTDB ;
GRANT SELECT ANY SEQUENCE TO TESTDB ;
GRANT SELECT ANY TRANSACTION TO TESTDB ;
GRANT UPDATE ANY TABLE TO TESTDB ;
GRANT INSERT ANY TABLE TO TESTDB ;
GRANT DELETE ANY TABLE TO TESTDB ;

create role TestRole;

grant TestRole to TESTDB;

ALTER SESSION SET CURRENT_SCHEMA = TESTDB;

create or replace trigger readonly_logon_trigger
after logon on database
begin
if (dbms_session.is_role_enabled('TestRole')) then
 execute immediate 'alter session set current_schema = MAINDB';
end if;
end;


来源: stackexchange

问:
why evil regular expression will cause ReDoS?
Currently I am looking into ReDoS: Regular express denial of Service

some bad(evil) regular expression will cause low performance of validation

but why.... I search for wiki and owasp, the answer is mainly for NFA DFA that I could hardly understand....

Could anyone help me with some good sample of explaination....?

答:
It's called Catastrophic Backtracking.

It occurs when there's no match, but there are O(2n) ways to not match that must all be explored before returning false.

The example in the linked article from https://www.regular-expressions.info is (x+x+)+y, which when used with input of xxxxxxxxxx will take about 2500 steps to discover there's no match. Add one x and it takes 5000 steps, and so on. With input of 100 xs, you're talking billions of years of computing time.

The reason is there are m ways that x+x+ can match m xs and there are n / m ways that (x+x+) can be repeated over n xs and m can be an arbitrary number less than n. The exploration tree is like a binary tree of ways of carving up the input, leading to the time complexity of O(2n).

ContentLicense: CC BY-SA 3.0


问:
Password-Box not showing any content
I have a small websolution that needs the user to input a password. I have two input boxes

```<code><input type="password" runat="server" id="m_txtPassword1"/>
</code>```

If I set some chars to the Value-property of the control like this:

```<code>m_txtPassword1.Value="someChars";
</code>```

The password box is rendered empty. No bullets are shown. If I look into the rendered html-source, also no value-tag has been rendered. If I change the type to

```<code><input type="text" runat="server" id="m_txtPassword1"/>
</code>```

the chars are shown. Is this by design? How can I disable this feature?

Please note, I don't want to put a real password into the value-property, I only want to show the user that there is already a password set, and this is IMO done best with some 8 bullets in the input-control. But for this, I need the possibility to set the value-property of the control.

Update

For all, having the same problem: I have tried to declare <asp:textbox id="m_txtPassword1" runat="server" TextMode="Password" /> with the same result. Also m_txtPassword1.Attributes["value"]="someChars" has not helped.

It seems that this is realy not possible.

As a workaround, I declared the password-boxes as plain html without the runat="server" and have set the value-property in markup (via two properties from the code-behind). Not nice but I really want to show the user that he has already entered a password.

Another workaround would be to set the value through javascript on load.

ContentLicense: CC BY-SA 2.5

Title: Password-Box not showing any content

Body:
I have a small websolution that needs the user to input a password. I have two input boxes

<input type="password" runat="server" id="m_txtPassword1"/>

If I set some chars to the Value-property of the control like this:

m_txtPassword1.Value="someChars";

The password box is rendered empty. No bullets are shown. If I look into the rendered html-source, also no value-tag has been rendered. If I change the type to

<input type="text" runat="server" id="m_txtPassword1"/>

the chars are shown. Is this by design? How can I disable this feature?

Please note, I don't want to put a real password into the value-property, I only want to show the user that there is already a password set, and this is IMO done best with some 8 bullets in the input-control. But for this, I need the possibility to set the value-property of the control.

Update

For all, having the same problem: I have tried to declare <asp:textbox id="m_txtPassword1" runat="server" TextMode="Password" /> with the same result. Also m_txtPassword1.Attributes["value"]="someChars" has not helped.

It seems that this is realy not possible.

As a workaround, I declared the password-boxes as plain html without the runat="server" and have set the value-property in markup (via two properties from the code-behind). Not nice but I really want to show the user that he has already entered a password.

Another workaround would be to set the value through javascript on load.

Body: Textbox11.Attributes.Add("Value",whatever_your_password_is)


问:
How to build with CMake to both release config and verbose
I am trying to build with CMake and to pass both options: config: Release and VERBOSE=ON:

```<code>cmake --build . --config Release -- VERBOSE=ON
</code>```

And in CMake of Visual I have the switch:

```<code>cmake -G "Visual Studio 14 2015"
-DCMAKE_VERBOSE_MAKEFILE:BOOL=ON ^
</code>```

if I pass only '--config Release' it works.

Now it's failing with this message:

```<code>15:40:51 MSBUILD : error MSB1008: Only one project can be specified.
15:40:51 Switch: VERBOSE=1
15:40:51
15:40:51 For switch syntax, type "MSBuild /help"
</code>```

答:
VERBOSE=ON is not understood by MSBuild.

You probably know that syntax from Unix Makefile generators, where setting eg. the VERBOSE environment variable will give you the verbose output. Note that this is a feature of the generator (ie. make) and not of CMake. Thus when switching to a different generator (in this case MSBuild), you have to find a different way to get the verbose output that works with that generator.

For MSBuild, that would be the /verbosity option. See also this answer for details.

As for the CMAKE_VERBOSE_MAKEFILE option, the manual clearly states that this option only has an effect for Makefile generators (emphasis added by me):

Users may enable the option in their local build tree to get more
  verbose output from Makefile builds and show each command line as it
  is launched.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to build with CMake and to pass both options: config: Release and VERBOSE=ON:

cmake --build . --config Release -- VERBOSE=ON

And in CMake of Visual I have the switch:

cmake -G "Visual Studio 14 2015"
-DCMAKE_VERBOSE_MAKEFILE:BOOL=ON ^

if I pass only '--config Release' it works.

Now it's failing with this message:

15:40:51 MSBUILD : error MSB1008: Only one project can be specified.
15:40:51 Switch: VERBOSE=1
15:40:51
15:40:51 For switch syntax, type "MSBuild /help"


问:
Multiple upload using Laravel Storage
I was try to upload multiple files using Storage so here's my code:

```<code>public function store(Request $request)
{
    $gallery  = new Gallery();
    $gallery->name = $request->name;
    $gallery->description = $request->description;
    $gallery->save();

    $path = 'public'.'/'.str_slug($request->name);
    Storage::makeDirectory(str_slug($request->name));

    $image = new Image();
    if ( is_array($request->images)) {
        foreach ($request->images as $file) {
            $image->gallery_id = $gallery->id;
            $image->name = $file->getClientOriginalName();
            $image->extension = $file->extension();
            $image->save();
            Storage::putFileAs($path, $file);
        }
    } else {
            $image->gallery_id = $gallery->id;
            $image->name = $request->images->getClientOriginalName();
            $image->save();
    }
}
</code>```

and I already setup my form like this:

```<code><div class="form-group">
    <label for="images" class="col-md-2 control-label">Images</label>
    <div class="col-md-6">
        <input type="file" class="form-control" name="images[]" id="images[]" multiple>
    </div>
</div>
</code>```

it give me an errors like this:

"Type error: Too few arguments to function Illuminate\Filesystem\FilesystemAdapter::putFileAs(), 2 passed in E:\laragon\www\blog\vendor\laravel\framework\src\Illuminate\Filesystem\FilesystemManager.php on line 343 and at least 3 expected ◀"

so the problem is it the way I check that it has multiple file using is_array is right? and the second what can cause this problems?

答:
Pass the 3rd argument to the putFileAs method

```<code>if( is_array($request->images)){
    foreach ($request->images as $file) {
        $image = new Image();
        $image->gallery_id = $gallery->id;
        $image->name = $file->getClientOriginalName();
        $image->extension = $file->extension();
        $image->size = 555;
        $image->save();

        // Or any custom name as the third argument
        Storage::putFileAs($path, $file, $file->getClientOriginalName());
    }
} else {
        $image = new Image();
        $image->gallery_id = $gallery->id;
        $image->name = $request->images->getClientOriginalName();;
        $image->save();

        // Or any custom name as the third argument
        Storage::putFileAs($path, $request->images, $request->images->getClientOriginalName());
}
return back();
</code>```

Documentation

Title: Multiple upload using Laravel Storage

Body:
I was try to upload multiple files using Storage so here's my code:

public function store(Request $request)
{
    $gallery  = new Gallery();
    $gallery->name = $request->name;
    $gallery->description = $request->description;
    $gallery->save();

    $path = 'public'.'/'.str_slug($request->name);
    Storage::makeDirectory(str_slug($request->name));

    $image = new Image();
    if ( is_array($request->images)) {
        foreach ($request->images as $file) {
            $image->gallery_id = $gallery->id;
            $image->name = $file->getClientOriginalName();
            $image->extension = $file->extension();
            $image->save();
            Storage::putFileAs($path, $file);
        }
    } else {
            $image->gallery_id = $gallery->id;
            $image->name = $request->images->getClientOriginalName();
            $image->save();
    }
}

and I already setup my form like this:

    Images

        <input type="file" class="form-control" name="images[]" id="images[]" multiple>

it give me an errors like this:

"Type error: Too few arguments to function Illuminate\Filesystem\FilesystemAdapter::putFileAs(), 2 passed in E:\laragon\www\blog\vendor\laravel\framework\src\Illuminate\Filesystem\FilesystemManager.php on line 343 and at least 3 expected ◀"

so the problem is it the way I check that it has multiple file using is_array is right? and the second what can cause this problems?

Body:
Pass the 3rd argument to the putFileAs method

if( is_array($request->images)){
    foreach ($request->images as $file) {
        $image = new Image();
        $image->gallery_id = $gallery->id;
        $image->name = $file->getClientOriginalName();
        $image->extension = $file->extension();
        $image->size = 555;
        $image->save();

        // Or any custom name as the third argument
        Storage::putFileAs($path, $file, $file->getClientOriginalName());
    }
} else {
        $image = new Image();
        $image->gallery_id = $gallery->id;
        $image->name = $request->images->getClientOriginalName();;
        $image->save();

        // Or any custom name as the third argument
        Storage::putFileAs($path, $request->images, $request->images->getClientOriginalName());
}
return back();

Documentation


问:
Null values when loading in multiple JSON objects in single line file into PySpark
I need some help with getting a series of JSON files from an S3 bucket into a PySpark DataFrame.

The files in this bucket all have a .json extension, but unfortunately do not adhere to the usual Spark requirement of having one JSON object per line, and instead, they are all on one line inside square brackets.

So instead of:

```<code>{"first_column": 12, "second_column": {"nested_column": "value"}}
{"first_column": 24, "second_column": {"nested_column": "value2"}}
</code>```

I have:

```<code>[{"first_column": 12, "second_column": {"nested_column": "value"}},{"first_column": 24, "second_column": {"nested_column": "value2"}}]
</code>```

We actually receive the files in this format, and there are so many of them, that it is not feasible to make any manual adjustments unfortunately.

The approaches that I have tried so far are as follows:

I've tried to use the spark.read.json method, using the following syntax with the wildcard * to load in multiple files at once. In this case spark is the sqlContext

```<code>df = spark.read.json("s3://path_to_bucket_*.json")
</code>```

This runs without raising any errors or warnings, and returns the desired schema:

```<code>df.printSchema()

root
 |-- first_column: long (nullable = true)
 |-- second_column: struct (nullable = true)
 |     |-- nested_column: string (nullable = true)
</code>```

However, when I try to view the data I get the following:

```<code>+------------+-------------+
|first_column|second_column|
+------------+-------------+
|        null|         null|
+------------+-------------+
</code>```

I have found a way of actually loading the data in from Databricks here which uses a Spark context sc to read in a Paired RDD as follows:

```<code>dfRDD = sc.wholeTextFiles("s3://path_to_bucket_*.json")
</code>```

This returns a PairedRDD with the filename, and the file body. However, what is not really confusing me is that when I call the following line using the body information from this RDD, it works fine and there are no null values at all:

```<code>df = spark.read.json(dfRDD.map(lambda x: x[1]))
</code>```

So, I am very confused as to why this is happening, as I would have thought that this was the same information being fed into the function as the body of the text in the RDD does not contain any line breaks, and instead contains JSON objects within square brackets (like the second example I showed above).

While this is a workaround, it is unfortunately lacking; first of all, it is much slower to use the RDD method, and more importantly, I need to get a column of the name of the file where I got this information from. I know that this is possible using the input_file_name function from the pyspark.sql.functions module when loading straight in from the files, but this does not work when using the RDD method. I have managed to write a pure Python function that gets the filename information from the first element of each pairedRDD into the JSON string, but this is painfully slow.

If anyone can help me out with this I would be very grateful. I appreciate that I might have to use the RDD method, but I am confused as to why the spark.read.json works perfectly in the one situation, and not the other.

答:
Although I am not sure what caused one solution to work and another not, I was able to solve the problem to some extent by only using sql.read.json.

Set parameters allowComments, allowUnquotedFieldNames, allowSingleQuotes, allowNumericLeadingZero, allowBackslashEscapingAnyCharacter in read.json as True. By this, I was able to remove null values and 90 % of the data was converted successfully in a dataframe without any null values.

Check out other parameters here

Body:
I need some help with getting a series of JSON files from an S3 bucket into a PySpark DataFrame.

The files in this bucket all have a .json extension, but unfortunately do not adhere to the usual Spark requirement of having one JSON object per line, and instead, they are all on one line inside square brackets.

So instead of:

{"first_column": 12, "second_column": {"nested_column": "value"}}
{"first_column": 24, "second_column": {"nested_column": "value2"}}

I have:

[{"first_column": 12, "second_column": {"nested_column": "value"}},{"first_column": 24, "second_column": {"nested_column": "value2"}}]

We actually receive the files in this format, and there are so many of them, that it is not feasible to make any manual adjustments unfortunately.

The approaches that I have tried so far are as follows:

I've tried to use the spark.read.json method, using the following syntax with the wildcard * to load in multiple files at once. In this case spark is the sqlContext

df = spark.read.json("s3://path_to_bucket_*.json")

This runs without raising any errors or warnings, and returns the desired schema:

df.printSchema()

root
 |-- first_column: long (nullable = true)
 |-- second_column: struct (nullable = true)
 |     |-- nested_column: string (nullable = true)

However, when I try to view the data I get the following:

+------------+-------------+
|first_column|second_column|
+------------+-------------+
|        null|         null|
+------------+-------------+

I have found a way of actually loading the data in from Databricks here which uses a Spark context sc to read in a Paired RDD as follows:

dfRDD = sc.wholeTextFiles("s3://path_to_bucket_*.json")

This returns a PairedRDD with the filename, and the file body. However, what is not really confusing me is that when I call the following line using the body information from this RDD, it works fine and there are no null values at all:

df = spark.read.json(dfRDD.map(lambda x: x[1]))

So, I am very confused as to why this is happening, as I would have thought that this was the same information being fed into the function as the body of the text in the RDD does not contain any line breaks, and instead contains JSON objects within square brackets (like the second example I showed above).

While this is a workaround, it is unfortunately lacking; first of all, it is much slower to use the RDD method, and more importantly, I need to get a column of the name of the file where I got this information from. I know that this is possible using the input_file_name function from the pyspark.sql.functions module when loading straight in from the files, but this does not work when using the RDD method. I have managed to write a pure Python function that gets the filename information from the first element of each pairedRDD into the JSON string, but this is painfully slow.

If anyone can help me out with this I would be very grateful. I appreciate that I might have to use the RDD method, but I am confused as to why the spark.read.json works perfectly in the one situation, and not the other.


问:
AWS DynamoDB data with and/or without types?
I'm using the aws-sdk for NodeJS to interact with a DynamoDB table. This is my first look at DynamoDB.

When using a call like getItem() or updateItem(), the data structure includes types, like this:

```<code>{
  'a': { S: 'My string' }
}
</code>```

Is there any way to pass and receive these objects without the types..? So...

```<code>{
  'a': 'My string'
}
</code>```

Or, any helper functions already written that will convert objects to and from this format..?

```<code>const data = dbToObj({ 'a': { S: 'My string' } })
// { 'a': 'My string' }
</code>```

So I could convert to it when populating call params, and convert from it when receiving data.

Trying to avoid accessing my data like:

```<code>const myData = data.Item.something.M.somethinElse.M.qwerty.S
</code>```

I know I could write something myself, just wondering if anyone knows of functions/options already available that would do this. I couldn't find any.

答:
Found this:

https://github.com/kayomarz/dynamodb-data-types

https://www.npmjs.com/package/dynamodb-data-types

Exactly what I was looking for.

Install: npm i dynamodb-data-types

Provides wrap({ 'a': 'My string' }) and unwrap({ 'a': { S: 'My string' } }) methods for doing the conversion to and from plain objects.

UPDATE

I've now also found this: AWS.DynamoDB.DocumentClient, which is part of the aws-sdk.

The document client simplifies working with items in Amazon DynamoDB by abstracting away the notion of attribute values. This abstraction annotates native JavaScript types supplied as input parameters, as well as converts annotated response data to native JavaScript types.

UPDATE 2

This is being worked on by Amazon under their awslabs github page:

Amazon DynamoDB Automarshaller

This library provides a Marshaller class that converts native JavaScript values to DynamoDB AttributeValues and back again. It's designed to work with ES6 features like sets, maps, and iterables, and can be configured to support data types only supported by JavaScript (such as empty binary buffers) or by Amazon DynamoDB (such as numbers of arbitrary size) with minimal tradeoffs.

It's part of their DynamoDB DataMapper For JavaScript package.

Body:
I'm using the aws-sdk for NodeJS to interact with a DynamoDB table. This is my first look at DynamoDB.

When using a call like getItem() or updateItem(), the data structure includes types, like this:

{
  'a': { S: 'My string' }
}

Is there any way to pass and receive these objects without the types..? So...

{
  'a': 'My string'
}

Or, any helper functions already written that will convert objects to and from this format..?

const data = dbToObj({ 'a': { S: 'My string' } })
// { 'a': 'My string' }

So I could convert to it when populating call params, and convert from it when receiving data.

Trying to avoid accessing my data like:

const myData = data.Item.something.M.somethinElse.M.qwerty.S

I know I could write something myself, just wondering if anyone knows of functions/options already available that would do this. I couldn't find any.


问:
Efficient way for replace strings from a vocabulary - Python
I have a vocabulary of phrases and I want to replace words of another file by these words. For example, I have the following vocabulary:

United States,
New York

and I want to replace the following file:

"I work for New York but I don't even live at the United States"

To this:

"I work for New_York but I don't even live at the United_States"

Currently I'm doing at this way:

```<code>import os

def _check_files_and_write_phrases(docs, worker_num):
    print("worker ", worker_num," started!")
    for i, file in enumerate(docs):
        file_path = DOCS_FOLDER + file
        with open(file_path) as f:
            text = f.read()
            for phrase in phrases:
                text = text.replace(phrase, phrase.replace(' ','_'))
            new_doc = PHRASES_DOCS_FOLDER + file[:-4] + '_phrases.txt'
            with open(new_doc, 'w') as nf:
                nf.write(text)

    print("job done on worker ", worker_num)

docs = os.listdir(DOCS_FOLDER)

import threading

threads = []
for i in range(1, 11):
    print(i)
    start = int((len(docs)/10) * (i - 1))
    end = int((len(docs)/10) * (i))
    print(start,end)
    if i != 10:
        t = threading.Thread(target=_check_files_and_write_phrases, args=(docs[start:end], i, ))
    else:
        t = threading.Thread(target=_check_files_and_write_phrases, args=(docs[start:], i, ))
    threads.append(t)
    t.start()

for t in threads:
    t.join()

print("all workers finished!")
</code>```

But it's way too slow! I thought that threads would do the job but I was wrong...

Is there another efficient way of doing this?

答:
Try to change the for loop to replace only phrases that exist in the text:

```<code>for phrase in set(phrases).intersection(text.split()):
...
</code>```

Try it with and without the threading.

Body:
I have a vocabulary of phrases and I want to replace words of another file by these words. For example, I have the following vocabulary:

United States,
New York

and I want to replace the following file:

"I work for New York but I don't even live at the United States"

To this:

"I work for New_York but I don't even live at the United_States"

Currently I'm doing at this way:

import os

def _check_files_and_write_phrases(docs, worker_num):
    print("worker ", worker_num," started!")
    for i, file in enumerate(docs):
        file_path = DOCS_FOLDER + file
        with open(file_path) as f:
            text = f.read()
            for phrase in phrases:
                text = text.replace(phrase, phrase.replace(' ','_'))
            new_doc = PHRASES_DOCS_FOLDER + file[:-4] + '_phrases.txt'
            with open(new_doc, 'w') as nf:
                nf.write(text)

    print("job done on worker ", worker_num)

docs = os.listdir(DOCS_FOLDER)

import threading

threads = []
for i in range(1, 11):
    print(i)
    start = int((len(docs)/10) * (i - 1))
    end = int((len(docs)/10) * (i))
    print(start,end)
    if i != 10:
        t = threading.Thread(target=_check_files_and_write_phrases, args=(docs[start:end], i, ))
    else:
        t = threading.Thread(target=_check_files_and_write_phrases, args=(docs[start:], i, ))
    threads.append(t)
    t.start()

for t in threads:
    t.join()

print("all workers finished!")

But it's way too slow! I thought that threads would do the job but I was wrong...

Is there another efficient way of doing this?

Body:
Try to change the for loop to replace only phrases that exist in the text:

for phrase in set(phrases).intersection(text.split()):
...

Try it with and without the threading.


答:
The problem is clear. You are trying to call the function "putFileAs" using 2 parameters, when she needs at least 3.

Just take a look in the documentation here

So

Title: Multiple upload using Laravel Storage


问:
Refresh associated view list
In CRM 2011, is there a way to refresh an associate view for an associated entity via Javascript? I know you can refresh a subrgid that's been placed on the form of the parent entity. But I cannot figure out a way to refresh the child entities associated view (the list you see if you click on the child entities link in the left hand navigation of the parent entities form, e.g. Case > Child Cases).

I'm trying to do this from a custom ribbon button. I have that calling a Javascript function.

答:
Managed to get this working.

Call $find(gridname).Refresh(); to refresh the grid. Replacing gridname with the name of the grid which you can find using developer tools in your browser and looking for the the value in the gridid attribute.

Title: Refresh associated view list


问:
Express.js can't handle GET route
I can't handle GET request which is in 'text/html' type.

app.js

```<code>...
const express = require('express');
const app = express();
const bodyParser = require('body-parser');

app.use(express.json());
//Tried these also
//app.use(bodyParser.json())
//app.use(bodyParser.text())
//app.use(bodyParser.text({type:'text/*'}))

require('./routes')(app);
...
</code>```

routes.js

```<code>const Api= require('./api');
module.exports = (app) => {
   app.get('/wa', Api.handleRequest);
}
</code>```

Request:

```<code>Request URL:http://localhost:8081/wa?action_name=dosomething&idsite=1&tp=1&aq=42215
Request Method:GET
Status Code:404 Not Found
Remote Address:[::1]:8081
Referrer Policy:no-referrer-when-downgrade
</code>```

Request Headers:

```<code>Accept:image/webp,image/apng,image/*,*/*;q=0.8
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.9,tr;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Cookie:....
Host:localhost:8081
Pragma:no-cache
Referer:http://localhost:8080/dashboard
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36
</code>```

As you can see I got 404. Thanks in advance.

答:
When I changed the route and the request url to '/wa.js' it works. In response I send a blank gif. Strange though..

Request

```<code>Request URL:http://localhost:8081/wa.js?action_name=dosomething&idsite=1&tp=1&aq=42215
</code>```

routes.js

```<code> ...
 app.get('/wa.js', Api.handleRequest);
 ...
</code>```

Title: Express.js can't handle GET route

Body:
I can't handle GET request which is in 'text/html' type.

app.js

...
const express = require('express');
const app = express();
const bodyParser = require('body-parser');

app.use(express.json());
//Tried these also
//app.use(bodyParser.json())
//app.use(bodyParser.text())
//app.use(bodyParser.text({type:'text/*'}))

require('./routes')(app);
...

routes.js

const Api= require('./api');
module.exports = (app) => {
   app.get('/wa', Api.handleRequest);
}

Request:

Request URL:http://localhost:8081/wa?action_name=dosomething&idsite=1&tp=1&aq=42215
Request Method:GET
Status Code:404 Not Found
Remote Address:[::1]:8081
Referrer Policy:no-referrer-when-downgrade

Request Headers:

Accept:image/webp,image/apng,image/*,*/*;q=0.8
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.9,tr;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Cookie:....
Host:localhost:8081
Pragma:no-cache
Referer:http://localhost:8080/dashboard
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36

As you can see I got 404. Thanks in advance.

Body:
When I changed the route and the request url to '/wa.js' it works. In response I send a blank gif. Strange though..

Request

Request URL:http://localhost:8081/wa.js?action_name=dosomething&idsite=1&tp=1&aq=42215

routes.js

 ...
 app.get('/wa.js', Api.handleRequest);
 ...


问:
How to fetch the data of a specific model from the collection list that is present to the user in backbone.js?
I have a list view that displays some contents from the api and along side a button that when clicked should show the details of the corresponding item from the list-view on another page, how to associate the button to the specific id and how to present a generic url that accepts these ids to route accordingly. I saw many similar posts but I didn't know how to route those or can't understand how each model is called at that route. Here's my current app, where I've not generalised the routing instead each button is associated to the first id and a route like /1 which takes it to a view to display details of the first element from the collection alone.

pollsscript.js

```<code>//defining the model
var QuestionModel = Backbone.Model.extend({
    // urlRoot : "http://localhost:8000/polls/api/v1/question/",

});

//defining collection
var QuestionCollection = Backbone.Collection.extend({

    url : "http://localhost:8000/polls/api/v1/question/",
    model: QuestionModel

});

//list view of all the questions
var QuestionListView = Backbone.View.extend({

    el: '.page',

    render : function(){

        var context = {};
        this.questionCollection = new QuestionCollection();
        this.questionCollection.fetch({
            success: () => {

                  context['models'] = this.questionCollection.toJSON();

                  var template = _.template($('#question-list-template').html(),{});

                  this.$el.html(template(context));
             }
        })
        return this;
    }
});

//individual questions
var QuestionDetailsView = Backbone.View.extend({

    el: '.page',

    render : function(){

        var context = {};
        this.questionCollection = new QuestionCollection();
        this.questionCollection.fetch({
            success: () => {

                  context['model'] = this.questionCollection.get(1).toJSON();

                  var template = _.template($('#question-detail-template').html(),{});

                  this.$el.html(template(context));
             }
        })
        return this;
    }
});

var questionListView = new QuestionListView();
var questionDetailsView = new QuestionDetailsView();

var PageRouter = Backbone.Router.extend({
    routes: {
        '' : 'home',
        '1' : 'details',
    },

    home : function(){
        questionListView.render();
    },

    details: function(){
        questionDetailsView.render();
    },

});

//initializing router and setting up history for routing to work
var pageRouter = new PageRouter();
Backbone.history.start();
</code>```

index.html

```<code><html>
<head>
    <title> </title>
</head>
<body>
    <div class="container">
        <h1>All polls</h1>
        <div class="page"></div>
    </div>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

<!-- main page template -->
    <script type="text/template" id="question-list-template">
        <table class = "table table-striped">
            <thead>
                <tr>
                    <th>Question</th>
                    <!-- <th>Date Published</th> -->
                    <th>Votes</th>
                    <th>Popular responses</th>
                    <th>Details</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <% _.each(models, function(model){ %>
                    <tr>
                        <td><%= model.question_text %></td>
                        <!-- <td><%= model.pub_date%></td> -->
                        <td><%= model.total_votes%></td>
                        <td><%= model.pop_response%></td>
                        <td><a href="#/1" class="btn btn-info">Show details</a></td>
                    </tr>
                    <% }); %>
                </tr>
            </tbody>
        </table>
    </script>

    <script type="text/template" id="question-detail-template">
        <div>
            <div><%= model.question_text %><div/>
            <div>
                <% _.each(model.choices, function(choices){ %>
                    <div><%= choices.choice_text %></div>
                    <div><%= choices.votes %></div>
            <% }); %>
            </div>
        </div>
    </script>

    <script type="text/javascript" src="jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="underscore-min.js"></script>
    <script type="text/javascript" src="backbone-min.js"></script>
    <script type="text/javascript" src="pollsscript.js"></script>
    <!-- <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>

</script>

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

答:
index.html

```<code><html>
<head>
    <title> </title>
</head>
<body>
    <div class="container">
        <h1>All polls</h1>
        <div class="page"></div>
    </div>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

<!-- main page template -->
    <script type="text/template" id="question-list-template">
        <table class = "table table-striped">
            <thead>
                <tr>
                    <!-- <th> ID </th> -->
                    <th>Question</th>
                    <th>Votes</th>
                    <th>Popular responses</th>
                    <th>Details</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <% _.each(models, function(model){ %>
                    <tr>
                        <!-- <td id="id"><%= model.id %></td> -->
                        <td><%= model.question_text %></td>
                        <td><%= model.total_votes%></td>
                        <td><%= model.pop_response%></td>
                        <td><a href="#<%= model.id %>" class="btn btn-info show-details">Show details</button></td>
                        <!-- <td><a href="#<%= model.id %>" class="btn btn-info show-details" data-id="<%= model.id %>">Show details</button></td> -->
                    </tr>
                    <% }); %>
                </tr>
            </tbody>
        </table>
    </script>

    <script type="text/template" id="question-detail-template">
        <div>
            <div><%= model.question_text %><div/>
            <div>
                <% _.each(model.choices, function(choices){ %>
                    <div><%= choices.choice_text %></div>
                    <div><%= choices.votes %></div>
            <% }); %>
            </div>
        </div>
    </script>

    <script type="text/javascript" src="jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="underscore-min.js"></script>
    <script type="text/javascript" src="backbone-min.js"></script>
    <script type="text/javascript" src="pollsscript.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>

</script>

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

pollsscript.js

```<code>//defining the model
var QuestionModel = Backbone.Model.extend({
    // urlRoot : "http://localhost:8000/polls/api/v1/question/",

});

//defining collection
var QuestionCollection = Backbone.Collection.extend({
    url : "http://localhost:8000/polls/api/v1/question/",
    model: QuestionModel
});

//list view of all the questions
var QuestionListView = Backbone.View.extend({
    el: '.page',
    template : _.template($('#question-list-template').html()),
    render : function(){
        var context = {};
        this.questionCollection = new QuestionCollection();
        this.questionCollection.fetch({
            success: () => {
                  context['models'] = this.questionCollection.toJSON();
                  this.$el.html(this.template(context));
             }
        })
        return this;
    },
    // events: {
    //  'click .show-details' : 'viewDetails',
    // },
    // viewDetails : function(e){
    //  var id = $(e.currentTarget).data("id");
    //  var item = this.questionCollection.get(id);
    //  var questionDetailsView = new QuestionDetailsView({
    //      model: item
    //  });
    //  questionDetailsView.render(); //get and pass model here
    // }
});

//individual questions
var QuestionDetailsView = Backbone.View.extend({
    el: '.page',
    template : _.template($('#question-detail-template').html()),
    render : function(){
        var context = {};
        context['model'] = this.model.toJSON();
        this.$el.html(this.template(context));
        return this;
    }
});

var PageRouter = Backbone.Router.extend({
    routes: {
        '' : 'home',
        ':id' : 'details'
    },
    home : function(){
        var questionListView = new QuestionListView();
        questionListView.render();
    },
    details : function(id){
        //alert(id);
        var context = {};
        this.questionCollection = new QuestionCollection();
        this.questionCollection.fetch({
            success: () => {
            var item = this.questionCollection.get(id);
            var questionDetailsView = new QuestionDetailsView({
            model: item
            });
            questionDetailsView.render();
            }
        })

    }
});

//initializing router and setting up history for routing to work
var pageRouter = new PageRouter();
Backbone.history.start();
</code>```

I tried this, later, I associated the data-id with the button and gave the model.id I fetched from the api and then got the id on click and then passed the model to be rendered on the detail-view.

Still this doesn't change the router in anyway so still looking for a better way to do it.

Edit
Updated the code and fixed by associating model id with href, and created routes to fetch and get the model from in the router function.

Body:
I have a list view that displays some contents from the api and along side a button that when clicked should show the details of the corresponding item from the list-view on another page, how to associate the button to the specific id and how to present a generic url that accepts these ids to route accordingly. I saw many similar posts but I didn't know how to route those or can't understand how each model is called at that route. Here's my current app, where I've not generalised the routing instead each button is associated to the first id and a route like /1 which takes it to a view to display details of the first element from the collection alone.

pollsscript.js

//defining the model
var QuestionModel = Backbone.Model.extend({
    // urlRoot : "http://localhost:8000/polls/api/v1/question/",

});

//defining collection
var QuestionCollection = Backbone.Collection.extend({

    url : "http://localhost:8000/polls/api/v1/question/",
    model: QuestionModel

});

//list view of all the questions
var QuestionListView = Backbone.View.extend({

    el: '.page',

    render : function(){

        var context = {};
        this.questionCollection = new QuestionCollection();
        this.questionCollection.fetch({
            success: () => {

                  context['models'] = this.questionCollection.toJSON();

                  var template = _.template($('#question-list-template').html(),{});

                  this.$el.html(template(context));
             }
        })
        return this;
    }
});

//individual questions
var QuestionDetailsView = Backbone.View.extend({

    el: '.page',

    render : function(){

        var context = {};
        this.questionCollection = new QuestionCollection();
        this.questionCollection.fetch({
            success: () => {

                  context['model'] = this.questionCollection.get(1).toJSON();

                  var template = _.template($('#question-detail-template').html(),{});

                  this.$el.html(template(context));
             }
        })
        return this;
    }
});

var questionListView = new QuestionListView();
var questionDetailsView = new QuestionDetailsView();

var PageRouter = Backbone.Router.extend({
    routes: {
        '' : 'home',
        '1' : 'details',
    },

    home : function(){
        questionListView.render();
    },

    details: function(){
        questionDetailsView.render();
    },

});

//initializing router and setting up history for routing to work
var pageRouter = new PageRouter();
Backbone.history.start();

index.html

    <title> </title>

All polls

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

</script>

Body:
index.html

<html>
<head>
    <title> </title>
</head>
<body>
    <div class="container">
        <h1>All polls</h1>
        <div class="page"></div>
    </div>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

<!-- main page template -->
    <script type="text/template" id="question-list-template">
        <table class = "table table-striped">
            <thead>
                <tr>
                    <!-- <th> ID </th> -->
                    <th>Question</th>
                    <th>Votes</th>
                    <th>Popular responses</th>
                    <th>Details</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <% _.each(models, function(model){ %>
                    <tr>
                        <!-- <td id="id"><%= model.id %></td> -->
                        <td><%= model.question_text %></td>
                        <td><%= model.total_votes%></td>
                        <td><%= model.pop_response%></td>
                        <td><a href="#<%= model.id %>" class="btn btn-info show-details">Show details</button></td>
                        <!-- <td><a href="#<%= model.id %>" class="btn btn-info show-details" data-id="<%= model.id %>">Show details</button></td> -->
                    </tr>
                    <% }); %>
                </tr>
            </tbody>
        </table>
    </script>

    <script type="text/template" id="question-detail-template">
        <div>
            <div><%= model.question_text %><div/>
            <div>
                <% _.each(model.choices, function(choices){ %>
                    <div><%= choices.choice_text %></div>
                    <div><%= choices.votes %></div>
            <% }); %>
            </div>
        </div>
    </script>

    <script type="text/javascript" src="jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="underscore-min.js"></script>
    <script type="text/javascript" src="backbone-min.js"></script>
    <script type="text/javascript" src="pollsscript.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>

</script>

</body>
</html>

pollsscript.js

//defining the model
var QuestionModel = Backbone.Model.extend({
    // urlRoot : "http://localhost:8000/polls/api/v1/question/",

});

//defining collection
var QuestionCollection = Backbone.Collection.extend({
    url : "http://localhost:8000/polls/api/v1/question/",
    model: QuestionModel
});

//list view of all the questions
var QuestionListView = Backbone.View.extend({
    el: '.page',
    template : _.template($('#question-list-template').html()),
    render : function(){
        var context = {};
        this.questionCollection = new QuestionCollection();
        this.questionCollection.fetch({
            success: () => {
                  context['models'] = this.questionCollection.toJSON();
                  this.$el.html(this.template(context));
             }
        })
        return this;
    },
    // events: {
    //  'click .show-details' : 'viewDetails',
    // },
    // viewDetails : function(e){
    //  var id = $(e.currentTarget).data("id");
    //  var item = this.questionCollection.get(id);
    //  var questionDetailsView = new QuestionDetailsView({
    //      model: item
    //  });
    //  questionDetailsView.render(); //get and pass model here
    // }
});

//individual questions
var QuestionDetailsView = Backbone.View.extend({
    el: '.page',
    template : _.template($('#question-detail-template').html()),
    render : function(){
        var context = {};
        context['model'] = this.model.toJSON();
        this.$el.html(this.template(context));
        return this;
    }
});

var PageRouter = Backbone.Router.extend({
    routes: {
        '' : 'home',
        ':id' : 'details'
    },
    home : function(){
        var questionListView = new QuestionListView();
        questionListView.render();
    },
    details : function(id){
        //alert(id);
        var context = {};
        this.questionCollection = new QuestionCollection();
        this.questionCollection.fetch({
            success: () => {
            var item = this.questionCollection.get(id);
            var questionDetailsView = new QuestionDetailsView({
            model: item
            });
            questionDetailsView.render();
            }
        })

    }
});

//initializing router and setting up history for routing to work
var pageRouter = new PageRouter();
Backbone.history.start();

I tried this, later, I associated the data-id with the button and gave the model.id I fetched from the api and then got the id on click and then passed the model to be rendered on the detail-view.

Still this doesn't change the router in anyway so still looking for a better way to do it.

Edit
Updated the code and fixed by associating model id with href, and created routes to fetch and get the model from in the router function.


问:
How to change the Column Names of a database created by Django (from models.py)?

So I have a MySQL Database in my local PHPMyAdmin with DBs and Tables already filled in with data. I have to now port that DB into django.

For example, the name of a table in the DB is "ratings". So using django, I have to first create an app named something (let's say "website") and then I can add the model ratings to that app. This creates a table "website_ratings" in the DB. Which is not what I want, I want the name of the table to be just ratings.

Is there any way to get this done?

答:
You can set the table name and column names in the model class. Here is an example:

```<code>class Rating(models.Model):
    field_name = models.CharField(db_column='column_name')
    # other fields

    class Meta:
        db_table = 'ratings'
</code>```

It means for every field you can specify a column name, which can be different than the field name. In the Meta class you can specify the table name. Otherwise Django creates it automatically out of the app label and the model class name.

If it is a legacy database and you want to create model classes, you can use the following command:

```<code>python manage.py inspectdb > models.py
</code>```

Usually you'll have to edit the file after that according to your needs.

Body:
You can set the table name and column names in the model class. Here is an example:

class Rating(models.Model):
    field_name = models.CharField(db_column='column_name')
    # other fields

    class Meta:
        db_table = 'ratings'

It means for every field you can specify a column name, which can be different than the field name. In the Meta class you can specify the table name. Otherwise Django creates it automatically out of the app label and the model class name.

If it is a legacy database and you want to create model classes, you can use the following command:

python manage.py inspectdb > models.py

Usually you'll have to edit the file after that according to your needs.


问:
How to remove angular expression attributes from element
I'd like to know whether it's possible to remove Angular expressions dynamically.
I tried the following without any success:

My button

```<code><button myDirective [disabled]="someExpression">Clippy</button>
</code>```

My Directive

```<code>@Directive({
   selector: '[myDirective]'
})
export class MyDirective {
   constructor(private element: ElementRef) {}

   ngOnInit() {
      this.element.nativeElement.removeAttribute('disabled');
   }
}
</code>```

The problem

Initially the button won't be disabled, but once someExpression re-evaluates it'll add the disabled attribute back to the element.

Just for clarification, I want to remove an Angular expression dynamically. In the above example it's [disabled]. But this can be any binding in the future. I want my directive to overrule the existing binding.

答:
Use @HostBinding, e.g.</p>

```<code>import { Directive, HostBinding } from '@angular/core';

@Directive({
  selector: '[statusDirective]',
})
export class StatusDirective {
  @HostBinding('disabled') disable = true;
  constructor() {}
}

//Your input never enabled
//<input type="text" name="id" [disabled]="false" statusDirective  >
</code>```

Body:
I'd like to know whether it's possible to remove Angular expressions dynamically.
I tried the following without any success:

My button

<button myDirective [disabled]="someExpression">Clippy</button>

My Directive

@Directive({
   selector: '[myDirective]'
})
export class MyDirective {
   constructor(private element: ElementRef) {}

   ngOnInit() {
      this.element.nativeElement.removeAttribute('disabled');
   }
}

The problem

Initially the button won't be disabled, but once someExpression re-evaluates it'll add the disabled attribute back to the element.

Just for clarification, I want to remove an Angular expression dynamically. In the above example it's [disabled]. But this can be any binding in the future. I want my directive to overrule the existing binding.

Body:
Use @HostBinding, e.g.

import { Directive, HostBinding } from '@angular/core';

@Directive({
  selector: '[statusDirective]',
})
export class StatusDirective {
  @HostBinding('disabled') disable = true;
  constructor() {}
}

//Your input never enabled
//<input type="text" name="id" [disabled]="false" statusDirective  >


问:
How to use .net framework from .net core?
I have a .net core xUnit project that references a .net framework project that references Microsoft's Azure Notification Hub API.

It builds, but when try and create a hub, I get the error...

Could not load file or assembly
  'System.Configuration.ConfigurationManager, Version=0.0.0.0,
  Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51

Which seems like an odd error to get given that System.Configuration is referenced.

How do I make the Azure referencing project act like a framework 4.7 project?

答:
Microsoft just shipped a new version that's compatible to .NET Standard 2.0,

https://azure.microsoft.com/en-us/updates/azure-notifications-hubs-net-sdk-now-compatible-with-net-standard-2-0/

Please upgrade your SDK to use that. Of course, you need to make other changes according to their documentation.


问:
How to replace value of column in a row in ListView using C#.net?
```<code>ID      Item          Code
1       Item a        1565
2       Item x        **2565**
3       Item w        1245
4       Item f        1345
</code>```

I have a ListView Details format like above and I want to change the value of a cell content which is in between ** mark.
How can I change it such a way that it will appear in same row and without need of updating other values in a row or a table.

Please Guide me in C#.net

答:
Basically, it depends on how you fill your ListView.

Anyway, a code like this, should work in almost every situations:

```<code>var idIdx = listView1.Columns["ID"].Index;
var codeIdx = listView1.Columns["Code"].Index;

foreach (ListViewItem item in listView1.Items)
{
    if (item.SubItems[idIdx].Text == "2")
    {
        item.SubItems[codeIdx].Text = "new value...";
        break;
    }
}
</code>```

Just a caveat:

to assure the first 2 lines of this code work, you must properly initialize your columns' Name property, when you create them:

either by using the proper add overload:

```<code>listView1.Columns.Add("ID", "ID");
</code>```

or by setting it later:

```<code>var col = listView1.Columns.Add("ID");
col.Name = "ID";
</code>```

Body:
ID      Item          Code
1       Item a        1565
2       Item x        **2565**
3       Item w        1245
4       Item f        1345

I have a ListView Details format like above and I want to change the value of a cell content which is in between ** mark.
How can I change it such a way that it will appear in same row and without need of updating other values in a row or a table.

Please Guide me in C#.net

Body:
Basically, it depends on how you fill your ListView.

Anyway, a code like this, should work in almost every situations:

var idIdx = listView1.Columns["ID"].Index;
var codeIdx = listView1.Columns["Code"].Index;

foreach (ListViewItem item in listView1.Items)
{
    if (item.SubItems[idIdx].Text == "2")
    {
        item.SubItems[codeIdx].Text = "new value...";
        break;
    }
}

Just a caveat:

to assure the first 2 lines of this code work, you must properly initialize your columns' Name property, when you create them:

either by using the proper add overload:

listView1.Columns.Add("ID", "ID");

or by setting it later:

var col = listView1.Columns.Add("ID");
col.Name = "ID";


问:
populate spinner with retrofit and moshi
i am beginner in android dev (both java or kotlin). I am trying to populate spinner from json with retrofit and moshi but I have no idea how to populate it into spinner. to be honest I dont know whether the return of Json data is correct or not, since Log.d() return is not detail as dump() laravel or php.

script in activity onCreate (Please read the comment of the script, i put debug result of Log.d() there):

```<code>val task = object : AsyncTask<Void, Void, Response<List<ProductTypeResponse>>>() {
        override fun doInBackground(vararg params: Void): Response<List<ProductTypeResponse>> {

            val typeAPI = RestAPI()
            val callResponse = typeAPI.getNews()
            val response = callResponse.execute()

            return response

        }

        override fun onPostExecute(response: Response<List<ProductTypeResponse>>) {
            if (response.isSuccessful) {
                val news = response.body()
                Log.d("test:", news!![0].data.toString()) //  method 'java.lang.String com.example.mockie.tigaer.api.TypeDataResponse.toString()' on a null object reference
                Log.d("test:", news!!.size.toString()) // it says 67 but the data from the url is 63 array of json object
                Log.d("test:", news!![0].toString()) // com.example.mockie.tigaer.api.ProductTypeResponse@f17fd5e
            }
        }
</code>```

RestApi.kt

```<code>import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory

class RestAPI() {

private val tigaerApi: TigaerApi

init {
    val retrofit = Retrofit.Builder()
            .baseUrl("http://app.tigaer.id/laravel/")
            .addConverterFactory(MoshiConverterFactory.create())
            .build()

    tigaerApi = retrofit.create(TigaerApi::class.java)
}

fun getNews(): Call<List<ProductTypeResponse>> {
    return tigaerApi.getTop()
}
}
</code>```

ApiModel.kt

```<code>package com.example.mockie.tigaer.api

class ProductTypeResponse(val data: TypeDataResponse)

class TypeDataResponse(
    val children: List<ProductTypeChildrenResponse>
 )

 class ProductTypeChildrenResponse(val data: ProductTypeDataResponse)

 class ProductTypeDataResponse(
    val productType: String,
    val readable: String
 )
</code>```

TigaerApi.kt

```<code>import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query

interface  TigaerApi {
@GET("api/type")
fun getTop(): Call<List<ProductTypeResponse>>
}
</code>```

return Json: https://jsoneditoronline.org/?id=ce90c41b859218e746e41d64eddb4c30

so my questions are :

is there any function to debug object/array as detail as in laravel ?

how to populate my json return data into spinner?

答:
is there any function to debug object/array as detail as in laravel ?

Go through this to run your app in debug mode. https://developer.android.com/studio/debug/index.html

You can always use breakpoints to evaluate expressions while the app is running. Instead of logging put a breakpoint at this line.

```<code> val news = response.body()
</code>```

so when you'll receive a response from server, app will stop at this point and you can check what you are getting in response in detail.

how to populate my json return data into spinner?

If you are getting response from server in Json format as shown in provided link, you'll have to parse the data into a list of objects(POJO).
And then you have to forward this data(maybe you'll have to iterate over list to get the required data because you have two fields in each object) into an adapter and set that adapter to your spinner. It is explained very clearly at following link.
https://developer.android.com/guide/topics/ui/controls/spinner.html

Body:
i am beginner in android dev (both java or kotlin). I am trying to populate spinner from json with retrofit and moshi but I have no idea how to populate it into spinner. to be honest I dont know whether the return of Json data is correct or not, since Log.d() return is not detail as dump() laravel or php.

script in activity onCreate (Please read the comment of the script, i put debug result of Log.d() there):

val task = object : AsyncTask<Void, Void, Response<List<ProductTypeResponse>>>() {
        override fun doInBackground(vararg params: Void): Response<List<ProductTypeResponse>> {

            val typeAPI = RestAPI()
            val callResponse = typeAPI.getNews()
            val response = callResponse.execute()

            return response

        }

        override fun onPostExecute(response: Response<List<ProductTypeResponse>>) {
            if (response.isSuccessful) {
                val news = response.body()
                Log.d("test:", news!![0].data.toString()) //  method 'java.lang.String com.example.mockie.tigaer.api.TypeDataResponse.toString()' on a null object reference
                Log.d("test:", news!!.size.toString()) // it says 67 but the data from the url is 63 array of json object
                Log.d("test:", news!![0].toString()) // com.example.mockie.tigaer.api.ProductTypeResponse@f17fd5e
            }
        }

RestApi.kt

import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory

class RestAPI() {

private val tigaerApi: TigaerApi

init {
    val retrofit = Retrofit.Builder()
            .baseUrl("http://app.tigaer.id/laravel/")
            .addConverterFactory(MoshiConverterFactory.create())
            .build()

    tigaerApi = retrofit.create(TigaerApi::class.java)
}

fun getNews(): Call<List<ProductTypeResponse>> {
    return tigaerApi.getTop()
}
}

ApiModel.kt

package com.example.mockie.tigaer.api

class ProductTypeResponse(val data: TypeDataResponse)

class TypeDataResponse(
    val children: List<ProductTypeChildrenResponse>
 )

 class ProductTypeChildrenResponse(val data: ProductTypeDataResponse)

 class ProductTypeDataResponse(
    val productType: String,
    val readable: String
 )

TigaerApi.kt

import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query

interface  TigaerApi {
@GET("api/type")
fun getTop(): Call<List<ProductTypeResponse>>
}

return Json: https://jsoneditoronline.org/?id=ce90c41b859218e746e41d64eddb4c30

so my questions are :

is there any function to debug object/array as detail as in laravel ?

how to populate my json return data into spinner?

Body:
is there any function to debug object/array as detail as in laravel ?

Go through this to run your app in debug mode. https://developer.android.com/studio/debug/index.html

You can always use breakpoints to evaluate expressions while the app is running. Instead of logging put a breakpoint at this line.

 val news = response.body()

so when you'll receive a response from server, app will stop at this point and you can check what you are getting in response in detail.

how to populate my json return data into spinner?

If you are getting response from server in Json format as shown in provided link, you'll have to parse the data into a list of objects(POJO).
And then you have to forward this data(maybe you'll have to iterate over list to get the required data because you have two fields in each object) into an adapter and set that adapter to your spinner. It is explained very clearly at following link.
https://developer.android.com/guide/topics/ui/controls/spinner.html


问:
Receive data via url Get
I am trying to receive data via url, but I have this question of how to receive this url

```<code>localhost:8080/?action&p[4]=2&p[7]=5&p[12]=0&p[15]=1
</code>```

I need the values of

```<code>[2] = 4

2
and
4
</code>```

答:
PHP automatically converts query-string arguments in the form param[key]=val&param[foo]=bar to an associative array: array (param => array (key => val, foo => bar)).

With the URL you gave, var_dump($_GET) returns:

```<code>array (size=2)
  'action' => string '' (length=0)
  'p' =>
    array (size=4)
      4 => string '2' (length=1)
      7 => string '5' (length=1)
      12 => string '0' (length=1)
      15 => string '1' (length=1)
</code>```

So you should be able to access the field at index 4 with $_GET['p'][4].

Title: Receive data via url Get

Body:
I am trying to receive data via url, but I have this question of how to receive this url

localhost:8080/?action&p[4]=2&p[7]=5&p[12]=0&p[15]=1

I need the values of

[2] = 4

2
and
4

Body:
PHP automatically converts query-string arguments in the form param[key]=val&param[foo]=bar to an associative array: array (param => array (key => val, foo => bar)).

With the URL you gave, var_dump($_GET) returns:

array (size=2)
  'action' => string '' (length=0)
  'p' =>
    array (size=4)
      4 => string '2' (length=1)
      7 => string '5' (length=1)
      12 => string '0' (length=1)
      15 => string '1' (length=1)

So you should be able to access the field at index 4 with $_GET['p'][4].


问:
How to track current location in android with new architecture components?
I have a project, in which I have successfully implemented location tracking feature, and is working perfectly. I am tracking users current location using fused location provider in every 30 seconds.(tracking starts when MainActivity started).

Now I am planning to update that project with newly introduced android architecture components. But I don't know how to implement location tracking with view model.Where is the right place to start location tracking, in MainActivity or Application class? Should I use ViewModel or AndroidViewModel? How to achieve this.

答:
The correct way would be to have a TrackingRepository where you do all calculations in a background thread of the device location. Create a MutableLiveData where you will assign the location. Then update its value using postValue() or setValue(). Write a public getter for this MutableLiveData. This repository will be your location API.

Then your ViewModel should call the method of your repository and assign its result to a LiveData variable of the ViewModel. Then in your Fragment/Activity observe the liveData of your ViewModel. Just as the Guide to App Architecture does.

Remember to use dependency injection which really helps with the new architecture.


问:
Neo4j Cypher return most consecutive "passes"

I am trying to return from a graph database the students with the most consecutive passes to a series of exams.

Below is my current code but not sure where I can take it from its current state to solve my issue.

```<code>MATCH (s:Student)-[r:TAKEN]->(e:Exam)
RETURN s.name, e.date,
  CASE
    WHEN r.score >= e.pass_mark THEN 1
  END as pass
ORDER BY e.date
</code>```

I would like a basic table which would show the student along with there most consecutive passes in a row.

For example:

```<code>| student   | pass/fail |
| joe       | pass      |
| matt      | pass      |
| joe       | fail      |
| matt      | pass      |
| joe       | pass      |
| matt      | pass      |
| joe       | pass      |
| matt      | fail      |
</code>```

And I would like the result from my query to display each student and their highest pass streak in a row.

```<code>| student  | passes in a row |
| joe      | 2               |
| matt     | 3               |
</code>```

I have been playing around with CASE but haven't been able to come up with a good solution, currently, it will just list all the students for each exam and have a 1 if they have passed it.

答:
You can do it with plain Cypher, but I don't think it's very practical - you essentially need to write a program with reduce.

Basically, the "split" works as follows: initialize an empty accumulator list and calculate streaks by iterating through the list of passes/fails, check whether the current element is the same as the previous one. For example ['pass', 'pass'] keeps the streak, ['pass', 'fail'] breaks it. If it breaks (like at the start of the list), append a new element to the accumulator. If it keeps, append a new element to the last element of the accumulator, e.g. with a new 'fail', [['pass', 'pass'], ['fail']] becomes [['pass', 'pass'], ['fail', 'fail]].

```<code>UNWIND
  [
    ['joe',  'pass'],
    ['matt', 'pass'],
    ['joe',  'fail'],
    ['matt', 'pass'],
    ['joe',  'pass'],
    ['matt', 'pass'],
    ['joe',  'pass'],
    ['matt', 'fail']
  ] AS row
WITH row[0] AS s, row[1] AS passed
WITH s, collect(passed) AS p
WITH s, reduce(acc = [], i IN range(0, size(p) - 1) |
    CASE p[i] = p[i-1]
      WHEN true THEN [j IN range(0, size(acc) - 1) |
          CASE j = size(acc) - 1
            WHEN true THEN acc[j] + [p[i]]
            ELSE acc[j]
          END
        ]
      ELSE acc + [[p[i]]]
    END
  ) AS streaks // (1)
UNWIND streaks AS streak
WITH s, streak
WHERE streak[0] <> 'fail'
RETURN s, max(size(streak)) AS consecutivePasses // (2)
</code>```

In step (1), this calculates streaks such as:

```<code>╒══════╤═════════════════════════════════╕
│"s"   │"streaks"                        │
╞══════╪═════════════════════════════════╡
│"matt"│[["pass","pass","pass"],["fail"]]│
├──────┼─────────────────────────────────┤
│"joe" │[["fail"],["pass","pass"]]       │
└──────┴─────────────────────────────────┘
</code>```

And in (2), it gives:

```<code>╒══════╤═══════════════════╕
│"s"   │"consecutivePasses"│
╞══════╪═══════════════════╡
│"matt"│3                  │
├──────┼───────────────────┤
│"joe" │2                  │
└──────┴───────────────────┘
</code>```

Of course, in this particular case it's not necessary to do the splitting: simply counting would be enough. But in 99% of practical situations, APOC is the way to go, so I did not bother optimising this solution.

Body:
I am trying to return from a graph database the students with the most consecutive passes to a series of exams.

Below is my current code but not sure where I can take it from its current state to solve my issue.

MATCH (s:Student)-[r:TAKEN]->(e:Exam)
RETURN s.name, e.date,
  CASE
    WHEN r.score >= e.pass_mark THEN 1
  END as pass
ORDER BY e.date

I would like a basic table which would show the student along with there most consecutive passes in a row.

For example:

| student   | pass/fail |
| joe       | pass      |
| matt      | pass      |
| joe       | fail      |
| matt      | pass      |
| joe       | pass      |
| matt      | pass      |
| joe       | pass      |
| matt      | fail      |

And I would like the result from my query to display each student and their highest pass streak in a row.

| student  | passes in a row |
| joe      | 2               |
| matt     | 3               |

I have been playing around with CASE but haven't been able to come up with a good solution, currently, it will just list all the students for each exam and have a 1 if they have passed it.

Body:
You can do it with plain Cypher, but I don't think it's very practical - you essentially need to write a program with reduce.

Basically, the "split" works as follows: initialize an empty accumulator list and calculate streaks by iterating through the list of passes/fails, check whether the current element is the same as the previous one. For example ['pass', 'pass'] keeps the streak, ['pass', 'fail'] breaks it. If it breaks (like at the start of the list), append a new element to the accumulator. If it keeps, append a new element to the last element of the accumulator, e.g. with a new 'fail', [['pass', 'pass'], ['fail']] becomes [['pass', 'pass'], ['fail', 'fail]].

UNWIND
  [
    ['joe',  'pass'],
    ['matt', 'pass'],
    ['joe',  'fail'],
    ['matt', 'pass'],
    ['joe',  'pass'],
    ['matt', 'pass'],
    ['joe',  'pass'],
    ['matt', 'fail']
  ] AS row
WITH row[0] AS s, row[1] AS passed
WITH s, collect(passed) AS p
WITH s, reduce(acc = [], i IN range(0, size(p) - 1) |
    CASE p[i] = p[i-1]
      WHEN true THEN [j IN range(0, size(acc) - 1) |
          CASE j = size(acc) - 1
            WHEN true THEN acc[j] + [p[i]]
            ELSE acc[j]
          END
        ]
      ELSE acc + [[p[i]]]
    END
  ) AS streaks // (1)
UNWIND streaks AS streak
WITH s, streak
WHERE streak[0] <> 'fail'
RETURN s, max(size(streak)) AS consecutivePasses // (2)

In step (1), this calculates streaks such as:

╒══════╤═════════════════════════════════╕
│"s"   │"streaks"                        │
╞══════╪═════════════════════════════════╡
│"matt"│[["pass","pass","pass"],["fail"]]│
├──────┼─────────────────────────────────┤
│"joe" │[["fail"],["pass","pass"]]       │
└──────┴─────────────────────────────────┘

And in (2), it gives:

╒══════╤═══════════════════╕
│"s"   │"consecutivePasses"│
╞══════╪═══════════════════╡
│"matt"│3                  │
├──────┼───────────────────┤
│"joe" │2                  │
└──────┴───────────────────┘

Of course, in this particular case it's not necessary to do the splitting: simply counting would be enough. But in 99% of practical situations, APOC is the way to go, so I did not bother optimising this solution.


问:
clearInterval is not working in reactjs
SetInterval is working fine, but clearInterval is not working

See my code, i have parent class Channel and and Child class Body, within body when componentDidMount is called, then i setInterval for function refreshState. In refreshState function i try to clearInterval which is not working

```<code>var Header = require('../../common/header.jsx');
var Sidebar = require('../../common/sidebar.jsx');
var Footer = require('../../common/footer.jsx');

var Body = React.createClass({

  componentDidMount: function() {
    this.intervalId  = setInterval(this.refreshStats, 1000);
  },

  componentWillUnmount: function(){
    clearInterval(this.intervalId);
  },

  refreshStats: function() {
        console.log(this.intervalId);
        clearInterval(this.intervalId);
  },

  render: function() {
    return (
      <Container id='body'>
        <Grid>
          <Row>
            <Col sm={12}>
              <PanelContainer>
                <Panel>
                  <PanelBody>
                    Test
                  </PanelBody>
                </Panel>
              </PanelContainer>
            </Col>
          </Row>
        </Grid>
      </Container>
    );
  }
});

var Channel = React.createClass({
  mixins: [SidebarMixin, State],
  render: function() {
    var classes = React.addons.classSet({
      'container-open': this.state.open
    });
    return (
      <Container id='container' className={classes}>
        <Sidebar />
        <Header />
        <Body />
        <Footer />
      </Container>
    );
  }
});

module.exports = Channel;
</code>```

答:
I got it working by using clearInterval on the internal Id from the object returned.</p>

```<code>componentDidMount() {
  this.interval = setInterval(this.timer, 1000)
  console.log(this.interval) // Timeout {_id: 5, _clearFn: ƒ}
}

componentWillUnmount() {
  clearInterval(this.interval._id)
}
</code>```

Title: clearInterval is not working in reactjs

Body:
SetInterval is working fine, but clearInterval is not working

See my code, i have parent class Channel and and Child class Body, within body when componentDidMount is called, then i setInterval for function refreshState. In refreshState function i try to clearInterval which is not working

var Header = require('../../common/header.jsx');
var Sidebar = require('../../common/sidebar.jsx');
var Footer = require('../../common/footer.jsx');

var Body = React.createClass({

  componentDidMount: function() {
    this.intervalId  = setInterval(this.refreshStats, 1000);
  },

  componentWillUnmount: function(){
    clearInterval(this.intervalId);
  },

  refreshStats: function() {
        console.log(this.intervalId);
        clearInterval(this.intervalId);
  },

  render: function() {
    return (
      <Container id='body'>
        <Grid>
          <Row>
            <Col sm={12}>
              <PanelContainer>
                <Panel>
                  <PanelBody>
                    Test
                  </PanelBody>
                </Panel>
              </PanelContainer>
            </Col>
          </Row>
        </Grid>
      </Container>
    );
  }
});

var Channel = React.createClass({
  mixins: [SidebarMixin, State],
  render: function() {
    var classes = React.addons.classSet({
      'container-open': this.state.open
    });
    return (
      <Container id='container' className={classes}>
        <Sidebar />

      </Container>
    );
  }
});

module.exports = Channel;

Body:
I got it working by using clearInterval on the internal Id from the object returned.

componentDidMount() {
  this.interval = setInterval(this.timer, 1000)
  console.log(this.interval) // Timeout {_id: 5, _clearFn: ƒ}
}

componentWillUnmount() {
  clearInterval(this.interval._id)
}


问:
Pass parameters to AlertDialog in Android
I was trying to pass some parameters to an AlertDialog, this dialog most show these two parameters (suppose "foo" and "bar" parameters), and I'm calling this dialog using showDialog(int id). There is another method in Activity class which take a Bundle object to pass parameters: showDialog(int id, Bundle args), but this method is only available to API 8 or greater and I need to work with API 7.

Here I put some chunks of code to make easier what I am doing.

In my activity I create AlertDialog like this:

```<code>    protected Dialog onCreateDialog(int id) {
        final LayoutInflater factory = LayoutInflater.from(this);

        switch(id) {
        case DIALOG_ID:
            final View view = factory.inflate(R.layout.dialog_layout, null);
            final TextView fooValue = (TextView)view.findViewById(R.id.foo_label);
            final TextView barValue = (TextView)view.findViewById(R.id.foo_label);
            //fooLabel.setText("HERE MUST BE FOO PARAMETER VALUE");
            //barLabel.setText("HERE MUST BE BAR PARAMETER VALUE");

            return new AlertDialog.Builder(this).
                setIcon(R.drawable.icon).
                setTitle(R.string.app_name).
                setView(view).
                setPositiveButton(R.string.close, null).
                create();
...
</code>```

And in other part I call this dialog:

```<code>    // THESE PARAMETERS MUST BE PASSED TO DIALOG
    int foo = result.getInt("foo");
    String bar = result.getString("bar");

    showDialog(DIALOG_ID);
...
</code>```

Thank you very much!

答:
try this example

```<code>LayoutInflater factory = LayoutInflater.from(this);
            final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);// this layout can created by yourself whatever you want.
            return new AlertDialog.Builder(AlertDialogSamples.this)
                .setIcon(R.drawable.alert_dialog_icon)
                .setTitle(R.string.alert_dialog_text_entry)
                .setView(textEntryView)
                .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        /* User clicked OK so do some stuff */
                    }
                })
                .setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        /* User clicked cancel so do some stuff */
                    }
                })
                .create();
</code>```

layoutname : main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView android:layout_width="fill_parent" android:textColor="#663355"
        android:layout_height="wrap_content" android:hint="@string/hello" />
</LinearLayout>
</code>```

Body:
I was trying to pass some parameters to an AlertDialog, this dialog most show these two parameters (suppose "foo" and "bar" parameters), and I'm calling this dialog using showDialog(int id). There is another method in Activity class which take a Bundle object to pass parameters: showDialog(int id, Bundle args), but this method is only available to API 8 or greater and I need to work with API 7.

Here I put some chunks of code to make easier what I am doing.

In my activity I create AlertDialog like this:

    protected Dialog onCreateDialog(int id) {
        final LayoutInflater factory = LayoutInflater.from(this);

        switch(id) {
        case DIALOG_ID:
            final View view = factory.inflate(R.layout.dialog_layout, null);
            final TextView fooValue = (TextView)view.findViewById(R.id.foo_label);
            final TextView barValue = (TextView)view.findViewById(R.id.foo_label);
            //fooLabel.setText("HERE MUST BE FOO PARAMETER VALUE");
            //barLabel.setText("HERE MUST BE BAR PARAMETER VALUE");

            return new AlertDialog.Builder(this).
                setIcon(R.drawable.icon).
                setTitle(R.string.app_name).
                setView(view).
                setPositiveButton(R.string.close, null).
                create();
...

And in other part I call this dialog:

    // THESE PARAMETERS MUST BE PASSED TO DIALOG
    int foo = result.getInt("foo");
    String bar = result.getString("bar");

    showDialog(DIALOG_ID);
...

Thank you very much!

Body:
try this example

LayoutInflater factory = LayoutInflater.from(this);
            final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);// this layout can created by yourself whatever you want.
            return new AlertDialog.Builder(AlertDialogSamples.this)
                .setIcon(R.drawable.alert_dialog_icon)
                .setTitle(R.string.alert_dialog_text_entry)
                .setView(textEntryView)
                .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        /* User clicked OK so do some stuff */
                    }
                })
                .setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        /* User clicked cancel so do some stuff */
                    }
                })
                .create();

layoutname : main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView android:layout_width="fill_parent" android:textColor="#663355"
        android:layout_height="wrap_content" android:hint="@string/hello" />
</LinearLayout>


问:
Settings to Windows Firewall to allow Docker for Windows to share drive
Windows Firewall is blocking my attempt to allows Docker for Windows to share C: on windows 10 machine.

Works fine when Windows Firewall off. When its on I get

A firewall is blocking file Sharing between Windows and the
  containers. See documentation for more info.

The documentation says

You do not need to open port 445 on any other network. By default,
  allow connections to 10.0.75.1 port 445 (the Windows host) from
  10.0.75.2 (the virtual machine).

I am "googled out" on trying to find how to do that - can someone advise?

答:
None of the above worked for me.

What finally did the trick was opening the properties of the "vEthernet (DockerNAT)" network and ticking the box "Hyper-V Extensible Virtual Switch" at the bottom of the list under the "Networking" tab.

Not sure if this is the actual fix or whether it just somehow reset the network adapter for me... but it worked!