问:
Filtering a Key Value from a Dictionary in C#
I'm new to C# and am currently trying to figure out the best way to implement the following:

I have a list of species with an associated group:

```<code>Bird: "Budgie", "Parrot"
Dog: "Pitbull", "Labrador"
Cat: "Cheetah", "Lion"
</code>```

Given a string of an animal, I need to return its group.
eg. "Cheetah" would return "Cat".

I have implemented the following:

```<code>// create list one and store values
List<string> valSetOne = new List<string>();
valSetOne.Add("Budgie");
valSetOne.Add("Parrot");

// create list two and store values
List<String> valSetTwo = new List<String>();
valSetTwo.Add("Lion");
valSetTwo.Add("Cheetah");

// create list three and store values
List<String> valSetThree = new List<String>();
valSetThree.Add("Labrador");
valSetThree.Add("Pitbull");

// add values into map
map.Add("Bird", valSetOne);
map.Add("Cat", valSetTwo);
map.Add("Dog", valSetThree);

foreach(KeyValuePair<string, List<string>> kvp in map){
    foreach(string value in kvp.Value)
    {
       Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, value);
    }
}
</code>```

Instead of having a foreach loop, is there a faster way to find the key given an animal value?

//EDIT:

Currently trying to initialize with a Tuple

```<code>var tupleList = new List<Tuple<string, List<string>>>
{
   new Tuple<string, List<string>>("cat", { "cheetah", "lion"})

};
</code>```

I'm getting the following error:     Unexpected symbol `{'

答:
I would make a class Animal, since you are working with animals, that would have two properties: Species and SubSpecies

```<code>public class Animal
{
    public string Species { get; set; }
    public string SubSpecies { get; set; }

    public Animal(string Species, string SubSpecies)
    {
        this.Species = Species;
        this.SubSpecies = SubSpecies;
    }
}
</code>```

Then you can instanciate all your animals inside a list :

```<code>List<Animal> myAnimals = new List<Animal>();
myAnimals.Add(new Animal("Bird", "Budgie"));
myAnimals.Add(new Animal("Bird", "Parrot"));
myAnimals.Add(new Animal("Dog", "Pitbull"));
myAnimals.Add(new Animal("Dog", "Labrador"));
myAnimals.Add(new Animal("Cat", "Cheetah"));
myAnimals.Add(new Animal("Cat", "Lion"));
</code>```

And finally, you can use Linq to find whatever you're looking for:

```<code>//Will return null if the subSpecies doesn't exist
public string FindTheSpecies(string SubSpecies)
{
    return myAnimals.FirstOrDefault(x => x.SubSpecies == SubSpecies)?.Species;
}
</code>```

Body:
I'm new to C# and am currently trying to figure out the best way to implement the following:

I have a list of species with an associated group:

Bird: "Budgie", "Parrot"
Dog: "Pitbull", "Labrador"
Cat: "Cheetah", "Lion"

Given a string of an animal, I need to return its group.
eg. "Cheetah" would return "Cat".

I have implemented the following:

// create list one and store values
List<string> valSetOne = new List<string>();
valSetOne.Add("Budgie");
valSetOne.Add("Parrot");

// create list two and store values
List<String> valSetTwo = new List<String>();
valSetTwo.Add("Lion");
valSetTwo.Add("Cheetah");

// create list three and store values
List<String> valSetThree = new List<String>();
valSetThree.Add("Labrador");
valSetThree.Add("Pitbull");

// add values into map
map.Add("Bird", valSetOne);
map.Add("Cat", valSetTwo);
map.Add("Dog", valSetThree);

foreach(KeyValuePair<string, List<string>> kvp in map){
    foreach(string value in kvp.Value)
    {
       Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, value);
    }
}

Instead of having a foreach loop, is there a faster way to find the key given an animal value?

//EDIT:

Currently trying to initialize with a Tuple

var tupleList = new List<Tuple<string, List<string>>>
{
   new Tuple<string, List<string>>("cat", { "cheetah", "lion"})

};

I'm getting the following error:     Unexpected symbol `{'

Body:
I would make a class Animal, since you are working with animals, that would have two properties: Species and SubSpecies

public class Animal
{
    public string Species { get; set; }
    public string SubSpecies { get; set; }

    public Animal(string Species, string SubSpecies)
    {
        this.Species = Species;
        this.SubSpecies = SubSpecies;
    }
}

Then you can instanciate all your animals inside a list :

List<Animal> myAnimals = new List<Animal>();
myAnimals.Add(new Animal("Bird", "Budgie"));
myAnimals.Add(new Animal("Bird", "Parrot"));
myAnimals.Add(new Animal("Dog", "Pitbull"));
myAnimals.Add(new Animal("Dog", "Labrador"));
myAnimals.Add(new Animal("Cat", "Cheetah"));
myAnimals.Add(new Animal("Cat", "Lion"));

And finally, you can use Linq to find whatever you're looking for:

//Will return null if the subSpecies doesn't exist
public string FindTheSpecies(string SubSpecies)
{
    return myAnimals.FirstOrDefault(x => x.SubSpecies == SubSpecies)?.Species;
}


来源: stackexchange

问:
Python array index slicing with [[ ]]
```<code>centers = np.array([[1,2,3],[4,5,6]])
print(centers[[0,0,0,0,0,1,1]])
</code>```

output:

```<code>[[1 2 3]
 [1 2 3]
 [1 2 3]
 [1 2 3]
 [1 2 3]
 [4 5 6]
 [4 5 6]]
</code>```

What is this feature? I'm not sure what is this called.

答:
You are simply indexing the array with a list, so center[...] is passed [0,0,0,0,0,1,1], there is no 'double' bracket syntax. Indexing with a list is a NumPy feature; from the Indexing chapter of the documentation:

NumPy arrays may be indexed with other arrays (or any other sequence- like object that can be converted to an array, such as lists, with the exception of tuples; see the end of this document for why this is).

You indexed the centers with another sequence, a list in this case, so a new array is created with index 0 repeated, followed by the value of index 1, once.

Note that this is not slicing the original array; you are indexing, and a new array with copies of the values is produced (altering values in centers won't be reflected in the new copy).

ContentLicense: CC BY-SA 3.0

Title: Python array index slicing with [[ ]]

Body:
centers = np.array([[1,2,3],[4,5,6]])
print(centers[[0,0,0,0,0,1,1]])

output:

[[1 2 3]
 [1 2 3]
 [1 2 3]
 [1 2 3]
 [1 2 3]
 [4 5 6]
 [4 5 6]]

What is this feature? I'm not sure what is this called.


问:
NPM Issue while running from jenkins
I am currently facing some issue which are related to gradle/NodeJS. What I did is used Node plugin by writing this in my gradle script:

```<code>apply plugin: 'com.moowork.node'

dependencies {
    classpath 'com.moowork.gradle:gradle-node-plugin:0.12'
 }
</code>```

now when I try to run install npm command from terminal(CentOS) by running:

```<code>gradle npmInstall
</code>```

it is running perfectly fine and installing all the required packages whereas when I run the same command from Jenkins (Jenkins installed in centos), I am getting following error msg:

```<code>:npmInstall FAILED
 FAILURE: Build failed with an exception.

* What went wrong:
  Execution failed for task ':npmInstall'.
  > A problem occurred starting process 'command 'npm''

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task
':npmInstall'.
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)

Caused by: org.gradle.process.internal.ExecException: A problem occurred starting process 'command 'npm''
at org.gradle.process.internal.DefaultExecHandle.setEndStateInfo(DefaultExecHandle.java:197)

Caused by: net.rubygrapefruit.platform.NativeException: Could not start 'npm'
at net.rubygrapefruit.platform.internal.DefaultProcessLauncher.start(DefaultProcessLauncher.java:27)
</code>```

Can somebody please help me with is. I am not getting what Wrong I am doing.
I am also getting the same error msg if try to run following command:

```<code>gradle npm_run_build_prod
</code>```

whereas the same list of commands are working for my local windows jenkins.

答:
My issue was resolved on the Gradle help forum.  The solution is to download Node.js during the build by adding this to build.gradle:</p>

```<code>node {
    download = true
    version='9.2.0'
}
</code>```

Title: NPM Issue while running from jenkins

Body:
I am currently facing some issue which are related to gradle/NodeJS. What I did is used Node plugin by writing this in my gradle script:

apply plugin: 'com.moowork.node'

dependencies {
    classpath 'com.moowork.gradle:gradle-node-plugin:0.12'
 }

now when I try to run install npm command from terminal(CentOS) by running:

gradle npmInstall

it is running perfectly fine and installing all the required packages whereas when I run the same command from Jenkins (Jenkins installed in centos), I am getting following error msg:

:npmInstall FAILED
 FAILURE: Build failed with an exception.

* What went wrong:
  Execution failed for task ':npmInstall'.
  > A problem occurred starting process 'command 'npm''

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task
':npmInstall'.
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)

Caused by: org.gradle.process.internal.ExecException: A problem occurred starting process 'command 'npm''
at org.gradle.process.internal.DefaultExecHandle.setEndStateInfo(DefaultExecHandle.java:197)

Caused by: net.rubygrapefruit.platform.NativeException: Could not start 'npm'
at net.rubygrapefruit.platform.internal.DefaultProcessLauncher.start(DefaultProcessLauncher.java:27)

Can somebody please help me with is. I am not getting what Wrong I am doing.
I am also getting the same error msg if try to run following command:

gradle npm_run_build_prod

whereas the same list of commands are working for my local windows jenkins.

Body:
My issue was resolved on the Gradle help forum.  The solution is to download Node.js during the build by adding this to build.gradle:

node {
    download = true
    version='9.2.0'
}

ContentLicense: CC BY-SA 4.0


问:
How to expose property by JMS/Serializer for only one method?
I'm using JMS serializer in my Symfony projuect and i have a question about it. I want ot expose property from entity for only one specific method (one route), in other cases i dont want this property to be exposed. I would be appreciate for any advices) </p>

答:
You can probably achieve this using the @Groups annotation on your properties and then tell the serializer which groups to serialize in your controller.

```<code>use JMS\Serializer\Annotation\Groups;

class BlogPost
{
    /** @Groups({"list", "details"}) */
    private $id;

    /** @Groups({"list", "details"}) */
    private $title;

    /** @Groups({"list"}) */
    private $nbComments;

    /** @Groups({"details"}) */
    private $comments;

    private $createdAt;
}
</code>```

And then:

```<code>use JMS\Serializer\SerializationContext;

$serializer->serialize(new BlogPost(), 'json', SerializationContext::create()->setGroups(array('list')));

//will output $id, $title and $nbComments.

$serializer->serialize(new BlogPost(), 'json', SerializationContext::create()->setGroups(array('Default', 'list')));

//will output $id, $title, $nbComments and $createdAt.
</code>```

More info here.

Body:
You can probably achieve this using the @Groups annotation on your properties and then tell the serializer which groups to serialize in your controller.

use JMS\Serializer\Annotation\Groups;

class BlogPost
{
    /** @Groups({"list", "details"}) */
    private $id;

    /** @Groups({"list", "details"}) */
    private $title;

