问:
What is the difference between intermediate and terminal operations?
can someone tell me What is the difference between intermediate and terminal operations for Stream?

Stream operations are combined into pipelines to process streams. All operations are either intermediate or terminal ..means?.

答:
A Stream supports several operations and these operations are divided into intermediate and terminal operations.

The distinction between this operations is that an intermediate operation is lazy while a terminal operation is not. When you invoke an intermediate operation on a stream, the operation is not executed immediately. It is executed only when a terminal operation is invoked on that stream. In a way, an intermediate operation is memorized and is recalled as soon as a terminal operation is invoked. You can chain multiple intermediate operations and none of them will do anything until you invoke a terminal operation. At that time, all of the intermediate operations that you invoked earlier will be invoked along with the terminal operation.

All intermediate operations return Stream (can be chained), while terminal operations don't. Intermediate Operations are:

```<code>filter(Predicate<T>)
map(Function<T>)
flatMap(Function<T>)
sorted(Comparator<T>)
peek(Consumer<T>)
distinct()
limit(long n)
skip(long n)
</code>```

Terminal operations produces a non-stream (cannot be chained) result such as primitive value, a collection or no value at all.

Terminal Operations are:

```<code>forEach
forEachOrdered
toArray
reduce
collect
min
max
count
anyMatch
allMatch
noneMatch
findFirst
findAny
</code>```

Last 5 are short-circuiting terminal operations.

Body:
A Stream supports several operations and these operations are divided into intermediate and terminal operations.

The distinction between this operations is that an intermediate operation is lazy while a terminal operation is not. When you invoke an intermediate operation on a stream, the operation is not executed immediately. It is executed only when a terminal operation is invoked on that stream. In a way, an intermediate operation is memorized and is recalled as soon as a terminal operation is invoked. You can chain multiple intermediate operations and none of them will do anything until you invoke a terminal operation. At that time, all of the intermediate operations that you invoked earlier will be invoked along with the terminal operation.

All intermediate operations return Stream (can be chained), while terminal operations don't. Intermediate Operations are:

filter(Predicate<T>)
map(Function<T>)
flatMap(Function<T>)
sorted(Comparator<T>)
peek(Consumer<T>)
distinct()
limit(long n)
skip(long n)

Terminal operations produces a non-stream (cannot be chained) result such as primitive value, a collection or no value at all.

Terminal Operations are:

forEach
forEachOrdered
toArray
reduce
collect
min
max
count
anyMatch
allMatch
noneMatch
findFirst
findAny

Last 5 are short-circuiting terminal operations.

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
Optimal way to create multiple property relations
I am trying to create multiple Users nodes in a single query. They are also linked with a friend relation in the same query. When I profile the query I see that for each property I set to a relation a db call is made. This is making the query expensive when there are many relations and properties of each relation. How can I reduce the cost for this query?

The query is the following:

```<code>PROFILE  MERGE (user: User {myId: "1"}) WITH user
UNWIND [
{myId: "2",userLastName: "2",userAddressId: "1",hasImage: false,randomId: 0},
{myId: "3",userLastName: "3",userAddressId: "3",hasImage: false,randomId: 0},
{myId: "4",userLastName: "4",userAddressId: "1",hasImage: false,randomId: 0},
{myId: "5",userLastName: "5",userAddressId: "1",hasImage: false,randomId: 0},
{myId: "6",userLastName: "6",userAddressId: "1",hasImage: false,randomId: 0},
{myId: "7",userLastName: "7",userAddressId: "1",hasImage: false,randomId: 0},
{myId: "8",userLastName: "8",userAddressId: "1",hasImage: false,randomId: 0},
{myId: "9",userLastName: "9",userAddressId: "1",hasImage: false,randomId: 0}
] as row
MERGE (friend: User {myId: row.myId})  ON CREATE SET friend.name = row.userLastName
MERGE (user)-[c:KNOWS]->(friend)  ON CREATE SET c = row
</code>```

As you can see in this profile result image there are over 88 db calls in just creating the relation properties from map

How can I avoid so many db calls for this query?

Note: CREATE CONSTRAINT ON (user:User) ASSERT user.myId IS UNIQUE is already set on the db.

Edit:

After following the instructions from @ChristopheWillemsen as explained in  this video, The execution time on my machine dropped from 500+ms to ~40ms for 100 to 500 records.

答:
You ask the DB to create some properties on the relationship, so it's normal to have some DB hits.

If you want to reduce a little the work of the DB, you can explicit all the SET you want to do on ON CREATE SET c = row like this :

```<code>MERGE (user)-[c:KNOWS]->(friend)
 ON CREATE SET c.myId = row.myId,
               c.userLastName=row.userLastName,
               c.userAddressId=row.userAddressId,
               c.hasImage=row.hasImage,
               c.randomId=row.randomId
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to create multiple Users nodes in a single query. They are also linked with a friend relation in the same query. When I profile the query I see that for each property I set to a relation a db call is made. This is making the query expensive when there are many relations and properties of each relation. How can I reduce the cost for this query?

The query is the following:

PROFILE  MERGE (user: User {myId: "1"}) WITH user
UNWIND [
{myId: "2",userLastName: "2",userAddressId: "1",hasImage: false,randomId: 0},
{myId: "3",userLastName: "3",userAddressId: "3",hasImage: false,randomId: 0},
{myId: "4",userLastName: "4",userAddressId: "1",hasImage: false,randomId: 0},
{myId: "5",userLastName: "5",userAddressId: "1",hasImage: false,randomId: 0},
{myId: "6",userLastName: "6",userAddressId: "1",hasImage: false,randomId: 0},
{myId: "7",userLastName: "7",userAddressId: "1",hasImage: false,randomId: 0},
{myId: "8",userLastName: "8",userAddressId: "1",hasImage: false,randomId: 0},
{myId: "9",userLastName: "9",userAddressId: "1",hasImage: false,randomId: 0}
] as row
MERGE (friend: User {myId: row.myId})  ON CREATE SET friend.name = row.userLastName
MERGE (user)-[c:KNOWS]->(friend)  ON CREATE SET c = row

As you can see in this profile result image there are over 88 db calls in just creating the relation properties from map

How can I avoid so many db calls for this query?

Note: CREATE CONSTRAINT ON (user:User) ASSERT user.myId IS UNIQUE is already set on the db.

Edit:

After following the instructions from @ChristopheWillemsen as explained in  this video, The execution time on my machine dropped from 500+ms to ~40ms for 100 to 500 records.

Body:
You ask the DB to create some properties on the relationship, so it's normal to have some DB hits.

If you want to reduce a little the work of the DB, you can explicit all the SET you want to do on ON CREATE SET c = row like this :

MERGE (user)-[c:KNOWS]->(friend)
 ON CREATE SET c.myId = row.myId,
               c.userLastName=row.userLastName,
               c.userAddressId=row.userAddressId,
               c.hasImage=row.hasImage,
               c.randomId=row.randomId


问:
LEFT JOIN confusion -- I need to retrieve a student count
I have four tables:

```<code>students
classes
teachers
teacher_assignments
</code>```

classes and teachers has a many-to-many relationship and so teacher_assignments acts as the xref table (with fields teacher_id and class_id).

Each student in students has a class_id (many-to-one -- many students to one class).

I should also mention that teacher_assignments has an active column (BOOL) which indicates whether that assignment is currently active

What I want to do:

I want to retrieve the following:

class_name -- a concat of its level and sub_level, e.g. 3 and A

teacher_names -- the names of the teachers currently assigned to that class

student_count -- a count of the students in each class

At first, I tried retrieving just the class_name and teacher_names, like so:

```<code>SELECT
    CONCAT(CONVERT(classes.level, CHAR(8)), classes.sub_level) AS class_name,
    GROUP_CONCAT(DISTINCT teachers.name SEPARATOR ',') AS teacher_names

FROM
    teacher_assignments
        LEFT JOIN teachers
            ON teachers.id = teacher_assignments.teacher_id
            AND teacher_assignments.active = TRUE
        LEFT JOIN classes
            ON classes.id = teacher_assignments.class_id

GROUP BY classes.id
</code>```

This works fine and outputs:

```<code> class_name | teacher_names
 --------------------------------------
 1A         | NULL
 2A         | John, Sam
 3B         | Sam, Sarah
</code>```

(Class 1A has no teachers currently, and so the NULL is expected)

... BUT, now I have no idea how to work the student_count into this.

My question:

How exactly should the students table be joined with the others in the above query so I can produce a student_count column?

答:
Use:

```<code>   SELECT CONCAT(CONVERT(c.level, CHAR(8)), c.sub_level) AS class_name,
          GROUP_CONCAT(DISTINCT teachers.name SEPARATOR ',') AS teacher_names,
          COUNT(s.id) AS studentCount
     FROM CLASSES c
LEFT JOIN TEACHER_ASSIGNMENTS ta ON ta.class_id = c.id
                                AND ta.active = TRUE
LEFT JOIN TEACHERS t ON t.id = ta.teacher_id
LEFT JOIN STUDENTS s ON s.class_id = c.id
 GROUP BY class_name
</code>```

Column aliases can be referenced in the GROUP BY when using MySQL, otherwise you'd have to duplicate the logic that produces the class_name column value.  This is also the column to GROUP on, as GROUP_CONCAT and COUNT are aggregate functions.

To get zero as the count value, you might need to use:

```<code>   SELECT CONCAT(CONVERT(c.level, CHAR(8)), c.sub_level) AS class_name,
          GROUP_CONCAT(DISTINCT teachers.name SEPARATOR ',') AS teacher_names,
          COALESCE(COUNT(s.id), 0) AS studentCount
     FROM CLASSES c
LEFT JOIN TEACHER_ASSIGNMENTS ta ON ta.class_id = c.id
                                AND ta.active = TRUE
LEFT JOIN TEACHERS t ON t.id = ta.teacher_id
LEFT JOIN STUDENTS s ON s.class_id = c.id
 GROUP BY class_name
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have four tables:

students
classes
teachers
teacher_assignments

classes and teachers has a many-to-many relationship and so teacher_assignments acts as the xref table (with fields teacher_id and class_id).

Each student in students has a class_id (many-to-one -- many students to one class).

I should also mention that teacher_assignments has an active column (BOOL) which indicates whether that assignment is currently active

What I want to do:

I want to retrieve the following:

class_name -- a concat of its level and sub_level, e.g. 3 and A

teacher_names -- the names of the teachers currently assigned to that class

student_count -- a count of the students in each class

At first, I tried retrieving just the class_name and teacher_names, like so:

SELECT
    CONCAT(CONVERT(classes.level, CHAR(8)), classes.sub_level) AS class_name,
    GROUP_CONCAT(DISTINCT teachers.name SEPARATOR ',') AS teacher_names

FROM
    teacher_assignments
        LEFT JOIN teachers
            ON teachers.id = teacher_assignments.teacher_id
            AND teacher_assignments.active = TRUE
        LEFT JOIN classes
            ON classes.id = teacher_assignments.class_id

GROUP BY classes.id

This works fine and outputs:

 class_name | teacher_names
 --------------------------------------
 1A         | NULL
 2A         | John, Sam
 3B         | Sam, Sarah

(Class 1A has no teachers currently, and so the NULL is expected)

... BUT, now I have no idea how to work the student_count into this.

My question:

How exactly should the students table be joined with the others in the above query so I can produce a student_count column?

Body:
Use:

   SELECT CONCAT(CONVERT(c.level, CHAR(8)), c.sub_level) AS class_name,
          GROUP_CONCAT(DISTINCT teachers.name SEPARATOR ',') AS teacher_names,
          COUNT(s.id) AS studentCount
     FROM CLASSES c
LEFT JOIN TEACHER_ASSIGNMENTS ta ON ta.class_id = c.id
                                AND ta.active = TRUE
LEFT JOIN TEACHERS t ON t.id = ta.teacher_id
LEFT JOIN STUDENTS s ON s.class_id = c.id
 GROUP BY class_name

Column aliases can be referenced in the GROUP BY when using MySQL, otherwise you'd have to duplicate the logic that produces the class_name column value.  This is also the column to GROUP on, as GROUP_CONCAT and COUNT are aggregate functions.

To get zero as the count value, you might need to use:

   SELECT CONCAT(CONVERT(c.level, CHAR(8)), c.sub_level) AS class_name,
          GROUP_CONCAT(DISTINCT teachers.name SEPARATOR ',') AS teacher_names,
          COALESCE(COUNT(s.id), 0) AS studentCount
     FROM CLASSES c
LEFT JOIN TEACHER_ASSIGNMENTS ta ON ta.class_id = c.id
                                AND ta.active = TRUE
LEFT JOIN TEACHERS t ON t.id = ta.teacher_id
LEFT JOIN STUDENTS s ON s.class_id = c.id
 GROUP BY class_name


问:
How does constant integer assignment in c++
could any please explain the below code

```<code>const uInt32 eVal = 8ul;
const uInt32 fVal = 5ul;
const uInt32 zVal = 0ul;
</code>```

what does ul and numbers 8,5,0 are stand for

答:
ul stands for unsigned long representation of numbers.  Here the number 8 or 5 or 0 of type unsigned long is being assigned to constant uInt32 type variable.

The 'ul' is used for representation. It need not be used also.

Body:
could any please explain the below code

const uInt32 eVal = 8ul;
const uInt32 fVal = 5ul;
const uInt32 zVal = 0ul;

what does ul and numbers 8,5,0 are stand for


问:
extract the text from doc file using python
```<code>import doc2txt
</code>```

I want to extract the string from the document file with Doc2txt it's give the following error.

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/dist-packages/doc2text/__init__.py", line 7, in <module>
    import PythonMagick
ImportError: No module named 'PythonMagick'
</code>```

答:
You can install the whl package manually if pip gives you problems.

Whl package:

https://www.lfd.uci.edu/~gohlke/pythonlibs/#pythonmagick

Select the version that you`d like to install

Usage:

pip install <whl file>

Body:
import doc2txt

I want to extract the string from the document file with Doc2txt it's give the following error.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/dist-packages/doc2text/__init__.py", line 7, in <module>
    import PythonMagick
ImportError: No module named 'PythonMagick'


问:
Testing using Arquillian in embedded Tomee: How to remove HSQL datasource?
I am trying to test a session bean with persistence with Arquillian using embedded Tomee. But Tomee tries to connect to its default HSQLDB datasource.

AFAIK, I should instruct Tomee to use tomee.xml where the HSQLDB datasource is commented.

How can I do that using arquillian.xml? Or there is another way?

My deployment method:

```<code>    @Deployment
public static WebArchive createTestArchive() {
    MavenResolverSystem resolver = Maven.resolver();
    File[] files = resolver.loadPomFromFile("pom.xml").importRuntimeDependencies().resolve().withTransitivity().asFile();

    for (File f : files) {
        System.out.println(f.getPath());
    }

    return ShrinkWrap.create(WebArchive.class)
            .addClasses(MyBean.class)
            .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
            .addAsManifestResource("persistence.xml", "persistence.xml")
            .addAsLibraries(files);
}
</code>```

My persistence.xml:

```<code>    <persistence-unit name="oracle">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <properties>
        <property name="hibernate.archive.autodetection" value="class" />
        <property name="hibernate.dialect"
            value="org.hibernate.dialect.OracleDialect"/>
        <property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver" />
        <property name="hibernate.connection.url" value="jdbc:oracle:thin:@localhost:1521:ORADB" />
        <property name="hibernate.connection.username" value="gk2" />
        <property name="hibernate.connection.password" value="qwerty" />
        <!-- <property name="hibernate.show_sql" value="true"/> -->
        <property name="hibernate.flushMode" value="FLUSH_AUTO" />
        <property name="hibernate.hbm2ddl.auto" value="validate" />
    </properties>
</persistence-unit>
</code>```

My arquillian.xml:

```<code><container qualifier="tomee" default="true">
    <configuration>
        <property name="httpPort">-1</property>
        <property name="stopPort">-1</property>
        <!--Optional Container Properties -->
        <property name="properties">
        </property>
    </configuration>
</container>
</code>```

答:
I have found the problem.

The data source should be configured in arquillian.xml:

```<code>        <property name="properties">
            oracle = new://Resource?type=DataSource
            oracle.JdbcUrl = jdbc:oracle:thin:@localhost:1521:ORADB
            oracle.JdbcDriver = oracle.jdbc.driver.OracleDriver
            oracle.UserName = username
            oracle.Password = password
            ...
        </property>
</code>```

Body:
I am trying to test a session bean with persistence with Arquillian using embedded Tomee. But Tomee tries to connect to its default HSQLDB datasource.

AFAIK, I should instruct Tomee to use tomee.xml where the HSQLDB datasource is commented.

How can I do that using arquillian.xml? Or there is another way?

My deployment method:

    @Deployment
public static WebArchive createTestArchive() {
    MavenResolverSystem resolver = Maven.resolver();
    File[] files = resolver.loadPomFromFile("pom.xml").importRuntimeDependencies().resolve().withTransitivity().asFile();

    for (File f : files) {
        System.out.println(f.getPath());
    }

    return ShrinkWrap.create(WebArchive.class)
            .addClasses(MyBean.class)
            .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml")
            .addAsManifestResource("persistence.xml", "persistence.xml")
            .addAsLibraries(files);
}

My persistence.xml:

    <persistence-unit name="oracle">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <properties>
        <property name="hibernate.archive.autodetection" value="class" />
        <property name="hibernate.dialect"
            value="org.hibernate.dialect.OracleDialect"/>
        <property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver" />
        <property name="hibernate.connection.url" value="jdbc:oracle:thin:@localhost:1521:ORADB" />
        <property name="hibernate.connection.username" value="gk2" />
        <property name="hibernate.connection.password" value="qwerty" />

        <property name="hibernate.flushMode" value="FLUSH_AUTO" />
        <property name="hibernate.hbm2ddl.auto" value="validate" />
    </properties>
</persistence-unit>

My arquillian.xml:

<container qualifier="tomee" default="true">
    <configuration>
        <property name="httpPort">-1</property>
        <property name="stopPort">-1</property>

        <property name="properties">
        </property>
    </configuration>
</container>

Body:
I have found the problem.

The data source should be configured in arquillian.xml:

        <property name="properties">
            oracle = new://Resource?type=DataSource
            oracle.JdbcUrl = jdbc:oracle:thin:@localhost:1521:ORADB
            oracle.JdbcDriver = oracle.jdbc.driver.OracleDriver
            oracle.UserName = username
            oracle.Password = password
            ...
        </property>


问:
UnauthorizedAccessException in LINQPad
```<code>    public void LoadVectors(string model_file)
{
    var file = model_file;
    using (var br = new BinaryReader(File.Open(file, FileMode.Open)))
    {
        wordCount = br.ReadInt32();
        Dimensions = br.ReadInt32();
        for (var w = 0; w < wordCount; w++)
        {
            var word = br.ReadString();
            var vec = new float[Dimensions];
            for (var d = 0; d < Dimensions; d++) vec[d] = br.ReadSingle();
            Normalise(vec);
            model[word] = vec;
        }
    }
}
</code>```

I am calling this function in this function

```<code>private static void Train()
{
    // Train vector model and save to file.
    var word2vec = new Word2Vec();
    word2vec.Train("corpus.txt", "model.bin");
}
</code>```

where corpus.txt is something that I already trained and doesn't matter in this question, and model.bin is something that I need to read.

But when I call this, it gives me an UnauthorizedAccessException at
'C:\Program Files (x86)\LINQPad5\model.bin' and this is not the right location for model.bin

When I try to put the absolute location of model.bin by doing

```<code>word2vec.Train("corpus.txt", @"D:\Users\user\Documents\Visual Studio 2017\Projects\word2VecTest\word2VecTest\bin\Debug\model.bin");
</code>```

It gives me the same error.

How can I set this location to work in LINQPad??

答: Try to run your program as admin. this could be your solution.</p>

Title: UnauthorizedAccessException in LINQPad

Body:
    public void LoadVectors(string model_file)
{
    var file = model_file;
    using (var br = new BinaryReader(File.Open(file, FileMode.Open)))
    {
        wordCount = br.ReadInt32();
        Dimensions = br.ReadInt32();
        for (var w = 0; w < wordCount; w++)
        {
            var word = br.ReadString();
            var vec = new float[Dimensions];
            for (var d = 0; d < Dimensions; d++) vec[d] = br.ReadSingle();
            Normalise(vec);
            model[word] = vec;
        }
    }
}

I am calling this function in this function

private static void Train()
{
    // Train vector model and save to file.
    var word2vec = new Word2Vec();
    word2vec.Train("corpus.txt", "model.bin");
}

where corpus.txt is something that I already trained and doesn't matter in this question, and model.bin is something that I need to read.

But when I call this, it gives me an UnauthorizedAccessException at
'C:\Program Files (x86)\LINQPad5\model.bin' and this is not the right location for model.bin

When I try to put the absolute location of model.bin by doing

word2vec.Train("corpus.txt", @"D:\Users\user\Documents\Visual Studio 2017\Projects\word2VecTest\word2VecTest\bin\Debug\model.bin");

It gives me the same error.

How can I set this location to work in LINQPad??


问:
How to send back the tokens to android using Firebase Auth
I am developing an Android app which uses Firebase and my own server running Django. What I intend to do is, I want to first authenticate the user using android app to the django server which then generates the custom tokens as specified in firebase docs. Then I want to send the generated custom token back to the android.

My question is how to send that custom token back to android? I tried to send as JSON object. But it says JWT are not JSON serializable.

I passed the username and password from android app as json object and authenticated with my django server.

Here is my minimal Django code:

```<code>import firebase_admin
from firebase_admin import credentials
from firebase_admin import auth

cred = credentials.Certificate("firebase-admin.json")
default_app = firebase_admin.initialize_app(cred)

def validateuser(request):
    json_data=json.loads(request.body.decode('utf-8'))

    try:
        // I verify the username and password and extract the uid
        uid = 'some-uid'
        custom_token = auth.create_custom_token(uid)

        result={'TAG_SUCCESS': 1, 'CUSTOM_TOKEN': custom_token }
    except:
        result={'TAG_SUCCESS': 0, 'CUSTOM_TOKEN': '0'}

    return HttpResponse(json.dumps(result), content_type='application/json')
</code>```

But it says the custom token is not JSON serializable. Is it not  the way to do like this? How do I send the custom token back to the android app?

And this is the error:

uid:  78b30d23-6238-4634-b2e4-73cc1f0f7486