    /** @Groups({"list"}) */
    private $nbComments;

    /** @Groups({"details"}) */
    private $comments;

    private $createdAt;
}

And then:

use JMS\Serializer\SerializationContext;

$serializer->serialize(new BlogPost(), 'json', SerializationContext::create()->setGroups(array('list')));

//will output $id, $title and $nbComments.

$serializer->serialize(new BlogPost(), 'json', SerializationContext::create()->setGroups(array('Default', 'list')));

//will output $id, $title, $nbComments and $createdAt.

More info here.


问:
How to get property value from response as JSON in Apache Synapse?
Is there a way to get value from response as JSON in Apache Synapse?

Here's an example api mediator.

```<code><api context="/accounts">
    <resource methods="GET">
        <inSequence>
            <log level="full"/>
            <send>
                <endpoint>
                    <address uri="http://localhost:8988/accounts/">
                    </address>
                </endpoint>
            </send>
        </inSequence>
        <outSequence>
            <log>
                <property name="Status" expression="get-property('status')">
            </log>
            <log level="full"/>
            <send/>
        </outSequence>
    </resource>
</api>
</code>```

Call from http://localhost:8988/accounts/ will result in this json:

```<code>{
   "accountNumber": "1234567890123456",
   "status": "active"
}
</code>```

Upon hit on outSeqeunce>log there's no result being get from get-property('status').

I know that there's a function in WSO2 like json-eval but solution must be limited on using Apache Synapse.

答:
Not sure if I really understand your question or  why you don't want to use JSON path expression.

Maybe this is a solution. You can transform the JSON to XML by simply setting a property.

```<code><property name="messageType" value="application/xml" scope="axis2"/>
</code>```

You should then be able to access it using XPath expressions. The following link will explain how to do this.

JSON Support

Body:
Is there a way to get value from response as JSON in Apache Synapse?

Here's an example api mediator.

<api context="/accounts">
    <resource methods="GET">
        <inSequence>
            <log level="full"/>
            <send>
                <endpoint>
                    <address uri="http://localhost:8988/accounts/">
                    </address>
                </endpoint>
            </send>
        </inSequence>
        <outSequence>
            <log>
                <property name="Status" expression="get-property('status')">
            </log>
            <log level="full"/>
            <send/>
        </outSequence>
    </resource>
</api>

Call from http://localhost:8988/accounts/ will result in this json:

{
   "accountNumber": "1234567890123456",
   "status": "active"
}

Upon hit on outSeqeunce>log there's no result being get from get-property('status').

I know that there's a function in WSO2 like json-eval but solution must be limited on using Apache Synapse.

Body:
Not sure if I really understand your question or  why you don't want to use JSON path expression.

Maybe this is a solution. You can transform the JSON to XML by simply setting a property.

<property name="messageType" value="application/xml" scope="axis2"/>

You should then be able to access it using XPath expressions. The following link will explain how to do this.

JSON Support


问:
How to use delta trigger in flink?
I want to use the deltatrigger in apache flink (flink 1.3) but I have some trouble with this code :

```<code>.trigger(DeltaTrigger.of(100, new DeltaFunction[uniqStruct] {
    override def getDelta(oldFp: uniqStruct, newFp: uniqStruct): Double = newFp.time - oldFp.time
  }, TypeInformation[uniqStruct]))
</code>```

And I have this error:

```<code>error: object org.apache.flink.api.common.typeinfo.TypeInformation is not a value [ERROR] }, TypeInformation[uniqStruct]))
</code>```

I don't understand why DeltaTrigger need  TypeSerializer[T]
and I don't know what to do to remove this error.

Thanks a lot everyone.

答:
DeltaTrigger needs a TypeSerializer because it uses Flink's managed state mechanism to store each element for later comparison with the next one (it just keeps one element, the last one, which is updated as new elements arrive).

You will find an example (in Java) here.

But if all you need is a window that triggers every 100msec, then it'll be easier to just use a TimeWindow, such as

```<code>input
  .keyBy(<key selector>)
  .timeWindow(Time.milliseconds(100)))
  .apply(<window function>)
</code>```

Updated:

To have hour-long windows that trigger every 100msec, you could use sliding windows. However, you would have 10 * 60 * 60 windows, and every event would be placed into each of these 36000 windows. So that's not a great idea.

If you use a GlobalWindow with a DeltaTrigger, then the window will be triggered only when events are more than 100msec apart, which isn't what you've said you want.

I suggest you look at ProcessFunction. It should be straightforward to get what you want that way.

Title: How to use delta trigger in flink?

Body:
I want to use the deltatrigger in apache flink (flink 1.3) but I have some trouble with this code :

.trigger(DeltaTrigger.of(100, new DeltaFunction[uniqStruct] {
    override def getDelta(oldFp: uniqStruct, newFp: uniqStruct): Double = newFp.time - oldFp.time
  }, TypeInformation[uniqStruct]))

And I have this error:

error: object org.apache.flink.api.common.typeinfo.TypeInformation is not a value [ERROR] }, TypeInformation[uniqStruct]))

I don't understand why DeltaTrigger need  TypeSerializer[T]
and I don't know what to do to remove this error.

Thanks a lot everyone.

Body:
DeltaTrigger needs a TypeSerializer because it uses Flink's managed state mechanism to store each element for later comparison with the next one (it just keeps one element, the last one, which is updated as new elements arrive).

You will find an example (in Java) here.

But if all you need is a window that triggers every 100msec, then it'll be easier to just use a TimeWindow, such as

input
  .keyBy(<key selector>)
  .timeWindow(Time.milliseconds(100)))
  .apply(<window function>)

Updated:

To have hour-long windows that trigger every 100msec, you could use sliding windows. However, you would have 10 * 60 * 60 windows, and every event would be placed into each of these 36000 windows. So that's not a great idea.

If you use a GlobalWindow with a DeltaTrigger, then the window will be triggered only when events are more than 100msec apart, which isn't what you've said you want.

I suggest you look at ProcessFunction. It should be straightforward to get what you want that way.


问:
ERROR 1137: Can't reopen table when joining a temporary table
I have a stored procedure:

```<code>DROP PROCEDURE IF EXISTS dijResolve;
DELIMITER |
CREATE PROCEDURE dijResolve( pFromNodeName VARCHAR(20), pToNodeName VARCHAR(20) )
BEGIN
  DECLARE vFromNodeID, vToNodeID, vNodeID, vCost, vPathID INT;
  CREATE TEMPORARY TABLE new_dijnodes engine=memory AS SELECT * FROM dijnodes;
  CREATE TEMPORARY TABLE new_dijpaths AS SELECT * FROM dijpaths;

  -- null out path info in the nodes table
  UPDATE new_dijnodes SET PathID = NULL,Cost = NULL,Calculated = 0;
  -- find nodeIDs referenced by input params
  SET vFromNodeID = ( SELECT NodeID FROM new_dijnodes WHERE NodeName = pFromNodeName );
  IF vFromNodeID IS NULL THEN
    SELECT CONCAT('From node name ', pFromNodeName, ' not found.' );
  ELSE
    BEGIN
      -- start at src node
      SET vNodeID = vFromNodeID;
      SET vToNodeID = ( SELECT NodeID FROM new_dijnodes WHERE NodeName = pToNodeName );
      IF vToNodeID IS NULL THEN
        SELECT CONCAT('From node name ', pToNodeName, ' not found.' );
      ELSE
        BEGIN
          -- calculate path costs till all are done
          UPDATE new_dijnodes SET Cost=0 WHERE NodeID = vFromNodeID;
          WHILE vNodeID IS NOT NULL DO
            BEGIN
              UPDATE
                new_dijnodes AS src
                JOIN new_dijpaths AS paths ON paths.FromNodeID = src.NodeID
                JOIN new_dijnodes AS dest ON dest.NodeID = Paths.ToNodeID
              SET dest.Cost = CASE
                                WHEN dest.Cost IS NULL THEN src.Cost + Paths.Cost
                                WHEN src.Cost + Paths.Cost < dest.Cost THEN src.Cost + Paths.Cost
                                ELSE dest.Cost
                              END,
                  dest.PathID = Paths.PathID
              WHERE
                src.NodeID = vNodeID
                AND (dest.Cost IS NULL OR src.Cost + Paths.Cost < dest.Cost)
                AND dest.Calculated = 0;

              UPDATE new_dijnodes SET Calculated = 1 WHERE NodeID = vNodeID;

              SET vNodeID = ( SELECT nodeID FROM new_dijnodes
                              WHERE Calculated = 0 AND Cost IS NOT NULL
                              ORDER BY Cost LIMIT 1
                            );
            END;
          END WHILE;
        END;
      END IF;
    END;
  END IF;
  IF EXISTS( SELECT 1 FROM new_dijnodes WHERE NodeID = vToNodeID AND Cost IS NULL ) THEN
    -- problem,  cannot proceed
    SELECT CONCAT( 'Node ',vNodeID, ' missed.' );
  ELSE
    BEGIN
      -- write itinerary to map table
      DROP TEMPORARY TABLE IF EXISTS map;
      CREATE TEMPORARY TABLE map (
        RowID INT PRIMARY KEY AUTO_INCREMENT,
        FromNodeName VARCHAR(20),
        ToNodeName VARCHAR(20),
        Cost INT
      ) ENGINE=MEMORY;
      WHILE vFromNodeID <> vToNodeID DO
        BEGIN
          SELECT
            src.NodeName,dest.NodeName,dest.Cost,dest.PathID
            INTO vFromNodeName, vToNodeName, vCost, vPathID
          FROM
            new_dijnodes AS dest
            JOIN new_dijpaths AS Paths ON Paths.PathID = dest.PathID
            JOIN new_dijnodes AS src ON src.NodeID = Paths.FromNodeID
          WHERE dest.NodeID = vToNodeID;

          INSERT INTO Map(FromNodeName,ToNodeName,Cost) VALUES(vFromNodeName,vToNodeName,vCost);

          SET vToNodeID = (SELECT FromNodeID FROM new_dijpaths WHERE PathID = vPathID);
        END;
      END WHILE;
      SELECT FromNodeName,ToNodeName,Cost FROM Map ORDER BY RowID DESC;
      DROP TEMPORARY TABLE Map;
    END;
  END IF;
END;
|
DELIMITER ;
</code>```

This function is taken from this site
http://www.artfulsoftware.com/infotree/qrytip.php?id=766

well I have changed it to be able to do calculations on temporary tables so it is not any need to save data in tables. But I faced a problem, Mysql does not let to call a temporary table with other names. so In above code I'll face an error which says

```<code>#1137 - Can't reopen table: 'src'
</code>```

the above error comes from this query

```<code>      UPDATE
        new_dijnodes AS src
        JOIN new_dijpaths AS paths ON paths.FromNodeID = src.NodeID
        JOIN new_dijnodes AS dest ON dest.NodeID = Paths.ToNodeID
      SET dest.Cost = CASE
                        WHEN dest.Cost IS NULL THEN src.Cost + Paths.Cost
                        WHEN src.Cost + Paths.Cost < dest.Cost THEN src.Cost + Paths.Cost
                        ELSE dest.Cost
                      END,
          dest.PathID = Paths.PathID
      WHERE
        src.NodeID = vNodeID
        AND (dest.Cost IS NULL OR src.Cost + Paths.Cost < dest.Cost)
        AND dest.Calculated = 0;
</code>```