custom_token: b'eyJraWQiOiAiZmFlNzA2MzZiY2UwZTk0Y2Y5YTM2OWRlNzc4ZDZlYWQ5NGMwM2MzYiIsICJhbGciOiAiUlMyNTYiLCAidHlwIjogIkpXVCJ9.eyJpc3MiOiAiZmlyZWJhc2UtYWRtaW5zZGstOXBtbjVAYnVzdHJhY2tlci0xZDE3OS5pYW0uZ3NlcnZpY2VhY2NvdW50LmNvbSIsICJ1aWQiOiAiNzhiMzBkMjMtNjIzOC00NjM0LWIyZTQtNzNjYzFmMGY3NDg2IiwgImF1ZCI6ICJodHRwczovL2lkZW50aXR5dG9vbGtpdC5nb29nbGVhcGlzLmNvbS9nb29nbGUuaWRlbnRpdHkuaWRlbnRpdHl0b29sa2l0LnYxLklkZW50aXR5VG9vbGtpdCIsICJleHAiOiAxNTA4MDc2OTA4LCAiaWF0IjogMTUwODA3MzMwOCwgInN1YiI6ICJmaXJlYmFzZS1hZG1pbnNkay05cG1uNUBidXN0cmFja2VyLTFkMTc5LmlhbS5nc2VydmljZWFjY291bnQuY29tIn0=.jgexW_xR5FeZvuO5TPWO8EOBnRJ28ut9OR_OxeajE1_o4ns4fwd2pMXlK2GkM464P5Vi-IxheG-IIJcANxGSDeZgvgpkLfKkHMZeSaraqfEQGq6N7ipuD8o1T7zd5qm79twmFbrQZRB1y7g1-zcjL69x8KFsThWOTmo0TYj5l3zf8_2Cxbw2SGefMWkCwL0d1yQjcUqVyuSAP3-Sg8KrrqCcG4cjNOXKeWxwbUQO7DobOQlT5TfRApwWk8Td6uPjD7d6jqMo-HPKOis0vRoXMBzflZKj36-hIOFkygZNbDWLTsQzbb3HZg8dBabA5GTy--iQi038TRMIm2W0irr0ng=='

Internal Server Error: /api/user/validateuser/ Traceback (most recent
  call last):   File
  "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py",
  line 41, in inner
      response = get_response(request)   File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py",
  line 249, in _legacy_get_response
      response = self._get_response(request)   File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py",
  line 187, in _get_response
      response = self.process_exception_by_middleware(e, request)   File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py",
  line 185, in _get_response
      response = wrapped_callback(request, *callback_args, **callback_kwargs)   File "/usr/local/lib/python3.5/dist-packages/django/views/decorators/csrf.py",
  line 58, in wrapped_view
      return view_func(*args, **kwargs)   File "/home/ubuntu/www/Tracker/user/api/views.py", line 251, in
  validateuser
      return HttpResponse(json.dumps(result), content_type='application/json')   File
  "/usr/lib/python3.5/json/init.py", line 230, in dumps
      return _default_encoder.encode(obj)   File "/usr/lib/python3.5/json/encoder.py", line 198, in encode
      chunks = self.iterencode(o, _one_shot=True)   File "/usr/lib/python3.5/json/encoder.py", line 256, in iterencode
      return _iterencode(o, 0)   File
  "/usr/lib/python3.5/json/encoder.py", line 179, in default

```<code>raise TypeError(repr(o) + " is not JSON serializable")
</code>```

答:
I think you are using python3 version. I found what the problem is.

The auth.create_custom_token(uid) method returns a bytes literal and bytes literal are not JSON serializable. That is why you are getting the error. You can see b' infront of the jwt token.

So, you need to just convert the byte literal to string using the code below.

```<code>custom_token = (auth.create_custom_token(uid)).decode()
</code>```

Body:
I am developing an Android app which uses Firebase and my own server running Django. What I intend to do is, I want to first authenticate the user using android app to the django server which then generates the custom tokens as specified in firebase docs. Then I want to send the generated custom token back to the android.

My question is how to send that custom token back to android? I tried to send as JSON object. But it says JWT are not JSON serializable.

I passed the username and password from android app as json object and authenticated with my django server.

Here is my minimal Django code:

import firebase_admin
from firebase_admin import credentials
from firebase_admin import auth

cred = credentials.Certificate("firebase-admin.json")
default_app = firebase_admin.initialize_app(cred)

def validateuser(request):
    json_data=json.loads(request.body.decode('utf-8'))

    try:
        // I verify the username and password and extract the uid
        uid = 'some-uid'
        custom_token = auth.create_custom_token(uid)

        result={'TAG_SUCCESS': 1, 'CUSTOM_TOKEN': custom_token }
    except:
        result={'TAG_SUCCESS': 0, 'CUSTOM_TOKEN': '0'}

    return HttpResponse(json.dumps(result), content_type='application/json')

But it says the custom token is not JSON serializable. Is it not  the way to do like this? How do I send the custom token back to the android app?

And this is the error:

uid:  78b30d23-6238-4634-b2e4-73cc1f0f7486

custom_token: b'eyJraWQiOiAiZmFlNzA2MzZiY2UwZTk0Y2Y5YTM2OWRlNzc4ZDZlYWQ5NGMwM2MzYiIsICJhbGciOiAiUlMyNTYiLCAidHlwIjogIkpXVCJ9.eyJpc3MiOiAiZmlyZWJhc2UtYWRtaW5zZGstOXBtbjVAYnVzdHJhY2tlci0xZDE3OS5pYW0uZ3NlcnZpY2VhY2NvdW50LmNvbSIsICJ1aWQiOiAiNzhiMzBkMjMtNjIzOC00NjM0LWIyZTQtNzNjYzFmMGY3NDg2IiwgImF1ZCI6ICJodHRwczovL2lkZW50aXR5dG9vbGtpdC5nb29nbGVhcGlzLmNvbS9nb29nbGUuaWRlbnRpdHkuaWRlbnRpdHl0b29sa2l0LnYxLklkZW50aXR5VG9vbGtpdCIsICJleHAiOiAxNTA4MDc2OTA4LCAiaWF0IjogMTUwODA3MzMwOCwgInN1YiI6ICJmaXJlYmFzZS1hZG1pbnNkay05cG1uNUBidXN0cmFja2VyLTFkMTc5LmlhbS5nc2VydmljZWFjY291bnQuY29tIn0=.jgexW_xR5FeZvuO5TPWO8EOBnRJ28ut9OR_OxeajE1_o4ns4fwd2pMXlK2GkM464P5Vi-IxheG-IIJcANxGSDeZgvgpkLfKkHMZeSaraqfEQGq6N7ipuD8o1T7zd5qm79twmFbrQZRB1y7g1-zcjL69x8KFsThWOTmo0TYj5l3zf8_2Cxbw2SGefMWkCwL0d1yQjcUqVyuSAP3-Sg8KrrqCcG4cjNOXKeWxwbUQO7DobOQlT5TfRApwWk8Td6uPjD7d6jqMo-HPKOis0vRoXMBzflZKj36-hIOFkygZNbDWLTsQzbb3HZg8dBabA5GTy--iQi038TRMIm2W0irr0ng=='

Internal Server Error: /api/user/validateuser/ Traceback (most recent
  call last):   File
  "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py",
  line 41, in inner
      response = get_response(request)   File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py",
  line 249, in _legacy_get_response
      response = self._get_response(request)   File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py",
  line 187, in _get_response
      response = self.process_exception_by_middleware(e, request)   File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py",
  line 185, in _get_response
      response = wrapped_callback(request, *callback_args, **callback_kwargs)   File "/usr/local/lib/python3.5/dist-packages/django/views/decorators/csrf.py",
  line 58, in wrapped_view
      return view_func(*args, **kwargs)   File "/home/ubuntu/www/Tracker/user/api/views.py", line 251, in
  validateuser
      return HttpResponse(json.dumps(result), content_type='application/json')   File
  "/usr/lib/python3.5/json/init.py", line 230, in dumps
      return _default_encoder.encode(obj)   File "/usr/lib/python3.5/json/encoder.py", line 198, in encode
      chunks = self.iterencode(o, _one_shot=True)   File "/usr/lib/python3.5/json/encoder.py", line 256, in iterencode
      return _iterencode(o, 0)   File
  "/usr/lib/python3.5/json/encoder.py", line 179, in default

raise TypeError(repr(o) + " is not JSON serializable")

Body:
I think you are using python3 version. I found what the problem is.

The auth.create_custom_token(uid) method returns a bytes literal and bytes literal are not JSON serializable. That is why you are getting the error. You can see b' infront of the jwt token.

So, you need to just convert the byte literal to string using the code below.

custom_token = (auth.create_custom_token(uid)).decode()


问:
Remove suffix from filename in Swift
When trying to remove the suffix from a filename, I'm only left with the suffix, which is exactly not what I want.

What (how many things) am I doing wrong here:

```<code>let myTextureAtlas = SKTextureAtlas(named: "demoArt")

let filename = (myTextureAtlas.textureNames.first?.characters.split{$0 == "."}.map(String.init)[1].replacingOccurrences(of: "\'", with: ""))! as String

print(filename)
</code>```

This prints png which is the most dull part of the whole thing.

答:
@Confused with Swift 4 you can do this:

```<code>let fileName = "demoArt.png"
// or on your specific case:
// let fileName = myTextureAtlas.textureNames.first

let name = String(fileName.split(separator: ".").first!)
print(name)
</code>```

Additionally you should also unwrapp first but I didn't want to complicate the sample code to solve your problem.

Btw, since I've also needed this recently, if you want to remove a specific suffix you know in advance, you can do something like this:

```<code>let fileName = "demoArt.png"
let fileNameExtension = ".png"

if fileName.hasSuffix(fileNameExtension) {
    let name = fileName.prefix(fileName.count - fileNameExtension.count)
    print(name)
}
</code>```

Title: Remove suffix from filename in Swift

Body:
When trying to remove the suffix from a filename, I'm only left with the suffix, which is exactly not what I want.

What (how many things) am I doing wrong here:

let myTextureAtlas = SKTextureAtlas(named: "demoArt")

let filename = (myTextureAtlas.textureNames.first?.characters.split{$0 == "."}.map(String.init)[1].replacingOccurrences(of: "\'", with: ""))! as String

print(filename)

This prints png which is the most dull part of the whole thing.

Body:
@Confused with Swift 4 you can do this:

let fileName = "demoArt.png"
// or on your specific case:
// let fileName = myTextureAtlas.textureNames.first

let name = String(fileName.split(separator: ".").first!)
print(name)

Additionally you should also unwrapp first but I didn't want to complicate the sample code to solve your problem.

Btw, since I've also needed this recently, if you want to remove a specific suffix you know in advance, you can do something like this:

let fileName = "demoArt.png"
let fileNameExtension = ".png"

if fileName.hasSuffix(fileNameExtension) {
    let name = fileName.prefix(fileName.count - fileNameExtension.count)
    print(name)
}


问:
Accessing an associative array by integer index in PHP
I want to set the value of an associative array using the array index of the key/value pair.  For example:

```<code>$my_arr = array( "bling" => "some bling", "bling2" => "lots O bling" );
$my_arr[1] = "not so much bling";  // Would change the value with key bling2.
</code>```

How can this be accomplish this without using the key string?

答:
There is no correlation between numeric and associative index keys.

When you say you want to set the value of an associative array using the array index of the key/value, then you have to use the given key, setting $array[1] is not the same as setting $array['foo'].

Consider this array

```<code>print_r( array('foo', 'foo' => 'bar', 'baz', 'some' => 'value') );
</code>```

This will give

```<code>Array
(
    [0] => foo
    [foo] => bar
    [1] => baz
    [some] => value
)
</code>```

The foo is the second element in the array. That's the offset, but it has nothing to do with the index 1. As you can see, in that array above, index 1 is associated with baz. It is wrong to assume that just because foo is the first associative key it has anything to do with the actual numeric key 1. Just like some does not correlate to 2.