here is http://sqlfiddle.com/#!9/bc5a01c data of my tables
As you can see the above query joins the same table once as src and again as dest and updates their fields. I tried to create another  new_dijnodes but I could not make it work,Here is my try

```<code>DROP PROCEDURE IF EXISTS dijResolve;
DELIMITER |
CREATE PROCEDURE dijResolve( pFromNodeName VARCHAR(20), pToNodeName VARCHAR(20) )
BEGIN
  DECLARE vFromNodeID, vToNodeID, vNodeID, vCost, vPathID INT;
  DECLARE vFromNodeName, vToNodeName VARCHAR(20);
  DROP TEMPORARY TABLE IF EXISTS new_dijnodes;
  DROP TEMPORARY TABLE IF EXISTS new_dijpaths;

  CREATE TEMPORARY TABLE new_dijnodes engine=memory AS SELECT * FROM dijnodes;
  CREATE TEMPORARY TABLE new_dijpaths AS SELECT * FROM dijpaths;

  -- null out path info in the nodes table
  UPDATE new_dijnodes SET PathID = NULL,Cost = NULL,Calculated = 0;
  -- find nodeIDs referenced by input params
  SET vFromNodeID = ( SELECT NodeID FROM new_dijnodes WHERE NodeName = pFromNodeName );
  IF vFromNodeID IS NULL THEN
    SELECT CONCAT('From node name ', pFromNodeName, ' not found.' );
  ELSE
    BEGIN
      -- start at src node
      SET vNodeID = vFromNodeID;
      SET vToNodeID = ( SELECT NodeID FROM new_dijnodes WHERE NodeName = pToNodeName );
      IF vToNodeID IS NULL THEN
        SELECT CONCAT('From node name ', pToNodeName, ' not found.' );
      ELSE
        BEGIN
          -- calculate path costs till all are done
          UPDATE new_dijnodes SET Cost=0 WHERE NodeID = vFromNodeID;
          WHILE vNodeID IS NOT NULL DO
            BEGIN
            DROP TEMPORARY TABLE IF EXISTS new_dijnodes_dst;
            CREATE TEMPORARY TABLE new_dijnodes_dst AS SELECT * FROM new_dijnodes;

              UPDATE
                new_dijnodes
                JOIN new_dijpaths  ON new_dijpaths.FromNodeID = new_dijnodes.NodeID
                JOIN new_dijnodes_dst ON new_dijnodes_dst.NodeID = new_dijpaths.ToNodeID
              SET new_dijnodes_dst.Cost = CASE
                                WHEN new_dijnodes_dst.Cost IS NULL THEN new_dijnodes.Cost + new_dijpaths.Cost
                                WHEN new_dijnodes.Cost + new_dijpaths.Cost < new_dijnodes_dst.Cost THEN new_dijnodes.Cost + new_dijpaths.Cost
                                ELSE new_dijnodes_dst.Cost
                              END,
                  new_dijnodes_dst.PathID = new_dijpaths.PathID
              WHERE
                new_dijnodes.NodeID = vNodeID
                AND (new_dijnodes_dst.Cost IS NULL OR new_dijnodes.Cost + new_dijpaths.Cost < new_dijnodes_dst.Cost)
                AND new_dijnodes_dst.Calculated = 0;

              UPDATE new_dijnodes SET Calculated = 1 WHERE NodeID = vNodeID;

              SET vNodeID = ( SELECT nodeID FROM new_dijnodes
                              WHERE Calculated = 0 AND Cost IS NOT NULL
                              ORDER BY Cost LIMIT 1
                            );
            END;
          END WHILE;
        END;
      END IF;
    END;
  END IF;
  IF EXISTS( SELECT 1 FROM new_dijnodes WHERE NodeID = vToNodeID AND Cost IS NULL ) THEN
    -- problem,  cannot proceed
    SELECT CONCAT( 'Node ',vNodeID, ' missed.' );
  ELSE
    BEGIN
      -- write itinerary to map table
      DROP TEMPORARY TABLE IF EXISTS map;
      CREATE TEMPORARY TABLE map (
        RowID INT PRIMARY KEY AUTO_INCREMENT,
        FromNodeName VARCHAR(20),
        ToNodeName VARCHAR(20),
        Cost INT
      ) ENGINE=MEMORY;
      WHILE vFromNodeID <> vToNodeID DO
        BEGIN
        DROP TEMPORARY TABLE IF EXISTS new_dijnodes_src;
        CREATE TEMPORARY TABLE new_dijnodes_src AS SELECT * FROM new_dijnodes;

          SELECT
            new_dijnodes_src.NodeName,new_dijnodes.NodeName,new_dijnodes.Cost,new_dijnodes.PathID
            INTO vFromNodeName, vToNodeName, vCost, vPathID
          FROM
            new_dijnodes
            JOIN new_dijpaths  ON new_dijpaths.PathID = new_dijnodes.PathID
            JOIN new_dijnodes_src  ON new_dijnodes_src.NodeID = new_dijpaths.FromNodeID
          WHERE new_dijnodes.NodeID = vToNodeID;

          INSERT INTO Map(FromNodeName,ToNodeName,Cost) VALUES(vFromNodeName,vToNodeName,vCost);

          SET vToNodeID = (SELECT FromNodeID FROM new_dijpaths WHERE PathID = vPathID);
        END;
      END WHILE;
      SELECT FromNodeName,ToNodeName,Cost FROM Map ORDER BY RowID DESC;
      DROP TEMPORARY TABLE Map;
    END;
  END IF;
END;
|
DELIMITER ;
</code>```

but it always returns  SELECT CONCAT( 'Node ',vNodeID, ' missed.' );  as It updates new_dijnodes_dst which is tables duplication.

I also can not make any real table as this procedure is unique for each user and its handling is not easy for multiuser.
what solutions are available to fix this problem?
thanks

答:
MySQL doc suggests

You cannot refer to a TEMPORARY table more than once in the same query

Please refer to this thread. Most practical solutions seem to be

Replace temporary table with permanent table

Replace subsequent calls of temporary table with sub-query behind temporary table

Duplicate temporary table

Find a workaround self joins

Since your particular problem is update with self join and you don't want permanent table, I'd recommend that making duplicate temporary tables is most suitable option.

I tried to create another  new_dijnodes but I could not make it work

Can you please share where are you having trouble in this?

Body:
I have a stored procedure:

DROP PROCEDURE IF EXISTS dijResolve;
DELIMITER |
CREATE PROCEDURE dijResolve( pFromNodeName VARCHAR(20), pToNodeName VARCHAR(20) )
BEGIN
  DECLARE vFromNodeID, vToNodeID, vNodeID, vCost, vPathID INT;
  CREATE TEMPORARY TABLE new_dijnodes engine=memory AS SELECT * FROM dijnodes;
  CREATE TEMPORARY TABLE new_dijpaths AS SELECT * FROM dijpaths;

  -- null out path info in the nodes table
  UPDATE new_dijnodes SET PathID = NULL,Cost = NULL,Calculated = 0;
  -- find nodeIDs referenced by input params
  SET vFromNodeID = ( SELECT NodeID FROM new_dijnodes WHERE NodeName = pFromNodeName );
  IF vFromNodeID IS NULL THEN
    SELECT CONCAT('From node name ', pFromNodeName, ' not found.' );
  ELSE
    BEGIN
      -- start at src node
      SET vNodeID = vFromNodeID;
      SET vToNodeID = ( SELECT NodeID FROM new_dijnodes WHERE NodeName = pToNodeName );
      IF vToNodeID IS NULL THEN
        SELECT CONCAT('From node name ', pToNodeName, ' not found.' );
      ELSE
        BEGIN
          -- calculate path costs till all are done
          UPDATE new_dijnodes SET Cost=0 WHERE NodeID = vFromNodeID;
          WHILE vNodeID IS NOT NULL DO
            BEGIN
              UPDATE
                new_dijnodes AS src
                JOIN new_dijpaths AS paths ON paths.FromNodeID = src.NodeID
                JOIN new_dijnodes AS dest ON dest.NodeID = Paths.ToNodeID
              SET dest.Cost = CASE
                                WHEN dest.Cost IS NULL THEN src.Cost + Paths.Cost
                                WHEN src.Cost + Paths.Cost < dest.Cost THEN src.Cost + Paths.Cost
                                ELSE dest.Cost
                              END,
                  dest.PathID = Paths.PathID
              WHERE
                src.NodeID = vNodeID
                AND (dest.Cost IS NULL OR src.Cost + Paths.Cost < dest.Cost)
                AND dest.Calculated = 0;

              UPDATE new_dijnodes SET Calculated = 1 WHERE NodeID = vNodeID;

              SET vNodeID = ( SELECT nodeID FROM new_dijnodes
                              WHERE Calculated = 0 AND Cost IS NOT NULL
                              ORDER BY Cost LIMIT 1
                            );
            END;
          END WHILE;
        END;
      END IF;
    END;
  END IF;
  IF EXISTS( SELECT 1 FROM new_dijnodes WHERE NodeID = vToNodeID AND Cost IS NULL ) THEN
    -- problem,  cannot proceed
    SELECT CONCAT( 'Node ',vNodeID, ' missed.' );
  ELSE
    BEGIN
      -- write itinerary to map table
      DROP TEMPORARY TABLE IF EXISTS map;
      CREATE TEMPORARY TABLE map (
        RowID INT PRIMARY KEY AUTO_INCREMENT,
        FromNodeName VARCHAR(20),
        ToNodeName VARCHAR(20),
        Cost INT
      ) ENGINE=MEMORY;
      WHILE vFromNodeID <> vToNodeID DO
        BEGIN
          SELECT
            src.NodeName,dest.NodeName,dest.Cost,dest.PathID
            INTO vFromNodeName, vToNodeName, vCost, vPathID
          FROM
            new_dijnodes AS dest
            JOIN new_dijpaths AS Paths ON Paths.PathID = dest.PathID
            JOIN new_dijnodes AS src ON src.NodeID = Paths.FromNodeID
          WHERE dest.NodeID = vToNodeID;

          INSERT INTO Map(FromNodeName,ToNodeName,Cost) VALUES(vFromNodeName,vToNodeName,vCost);

          SET vToNodeID = (SELECT FromNodeID FROM new_dijpaths WHERE PathID = vPathID);
        END;
      END WHILE;
      SELECT FromNodeName,ToNodeName,Cost FROM Map ORDER BY RowID DESC;
      DROP TEMPORARY TABLE Map;
    END;
  END IF;
END;
|
DELIMITER ;

This function is taken from this site
http://www.artfulsoftware.com/infotree/qrytip.php?id=766

well I have changed it to be able to do calculations on temporary tables so it is not any need to save data in tables. But I faced a problem, Mysql does not let to call a temporary table with other names. so In above code I'll face an error which says

#1137 - Can't reopen table: 'src'