Likewise, for a mixed array like shown above, the solution with array_keys suggested elsewhere on this site will not work, because

```<code>print_r( array_keys(array('foo', 'foo' => 'bar', 'baz', 'some' => 'value')) );
</code>```

will give

```<code>Array
(
    [0] => 0
    [1] => foo
    [2] => 1
    [3] => some
)
</code>```

So when you do $array[$keys[1]] you are really doing $array['foo']. But if you wanted to access the second associative value in that array ('some'), you cannot do $array[$keys[2]] because that would evaluate to $array[1] and that's baz.

The Offset of an element is completely unrelated to it's key or value

```<code>print_r(
    array(
        100    => 'foo',
        'foo'  => 'bar',
        50     => 'baz',
        'some' => 'value'
    )
);
</code>```

really means

```<code>Array
( //key       value     offset/position
    [100]  => foo       // 0
    [foo]  => bar       // 1
    [50]   => baz       // 2
    [some] => value     // 3
)
</code>```

which means the element at offset 0 is foo although it's key is 100. If you want to extract elements from an array by offset, you have to use

```<code>$third = array_splice($array, 2, 1);
echo $third[0]; // baz
</code>```

This would create an array holding only the element at the third position.

Or you could use an ArrayIterator. The ArrayIterator implements a Seekable interface that lets you seek to a specific position/offset in the array and then fetch that:

```<code>$iterator = new ArrayIterator($array);
$iterator->seek(3);
echo $iterator->current(); // value
</code>```

Body:
I want to set the value of an associative array using the array index of the key/value pair.  For example:

$my_arr = array( "bling" => "some bling", "bling2" => "lots O bling" );
$my_arr[1] = "not so much bling";  // Would change the value with key bling2.

How can this be accomplish this without using the key string?

Body:
There is no correlation between numeric and associative index keys.

When you say you want to set the value of an associative array using the array index of the key/value, then you have to use the given key, setting $array[1] is not the same as setting $array['foo'].

Consider this array

print_r( array('foo', 'foo' => 'bar', 'baz', 'some' => 'value') );

This will give

Array
(
    [0] => foo
    [foo] => bar
    [1] => baz
    [some] => value
)

The foo is the second element in the array. That's the offset, but it has nothing to do with the index 1. As you can see, in that array above, index 1 is associated with baz. It is wrong to assume that just because foo is the first associative key it has anything to do with the actual numeric key 1. Just like some does not correlate to 2.

Likewise, for a mixed array like shown above, the solution with array_keys suggested elsewhere on this site will not work, because

print_r( array_keys(array('foo', 'foo' => 'bar', 'baz', 'some' => 'value')) );

will give

Array
(
    [0] => 0
    [1] => foo
    [2] => 1
    [3] => some
)

So when you do $array[$keys[1]] you are really doing $array['foo']. But if you wanted to access the second associative value in that array ('some'), you cannot do $array[$keys[2]] because that would evaluate to $array[1] and that's baz.

The Offset of an element is completely unrelated to it's key or value

print_r(
    array(
        100    => 'foo',
        'foo'  => 'bar',
        50     => 'baz',
        'some' => 'value'
    )
);

really means

Array
( //key       value     offset/position
    [100]  => foo       // 0
    [foo]  => bar       // 1
    [50]   => baz       // 2
    [some] => value     // 3
)

which means the element at offset 0 is foo although it's key is 100. If you want to extract elements from an array by offset, you have to use

$third = array_splice($array, 2, 1);
echo $third[0]; // baz

This would create an array holding only the element at the third position.

Or you could use an ArrayIterator. The ArrayIterator implements a Seekable interface that lets you seek to a specific position/offset in the array and then fetch that:

$iterator = new ArrayIterator($array);
$iterator->seek(3);
echo $iterator->current(); // value


问:
Close dropdown when second is opened / document.click blocked by click Angular 5
I am trying to create a directive for a drop-down, as long as I am working with single one it works like a charm. I can spot click outside dropdown using following code:

```<code>@HostListener('document:click', ['$event'])
  onDocumentClick(event: any): void {
    console.log("document click");
    // close
}
@HostListener('click')
  onClick(): void {
    console.log('click on ');
    // toggle
  }
</code>```

The problem occurs when there are 2 dropdowns created. I would like close first drop-down when second is opened, however when I click on the second dropdown, only "click" event is getting triggered and "document.click" is not getting executed. I would expect that both events should occur unless I explicitly use preventDefault on click but apparently this happens automatically.

What should be correct approach in Angular 5 to close first drop-down when second is opened?

答:
Maybe you can try something like this:

```<code> @HostListener('document:click', ['$event'])
  onClick(event) {
    if(this.eRef.nativeElement.contains(event.target)) {
      // toggle logic
    } else {
      // close logic
    }
}
</code>```

So instead of having two events conflicting with each other you would have one event with two pieces of logic to handle exactly what you need depending if you clicked inside or outside the element itself. Makes sense?

This was taken from here

Body:
I am trying to create a directive for a drop-down, as long as I am working with single one it works like a charm. I can spot click outside dropdown using following code:

@HostListener('document:click', ['$event'])
  onDocumentClick(event: any): void {
    console.log("document click");
    // close
}
@HostListener('click')
  onClick(): void {
    console.log('click on ');
    // toggle
  }

The problem occurs when there are 2 dropdowns created. I would like close first drop-down when second is opened, however when I click on the second dropdown, only "click" event is getting triggered and "document.click" is not getting executed. I would expect that both events should occur unless I explicitly use preventDefault on click but apparently this happens automatically.

What should be correct approach in Angular 5 to close first drop-down when second is opened?

Body:
Maybe you can try something like this:

 @HostListener('document:click', ['$event'])
  onClick(event) {
    if(this.eRef.nativeElement.contains(event.target)) {
      // toggle logic
    } else {
      // close logic
    }
}

So instead of having two events conflicting with each other you would have one event with two pieces of logic to handle exactly what you need depending if you clicked inside or outside the element itself. Makes sense?

This was taken from here


问:
Java 9 - How to see help on Jshell?
Anybody here familiar with any good documentation on how could we work with jshell. I am struggling even to find help for same inside the jshell. Any good reference will work too.</p>

答:
In console when you run jshell just type /help

Also you may see verbose description and options for single command by type help before command in console, example: jshell> /help /list

From the documentation:

Tab Completion for Commands

Similar to snippet completion, when you enter commands and command
  options, use the Tab key to automatically complete the command or
  option. If the completion can’t be determined from what was entered,
  then possible choices are provided.

The following example shows the feedback when Tab is pressed after the
  leading slash (/) for commands:

```<code>jshell> /<Tab>
/!          /?          /drop       /edit       /env        /exit       /help
/history    /imports    /list       /methods    /open       /reload     /reset
/save       /set        /types      /vars

<press tab again to see synopsis>

jshell> /
</code>```

Title: Java 9 - How to see help on Jshell?

Body:
In console when you run jshell just type /help

Also you may see verbose description and options for single command by type help before command in console, example: jshell> /help /list

From the documentation:

Tab Completion for Commands

Similar to snippet completion, when you enter commands and command
  options, use the Tab key to automatically complete the command or
  option. If the completion can’t be determined from what was entered,
  then possible choices are provided.

The following example shows the feedback when Tab is pressed after the
  leading slash (/) for commands:

jshell> /<Tab>
/!          /?          /drop       /edit       /env        /exit       /help
/history    /imports    /list       /methods    /open       /reload     /reset
/save       /set        /types      /vars

<press tab again to see synopsis>

jshell> /


问:
Cosmos DB: save object type as a property in document
I want to save object type as a part of json object when upsert my object into cosmos db. I've tried to pass a json serializer when instantiating instance of Cosmos Client, but it doesn't work. I still don't see type of object in document.
What I was trying to do:

```<code>    public static readonly JsonSerializerSettings DefaultJsonSerializerSettings =
        new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.All,
            DateFormatString = "o",
            DateFormatHandling = DateFormatHandling.IsoDateFormat,
        };

    var CosmosClient =
            new DocumentClient(
                new Uri(CosmosConfig.ServiceEndpoint),
                CosmosConfig.AuthNKey,
                DefaultJsonSerializerSettings,
                connectionPolicySettings);
</code>```

Any other way to have such a behavior without preprocessing (converting object to jObject) first?
Thanks

Upd:

What I trying to achive is smth like next structure in my document (automaticaly serialized type):

```<code>    {
      "$type" : "MyNamespace.Foo",
      "Id": "1560e1be-bf87-4720-a22e-b7e2c4c37f2e",
      "Name" : "Vasia"
    }
</code>```

instead of current one like this (without type):

```<code>    {
      "Id": "1560e1be-bf87-4720-a22e-b7e2c4c37f2e",
      "Name" : "Vasia"
    }
</code>```

答:
According to my understanding you mean to say that you want to recognise the type of entity like Customer, Seller,etc.

If that is so I would like to inform you that Cosmos DB is schema less database and hence you cannot have it in format like Customer,etc. If you really need to recognize the type of object in Cosmos DB you will have to add one property like Type="Customer" or Type="Employee" in your object or entity which you want to save because all objects in DocumentDB are stored in similar form and that is JSON there is nothing concept like table of Customer/Employee as in SQL.

Dont forget to mark my answer if it helps you..

Body:
I want to save object type as a part of json object when upsert my object into cosmos db. I've tried to pass a json serializer when instantiating instance of Cosmos Client, but it doesn't work. I still don't see type of object in document.
What I was trying to do:

    public static readonly JsonSerializerSettings DefaultJsonSerializerSettings =
        new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.All,
            DateFormatString = "o",
            DateFormatHandling = DateFormatHandling.IsoDateFormat,
        };

    var CosmosClient =
            new DocumentClient(
                new Uri(CosmosConfig.ServiceEndpoint),
                CosmosConfig.AuthNKey,
                DefaultJsonSerializerSettings,
                connectionPolicySettings);

Any other way to have such a behavior without preprocessing (converting object to jObject) first?
Thanks

Upd:

What I trying to achive is smth like next structure in my document (automaticaly serialized type):

    {
      "$type" : "MyNamespace.Foo",
      "Id": "1560e1be-bf87-4720-a22e-b7e2c4c37f2e",
      "Name" : "Vasia"
    }

instead of current one like this (without type):

    {
      "Id": "1560e1be-bf87-4720-a22e-b7e2c4c37f2e",
      "Name" : "Vasia"
    }


问:
How do I load Angular 4 into an AngularJS app using SystemJS?
I want to convert an AngularJS app to Angular 4. I'm reading the official Angular documentation for upgrading from AngularJS at https://angular.io/guide/upgrade. It states this:

To begin converting your AngularJS application to a hybrid, you need
  to load the Angular framework. You can see how this can be done with
  SystemJS by following the instructions in Setup, selectively copying
  code from the QuickStart github repository.

The 'Setup' link however leads to a page which doesn't mention SystemJS. How do I use SystemJS to load/build the Angular 4 framework into the existing AngularJS app?

答:
The link you specified points to the Angular quickstart project which uses systemjs. https://github.com/angular/quickstart

Although the project is marked as deprecated it is currently still valid in how you can setup Angular with systemjs.

You can then use the quickstart as the basis for porting your code across and will enable you to follow the additional instructions in that setup steps.


问:
Cleanup of resources Wicket 6
In Java Wicket 6, I'm trying to find out how to get notified in a Page or Component when that Page / component is no longer used.

The context is I have a configuration service that can have listeners added to it to notify when configuration has changed / reloaded.

Obviously, if a page/component is no longer needed then I should remove it as a listener from the service, but I can't find a way of being notified or that fact.

onRemove() doesn't cut it, as it doesn't appear to be called on the page or components in the page since I'm not explicitly REMOVING anything. I'm just letting pages/components drift away into the ether.

Any ideas on how I can clean up my resources to make sure my listener list / memory footprint doesn't balloon over a period of time?

My pages are stateful, btw (although I'm not sure they need to be atm). The Configuration Service is injected into a Page/Component via @SpringBean.

One possible way to propagate a configuration update it to have the page listen ONLY and then fire a Wicket event to contained components. This would cut down on the number of listeners to the Service, but this doesn't FEEL very nice if the components have a reference to the Configuration Service anyway to then be told by something else that it needs to reconfigure. Maybe.

Even so, with the above solution I'd still like to clear the Page from the listener list when no longer needed.

答:
By using @SpringBean you do not make a hard reference between the Page/Component and the real service instance!

@SpringBean injects a (serializable) Proxy that has logic to lookup the Spring bean from Spring's ApplicationContext. So I think you have nothing to clean actually.

Title: Cleanup of resources Wicket 6


问:
laravel Undefined variable when i post multiple value to view
In controller when i try to send multiple value to view such as this codes:

```<code>$content = Contents::find($contents);
$content_categories['categories'] = ContentCategories::all()->pluck('title', 'id');
$selected_categories['selected_categories'] = $content->categories()->pluck('title', 'id');

return view('layouts.backend.pages.manage_contents.edit', compact($selected_categories, $content_categories, ['content' => $content]));
</code>```

i get error for this variables into view:

```<code>$categories
$selected_categories
$content
</code>```

result of dd(['content' => $content], $content_categories, $selected_categories); is:

```<code>array:1 [▼
  "content" => Contents {#220 ▶}
]

array:1 [▼
  "categories" => Collection {#214 ▶}
]

array:1 [▼
  "selected_categories" => Collection {#227 ▶}
]
</code>```

whats problem of my code to parse them on view or send them with correct way

my view:

```<code>1) {{ Form::select('categories[]', $categories, $selected_categories, array('class' => 'multiselect-success','multiple'=>'multiple')) }}

2) action="{{ route('manage_contents.update' , ['id' => $content->id ]) }}"
</code>```

Errors:

```<code>"Undefined variable: categories (View: /Applications/XAMPP/xamppfiles/htdocs/alachiqServer/resources/views/layouts/backend/pages/manage_contents/edit.blade.php)"

"Undefined variable: selected_categories (View: /Applications/XAMPP/xamppfiles/htdocs/alachiqServer/resources/views/layouts/backend/pages/manage_contents/edit.blade.php)"

"Undefined variable: content (View: /Applications/XAMPP/xamppfiles/htdocs/alachiqServer/resources/views/layouts/backend/pages/manage_contents/edit.blade.php)"
</code>```

答:
Try this way:</p>

```<code>return view('layouts.backend.pages.manage_contents.edit', compact('selected_categories', 'content_categories', 'content'));
</code>```

Body:
In controller when i try to send multiple value to view such as this codes:

$content = Contents::find($contents);
$content_categories['categories'] = ContentCategories::all()->pluck('title', 'id');
$selected_categories['selected_categories'] = $content->categories()->pluck('title', 'id');

return view('layouts.backend.pages.manage_contents.edit', compact($selected_categories, $content_categories, ['content' => $content]));

i get error for this variables into view:

$categories
$selected_categories
$content

result of dd(['content' => $content], $content_categories, $selected_categories); is:

array:1 [▼
  "content" => Contents {#220 ▶}
]

array:1 [▼
  "categories" => Collection {#214 ▶}
]

array:1 [▼
  "selected_categories" => Collection {#227 ▶}
]

whats problem of my code to parse them on view or send them with correct way

my view:

1) {{ Form::select('categories[]', $categories, $selected_categories, array('class' => 'multiselect-success','multiple'=>'multiple')) }}

2) action="{{ route('manage_contents.update' , ['id' => $content->id ]) }}"

Errors:

"Undefined variable: categories (View: /Applications/XAMPP/xamppfiles/htdocs/alachiqServer/resources/views/layouts/backend/pages/manage_contents/edit.blade.php)"

"Undefined variable: selected_categories (View: /Applications/XAMPP/xamppfiles/htdocs/alachiqServer/resources/views/layouts/backend/pages/manage_contents/edit.blade.php)"

"Undefined variable: content (View: /Applications/XAMPP/xamppfiles/htdocs/alachiqServer/resources/views/layouts/backend/pages/manage_contents/edit.blade.php)"

Body:
Try this way:

return view('layouts.backend.pages.manage_contents.edit', compact('selected_categories', 'content_categories', 'content'));


问:
Align a piechart in plot area
I'm generating a pie chart that I would like to incorporate into a Shiny page. The plot area (i.e.: the white space surrounding the plot) will be fluid. I'd like the plot itself (the grey area and the pie chart) to align to the left-hand side of the plot area, instead of appearing centered. Any ideas?

```<code>ggplot(treeData, aes(x = "", fill = ClassName)) +
  ggtitle("Species distribution") +
  geom_bar(width = 1) +
  coord_polar("y", start=0) +
  xlab("") + ylab("") +
  theme(
    axis.text.x=element_blank(),
    axis.text = element_blank(),
    axis.ticks = element_blank(),
    panel.grid  = element_blank(),
    plot.margin=unit(c(25,0,0,0), "pt")) +
  scale_fill_manual(values= c("#ffff00", "#008080", "#00ff00"))
</code>```

答:
You can try to change the margins by adding

```<code>theme(plot.margin = unit(c(5.5, 100, 5.5, -100), "points"))
</code>```

or use the cowplot function

```<code>cowplot::plot_grid(your_plot, NULL, ncol=2, rel_widths = c(2,1))
</code>```

Title: Align a piechart in plot area

Body:
I'm generating a pie chart that I would like to incorporate into a Shiny page. The plot area (i.e.: the white space surrounding the plot) will be fluid. I'd like the plot itself (the grey area and the pie chart) to align to the left-hand side of the plot area, instead of appearing centered. Any ideas?

ggplot(treeData, aes(x = "", fill = ClassName)) +
  ggtitle("Species distribution") +
  geom_bar(width = 1) +
  coord_polar("y", start=0) +
  xlab("") + ylab("") +
  theme(
    axis.text.x=element_blank(),
    axis.text = element_blank(),
    axis.ticks = element_blank(),
    panel.grid  = element_blank(),
    plot.margin=unit(c(25,0,0,0), "pt")) +
  scale_fill_manual(values= c("#ffff00", "#008080", "#00ff00"))

Body:
You can try to change the margins by adding

theme(plot.margin = unit(c(5.5, 100, 5.5, -100), "points"))

or use the cowplot function

cowplot::plot_grid(your_plot, NULL, ncol=2, rel_widths = c(2,1))


问:
keyevent in jQuery not working
I've got an HTML element that I want to fill with specific content after someone presses "1" on the keyboard.
I use an external .js file which contains the following code:

```<code>$(document).ready(function() {
    $("#myid").html("Hello, 0111");
    $("#myid2").html("Lorem Ipsum");

    $(document).keyup(function (pressed_key) {
        if (pressed_key.key === "1") {
            $("#myid").html("Button pressed");

            setTimeout(￼function () {
                $("#myid").html("Button not pressed");
            }, 1000);
        }
    }

});
</code>```

My HTML body looks like this:

```<code><body>
    <div id="myid">0129</div>
    <div id="myid2"></div>
    <script src="js/libs/jquery/jquery.min.js"></script>
    <script src="js/script.js"></script>
</body>
</code>```

The code is not working, it outputs the content of the HTML document.

However, if I comment out the .keyup function, the rest of the JavaScript code works and changes the HTML content accordingly.

Any ideas?

答:
The issue is because the argument passed to the keyup handler is the event, not the value of the character which was typed.

To fix this you can use String.fromCharCode(), along with the which property of the event, to get the character, like this:

$(document).ready(function() {
  $("#myid").html("Hello, 0111");
  $("#myid2").html("Lorem Ipsum");

  $(document).keyup(function(e) {
    if (String.fromCharCode(e.which) === "1") {
      $("#myid").html("Button pressed");

      setTimeout(function() {
        $("#myid").html("Button not pressed");
      }, 1000);
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myid">0129</div>
<div id="myid2"></div></code>```

Title: keyevent in jQuery not working

Body:
I've got an HTML element that I want to fill with specific content after someone presses "1" on the keyboard.
I use an external .js file which contains the following code:

$(document).ready(function() {
    $("#myid").html("Hello, 0111");
    $("#myid2").html("Lorem Ipsum");

    $(document).keyup(function (pressed_key) {
        if (pressed_key.key === "1") {
            $("#myid").html("Button pressed");

            setTimeout(￼function () {
                $("#myid").html("Button not pressed");
            }, 1000);
        }
    }

});

My HTML body looks like this:

0129

The code is not working, it outputs the content of the HTML document.

However, if I comment out the .keyup function, the rest of the JavaScript code works and changes the HTML content accordingly.

Any ideas?

Body:
The issue is because the argument passed to the keyup handler is the event, not the value of the character which was typed.

To fix this you can use String.fromCharCode(), along with the which property of the event, to get the character, like this:

$(document).ready(function() {
  $("#myid").html("Hello, 0111");
  $("#myid2").html("Lorem Ipsum");

  $(document).keyup(function(e) {
    if (String.fromCharCode(e.which) === "1") {
      $("#myid").html("Button pressed");

      setTimeout(function() {
        $("#myid").html("Button not pressed");
      }, 1000);
    }
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myid">0129</div>
<div id="myid2"></div>


问:
How to split a file by a multi-character delimiter?
On Unix, without adding anything to the OS (i.e. only using grep, awk, sed, cut, etc.), how can I extract the "text" line in only the "codeView" section (and ignore that in the "probableStartLocationView" section)?

```<code>. . .
      "events" : [ {
"id" : "12345",
"important" : true,
"type" : "Creation",
"description" : "Something happened here",
"extraDetails" : null,
"codeView" : {
  "lines" : [ {
    "fragments" : [ {
      "type" : "NORMAL_CODE",
      "value" : "str = wrapper.getParameter("
    }, {
      "type" : "CODE_STRING",
      "value" : ""abcd""
    }, {
      "type" : "NORMAL_CODE",
      "value" : ")"
    } ],
    "text" : "str = wrapper.getParameter("abcd")"
  } ],
  "nested" : false
},
"probableStartLocationView" : {
  "lines" : [ {
    "fragments" : [ {
      "type" : "STACKTRACE_LINE",
      "value" : "<init>() @ JSONInputData.java:72"
    } ],
    "text" : "<init>() @ JSONInputData.java:72"
  } ],
  "nested" : false
},
. . .
</code>```

答:
This might work for you (GNU sed):

```<code>sed -n '/^"[^"]*"/h;//!G;/"text".*\n"codeView"/P;d' file
</code>```

Save the current section in the hold space and append it to each line within that section. Using the grep-like option -n prevents lines being printed as normal and using a regexp and the P command print the line that meets your criteria.

Body:
On Unix, without adding anything to the OS (i.e. only using grep, awk, sed, cut, etc.), how can I extract the "text" line in only the "codeView" section (and ignore that in the "probableStartLocationView" section)?

. . .
      "events" : [ {
"id" : "12345",
"important" : true,
"type" : "Creation",
"description" : "Something happened here",
"extraDetails" : null,
"codeView" : {
  "lines" : [ {
    "fragments" : [ {
      "type" : "NORMAL_CODE",
      "value" : "str = wrapper.getParameter("
    }, {
      "type" : "CODE_STRING",
      "value" : ""abcd""
    }, {
      "type" : "NORMAL_CODE",
      "value" : ")"
    } ],
    "text" : "str = wrapper.getParameter("abcd")"
  } ],
  "nested" : false
},
"probableStartLocationView" : {
  "lines" : [ {
    "fragments" : [ {
      "type" : "STACKTRACE_LINE",
      "value" : "<init>() @ JSONInputData.java:72"
    } ],
    "text" : "<init>() @ JSONInputData.java:72"
  } ],
  "nested" : false
},
. . .

Body:
This might work for you (GNU sed):

sed -n '/^"[^"]*"/h;//!G;/"text".*\n"codeView"/P;d' file

Save the current section in the hold space and append it to each line within that section. Using the grep-like option -n prevents lines being printed as normal and using a regexp and the P command print the line that meets your criteria.


问:
php string in a string with double and single quotes as 1 string

Hello, I am trying to make a array in php that looks like this:

```<code>$array= array("test"2"", "'test"2"'");
</code>```

Of course this doesn't work because of the two strings, but is there a way in php to get is to ignore all quotes in such a string so it sees it as a valid string? The problem being that I need the quotes in my string and it are double quotes and single quotes.

EDIT:
Thanks for the quick response! I was wondering if there is a way of doing this with code? I have a huge string to do this with?

```<code>$array= array("test\"2\"", "'test\"2\"'");
</code>```

答:
If your array $array= array("test\"2\"", "'test\"2\"'"); is build using a loop then simply use PHP function addslashes() that will escape the redundant qotations.

```<code>$strings = array('abc"def', "efg'hij");

foreach($strings as $str){
  echo  addslashes($str) .PHP_EOL;
}
</code>```

https://eval.in/914320

Body:
Hello, I am trying to make a array in php that looks like this:

$array= array("test"2"", "'test"2"'");

Of course this doesn't work because of the two strings, but is there a way in php to get is to ignore all quotes in such a string so it sees it as a valid string? The problem being that I need the quotes in my string and it are double quotes and single quotes.

EDIT:
Thanks for the quick response! I was wondering if there is a way of doing this with code? I have a huge string to do this with?

$array= array("test\"2\"", "'test\"2\"'");

Body:
If your array $array= array("test\"2\"", "'test\"2\"'"); is build using a loop then simply use PHP function addslashes() that will escape the redundant qotations.

$strings = array('abc"def', "efg'hij");

foreach($strings as $str){
  echo  addslashes($str) .PHP_EOL;
}

https://eval.in/914320


问:
How to reliably determine the PreferredSize for System.Windows.Forms.MonthCalendar control?
On my form, I have a System.Windows.Forms.TableLayoutPanel in which I have a System.Windows.Forms.Panel set to DockStyle.Fill, and in the panel, a System.Windows.Forms.MonthCalendar control (also set to fill).

The calendar is an inherited control, simply to allow overriding the theme so I can set colors, etc.  The inherited part came from another SO question that I've since lost track of.

The code:

```<code>public class NativeMethods
{
    [DllImport("uxtheme.dll")]
    public static extern Int32 SetWindowTheme(IntPtr hWnd, String appname, String idlist);
}

public class CustomMonthCalendar : MonthCalendar
{
    public CustomMonthCalendar()
    {
        InitializeComponent();
        Margin = new Padding(0);
    }

    private void InitializeComponent()
    {
        SuspendLayout();
        ResumeLayout(false);
    }

    protected override void OnHandleCreated(EventArgs e)
    {
        NativeMethods.SetWindowTheme(Handle, String.Empty, String.Empty);
        base.OnHandleCreated(e);
    }
}

public class CustomCalendar : UserControl
{
    DayPickerControl = new CustomMonthCalendar();
    DayPickerControl.ForeColor = SystemColors.ControlText;
    DayPickerControl.BackColor = BackgroundColor;
    DayPickerControl.TitleForeColor = TextColor.Lighten(1.2f);
    DayPickerControl.TitleBackColor = BackgroundColor;
    DayPickerControl.TrailingForeColor = Color.Gray;
    DayPickerControl.Dock = DockStyle.Fill;
    DayPickerControl.FirstDayOfWeek = Day.Sunday;
    DayPickerControl.Font = new Font("Microsoft Sans Serif", 9f, FontStyle.Regular);
    DayPickerControl.MaxDate = new DateTime(2999, 12, 31, 0, 0, 0, 0);
    DayPickerControl.MaxSelectionCount = 7;
    DayPickerControl.MinDate = new DateTime(1900, 1, 1, 0, 0, 0, 0);
    DayPickerControl.ScrollChange = 1;
    DayPickerControl.SetCalendarDimensions(1, 1);
    DayPickerControl.ShowToday = true;
    DayPickerControl.ShowTodayCircle = true;
    DayPickerControl.Text = null;

    DayPickerPanel = new Panel();
    DayPickerPanel.BorderStyle = BorderStyle.None;
    DayPickerPanel.Dock = DockStyle.Fill;
    DayPickerPanel.Location = new Point(0, 0);
    DayPickerPanel.Padding = new Padding(2);
    Size prefSize = DayPickerControl.GetPreferredSize(new Size(200, 200));
    DayPickerPanel.Size = new Size(prefSize.Width + 5, prefSize.Height + 5);
    DayPickerPanel.Paint += panelBorder_Paint;
    DayPickerPanel.Controls.Add(DayPickerControl);
}
</code>```

So the question is about determining what size the calendar control wants to be.  No matter what I do, the size I get back from GetPreferredSize() is always 178, 155.  On-screen, however, the right-hand edge of the calendar is cut-off, meaning it's larger than the panel in which it's docked.  That suggests to me that it might also not care much about being docked.  Not sure.

I have fiddled around with various docked/undocked vs anchored settings, but always the same results.

Why am I getting a seemingly incorrect size?  And how do I determine the correct size to fit it to?

EDIT:  Using Hans Passant's suggestion, I arrived at this solution:

```<code>//A new event in the CustomMonthCalendar class
public event EventHandler<AfterHandleCreatedArgs> AfterHandleCreated;

//A modified version of the OnHandleCreated() method shown above (add event call)
protected override void OnHandleCreated(EventArgs e)
{
    NativeMethods.SetWindowTheme(Handle, String.Empty, String.Empty);
    base.OnHandleCreated(e);
    if (this.IsHandleCreated && AfterHandleCreated != null)
        AfterHandleCreated(this, new AfterHandleCreatedArgs(new Size(this.Size.Width + 5, this.Size.Height + 5)));  //cosmetic padding
}

//A new class for the event args it passes...
public class AfterHandleCreatedArgs : EventArgs
{
    private Size _newSize = Size.Empty;
    public Size NewSize { get { return _newSize; } set { _newSize = value; } }

    public AfterHandleCreatedArgs(Size newSize)
    {
        _newSize = newSize;
    }
}

//And a handler to attach to that new event (in CustomCalendar class)...
private void DayPickerControl_AfterHandleCreated(Object sender, AfterHandleCreatedArgs e)
{
    if (!e.NewSize.Equals(Size.Empty))
        DayPickerPanel.Size = e.NewSize;
}
</code>```

答:
You can force the calendar to size itself by asking for it's handle:</p>

```<code>IntPtr h = calendar.Handle;
</code>```

Body:
On my form, I have a System.Windows.Forms.TableLayoutPanel in which I have a System.Windows.Forms.Panel set to DockStyle.Fill, and in the panel, a System.Windows.Forms.MonthCalendar control (also set to fill).

The calendar is an inherited control, simply to allow overriding the theme so I can set colors, etc.  The inherited part came from another SO question that I've since lost track of.

The code:

public class NativeMethods
{
    [DllImport("uxtheme.dll")]
    public static extern Int32 SetWindowTheme(IntPtr hWnd, String appname, String idlist);
}

public class CustomMonthCalendar : MonthCalendar
{
    public CustomMonthCalendar()
    {
        InitializeComponent();
        Margin = new Padding(0);
    }

    private void InitializeComponent()
    {
        SuspendLayout();
        ResumeLayout(false);
    }

    protected override void OnHandleCreated(EventArgs e)
    {
        NativeMethods.SetWindowTheme(Handle, String.Empty, String.Empty);
        base.OnHandleCreated(e);
    }
}

public class CustomCalendar : UserControl
{
    DayPickerControl = new CustomMonthCalendar();
    DayPickerControl.ForeColor = SystemColors.ControlText;
    DayPickerControl.BackColor = BackgroundColor;
    DayPickerControl.TitleForeColor = TextColor.Lighten(1.2f);
    DayPickerControl.TitleBackColor = BackgroundColor;
    DayPickerControl.TrailingForeColor = Color.Gray;
    DayPickerControl.Dock = DockStyle.Fill;
    DayPickerControl.FirstDayOfWeek = Day.Sunday;
    DayPickerControl.Font = new Font("Microsoft Sans Serif", 9f, FontStyle.Regular);
    DayPickerControl.MaxDate = new DateTime(2999, 12, 31, 0, 0, 0, 0);
    DayPickerControl.MaxSelectionCount = 7;
    DayPickerControl.MinDate = new DateTime(1900, 1, 1, 0, 0, 0, 0);
    DayPickerControl.ScrollChange = 1;
    DayPickerControl.SetCalendarDimensions(1, 1);
    DayPickerControl.ShowToday = true;
    DayPickerControl.ShowTodayCircle = true;
    DayPickerControl.Text = null;

    DayPickerPanel = new Panel();
    DayPickerPanel.BorderStyle = BorderStyle.None;
    DayPickerPanel.Dock = DockStyle.Fill;
    DayPickerPanel.Location = new Point(0, 0);
    DayPickerPanel.Padding = new Padding(2);
    Size prefSize = DayPickerControl.GetPreferredSize(new Size(200, 200));
    DayPickerPanel.Size = new Size(prefSize.Width + 5, prefSize.Height + 5);
    DayPickerPanel.Paint += panelBorder_Paint;
    DayPickerPanel.Controls.Add(DayPickerControl);
}

So the question is about determining what size the calendar control wants to be.  No matter what I do, the size I get back from GetPreferredSize() is always 178, 155.  On-screen, however, the right-hand edge of the calendar is cut-off, meaning it's larger than the panel in which it's docked.  That suggests to me that it might also not care much about being docked.  Not sure.

I have fiddled around with various docked/undocked vs anchored settings, but always the same results.

Why am I getting a seemingly incorrect size?  And how do I determine the correct size to fit it to?

EDIT:  Using Hans Passant's suggestion, I arrived at this solution:

//A new event in the CustomMonthCalendar class
public event EventHandler<AfterHandleCreatedArgs> AfterHandleCreated;

//A modified version of the OnHandleCreated() method shown above (add event call)
protected override void OnHandleCreated(EventArgs e)
{
    NativeMethods.SetWindowTheme(Handle, String.Empty, String.Empty);
    base.OnHandleCreated(e);
    if (this.IsHandleCreated && AfterHandleCreated != null)
        AfterHandleCreated(this, new AfterHandleCreatedArgs(new Size(this.Size.Width + 5, this.Size.Height + 5)));  //cosmetic padding
}

//A new class for the event args it passes...
public class AfterHandleCreatedArgs : EventArgs
{
    private Size _newSize = Size.Empty;
    public Size NewSize { get { return _newSize; } set { _newSize = value; } }

    public AfterHandleCreatedArgs(Size newSize)
    {
        _newSize = newSize;
    }
}

//And a handler to attach to that new event (in CustomCalendar class)...
private void DayPickerControl_AfterHandleCreated(Object sender, AfterHandleCreatedArgs e)
{
    if (!e.NewSize.Equals(Size.Empty))
        DayPickerPanel.Size = e.NewSize;
}

Body:
You can force the calendar to size itself by asking for it's handle:

IntPtr h = calendar.Handle;


问:
qtest: No rule to make target error when compiling test
I have been working through creating a unit test. I need to learn this to test our gui objects.  So far this site has answered many questions (most were asked and answered previously). However, I am now at a point where I am getting an error and I cannot find a link to help me resolve it. I get "No rule to make target 'TestGui.cpp', needed by 'TestGui.o'. Stop". Can anyone tell me how to fix this and get my test compiled? This is my first attempt at testing...

This is my test file-

```<code>#include <QString>
#include <QObject>
#include <QtTest>
#include <QLineEdit>
#include <QWidget>
#include <QApplication>

class SampleTest : public QObject
{
    Q_OBJECT

public:
    SampleTest();

private Q_SLOTS:
    void initTestCase();
    void cleanupTestCase();
    void TestGui();
    void TestQstring();
};

SampleTest::SampleTest()
{
}

void SampleTest::initTestCase()
{
}

void SampleTest::cleanupTestCase()
{
}

void SampleTest::TestGui()
{
    QLineEdit line_edit;

    QTest::keyClicks(&line_edit, "hello world");

    QCOMPARE(line_edit.text(), QString("hello world"));
}

void SampleTest::TestQstring()
{
    QString str = "hello world";
    QCOMPARE(str.toUpper(), QString("HELLO wORLD"));
}

QTEST_MAIN(SampleTest)

#include "SampleTest.moc"
</code>```

My test.pro file is here -

```<code>#-------------------------------------------------
#
# Project created by QtCreator 2015-09-03T09:46:40
#
#-------------------------------------------------

QT       += core widgets gui testlib

TARGET = SampleTest
CONFIG   += console
CONFIG   -= app_bundle

TEMPLATE = app

SOURCES += ../sample_project/TestGui.cpp \
            SampleTest.cpp

HEADERS +=  ../sample_project/TestGui.h

FORMS += ../sample_project/TestGui.ui

DEFINES += SRCDIR=\\\"$$PWD/\\\"

INCLUDEPATH += $$PWD/../sample_project

include(../sample_project/sample_project.pri)
</code>```

This is my project .pro file -

```<code>#-------------------------------------------------
#
# Project created by QtCreator 2015-09-03T09:29:42
#
#-------------------------------------------------

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = sample_project
TEMPLATE = app

SOURCES += main.cpp\
        TestGui.cpp \
    TestBox.cpp

HEADERS  += TestGui.h \
           TestBox.h

FORMS    += TestGui.ui \
       TestBox.ui
</code>```

My project .pri file hs the source and header for my project -

```<code>SOURCES += TestGui.cpp
HEADRES += TestGui.h
</code>```

答:
Try to rename the class name accordingly to the filename. In your case, SampleTest => TestGui

QtCreator tries to find appropriate class definition. If not, it ignores to create target ".moc:" in projects Makefile.

Body:
I have been working through creating a unit test. I need to learn this to test our gui objects.  So far this site has answered many questions (most were asked and answered previously). However, I am now at a point where I am getting an error and I cannot find a link to help me resolve it. I get "No rule to make target 'TestGui.cpp', needed by 'TestGui.o'. Stop". Can anyone tell me how to fix this and get my test compiled? This is my first attempt at testing...

This is my test file-

#include <QString>
#include <QObject>
#include <QtTest>
#include <QLineEdit>
#include <QWidget>
#include <QApplication>

class SampleTest : public QObject
{
    Q_OBJECT

public:
    SampleTest();

private Q_SLOTS:
    void initTestCase();
    void cleanupTestCase();
    void TestGui();
    void TestQstring();
};

SampleTest::SampleTest()
{
}

void SampleTest::initTestCase()
{
}

void SampleTest::cleanupTestCase()
{
}

void SampleTest::TestGui()
{
    QLineEdit line_edit;

    QTest::keyClicks(&line_edit, "hello world");

    QCOMPARE(line_edit.text(), QString("hello world"));
}

void SampleTest::TestQstring()
{
    QString str = "hello world";
    QCOMPARE(str.toUpper(), QString("HELLO wORLD"));
}

QTEST_MAIN(SampleTest)

#include "SampleTest.moc"

My test.pro file is here -

#-------------------------------------------------
#
# Project created by QtCreator 2015-09-03T09:46:40
#
#-------------------------------------------------

QT       += core widgets gui testlib

TARGET = SampleTest
CONFIG   += console
CONFIG   -= app_bundle

TEMPLATE = app

SOURCES += ../sample_project/TestGui.cpp \
            SampleTest.cpp

HEADERS +=  ../sample_project/TestGui.h

FORMS += ../sample_project/TestGui.ui

DEFINES += SRCDIR=\\\"$$PWD/\\\"

INCLUDEPATH += $$PWD/../sample_project

include(../sample_project/sample_project.pri)

This is my project .pro file -

#-------------------------------------------------
#
# Project created by QtCreator 2015-09-03T09:29:42
#
#-------------------------------------------------

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = sample_project
TEMPLATE = app

SOURCES += main.cpp\
        TestGui.cpp \
    TestBox.cpp

HEADERS  += TestGui.h \
           TestBox.h

FORMS    += TestGui.ui \
       TestBox.ui

My project .pri file hs the source and header for my project -

SOURCES += TestGui.cpp
HEADRES += TestGui.h


问:
Using Button(GUI) and WhileLoop in Python
I have simple Python code whitch starts from command line on Raspberry PI like:

```<code>import ...

def def_1(....)
def def_2(....)

 if __name__ == ‘__main__’:
    while:
         def_1(....)
         def_2(....)
</code>```

So,I want to add 3 buttons(GUI):

Which starts only def_1(infinite loop)

Which starts only def_2(infinite loop)

Whitch end def_1 or def_2

How I can do it?

答:
On Raspberry PI I am using Kivy for GUI.
You can do it in that way:

```<code>from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button

import threading
import time

class ButtonDemo(BoxLayout):
    def __init__(self, **kwargs):
        super(ButtonDemo, self).__init__(**kwargs)
        self.orientation = "vertical"
        self.add_widget(Button(text = "Action #1", on_press = self.def_1))
        self.add_widget(Button(text = "Action #2", on_press = self.def_2))
        self.add_widget(Button(text = "Stop", on_press = self.stop))

        loop_thread_1 = threading.Thread()
        loop_thread_2 = threading.Thread()
        loop_running_1 = False
        loop_running_2 = False

    def def_1(self, instance):
        print("DEF 1")
        self.loop_thread_1 = threading.Thread(target = self.loop_1)
        self.loop_thread_1.start()

    def def_2(self, instance):
        self.loop_thread_2 = threading.Thread(target = self.loop_2)
        self.loop_thread_2.start()

    def stop(self, instance):
        if self.loop_running_1:
            self.loop_running_1 = False

        if self.loop_running_2:
            self.loop_running_2 = False

    def loop_1(self):
        self.loop_running_1 = True
        while self.loop_running_1:
            print("loop 1")
            time.sleep(1)

    def loop_2(self):
        self.loop_running_2 = True
        while self.loop_running_2:
            print("loop 2")
            time.sleep(1)

class TestButtonApp(App):
    def build(self):
        return ButtonDemo()

if __name__ == '__main__':
    TestButtonApp().run()
</code>```

Each loop starts in new thread, so program will not freeze. Stop button stops running threads as you wanted.

Body:
I have simple Python code whitch starts from command line on Raspberry PI like:

import ...

def def_1(....)
def def_2(....)

 if __name__ == ‘__main__’:
    while:
         def_1(....)
         def_2(....)

So,I want to add 3 buttons(GUI):

Which starts only def_1(infinite loop)

Which starts only def_2(infinite loop)

Whitch end def_1 or def_2

How I can do it?

Body:
On Raspberry PI I am using Kivy for GUI.
You can do it in that way:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button

import threading
import time

class ButtonDemo(BoxLayout):
    def __init__(self, **kwargs):
        super(ButtonDemo, self).__init__(**kwargs)
        self.orientation = "vertical"
        self.add_widget(Button(text = "Action #1", on_press = self.def_1))
        self.add_widget(Button(text = "Action #2", on_press = self.def_2))
        self.add_widget(Button(text = "Stop", on_press = self.stop))

        loop_thread_1 = threading.Thread()
        loop_thread_2 = threading.Thread()
        loop_running_1 = False
        loop_running_2 = False

    def def_1(self, instance):
        print("DEF 1")
        self.loop_thread_1 = threading.Thread(target = self.loop_1)
        self.loop_thread_1.start()

    def def_2(self, instance):
        self.loop_thread_2 = threading.Thread(target = self.loop_2)
        self.loop_thread_2.start()

    def stop(self, instance):
        if self.loop_running_1:
            self.loop_running_1 = False

        if self.loop_running_2:
            self.loop_running_2 = False

    def loop_1(self):
        self.loop_running_1 = True
        while self.loop_running_1:
            print("loop 1")
            time.sleep(1)

    def loop_2(self):
        self.loop_running_2 = True
        while self.loop_running_2:
            print("loop 2")
            time.sleep(1)

class TestButtonApp(App):
    def build(self):
        return ButtonDemo()

if __name__ == '__main__':
    TestButtonApp().run()

Each loop starts in new thread, so program will not freeze. Stop button stops running threads as you wanted.


问:
In java, how to clear byte[] array inside every method to protect the value from memory dump?
In java,

If I run below code, pwd value exists all over the memory because byte array value is copied to digest method which also copies the value to some other methods.

```<code>    import java.security.MessageDigest

    byte[] pwd = "some_pwd".getBytes();
    MessageDigest md = MessageDigest.getInstance("SHA");
    for (int i = 0; i < 100; i++) {
        byte[] hash = md.digest(pwd);
    }
</code>```

Memory dump software shows the password value which my customer does not like.

I checked that byte[] is copied by value from method to method.

Is there anyway to protect the important byte array value ?

答:
Password text should preferably not be passed as String, but let's assume this is an example:

Then ensure the bytes do not occur in the strings for the test.

```<code>byte[] pwd = "rnld^ovc".getBytes(StandardCharsets.UTF_8); // "some_pwd"
for (int i = 0; i < pwd.length; ++i) {
    pwd[i]++;
}
</code>```

And then the solution:

```<code>MessageDigest md = MessageDigest.getInstance("SHA");
for (int i = 0; i < 100; i++) {
    //byte[] hash = md.digest(pwd);
    for (byte b : pwd) {
        md.update(b - 1); // Maybe -1 if the string was the real password
    }
    byte[] hash = md.digest();
}
Arrays.fill(pwd, (byte)0);
</code>```

Now the MessageDigest cannot maintain a copy of the array on the call to digest.

If you do not want to even have the pwd array, you would need to just take a char/byte at a time from the password field.

Body:
In java,

If I run below code, pwd value exists all over the memory because byte array value is copied to digest method which also copies the value to some other methods.

    import java.security.MessageDigest

    byte[] pwd = "some_pwd".getBytes();
    MessageDigest md = MessageDigest.getInstance("SHA");
    for (int i = 0; i < 100; i++) {
        byte[] hash = md.digest(pwd);
    }

Memory dump software shows the password value which my customer does not like.

I checked that byte[] is copied by value from method to method.

Is there anyway to protect the important byte array value ?

Body:
Password text should preferably not be passed as String, but let's assume this is an example:

Then ensure the bytes do not occur in the strings for the test.

byte[] pwd = "rnld^ovc".getBytes(StandardCharsets.UTF_8); // "some_pwd"
for (int i = 0; i < pwd.length; ++i) {
    pwd[i]++;
}

And then the solution:

MessageDigest md = MessageDigest.getInstance("SHA");
for (int i = 0; i < 100; i++) {
    //byte[] hash = md.digest(pwd);
    for (byte b : pwd) {
        md.update(b - 1); // Maybe -1 if the string was the real password
    }
    byte[] hash = md.digest();
}
Arrays.fill(pwd, (byte)0);

Now the MessageDigest cannot maintain a copy of the array on the call to digest.

If you do not want to even have the pwd array, you would need to just take a char/byte at a time from the password field.


问:
Plotting line through scatter plot in xlsx writer
Here's a scatter plot :

All Im trying to do is simply add a line through the point -.8 (y axis) , to .4 (x axis) , which crosses trough (0,0), but this is what I end up getting:

Here's my code:

```<code>diagonal = workbook.add_chart({'type':'line'})

###for line
worksheet.write(0,0,-.8)
worksheet.write(1,0,.4)

###net and gain are just excel columns  (for scatterplot)
diagonal.add_series({'values':['sheet',0,0,1,0],'categories':net)
scatter = workbook.add_chart({'type':'scatter'})
scatter.add_series({'values':gain,'categories':net)

diagonal.combine(scatter)
worksheet.insert_chart(1,1,diagonal)
</code>```

答:
You would probably get the same result if you combined a line and scatter chart in Excel. Somewhat confusingly a "line" chart in Excel is based on fixed division categories. What you probably need is a to plot a second "scatter" series for the line.

Something like this:

```<code>import xlsxwriter

workbook = xlsxwriter.Workbook('chart_scatter.xlsx')
worksheet = workbook.add_worksheet()
bold = workbook.add_format({'bold': 1})

# Add the worksheet data that the charts will refer to.
worksheet.write_column('A1', [-0.2,  0.3, -0.4,  0.15, -0.6,  0.37])
worksheet.write_column('B1', [0.1,  -0.4, -0.5, -0.25,  0.1, -0.51])
worksheet.write_column('C1', [-0.8, 0.4])
worksheet.write_column('D1', [   0,   0])

# Create a new scatter chart.
chart = workbook.add_chart({'type': 'scatter'})

# Add the scatter data.
chart.add_series({
    'categories': ['Sheet1', 0, 0, 5, 0],
    'values':     ['Sheet1', 0, 1, 5, 1],
    'marker': {
            'type': 'circle',
            'border': {'color': 'red'},
            'fill':   {'color': 'red'},
        },
})

# Add the straight lines series.
chart.add_series({
    'categories': ['Sheet1', 0, 2, 1, 2],
    'values':     ['Sheet1', 0, 3, 1, 3],
    'line':       {'color': 'blue'},
    'marker':     {'type': 'none'},
})

# Format the chart.
chart.set_x_axis({'min': -0.8, 'max': 0.4})
chart.set_legend({'none': True})

worksheet.insert_chart('D5', chart)

workbook.close()
</code>```

Output:

The key here is to figure out what you want to do in Excel first and then try apply that to an XlsxWriter program.

Body:
Here's a scatter plot :

All Im trying to do is simply add a line through the point -.8 (y axis) , to .4 (x axis) , which crosses trough (0,0), but this is what I end up getting:

Here's my code:

diagonal = workbook.add_chart({'type':'line'})

###for line
worksheet.write(0,0,-.8)
worksheet.write(1,0,.4)

###net and gain are just excel columns  (for scatterplot)
diagonal.add_series({'values':['sheet',0,0,1,0],'categories':net)
scatter = workbook.add_chart({'type':'scatter'})
scatter.add_series({'values':gain,'categories':net)

diagonal.combine(scatter)
worksheet.insert_chart(1,1,diagonal)

Body:
You would probably get the same result if you combined a line and scatter chart in Excel. Somewhat confusingly a "line" chart in Excel is based on fixed division categories. What you probably need is a to plot a second "scatter" series for the line.

Something like this:

import xlsxwriter

workbook = xlsxwriter.Workbook('chart_scatter.xlsx')
worksheet = workbook.add_worksheet()
bold = workbook.add_format({'bold': 1})

# Add the worksheet data that the charts will refer to.
worksheet.write_column('A1', [-0.2,  0.3, -0.4,  0.15, -0.6,  0.37])
worksheet.write_column('B1', [0.1,  -0.4, -0.5, -0.25,  0.1, -0.51])
worksheet.write_column('C1', [-0.8, 0.4])
worksheet.write_column('D1', [   0,   0])

# Create a new scatter chart.
chart = workbook.add_chart({'type': 'scatter'})

# Add the scatter data.
chart.add_series({
    'categories': ['Sheet1', 0, 0, 5, 0],
    'values':     ['Sheet1', 0, 1, 5, 1],
    'marker': {
            'type': 'circle',
            'border': {'color': 'red'},
            'fill':   {'color': 'red'},
        },
})

# Add the straight lines series.
chart.add_series({
    'categories': ['Sheet1', 0, 2, 1, 2],
    'values':     ['Sheet1', 0, 3, 1, 3],
    'line':       {'color': 'blue'},
    'marker':     {'type': 'none'},
})

# Format the chart.
chart.set_x_axis({'min': -0.8, 'max': 0.4})
chart.set_legend({'none': True})

worksheet.insert_chart('D5', chart)

workbook.close()

Output:

The key here is to figure out what you want to do in Excel first and then try apply that to an XlsxWriter program.


问:
Android O Error in use of IMPORTANCE_UNSPECIFIED with notification channel in service
I want to display notification from my service for android O but i got this crash and i want's to use IMPORTANCE_UNSPECIFIED with notification channel

```<code> java.lang.IllegalArgumentException: Invalid importance level
</code>```

here is my code.

```<code> if (android.os.Build.VERSION.SDK_INT >= 26) {
            try {

                  // Create the channel for the notification
                    NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_UNSPECIFIED);

                    // Set the Notification Channel for the Notification Manager.
                    mNotificationManager.createNotificationChannel(mChannel);

                    Notification.Builder builder = new Notification.Builder(this, CHANNEL_ID)
                            .setSmallIcon(R.mipmap.instant_app_icon)
                            .setContentTitle(getString(R.string.app_name))
                            //  .setContentText("Instant Service")
                            .setAutoCancel(true);

                    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                            new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);

                    builder.setContentIntent(contentIntent);

                    Notification notification = builder.build();
                    startForeground(1, notification);

                }

                catch (Exception ex){
                    ex.printStackTrace();
                }
            }
</code>```

答:
Hi Avinash You can't use this as per document
IMPORTANCE_UNSPECIFIED

added in API level 24 int IMPORTANCE_UNSPECIFIED Value signifying that
  the user has not expressed an importance. This value is for persisting
  preferences, and should never be associated with an actual
  notification.
  for more info you can read here
  https://developer.android.com/reference/android/app/NotificationManager.html#IMPORTANCE_UNSPECIFIED

Edit:
Instead you can use any other importance based on your need

IMPORTANCE_DEFAULT

IMPORTANCE_HIGH

IMPORTANCE_LOW

IMPORTANCE_MAX

IMPORTANCE_MIN

Body:
I want to display notification from my service for android O but i got this crash and i want's to use IMPORTANCE_UNSPECIFIED with notification channel

 java.lang.IllegalArgumentException: Invalid importance level

here is my code.

 if (android.os.Build.VERSION.SDK_INT >= 26) {
            try {

                  // Create the channel for the notification
                    NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_UNSPECIFIED);

                    // Set the Notification Channel for the Notification Manager.
                    mNotificationManager.createNotificationChannel(mChannel);

                    Notification.Builder builder = new Notification.Builder(this, CHANNEL_ID)
                            .setSmallIcon(R.mipmap.instant_app_icon)
                            .setContentTitle(getString(R.string.app_name))
                            //  .setContentText("Instant Service")
                            .setAutoCancel(true);

                    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                            new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);

                    builder.setContentIntent(contentIntent);

                    Notification notification = builder.build();
                    startForeground(1, notification);

                }

                catch (Exception ex){
                    ex.printStackTrace();
                }
            }


问:
Help with a foreach loop
In my website I am trying to display all the applicants to jobs that a user has posted, basically I want the out put to simimlar too,

Job Title 1

  Aplicant Name 1

  Aplicant Name 2

  Applicant Name 3

Job Title 2

  Applicant Name 4
  Application Name 5

Basically I want the applications to be gathered under the jobs they applied for, however the out put I am current getting is,

Job Title 1

  Application Name 1

Job Title 1

  Applicant Name 2

The code I am using to do this foreach loop is as follows

```<code><?php foreach($applications as $a) : ?>
        <h3><?php echo $a['jobtitle']; ?></h3>
    <li>
        <img src="/media/uploads/candidates/<?php echo preg_replace('/(.gif|.jpg|.png)/', '_thumb$1', $a['profile_image']);?>" width="90" height="60"/>
        <p><?php echo $a['name']; ?></p>
    </li>
    <?php endforeach; ?>
</code>```

答:
Well you are getting that because you are only outputting

```<code>$a['jobtitle']
</code>```

and

```<code>$a['name']
</code>```

Where are the other names stored? Something like this is probably what you want, although that won't work if you copy/paste it as it seems that $applications[x]['name'] is not an array:

```<code><?php foreach($applications as $a) : ?>
        <h3><?php echo $a['jobtitle']; ?></h3>
    <li>
        <img src="/media/uploads/candidates/<?php echo preg_replace('/(.gif|.jpg|.png)/', '_thumb$1', $a['profile_image']);?>" width="90" height="60"/>
        <?php foreach($a['name'] as $name)?>
        <p><?php echo $name; ?></p>
        <?php endforeach; ?>
    </li>
    <?php endforeach; ?>
</code>```

Title: Help with a foreach loop

Body:
In my website I am trying to display all the applicants to jobs that a user has posted, basically I want the out put to simimlar too,

Job Title 1

  Aplicant Name 1

  Aplicant Name 2

  Applicant Name 3

Job Title 2

  Applicant Name 4
  Application Name 5

Basically I want the applications to be gathered under the jobs they applied for, however the out put I am current getting is,

Job Title 1

  Application Name 1

Job Title 1

  Applicant Name 2

The code I am using to do this foreach loop is as follows

<?php foreach($applications as $a) : ?>

<?php echo $a['jobtitle']; ?>

        <img src="/media/uploads/candidates/<?php echo preg_replace('/(.gif|.jpg|.png)/', '_thumb$1', $a['profile_image']);?>" width="90" height="60"/>

<?php echo $a['name']; ?>

    <?php endforeach; ?>

Body:
Well you are getting that because you are only outputting

$a['jobtitle']

and

$a['name']

Where are the other names stored? Something like this is probably what you want, although that won't work if you copy/paste it as it seems that $applications[x]['name'] is not an array:

<?php foreach($applications as $a) : ?>
        <h3><?php echo $a['jobtitle']; ?></h3>
    <li>
        <img src="/media/uploads/candidates/<?php echo preg_replace('/(.gif|.jpg|.png)/', '_thumb$1', $a['profile_image']);?>" width="90" height="60"/>
        <?php foreach($a['name'] as $name)?>
        <p><?php echo $name; ?></p>
        <?php endforeach; ?>
    </li>
    <?php endforeach; ?>