the above error comes from this query

      UPDATE
        new_dijnodes AS src
        JOIN new_dijpaths AS paths ON paths.FromNodeID = src.NodeID
        JOIN new_dijnodes AS dest ON dest.NodeID = Paths.ToNodeID
      SET dest.Cost = CASE
                        WHEN dest.Cost IS NULL THEN src.Cost + Paths.Cost
                        WHEN src.Cost + Paths.Cost < dest.Cost THEN src.Cost + Paths.Cost
                        ELSE dest.Cost
                      END,
          dest.PathID = Paths.PathID
      WHERE
        src.NodeID = vNodeID
        AND (dest.Cost IS NULL OR src.Cost + Paths.Cost < dest.Cost)
        AND dest.Calculated = 0;

here is http://sqlfiddle.com/#!9/bc5a01c data of my tables
As you can see the above query joins the same table once as src and again as dest and updates their fields. I tried to create another  new_dijnodes but I could not make it work,Here is my try

DROP PROCEDURE IF EXISTS dijResolve;
DELIMITER |
CREATE PROCEDURE dijResolve( pFromNodeName VARCHAR(20), pToNodeName VARCHAR(20) )
BEGIN
  DECLARE vFromNodeID, vToNodeID, vNodeID, vCost, vPathID INT;
  DECLARE vFromNodeName, vToNodeName VARCHAR(20);
  DROP TEMPORARY TABLE IF EXISTS new_dijnodes;
  DROP TEMPORARY TABLE IF EXISTS new_dijpaths;

  CREATE TEMPORARY TABLE new_dijnodes engine=memory AS SELECT * FROM dijnodes;
  CREATE TEMPORARY TABLE new_dijpaths AS SELECT * FROM dijpaths;

  -- null out path info in the nodes table
  UPDATE new_dijnodes SET PathID = NULL,Cost = NULL,Calculated = 0;
  -- find nodeIDs referenced by input params
  SET vFromNodeID = ( SELECT NodeID FROM new_dijnodes WHERE NodeName = pFromNodeName );
  IF vFromNodeID IS NULL THEN
    SELECT CONCAT('From node name ', pFromNodeName, ' not found.' );
  ELSE
    BEGIN
      -- start at src node
      SET vNodeID = vFromNodeID;
      SET vToNodeID = ( SELECT NodeID FROM new_dijnodes WHERE NodeName = pToNodeName );
      IF vToNodeID IS NULL THEN
        SELECT CONCAT('From node name ', pToNodeName, ' not found.' );
      ELSE
        BEGIN
          -- calculate path costs till all are done
          UPDATE new_dijnodes SET Cost=0 WHERE NodeID = vFromNodeID;
          WHILE vNodeID IS NOT NULL DO
            BEGIN
            DROP TEMPORARY TABLE IF EXISTS new_dijnodes_dst;
            CREATE TEMPORARY TABLE new_dijnodes_dst AS SELECT * FROM new_dijnodes;

              UPDATE
                new_dijnodes
                JOIN new_dijpaths  ON new_dijpaths.FromNodeID = new_dijnodes.NodeID
                JOIN new_dijnodes_dst ON new_dijnodes_dst.NodeID = new_dijpaths.ToNodeID
              SET new_dijnodes_dst.Cost = CASE
                                WHEN new_dijnodes_dst.Cost IS NULL THEN new_dijnodes.Cost + new_dijpaths.Cost
                                WHEN new_dijnodes.Cost + new_dijpaths.Cost < new_dijnodes_dst.Cost THEN new_dijnodes.Cost + new_dijpaths.Cost
                                ELSE new_dijnodes_dst.Cost
                              END,
                  new_dijnodes_dst.PathID = new_dijpaths.PathID
              WHERE
                new_dijnodes.NodeID = vNodeID
                AND (new_dijnodes_dst.Cost IS NULL OR new_dijnodes.Cost + new_dijpaths.Cost < new_dijnodes_dst.Cost)
                AND new_dijnodes_dst.Calculated = 0;

              UPDATE new_dijnodes SET Calculated = 1 WHERE NodeID = vNodeID;

              SET vNodeID = ( SELECT nodeID FROM new_dijnodes
                              WHERE Calculated = 0 AND Cost IS NOT NULL
                              ORDER BY Cost LIMIT 1
                            );
            END;
          END WHILE;
        END;
      END IF;
    END;
  END IF;
  IF EXISTS( SELECT 1 FROM new_dijnodes WHERE NodeID = vToNodeID AND Cost IS NULL ) THEN
    -- problem,  cannot proceed
    SELECT CONCAT( 'Node ',vNodeID, ' missed.' );
  ELSE
    BEGIN
      -- write itinerary to map table
      DROP TEMPORARY TABLE IF EXISTS map;
      CREATE TEMPORARY TABLE map (
        RowID INT PRIMARY KEY AUTO_INCREMENT,
        FromNodeName VARCHAR(20),
        ToNodeName VARCHAR(20),
        Cost INT
      ) ENGINE=MEMORY;
      WHILE vFromNodeID <> vToNodeID DO
        BEGIN
        DROP TEMPORARY TABLE IF EXISTS new_dijnodes_src;
        CREATE TEMPORARY TABLE new_dijnodes_src AS SELECT * FROM new_dijnodes;

          SELECT
            new_dijnodes_src.NodeName,new_dijnodes.NodeName,new_dijnodes.Cost,new_dijnodes.PathID
            INTO vFromNodeName, vToNodeName, vCost, vPathID
          FROM
            new_dijnodes
            JOIN new_dijpaths  ON new_dijpaths.PathID = new_dijnodes.PathID
            JOIN new_dijnodes_src  ON new_dijnodes_src.NodeID = new_dijpaths.FromNodeID
          WHERE new_dijnodes.NodeID = vToNodeID;

          INSERT INTO Map(FromNodeName,ToNodeName,Cost) VALUES(vFromNodeName,vToNodeName,vCost);

          SET vToNodeID = (SELECT FromNodeID FROM new_dijpaths WHERE PathID = vPathID);
        END;
      END WHILE;
      SELECT FromNodeName,ToNodeName,Cost FROM Map ORDER BY RowID DESC;
      DROP TEMPORARY TABLE Map;
    END;
  END IF;
END;
|
DELIMITER ;

but it always returns  SELECT CONCAT( 'Node ',vNodeID, ' missed.' );  as It updates new_dijnodes_dst which is tables duplication.

I also can not make any real table as this procedure is unique for each user and its handling is not easy for multiuser.
what solutions are available to fix this problem?
thanks


问:
How to encrypt the Data in swift3? When I m encrypting the data and printing it .it is showing me in Bytes .I have use RNCryptor
String to Data:

```<code>let ciphertext = RNCryptor.encrypt(data: testString.data(using:
              String.Encoding.utf8)!, withPassword: password)

print(ciphertext)
</code>```

Back to string:

```<code>var backToString = String(data: ciphertext, encoding:
                 String.Encoding.utf8) as String!

print(backToString)
</code>```

答:
For decryption employ RNCryptor.decrypt() method, not default String(data: ..).

```<code>// Decryption
do {
    let originalData = try RNCryptor.decrypt(data: ciphertext, withPassword: password)
    // ...
} catch {
    print(error)
}
</code>```

And then manipulate the original data as you do it:

```<code>var backToString = String(data: originalData, encoding:
                 String.Encoding.utf8) as String!

print(backToString)
</code>```

Body:
String to Data:

let ciphertext = RNCryptor.encrypt(data: testString.data(using:
              String.Encoding.utf8)!, withPassword: password)

print(ciphertext)

Back to string:

var backToString = String(data: ciphertext, encoding:
                 String.Encoding.utf8) as String!

print(backToString)

Body:
For decryption employ RNCryptor.decrypt() method, not default String(data: ..).

// Decryption
do {
    let originalData = try RNCryptor.decrypt(data: ciphertext, withPassword: password)
    // ...
} catch {
    print(error)
}

And then manipulate the original data as you do it:

var backToString = String(data: originalData, encoding:
                 String.Encoding.utf8) as String!

print(backToString)


问:
How to get database value on label in vb.net?
I am beginner level programmer. Actually i have used two combo box named as "Category" and "Location". When i will click on submit then it should display the category of chemicals and location respectively from database on the labels itself. </p>

答:
I think you might be looking for something like this?</p>

```<code> Dim connetionString As String
    Dim connection As SqlConnection
    Dim adapter As SqlDataAdapter
    Dim ds As New DataSet

    connetionString = "ConnetionString;"
    connection = New SqlConnection(connetionString)
    Try
        connection.Open()
        adapter = New SqlDataAdapter("Select column1, column2, column3, column4 from Table1 where Id='" & TextBox9.Text & "'", connection)
        adapter.Fill(ds)
        connection.Close()

        If ds.Tables(0).Rows.Count > 0 Then
            label1.Text = "blablabla" & ds.Tables(0).Rows(0)("column1").ToString()
            label2.Text = "blablabla" & ds.Tables(0).Rows(0)("column2").ToString()
            label3.Text = "blablabla" & ds.Tables(0).Rows(0)("column3").ToString()
            label4.Text = "blablabla" & ds.Tables(0).Rows(0)("column4").ToString()

        End If
    Catch ex As Exception
        Form4.TextBox1.Text = "Failed to connect to database"
        Form4.Show()

    End Try
    Return False
</code>```

Body:
I think you might be looking for something like this?

 Dim connetionString As String
    Dim connection As SqlConnection
    Dim adapter As SqlDataAdapter
    Dim ds As New DataSet

    connetionString = "ConnetionString;"
    connection = New SqlConnection(connetionString)
    Try
        connection.Open()
        adapter = New SqlDataAdapter("Select column1, column2, column3, column4 from Table1 where Id='" & TextBox9.Text & "'", connection)
        adapter.Fill(ds)
        connection.Close()

        If ds.Tables(0).Rows.Count > 0 Then
            label1.Text = "blablabla" & ds.Tables(0).Rows(0)("column1").ToString()
            label2.Text = "blablabla" & ds.Tables(0).Rows(0)("column2").ToString()
            label3.Text = "blablabla" & ds.Tables(0).Rows(0)("column3").ToString()
            label4.Text = "blablabla" & ds.Tables(0).Rows(0)("column4").ToString()

        End If
    Catch ex As Exception
        Form4.TextBox1.Text = "Failed to connect to database"
        Form4.Show()

    End Try
    Return False


问:
Is there a way to check for shift held down THEN control held down for each input?
I'm trying to use _getch to get keyboard strokes for incrementing money in a game. If I want the money to be incremented faster, in 10's while shift is held down and 100's control is held down what would be the best way to do that? If I just check for shifts it's easy enough, but if I want to check for a shift then a control afterwards it won't work.

For instance checking to increment by 1 or 10 I'd do something like this

```<code>key = _getch();
if (key == 224)
{
    key = _getch();
    if (key == 75) // left arrow
    {
        if (GetAsyncKeyState(VK_SHIFT)
            for (int i = 0; i < 10; i++) // go left 10 times
                    left();
        else
            left();
    }
}
</code>```

If I add an else if for control for 100's it will NOT work. Most likely because running the GetAsyncKeyState fucntion again makes it not read the key state properly.

```<code>else if (GetAsyncKeyState(VK_CONTROL)
    for (int i = 0; i < 100; i++) // go left 100 times
        left();
</code>```

Any possible workaround? Thanks!

答: Turns out control prevent the console from "flushing". So, it was just a problem with control itself causing the error, I decided to use while-shift held for 10's and while-tab held for 100's. If there is a way to use alt, which I don't think there is, I'd use that. This is just a typical case of me being stupid and taking like 3 hours to realize it was the keybind interacting with the cmd prompt causing the issue.</p>

Body:
I'm trying to use _getch to get keyboard strokes for incrementing money in a game. If I want the money to be incremented faster, in 10's while shift is held down and 100's control is held down what would be the best way to do that? If I just check for shifts it's easy enough, but if I want to check for a shift then a control afterwards it won't work.

For instance checking to increment by 1 or 10 I'd do something like this

key = _getch();
if (key == 224)
{
    key = _getch();
    if (key == 75) // left arrow
    {
        if (GetAsyncKeyState(VK_SHIFT)
            for (int i = 0; i < 10; i++) // go left 10 times
                    left();
        else
            left();
    }
}

If I add an else if for control for 100's it will NOT work. Most likely because running the GetAsyncKeyState fucntion again makes it not read the key state properly.

else if (GetAsyncKeyState(VK_CONTROL)
    for (int i = 0; i < 100; i++) // go left 100 times
        left();

Any possible workaround? Thanks!


问:
help with if statement - min of 3 characters
Since there is no minlength="" for input, how can I make an if statement that does the following:

If the user has not input more than 3 characters it will not be saved in a database.

Here is the input:

```<code> QTY<input title="QUANTITY PER ITEM" size="1"  name="inputQTY" value="**(minimun of 3 characters)**"/>
</code>```

any ideas??

答:
Note: it doesn't matter if there's a min value restriction on the input field or not; a user can still spoof the form to contain whatever value he or she wants. Thus, you need to validate on the server side.

Let's say you're using PHP as your server side language.

```<code>$inputQTY = $_POST['inputQTY'];
if (strlen($inputQTY) < 3) {
   // DO NOT INSERT INTO DB
}
else {
   // insert after further scrubbing input
}
</code>```

Read this: What's the best method for sanitizing user input with PHP?

ContentLicense: CC BY-SA 2.5

Body:
Since there is no minlength="" for input, how can I make an if statement that does the following:

If the user has not input more than 3 characters it will not be saved in a database.

Here is the input:

 QTY<input title="QUANTITY PER ITEM" size="1"  name="inputQTY" value="**(minimun of 3 characters)**"/>

any ideas??

Body:
Note: it doesn't matter if there's a min value restriction on the input field or not; a user can still spoof the form to contain whatever value he or she wants. Thus, you need to validate on the server side.

Let's say you're using PHP as your server side language.

$inputQTY = $_POST['inputQTY'];
if (strlen($inputQTY) < 3) {
   // DO NOT INSERT INTO DB
}
else {
   // insert after further scrubbing input
}

Read this: What's the best method for sanitizing user input with PHP?


问:
Endless spinning wheel at Woocommerce checkout
I am in the process of building a shop on wordpress using woocommerce. All is well except that at checkout there is an endless spinning wheel blocking the payment processing.

I have checked the error logs - which show no errors
I have disabled all plug ins - which makes no difference
I have reverted to the default woocommerce shopfront theme - which has the same result.
The console shows no errors.

I have also followed the instructions here https://docs.woocommerce.com/document/endless-loadingspinner-on-the-checkout-page/ which assumes its a memory limit issue. This did not work.

So, after a bit of digging I found some reference here https://mikejolley.com/2015/11/12/debugging-unexpected-token-in-woocommerce-2-4/ and here https://www.maxsangster.com/blog/woocommerce-endless-loading-spinner-on-checkout/

Referring to these two pages I have been able to see that the json response from /?wc-ajax=checkout is just returning HTML which I would imagine is where the issue is.

However I am running an Apache server rather than Nginx as has been mentioned in some threads and articles. Assuming there is a server misconfiguration of the server or something that needs changing what might that be? Bearing in mind that I do not have direct access to this, so will need to be asking someone else to sort it out for me.

And finally if there is something else I can try what might that be?

答:
Thank you to @plushyObject for generating the spark for this one.

The issue turned out that I had a legacy static html holding page in place as the site's homepage rather than having one set up with wordpress. Simply removing the .html page and letting wordpress's homepage take over solves the problem.

The moral of the story create your holding page in wordpress.


问:
Span jumping down when I have an img tag before
I am making a template for a site that im working on for myself... I have added a comment icon and a span to declare how much comments it is on the post. It is just a template of how I want it to be and it is not really working.

The thing is that the icon and the span (with the comment) jumps down a row and displace itself the post has an image:

This is the post class I have every block in;

Without picture:

```<code><a href="posts/post1.php" class="postlink">
  <div class="post">
    <img src="img\userprofile.png" alt="img\userprofile.png" width="100px" height="100px">
    <p class="context">Random Text</p>
    <i class="fa fa-comment-o"></i><span class="comment">  300</span>
  </div>
</a>
<a href="posts/post2.php" class="postlink">
  <div class="post">
    <img src="img\userprofile.png" alt="img\userprofile.png" width="100px" height="100px">
    <img src="img/baugette.jpg" width="220" height="150" class="postimg">
    <p class="context">Random Text</p>
    <i class="fa fa-comment-o"></i><span class="comment">  500</span><br>
  </div>
</code>```

With picture:

```<code><a href="posts/post1.php" class="postlink">
  <div class="post">
    <img src="img\userprofile.png" alt="img\userprofile.png" width="100px" height="100px">
    <p class="context">Random Text</p>
    <i class="fa fa-comment-o"></i><span class="comment">  300</span>
  </div>
</a>
<a href="posts/post2.php" class="postlink">
  <div class="post">
    <img src="img\userprofile.png" alt="img\userprofile.png" width="100px" height="100px">
    <img src="img/baugette.jpg" width="220" height="150" class="postimg">
    <p class="context">Random Text</p>
    <i class="fa fa-comment-o"></i><span class="comment">  500</span><br>
  </div>
</code>```

And this is the ONLY CSS code for that image:

```<code>img.postimg {
    margin-top: -100px;
}
</code>```

答:
Wrap your image and text in separate divs like below

```<code><a href="posts/post1.php" class="postlink">
  <div class="post">
    <div class="image">
        <img src="img\userprofile.png" alt="img\userprofile.png" width="100px" height="100px">
    </div>
    <div class="text">
        <p class="context">Random Text</p>
        <i class="fa fa-comment-o"></i><span class="comment">  300</span>
    </div>
  </div>
</a>
</code>```

and then specify width in css for these elements.

```<code>.image{
    width:50%;
}
.text{
    width:50%;
}
</code>```

try changing width values and try adding float:left or float:right

Body:
I am making a template for a site that im working on for myself... I have added a comment icon and a span to declare how much comments it is on the post. It is just a template of how I want it to be and it is not really working.

The thing is that the icon and the span (with the comment) jumps down a row and displace itself the post has an image:

This is the post class I have every block in;

Without picture:

Random Text

      300

Random Text

      500

With picture:

Random Text

      300

Random Text

      500

And this is the ONLY CSS code for that image:

img.postimg {
    margin-top: -100px;
}

Body:
Wrap your image and text in separate divs like below

<a href="posts/post1.php" class="postlink">
  <div class="post">
    <div class="image">
        <img src="img\userprofile.png" alt="img\userprofile.png" width="100px" height="100px">
    </div>
    <div class="text">
        <p class="context">Random Text</p>
        <i class="fa fa-comment-o"></i><span class="comment">  300</span>
    </div>
  </div>
</a>

and then specify width in css for these elements.

.image{
    width:50%;
}
.text{
    width:50%;
}

try changing width values and try adding float:left or float:right


问:
Docker—purge unneeded interfaces
I am using docker(-compose) mostly for development, so I have a bunch of Projects with one or more containers each on my development machine. I have stopped and removed all containers, but running docker network ls still yields:

and looking at the »connection information« window shows:

How can I »purge« all unneeded interfaces, which were created by a docker run … or docker-compose up?

答:
You can remove all unused networks by running: docker network prune

```<code>> docker network prune --help

Usage:  docker network prune [OPTIONS]
Remove all unused networks
</code>```

Title: Docker—purge unneeded interfaces

Body:
You can remove all unused networks by running: docker network prune

> docker network prune --help

Usage:  docker network prune [OPTIONS]
Remove all unused networks


问:
XML C# Parse - Complex
I have been on google for a while but am just stumped.  I need to parse xml of this nature.  I can't seem to skip to elements in the middle, e.g. Folder.  I have limited the xml as there were many 'Folder' elements.  Any guidance would be appreciated.  I was after the FolderID element's attribute ID.</p>

```<code><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <h:ServerVersionInfo MajorVersion="14"
        MinorVersion="1"
        MajorBuildNumber="225"
        MinorBuildNumber="46"
        Version="Exchange2010_SP1"
        xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types"
        xmlns="http://schemas.microsoft.com/exchange/services/2006/types"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
  </s:Header>
  <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <m:GetFolderResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"
        xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
      <m:ResponseMessages>
        <m:GetFolderResponseMessage ResponseClass="Success">
          <m:ResponseCode>NoError</m:ResponseCode>
          <m:Folders>
            <t:Folder>
              <t:FolderId Id="AAMkADk5MmY1ZThmLTM2MzAtNGVh" ChangeKey="AQAAABYAAACSe/NBrSZiQKqHx8yL+lIRAAAA1EWM" />
              <t:ParentFolderId Id="AAMkADk5MmY1ZThmLTM2MzAtNGVh" ChangeKey="AQAAAA==" />
              <t:DisplayName>Top of Information Store</t:DisplayName>
              <t:TotalCount>0</t:TotalCount>
              <t:ChildFolderCount>15</t:ChildFolderCount>
              <t:EffectiveRights>
                <t:CreateAssociated>true</t:CreateAssociated>
                <t:CreateContents>true</t:CreateContents>
                <t:CreateHierarchy>true</t:CreateHierarchy>
                <t:Delete>true</t:Delete>
                <t:Modify>true</t:Modify>
                <t:Read>true</t:Read>
                <t:ViewPrivateItems>true</t:ViewPrivateItems>
              </t:EffectiveRights>
              <t:PermissionSet>
                <t:Permissions>
                  <t:Permission>
                    <t:UserId>
                      <t:DistinguishedUser>Default</t:DistinguishedUser>
                    </t:UserId>
                    <t:CanCreateItems>false</t:CanCreateItems>
                    <t:CanCreateSubFolders>false</t:CanCreateSubFolders>
                    <t:IsFolderOwner>false</t:IsFolderOwner>
                    <t:IsFolderVisible>false</t:IsFolderVisible>
                    <t:IsFolderContact>false</t:IsFolderContact>
                    <t:EditItems>None</t:EditItems>
                    <t:DeleteItems>None</t:DeleteItems>
                    <t:ReadItems>None</t:ReadItems>
                    <t:PermissionLevel>None</t:PermissionLevel>
                  </t:Permission>
                  <t:Permission>
                    <t:UserId>
                      <t:DistinguishedUser>Anonymous</t:DistinguishedUser>
                    </t:UserId>
                    <t:CanCreateItems>false</t:CanCreateItems>
                    <t:CanCreateSubFolders>false</t:CanCreateSubFolders>
                    <t:IsFolderOwner>false</t:IsFolderOwner>
                    <t:IsFolderVisible>false</t:IsFolderVisible>
                    <t:IsFolderContact>false</t:IsFolderContact>
                    <t:EditItems>None</t:EditItems>
                    <t:DeleteItems>None</t:DeleteItems>
                    <t:ReadItems>None</t:ReadItems>
                    <t:PermissionLevel>None</t:PermissionLevel>
                  </t:Permission>
                </t:Permissions>
              </t:PermissionSet>
              <t:UnreadCount>0</t:UnreadCount>
            </t:Folder>
          </m:Folders>
        </m:GetFolderResponseMessage>
      </m:ResponseMessages>
    </m:GetFolderResponse>
  </s:Body>
</s:Envelope>
</code>```

答:
Using xml linq</p>

```<code>            XDocument doc = XDocument.Load(FILENAME);

            List<XElement> folders = doc.Descendants().Where(x => x.Name.LocalName == "Folder").ToList();
            XNamespace tNs = folders.FirstOrDefault().GetNamespaceOfPrefix("t");
            XElement id_AAMkADk5MmY1ZThmLTM2MzAtNGVh = folders.Where(x => (string)x.Element(tNs + "FolderId").Attribute("Id") == "AAMkADk5MmY1ZThmLTM2MzAtNGVh").FirstOrDefault();
</code>```

Title: XML C# Parse - Complex

Body:
I have been on google for a while but am just stumped.  I need to parse xml of this nature.  I can't seem to skip to elements in the middle, e.g. Folder.  I have limited the xml as there were many 'Folder' elements.  Any guidance would be appreciated.  I was after the FolderID element's attribute ID.

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <h:ServerVersionInfo MajorVersion="14"
        MinorVersion="1"
        MajorBuildNumber="225"
        MinorBuildNumber="46"
        Version="Exchange2010_SP1"
        xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types"
        xmlns="http://schemas.microsoft.com/exchange/services/2006/types"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
  </s:Header>
  <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <m:GetFolderResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"
        xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
      <m:ResponseMessages>
        <m:GetFolderResponseMessage ResponseClass="Success">
          <m:ResponseCode>NoError</m:ResponseCode>
          <m:Folders>
            <t:Folder>
              <t:FolderId Id="AAMkADk5MmY1ZThmLTM2MzAtNGVh" ChangeKey="AQAAABYAAACSe/NBrSZiQKqHx8yL+lIRAAAA1EWM" />
              <t:ParentFolderId Id="AAMkADk5MmY1ZThmLTM2MzAtNGVh" ChangeKey="AQAAAA==" />
              <t:DisplayName>Top of Information Store</t:DisplayName>
              <t:TotalCount>0</t:TotalCount>
              <t:ChildFolderCount>15</t:ChildFolderCount>
              <t:EffectiveRights>
                <t:CreateAssociated>true</t:CreateAssociated>
                <t:CreateContents>true</t:CreateContents>
                <t:CreateHierarchy>true</t:CreateHierarchy>
                <t:Delete>true</t:Delete>
                <t:Modify>true</t:Modify>
                <t:Read>true</t:Read>
                <t:ViewPrivateItems>true</t:ViewPrivateItems>
              </t:EffectiveRights>
              <t:PermissionSet>
                <t:Permissions>
                  <t:Permission>
                    <t:UserId>
                      <t:DistinguishedUser>Default</t:DistinguishedUser>
                    </t:UserId>
                    <t:CanCreateItems>false</t:CanCreateItems>
                    <t:CanCreateSubFolders>false</t:CanCreateSubFolders>
                    <t:IsFolderOwner>false</t:IsFolderOwner>
                    <t:IsFolderVisible>false</t:IsFolderVisible>
                    <t:IsFolderContact>false</t:IsFolderContact>
                    <t:EditItems>None</t:EditItems>
                    <t:DeleteItems>None</t:DeleteItems>
                    <t:ReadItems>None</t:ReadItems>
                    <t:PermissionLevel>None</t:PermissionLevel>
                  </t:Permission>
                  <t:Permission>
                    <t:UserId>
                      <t:DistinguishedUser>Anonymous</t:DistinguishedUser>
                    </t:UserId>
                    <t:CanCreateItems>false</t:CanCreateItems>
                    <t:CanCreateSubFolders>false</t:CanCreateSubFolders>
                    <t:IsFolderOwner>false</t:IsFolderOwner>
                    <t:IsFolderVisible>false</t:IsFolderVisible>
                    <t:IsFolderContact>false</t:IsFolderContact>
                    <t:EditItems>None</t:EditItems>
                    <t:DeleteItems>None</t:DeleteItems>
                    <t:ReadItems>None</t:ReadItems>
                    <t:PermissionLevel>None</t:PermissionLevel>
                  </t:Permission>
                </t:Permissions>
              </t:PermissionSet>
              <t:UnreadCount>0</t:UnreadCount>
            </t:Folder>
          </m:Folders>
        </m:GetFolderResponseMessage>
      </m:ResponseMessages>
    </m:GetFolderResponse>
  </s:Body>
</s:Envelope>

Body:
Using xml linq

            XDocument doc = XDocument.Load(FILENAME);

            List<XElement> folders = doc.Descendants().Where(x => x.Name.LocalName == "Folder").ToList();
            XNamespace tNs = folders.FirstOrDefault().GetNamespaceOfPrefix("t");
            XElement id_AAMkADk5MmY1ZThmLTM2MzAtNGVh = folders.Where(x => (string)x.Element(tNs + "FolderId").Attribute("Id") == "AAMkADk5MmY1ZThmLTM2MzAtNGVh").FirstOrDefault();


问:
How to load packages installed by `bundle` in webpack?
In a Ruby on Rails application, how can we require or import a package which was not installed via npm or yarn, but via bundle?

I tried:

```<code>//= require package-name
</code>```

But that doesn't seem to work with webpacker.

require("package-name") doesn't work either (because it is not found in node_modules).

答:
For normal Rails environment, you can use normal directory path if you want to require some files.

Suppose your assets folder looks like this

```<code>├── application.js
└── something.js
</code>```

and you want to require something.js then you just need to write

```<code>//= require ./something.js
</code>```

to your application.js

For a package that you manually place somewhere, then you have to add the place of packages to Rails.application.config.assets.paths

If you are using Rails v5, you can check the config/initializers/assets.rb to see the magic of loading node_modules happened

Body:
In a Ruby on Rails application, how can we require or import a package which was not installed via npm or yarn, but via bundle?

I tried:

//= require package-name

But that doesn't seem to work with webpacker.

require("package-name") doesn't work either (because it is not found in node_modules).

Body:
For normal Rails environment, you can use normal directory path if you want to require some files.

Suppose your assets folder looks like this

├── application.js
└── something.js

and you want to require something.js then you just need to write

//= require ./something.js

to your application.js

For a package that you manually place somewhere, then you have to add the place of packages to Rails.application.config.assets.paths

If you are using Rails v5, you can check the config/initializers/assets.rb to see the magic of loading node_modules happened


问:
How to check divisibility of a number not in base 10 without converting?
Let's say I have a number of base 3, 1211. How could I check this number is divisible by 2 without converting it back to base 10?

Update

The original problem is from TopCoder

The digits 3 and 9 share an interesting property. If you take any multiple of 3 and sum its digits, you get another multiple of 3. For example, 118*3 = 354 and 3+5+4 = 12, which is a multiple of 3. Similarly, if you take any multiple of 9 and sum its digits, you get another multiple of 9. For example, 75*9 = 675 and 6+7+5 = 18, which is a multiple of 9. Call any digit for which this property holds interesting, except for 0 and 1, for which the property holds trivially.
A digit that is interesting in one base is not necessarily interesting in another base. For example, 3 is interesting in base 10 but uninteresting in base 5. Given an int base, your task is to return all the interesting digits for that base in increasing order. To determine whether a particular digit is interesting or not, you need not consider all multiples of the digit. You can be certain that, if the property holds for all multiples of the digit with fewer than four digits, then it also holds for multiples with more digits. For example, in base 10, you would not need to consider any multiples greater than 999.

Notes

-  When base is greater than 10, digits may have a numeric value greater than 9. Because integers are displayed in base 10 by default, do not be alarmed when such digits appear on your screen as more than one decimal digit. For example, one of the interesting digits in base 16 is 15.

Constraints

-  base is between 3 and 30, inclusive.

This is my solution:

```<code>class InterestingDigits {
public:
    vector<int> digits( int base ) {
        vector<int> temp;
        for( int i = 2; i <= base; ++i )
            if( base % i == 1 )
                temp.push_back( i );
        return temp;
    }
};
</code>```

The trick was well explained here : https://math.stackexchange.com/questions/17242/how-does-base-of-a-number-relate-to-modulos-of-its-each-individual-digit

Thanks,

Chan

答:
I'm not sure on what CPU you have a number in base-3, but the normal way to do this is to perform a modulus/remainder operation.

```<code>if (n % 2 == 0) {
    // divisible by 2, so even
} else {
    // odd
}
</code>```

How to implement the modulus operator is going to depend on how you're storing your base-3 number. The simplest to code will probably be to implement normal pencil-and-paper long division, and get the remainder from that.

```<code>    0 2 2 0
    _______
2 ⟌ 1 2 1 1
    0
    ---
    1 2
    1 1
    -----
      1 1
      1 1
      -----
        0 1 <--- remainder = 1 (so odd)
</code>```

(This works regardless of base, there are "tricks" for base-3 as others have mentioned)

Body:
Let's say I have a number of base 3, 1211. How could I check this number is divisible by 2 without converting it back to base 10?

Update

The original problem is from TopCoder

The digits 3 and 9 share an interesting property. If you take any multiple of 3 and sum its digits, you get another multiple of 3. For example, 118*3 = 354 and 3+5+4 = 12, which is a multiple of 3. Similarly, if you take any multiple of 9 and sum its digits, you get another multiple of 9. For example, 75*9 = 675 and 6+7+5 = 18, which is a multiple of 9. Call any digit for which this property holds interesting, except for 0 and 1, for which the property holds trivially.
A digit that is interesting in one base is not necessarily interesting in another base. For example, 3 is interesting in base 10 but uninteresting in base 5. Given an int base, your task is to return all the interesting digits for that base in increasing order. To determine whether a particular digit is interesting or not, you need not consider all multiples of the digit. You can be certain that, if the property holds for all multiples of the digit with fewer than four digits, then it also holds for multiples with more digits. For example, in base 10, you would not need to consider any multiples greater than 999.

Notes

-  When base is greater than 10, digits may have a numeric value greater than 9. Because integers are displayed in base 10 by default, do not be alarmed when such digits appear on your screen as more than one decimal digit. For example, one of the interesting digits in base 16 is 15.

Constraints

-  base is between 3 and 30, inclusive.

This is my solution:

class InterestingDigits {
public:
    vector<int> digits( int base ) {
        vector<int> temp;
        for( int i = 2; i <= base; ++i )
            if( base % i == 1 )
                temp.push_back( i );
        return temp;
    }
};

The trick was well explained here : https://math.stackexchange.com/questions/17242/how-does-base-of-a-number-relate-to-modulos-of-its-each-individual-digit

Thanks,

Chan

Body:
I'm not sure on what CPU you have a number in base-3, but the normal way to do this is to perform a modulus/remainder operation.

if (n % 2 == 0) {
    // divisible by 2, so even
} else {
    // odd
}

How to implement the modulus operator is going to depend on how you're storing your base-3 number. The simplest to code will probably be to implement normal pencil-and-paper long division, and get the remainder from that.

    0 2 2 0
    _______
2 ⟌ 1 2 1 1
    0
    ---
    1 2
    1 1
    -----
      1 1
      1 1
      -----
        0 1 <--- remainder = 1 (so odd)

(This works regardless of base, there are "tricks" for base-3 as others have mentioned)


问:
bootstrap center 3 col-md-3 divs
I have a wrapper like so:

and inside this wrapper I have 3 col-md-3 divs:

```<code><div class="col-md-3"></div>
<div class="col-md-3"></div>
<div class="col-md-3"></div>
</code>```

what I am trying to do is center these 3 divs inside the wrapper, how would I accomplish this ?

Here is the CSS:

```<code>.community-images {
  padding: 40px 0px 40px 0px;
}

.col-md-3 {
  border: 1px solid #ccc;
  padding: 10px;
  margin: 10px;
  min-height: 300px;
  box-shadow: 10px 10px 5px #888888;
}
</code>```

答:
Code :

```<code><div class="community-images">
<div class="col-md-3 community-margin"></div>
<div class="col-md-3"></div>
<div class="col-md-3"></div>
</div>
</code>```

css :

```<code>@media (min-width: 768px) {
.community-margin{
    margin-left: 12.5%;
}
}

.community-images {
  padding: 40px 0px 40px 0px;
}

.col-md-3 {
  border: 1px solid #ccc;
  padding: 10px;
  margin: 10px;
  min-height: 300px;
  box-shadow: 10px 10px 5px #888888;
}
</code>```

Try above code. You definitely get a solution. You can refer below link also : https://wordpress.com/post/wpkuldip.wordpress.com/61

Title: bootstrap center 3 col-md-3 divs

Body:
I have a wrapper like so:

and inside this wrapper I have 3 col-md-3 divs:

what I am trying to do is center these 3 divs inside the wrapper, how would I accomplish this ?

Here is the CSS:

.community-images {
  padding: 40px 0px 40px 0px;
}

.col-md-3 {
  border: 1px solid #ccc;
  padding: 10px;
  margin: 10px;
  min-height: 300px;
  box-shadow: 10px 10px 5px #888888;
}

Body:
Code :

<div class="community-images">
<div class="col-md-3 community-margin"></div>
<div class="col-md-3"></div>
<div class="col-md-3"></div>
</div>

css :

@media (min-width: 768px) {
.community-margin{
    margin-left: 12.5%;
}
}

.community-images {
  padding: 40px 0px 40px 0px;
}

.col-md-3 {
  border: 1px solid #ccc;
  padding: 10px;
  margin: 10px;
  min-height: 300px;
  box-shadow: 10px 10px 5px #888888;
}

Try above code. You definitely get a solution. You can refer below link also : https://wordpress.com/post/wpkuldip.wordpress.com/61


答:
It is the gaps and islands problem. It can be solved as follows:

```<code>select t.status,
   t.from_time,
   coalesce(CAST(lead(from_time) over (partition by id_device order by from_time) AS varchar(20)), 'NOW') to_date,
   t.id_device
from
(
    select t.status, min(checking_time) from_time, t.id_device
    from
    (
        select *, row_number() over (partition by id_device, status order by checking_time) -
                  row_number() over (partition by id_device order by checking_time) grn
        from data
    ) t
    group by t.id_device, grn, t.status
) t
order by  t.id_device, t.from_time
</code>```

dbffile demo

The crucial is the most nested subquery where I use two row_number functions in order to isolate consecutive occurrence of the same status on a device. Once you have the grn value then the rest is easy.

Result

```<code>status  from_time           to_time             id_device
------------------------------------------------------------
OK      2017-01-01 00:00:00 2017-01-01 00:01:00 1
Failed  2017-01-01 00:01:00 2017-01-01 00:04:00 1
OK      2017-01-01 00:04:00 NOW                 1
OK      2017-01-01 00:00:00 NOW                 2
OK      2017-01-01 00:00:00 NOW                 3
</code>```

Similar questions

SQL query to get min, max rows

Title: Postgresql Table Same Data last adjacent occurance and first In One row

Body:
I have a program that checks status of Computers in a network by PING each minutes.
Each time it will insert a new row to DB as follows (I'm using postgresql)

id_status   status   checking_time(timestamp)   id_device(int)

1           OK       '2017-01-01 00:00:00'      1
2           OK       '2017-01-01 00:00:00'      2
3           OK       '2017-01-01 00:00:00'      3

4           Failed   '2017-01-01 00:01:00'      1
5           OK       '2017-01-01 00:01:00'      2
6           OK       '2017-01-01 00:01:00'      3

7           Failed   '2017-01-01 00:02:00'      1
8           OK       '2017-01-01 00:02:00'      2
9           OK       '2017-01-01 00:02:00'      3

10          Failed   '2017-01-01 00:03:00'      1
11          OK       '2017-01-01 00:03:00'      2
12          OK       '2017-01-01 00:03:00'      3

13          OK       '2017-01-01 00:04:00'      1
14          OK       '2017-01-01 00:04:00'      2
15          OK       '2017-01-01 00:04:00'      3

I want result to be as follows

status   from_time(timestamp)    to_time(timestamp)      id_device(int)

OK       '2017-01-01 00:00:00'   '2017-01-01 00:01:00'   1
Failed   '2017-01-01 00:01:00'   '2017-01-01 00:04:00'   1
OK       '2017-01-01 00:04:00'   NOW                     1

OK       '2017-01-01 00:00:00'   NOW                     2
OK       '2017-01-01 00:00:00'   NOW                     3

How can I get this output?.

Body:
It is the gaps and islands problem. It can be solved as follows:

select t.status,
   t.from_time,
   coalesce(CAST(lead(from_time) over (partition by id_device order by from_time) AS varchar(20)), 'NOW') to_date,
   t.id_device
from
(
    select t.status, min(checking_time) from_time, t.id_device
    from
    (
        select *, row_number() over (partition by id_device, status order by checking_time) -
                  row_number() over (partition by id_device order by checking_time) grn
        from data
    ) t
    group by t.id_device, grn, t.status
) t
order by  t.id_device, t.from_time

dbffile demo

The crucial is the most nested subquery where I use two row_number functions in order to isolate consecutive occurrence of the same status on a device. Once you have the grn value then the rest is easy.

Result

status  from_time           to_time             id_device
------------------------------------------------------------
OK      2017-01-01 00:00:00 2017-01-01 00:01:00 1
Failed  2017-01-01 00:01:00 2017-01-01 00:04:00 1
OK      2017-01-01 00:04:00 NOW                 1
OK      2017-01-01 00:00:00 NOW                 2
OK      2017-01-01 00:00:00 NOW                 3

Similar questions

SQL query to get min, max rows


问:
Insert to list with variable names in python
I have three lists, named list0, list1 and list2.

Here is what i want to do

```<code>for n in range(10):
    x = n%3
    listx.append(n)
</code>```

where x can be 0, 1 or 2. How can I do this? Basically, I don't want to create 3 if/elif cases but just change the third line in above program

PS - I know this not the best method for this problem but my project is quite different from this

答:
If you insist, you can use locals() (or globals() to get your lists from the outer scope) to get your lists by name:

```<code>list0, list1, list2 = [], [], []

for n in range(10):
    x = n % 3
    locals()["list" + str(x)].append(n)

print(list0, list1, list2)  # [0, 3, 6, 9] [1, 4, 7] [2, 5, 8]
</code>```

But that's really a bad practice.

Body:
I have three lists, named list0, list1 and list2.

Here is what i want to do

for n in range(10):
    x = n%3
    listx.append(n)

where x can be 0, 1 or 2. How can I do this? Basically, I don't want to create 3 if/elif cases but just change the third line in above program

PS - I know this not the best method for this problem but my project is quite different from this

Body:
If you insist, you can use locals() (or globals() to get your lists from the outer scope) to get your lists by name:

list0, list1, list2 = [], [], []

for n in range(10):
    x = n % 3
    locals()["list" + str(x)].append(n)

print(list0, list1, list2)  # [0, 3, 6, 9] [1, 4, 7] [2, 5, 8]

But that's really a bad practice.


问:
Aurelia - Trouble with EventAggregator. Cant read property "publish"
I have eventAggregator working in all other parts oh my project. I have two roots and I am using eventAggregator to publish messages to a message div and it works.

In my public root I have "public.ts" which has my route configuration. In there I have a PostRenderStep in which I publish a message.. well I am publishing an empty message to force the message to disappear.

Here is my PostRenderStep class:

```<code>class PostRenderStep {

    constructor(private eventAggregator: EventAggregator) { }

    run(navigationInstruction: NavigationInstruction, next: Next): Promise<any> {
        console.log("I'm inside the POST activate step!")
        return Promise.resolve()
            .then(() => this.eventAggregator.publish('messages', new MessagePayload("", "", "")))
            .then(result => next());
    }
}
</code>```

When I run this I get two errors - the first is with the event aggregator:

```<code>aurelia-logging-console.js:47 ERROR [app-router] TypeError: Cannot read property 'publish' of undefined
at public.ts:87
at <anonymous>
</code>```

and right after this error is:

```<code>ERROR [app-router] Router navigation failed, and no previous location or fallbackRoute could be restored.
</code>```

I suspect that the postRenderStep with the navigation is failing because of the eventAggregator line and cause this second error.

I investigated this to find out if it was my event aggregator that wasnt working in the public root but the fact I posted a message after I changed roots and this displays says its working. I also placed a button that when clicked had a publish in it which also worked indicated that its working - just not in this class.

Could someone explain in more detail what this error is saying and further why its happening and how to fix it...

It works perfectly in my other root just not in this one.

The full public.ts file

```<code>import { Aurelia, PLATFORM, autoinject } from 'aurelia-framework';
import {
    Redirect,
    NavigationInstruction,
    Router,
    RouterConfiguration,
    Next,
    PipelineProvider
} from "aurelia-router";
import { EventAggregator } from 'aurelia-event-aggregator';

import { Messages, MessagePayload } from '../../services/messages/messages'

@autoinject
export class Public {
    public router: Router;

    configureRouter(config: RouterConfiguration, router: Router): void {
        this.router = router;
        config.title = "Aurelia";
        config.addPostRenderStep(PostRenderStep);

        config.map([
            {
                route: ["", "home"],
                name: "home",
                settings: { icon: "home" },
                moduleId: PLATFORM.moduleName("../components/home/home"),
                nav: true,
                title: "Home"
            },
            {
                route: "counter",
                name: "counter",
                settings: { icon: "education", auth: false },
                moduleId: PLATFORM.moduleName("../components/counter/counter"),
                nav: true,
                title: "Counter"
            },
            {
                route: "fetch-data",
                name: "fetchdata",
                settings: { icon: "th-list", auth: false },
                moduleId: PLATFORM.moduleName("../components/fetchdata/fetchdata"),
                nav: true,
                title: "Fetch data"
            },
            {
                route: "login",
                name: "login",
                settings: { icon: "user", auth: false, },
                moduleId: PLATFORM.moduleName("../components/login/login"),
                nav: true,
                title: "Login"
            },
            {
                route: "notFound",
                name: "notFound",
                settings: { auth: false, },
                moduleId: PLATFORM.moduleName("../components/notFound/notFound"),
                nav: false,
                title: "Not Found"
            }
        ]);

        config.mapUnknownRoutes('../components/notFound/notFound');

    }
}

    class PostRenderStep {

        constructor(private eventAggregator: EventAggregator) { }

        run(navigationInstruction: NavigationInstruction, next: Next): Promise<any> {
            console.log("I'm inside the POST activate step!")
            return Promise.resolve()
                .then(() => this.eventAggregator.publish('messages', new MessagePayload("", "", "")))
                .then(result => next());
        }
    }
</code>```

答:
You didn't autoinject in your PostRenderStep

```<code>@autoinject
class PostRenderStep {

}
</code>```

Body:
I have eventAggregator working in all other parts oh my project. I have two roots and I am using eventAggregator to publish messages to a message div and it works.

In my public root I have "public.ts" which has my route configuration. In there I have a PostRenderStep in which I publish a message.. well I am publishing an empty message to force the message to disappear.

Here is my PostRenderStep class:

class PostRenderStep {

    constructor(private eventAggregator: EventAggregator) { }

    run(navigationInstruction: NavigationInstruction, next: Next): Promise<any> {
        console.log("I'm inside the POST activate step!")
        return Promise.resolve()
            .then(() => this.eventAggregator.publish('messages', new MessagePayload("", "", "")))
            .then(result => next());
    }
}

When I run this I get two errors - the first is with the event aggregator:

aurelia-logging-console.js:47 ERROR [app-router] TypeError: Cannot read property 'publish' of undefined
at public.ts:87
at <anonymous>

and right after this error is:

ERROR [app-router] Router navigation failed, and no previous location or fallbackRoute could be restored.

I suspect that the postRenderStep with the navigation is failing because of the eventAggregator line and cause this second error.

I investigated this to find out if it was my event aggregator that wasnt working in the public root but the fact I posted a message after I changed roots and this displays says its working. I also placed a button that when clicked had a publish in it which also worked indicated that its working - just not in this class.

Could someone explain in more detail what this error is saying and further why its happening and how to fix it...

It works perfectly in my other root just not in this one.

The full public.ts file

import { Aurelia, PLATFORM, autoinject } from 'aurelia-framework';
import {
    Redirect,
    NavigationInstruction,
    Router,
    RouterConfiguration,
    Next,
    PipelineProvider
} from "aurelia-router";
import { EventAggregator } from 'aurelia-event-aggregator';

import { Messages, MessagePayload } from '../../services/messages/messages'

@autoinject
export class Public {
    public router: Router;

    configureRouter(config: RouterConfiguration, router: Router): void {
        this.router = router;
        config.title = "Aurelia";
        config.addPostRenderStep(PostRenderStep);

        config.map([
            {
                route: ["", "home"],
                name: "home",
                settings: { icon: "home" },
                moduleId: PLATFORM.moduleName("../components/home/home"),
                nav: true,
                title: "Home"
            },
            {
                route: "counter",
                name: "counter",
                settings: { icon: "education", auth: false },
                moduleId: PLATFORM.moduleName("../components/counter/counter"),
                nav: true,
                title: "Counter"
            },
            {
                route: "fetch-data",
                name: "fetchdata",
                settings: { icon: "th-list", auth: false },
                moduleId: PLATFORM.moduleName("../components/fetchdata/fetchdata"),
                nav: true,
                title: "Fetch data"
            },
            {
                route: "login",
                name: "login",
                settings: { icon: "user", auth: false, },
                moduleId: PLATFORM.moduleName("../components/login/login"),
                nav: true,
                title: "Login"
            },
            {
                route: "notFound",
                name: "notFound",
                settings: { auth: false, },
                moduleId: PLATFORM.moduleName("../components/notFound/notFound"),
                nav: false,
                title: "Not Found"
            }
        ]);

        config.mapUnknownRoutes('../components/notFound/notFound');

    }
}

    class PostRenderStep {

        constructor(private eventAggregator: EventAggregator) { }

        run(navigationInstruction: NavigationInstruction, next: Next): Promise<any> {
            console.log("I'm inside the POST activate step!")
            return Promise.resolve()
                .then(() => this.eventAggregator.publish('messages', new MessagePayload("", "", "")))
                .then(result => next());
        }
    }

Body:
You didn't autoinject in your PostRenderStep

@autoinject
class PostRenderStep {

}


问:
How to set cronjob with non-root user?
Error :   crontab: must be suid to work properly

I want to set cronjob in docker container with non-root user. Is it possible to set a cron without using sudo and without installing cron?
I am using alpine docker container.

答:
/etc/crontab is the system wide crontab.

The format of /etc/crontab is like this:

```<code># m h dom mon dow user      command
*   *  *   *   *  someuser  echo 'foo'
</code>```

while crontab -e is per user, it's worth mentioning with no -u argument the crontab command goes to the current users crontab. You can do crontab -e -u <username> to edit a specific users crontab.

Notice in a per user crontab there is no 'user' field.

```<code># m h  dom mon dow  command
*   *   *   *   *   echo 'foo'
</code>```

An aspect of crontabs that may be confusing is that root also has its own crontab. e.g. crontab -e -u root will not edit /etc/crontab

See Configuring cron for more information: https://www.freebsd.org/doc/handbook/configtuning-cron.html

In most Linux distros, per user crontabs are typically stored in: /var/spool/cron/crontabs/<username>

Title: How to set cronjob with non-root user?

Body:
/etc/crontab is the system wide crontab.

The format of /etc/crontab is like this:

# m h dom mon dow user      command
*   *  *   *   *  someuser  echo 'foo'

while crontab -e is per user, it's worth mentioning with no -u argument the crontab command goes to the current users crontab. You can do crontab -e -u <username> to edit a specific users crontab.

Notice in a per user crontab there is no 'user' field.

# m h  dom mon dow  command
*   *   *   *   *   echo 'foo'

An aspect of crontabs that may be confusing is that root also has its own crontab. e.g. crontab -e -u root will not edit /etc/crontab

See Configuring cron for more information: https://www.freebsd.org/doc/handbook/configtuning-cron.html

In most Linux distros, per user crontabs are typically stored in: /var/spool/cron/crontabs/<username>


问:
Apple-app-site-association : banner displays while no file in server
I have apple-app-site-association file in my server root directory, so getting banner on my iOS safari browser, but when I remove the file from server, cleared my browser history, then reset my phone too, but still getting the banner.

Note : changed my app ID in the file, but not reflects in banner.

```<code>https://example.com/apple-app-site-association
</code>```

apple-app-site-association file :

```<code>{
    "applinks": {
        "apps": [],
        "details": [
            {
                "appID": "123456789.com.abc.example",
                "paths": [ "*" ]
            }
        ]
    }
}
</code>```

答:
Your are getting the banner still because you haven't build the app again.
During the build process of the ios app it downloads the apple-app-association-file from the asociated domain and save it in the app for deeplinking purpose.

Once you get the new build with the updated apple-app-association-file
your problem will be solved.

To remove the banner from all the pages you can just try below code:

```<code>{
"applinks": {
    "apps": [],
    "details": [
        {
            "appID": "your app id here",
            "paths": [
                "NOT /*"
            ]
        }
    ]
} }
</code>```

Body:
I have apple-app-site-association file in my server root directory, so getting banner on my iOS safari browser, but when I remove the file from server, cleared my browser history, then reset my phone too, but still getting the banner.

Note : changed my app ID in the file, but not reflects in banner.

https://example.com/apple-app-site-association

apple-app-site-association file :

{
    "applinks": {
        "apps": [],
        "details": [
            {
                "appID": "123456789.com.abc.example",
                "paths": [ "*" ]
            }
        ]
    }
}

Body:
Your are getting the banner still because you haven't build the app again.
During the build process of the ios app it downloads the apple-app-association-file from the asociated domain and save it in the app for deeplinking purpose.

Once you get the new build with the updated apple-app-association-file
your problem will be solved.

To remove the banner from all the pages you can just try below code:

{
"applinks": {
    "apps": [],
    "details": [
        {
            "appID": "your app id here",
            "paths": [
                "NOT /*"
            ]
        }
    ]
} }


问:
Saving camera api videos in internal storage directory
I am building an app which  record videos with camera API. I followed a tutorial from android developers site after the video records, It is saved in an external storage directory. How do I save in internal storage instead of  external storage.

```<code>    public static final int MEDIA_TYPE_VIDEO = 2;

    /** Create a file Uri for saving an image or video */
    private static Uri getOutputMediaFileUri(int type){
          return Uri.fromFile(getOutputMediaFile(type));
    }

    /** Create a File for saving an image or video */
    private static File getOutputMediaFile(int type){
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.

        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
          Environment.DIRECTORY_PICTURES), "MyCameraApp");
        // This location works best if you want the created images to be shared
        // between applications and persist after your app has been uninstalled.

        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
        Log.d("MyCameraApp", "failed to create directory");
        return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
       if(type == MEDIA_TYPE_VIDEO) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
    "VID_"+ timeStamp + ".mp4");
        } else {
            return null;
        }

        return mediaFile;
    }
</code>```

答: All you need is in the official android dev site: https://developer.android.com/guide/topics/data/data-storage.html#filesInternal</p>

Body:
I am building an app which  record videos with camera API. I followed a tutorial from android developers site after the video records, It is saved in an external storage directory. How do I save in internal storage instead of  external storage.

    public static final int MEDIA_TYPE_VIDEO = 2;

    /** Create a file Uri for saving an image or video */
    private static Uri getOutputMediaFileUri(int type){
          return Uri.fromFile(getOutputMediaFile(type));
    }

    /** Create a File for saving an image or video */
    private static File getOutputMediaFile(int type){
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.

        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
          Environment.DIRECTORY_PICTURES), "MyCameraApp");
        // This location works best if you want the created images to be shared
        // between applications and persist after your app has been uninstalled.

        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
        Log.d("MyCameraApp", "failed to create directory");
        return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
       if(type == MEDIA_TYPE_VIDEO) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator +
    "VID_"+ timeStamp + ".mp4");
        } else {
            return null;
        }

        return mediaFile;
    }