问:
In gradle, how to use a variable for a plugin version?
One of my build scripts imports that nebula plugin:

```<code>plugins {
  id 'nebula.ospackage' version '3.5.0'
}
</code>```

I've been moving all of my version info into a separate file that all projects have access to and am wondering what is the correct syntax to convert to something like:

```<code>plugins {
  id 'nebula.ospackage' version "$versions.nebula_gradle_ospackage_plugin"
}
</code>```

When I try running the above with "gradle clean build", I get the following error:

build file 'build.gradle': 2: argument list must be exactly 1 literal
  non empty string

See
  https://docs.gradle.org/2.7/userguide/plugins.html#sec:plugins_block
  for information on the plugins {} block

@ line 2, column 33.
         id 'nebula.ospackage' version "$versions.nebula_gradle_ospackage_plugin"

The linked article shows how I could use the "buildscript" block, which works, but it seems like there must be a way to make this work in a single line?

答:
Summary

Omit the version from the plugin block

Move/specify the version in the buildscript.dependencies block, instead

Use a variable in that block that is a const variable

In short, plugin blocks require string literals or properties whereas dependency blocks permit varables. The original question asks for doing this in a "single line" and with this approach, your plugin block is shorter and all your dependencies live in one place for all modules. Depending on your goals, that might be better than doing everything in "one line."

Full Example

For Android, I was able to do this by omitting the version from the plugin block and then specifying it as a const in the buildscript dependencies, instead. That block allows variables, whereas the plugin block only allows string literals. From there, I use an object in buildSrc because that provides the most flexibility, while keeping all dependency info in one file for all modules. So my setup looks like this:

```<code>├── project/
│   ├── build.gradle
|   └── app/
|       └── build.gradle
|   └── buildSrc/
|       └── build.gradle.kts
|       └── src/main/java/com/example/package/Deps.kt
</code>```

From there, to specify any plugin version as a variable in one place, the app/build.gradle file omits the version (using kotlin as an example but the same approach works for any plugin):

app/build.gradle

plugins {
    id 'kotlin-android' // omit version property here but provide it in buildscript dependencies
    ...
}
...
dependencies {
    ...
    // Dagger
    implementation Deps.Dagger.ANDROID_SUPPORT
    kapt Deps.Dagger.ANDROID_PROCESSOR
    kapt Deps.Dagger.COMPILER
}
```

<p>Then the buildscript dependency section (usually in the parent <code>build.gradle</code> file but can also be in the same file) provides the version USING A VARIABLE!</p>

<strong>project/build.gradle</strong>

<pre class="lang-java prettyprint-override"><code>import com.example.package.Deps // object in the buildSrc folder with all version info
buildscript {
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${Deps.kotlinVersion}"
    }
}
</code>```

Lastly, all the version information is managed in buildSrc, with an object in the Deps.kt file (there are many blog posts out there on using buildSrc with Android projects):

Deps.kt

object Deps {
    // For use in the top-level buildscript dependency section which only works with a constant rather than `Deps.Kotlin.version`
    const val kotlinVersion = "1.3.72"

    object Kotlin :             Version(kotlinVersion) {
        val STDLIB =            "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$version"
    }

    object Dagger :             Version("2.25.2") {
        val ANDROID_SUPPORT =   "com.google.dagger:dagger-android-support:$version"
        val ANDROID_PROCESSOR = "com.google.dagger:dagger-android-processor:$version"
        val COMPILER =          "com.google.dagger:dagger-compiler:$version"
    }

}
open class Version(@JvmField val version: String)
```

Overall, I really like this setup. It's flexible, all dependency info is in one place, even across multiple modules and, best of all, it allows for code completion in the gradle files, when typing dependencies!

Body:
One of my build scripts imports that nebula plugin:

plugins {
  id 'nebula.ospackage' version '3.5.0'
}

I've been moving all of my version info into a separate file that all projects have access to and am wondering what is the correct syntax to convert to something like:

plugins {
  id 'nebula.ospackage' version "$versions.nebula_gradle_ospackage_plugin"
}

When I try running the above with "gradle clean build", I get the following error:

build file 'build.gradle': 2: argument list must be exactly 1 literal
  non empty string

See
  https://docs.gradle.org/2.7/userguide/plugins.html#sec:plugins_block
  for information on the plugins {} block

@ line 2, column 33.
         id 'nebula.ospackage' version "$versions.nebula_gradle_ospackage_plugin"

The linked article shows how I could use the "buildscript" block, which works, but it seems like there must be a way to make this work in a single line?

Body:
Summary

Omit the version from the plugin block

Move/specify the version in the buildscript.dependencies block, instead

Use a variable in that block that is a const variable

In short, plugin blocks require string literals or properties whereas dependency blocks permit varables. The original question asks for doing this in a "single line" and with this approach, your plugin block is shorter and all your dependencies live in one place for all modules. Depending on your goals, that might be better than doing everything in "one line."

Full Example

For Android, I was able to do this by omitting the version from the plugin block and then specifying it as a const in the buildscript dependencies, instead. That block allows variables, whereas the plugin block only allows string literals. From there, I use an object in buildSrc because that provides the most flexibility, while keeping all dependency info in one file for all modules. So my setup looks like this:

├── project/
│   ├── build.gradle
|   └── app/
|       └── build.gradle
|   └── buildSrc/
|       └── build.gradle.kts
|       └── src/main/java/com/example/package/Deps.kt

From there, to specify any plugin version as a variable in one place, the app/build.gradle file omits the version (using kotlin as an example but the same approach works for any plugin):

app/build.gradle

plugins {
    id 'kotlin-android' // omit version property here but provide it in buildscript dependencies
    ...
}
...
dependencies {
    ...
    // Dagger
    implementation Deps.Dagger.ANDROID_SUPPORT
    kapt Deps.Dagger.ANDROID_PROCESSOR
    kapt Deps.Dagger.COMPILER
}

Then the buildscript dependency section (usually in the parent build.gradle file but can also be in the same file) provides the version USING A VARIABLE!

project/build.gradle

import com.example.package.Deps // object in the buildSrc folder with all version info
buildscript {
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${Deps.kotlinVersion}"
    }
}

Lastly, all the version information is managed in buildSrc, with an object in the Deps.kt file (there are many blog posts out there on using buildSrc with Android projects):

Deps.kt

object Deps {
    // For use in the top-level buildscript dependency section which only works with a constant rather than `Deps.Kotlin.version`
    const val kotlinVersion = "1.3.72"

    object Kotlin :             Version(kotlinVersion) {
        val STDLIB =            "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$version"
    }

    object Dagger :             Version("2.25.2") {
        val ANDROID_SUPPORT =   "com.google.dagger:dagger-android-support:$version"
        val ANDROID_PROCESSOR = "com.google.dagger:dagger-android-processor:$version"
        val COMPILER =          "com.google.dagger:dagger-compiler:$version"
    }

}
open class Version(@JvmField val version: String)

Overall, I really like this setup. It's flexible, all dependency info is in one place, even across multiple modules and, best of all, it allows for code completion in the gradle files, when typing dependencies!


来源: stackexchange

问:
Evaluating many expressions at once in Intellij Idea
In Intellij Idea, I'm looking for a way to evaluate many expressions in debug mode with one command.

Normally I can evaluate single command with Right Click → Evaluate Expression (ALT+F8). I would like to have possibility to evaluate a bunch of expressions like:

```<code>System.out.println(myVar1);
System.out.println(myVar2);
</code>```

In Eclipse this is possible to execute such "script of expressions", but I can not find a solution in Idea.

答:
well i was also struggling a lot with this, until i figured out that in the code it needs fully qualified paths for classes (for classes outside of java.*)

for example in this code below , i needed to find out , xml string representation from the document object (doc is my document object)

so i had to put this code into evaluate tab , which you can open from run window -after putting in below expression and clicking on evaluate - my xml string was printed in console

```<code>    javax.xml.transform.TransformerFactory tf = javax.xml.transform.TransformerFactory.newInstance();
    javax.xml.transform.Transformer transformer = tf.newTransformer();
    java.io.StringWriter writer = new java.io.StringWriter();
    transformer.transform(new javax.xml.transform.dom.DOMSource(doc), new javax.xml.transform.stream.StreamResult(writer));
    System.out.println(writer.getBuffer().toString());
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In Intellij Idea, I'm looking for a way to evaluate many expressions in debug mode with one command.

Normally I can evaluate single command with Right Click → Evaluate Expression (ALT+F8). I would like to have possibility to evaluate a bunch of expressions like:

System.out.println(myVar1);
System.out.println(myVar2);

In Eclipse this is possible to execute such "script of expressions", but I can not find a solution in Idea.

Body:
well i was also struggling a lot with this, until i figured out that in the code it needs fully qualified paths for classes (for classes outside of java.*)

for example in this code below , i needed to find out , xml string representation from the document object (doc is my document object)

so i had to put this code into evaluate tab , which you can open from run window -after putting in below expression and clicking on evaluate - my xml string was printed in console

    javax.xml.transform.TransformerFactory tf = javax.xml.transform.TransformerFactory.newInstance();
    javax.xml.transform.Transformer transformer = tf.newTransformer();
    java.io.StringWriter writer = new java.io.StringWriter();
    transformer.transform(new javax.xml.transform.dom.DOMSource(doc), new javax.xml.transform.stream.StreamResult(writer));
    System.out.println(writer.getBuffer().toString());

ContentLicense: CC BY-SA 4.0


问:
pg-promise quick way to delete set of tuples
Is there a better way to write the following:

```<code>DELETE FROM
    table
WHERE
    _id = $<id>
    AND (
        item_id = $<item_id>
        AND map_id = $<map_id>
        OR
        item_id = $<another_id>
        AND map_id = $<another_map_id>
        ...
    )
</code>```

The dataset format I have is:

```<code>[
    {
        item_id: "some_id",
        map_id: "other_id"
    }
    ...
]
</code>```

What would be a good way to write this in pg-promise, or even just plain postgreSQL?

答:
DELETE FROM table
WHERE
    _id = $<id>
    AND (item_id, map_id) IN ($<values:raw>)
```
<p>If you have the following as your input data:</p>
<pre class="lang-js prettyprint-override"><code>const input = [
    {
        item_id: 'some_id',
        map_id: 'other_id'
    }
    ...
];
</code>```

then you can generate values with pg-promise as follows (see helpers.values):

const values = pgp.helpers.values(input, ['item_id', 'map_id']);
```

or you can pass columns as a full ColumnSet, if more details are needed, like type casting, etc.

Body:
Is there a better way to write the following:

DELETE FROM
    table
WHERE
    _id = $<id>
    AND (
        item_id = $<item_id>
        AND map_id = $<map_id>
        OR
        item_id = $<another_id>
        AND map_id = $<another_map_id>
        ...
    )

The dataset format I have is:

[
    {
        item_id: "some_id",
        map_id: "other_id"
    }
    ...
]

What would be a good way to write this in pg-promise, or even just plain postgreSQL?

Body:
DELETE FROM table
WHERE
    _id = $<id>
    AND (item_id, map_id) IN ($<values:raw>)

If you have the following as your input data:

const input = [
    {
        item_id: 'some_id',
        map_id: 'other_id'
    }
    ...
];

then you can generate values with pg-promise as follows (see helpers.values):

const values = pgp.helpers.values(input, ['item_id', 'map_id']);

or you can pass columns as a full ColumnSet, if more details are needed, like type casting, etc.


问:
Why am I getting result NONE in this simple python program?
I'm learning python 3. I expect this program to sum together a decreasing sequence of integers. Instead, I get NONE.

If this was throwing an error I might be able to figure out what I'm doing wrong, but in this case I am stumped.

```<code>def add_many_things(init_value):
    accumulator = 0
    while init_value > 0 :
        accumulator = accumulator + init_value
        init_value = init_value - 1

result = add_many_things(37)
print(f"{result}")
</code>```

答:
Try this:

```<code>def add_many_things(init_value):
    accumulator = 0
    while init_value > 0 :
        accumulator = accumulator + init_value
        init_value = init_value - 1
    return accumulator

result = add_many_things(37)
print(f"{result}")
</code>```

You miss to add the return statement to the add_many_things function.

Python allows this case and evaluate the return value to None.

Body:
I'm learning python 3. I expect this program to sum together a decreasing sequence of integers. Instead, I get NONE.

If this was throwing an error I might be able to figure out what I'm doing wrong, but in this case I am stumped.

def add_many_things(init_value):
    accumulator = 0
    while init_value > 0 :
        accumulator = accumulator + init_value
        init_value = init_value - 1

result = add_many_things(37)
print(f"{result}")

Body:
Try this:

def add_many_things(init_value):
    accumulator = 0
    while init_value > 0 :
        accumulator = accumulator + init_value
        init_value = init_value - 1
    return accumulator

result = add_many_things(37)
print(f"{result}")

You miss to add the return statement to the add_many_things function.

Python allows this case and evaluate the return value to None.


问:
Bootstrap Carousel with Responsive Images
I'm having trouble with containing responsive images inside a carousel slide and currently the carousel is not able to slide to either the next or previous one. Any help is appreciated, thanks.</p>

```<code>
  <h2 class="caption-2"> UI Snippets</h2>
  <h2 class="description-2"> .</h2>

  <div id="ui-carousel" class="carousel slide" data-ride="false">

    <div class="carousel-inner" role="listbox" style="max-width:100%; max-height:630px !important;">

      <div class="carousel-item active container-fluid">
        <img class="design-1" src="UI-Designs/Day&Night.png" alt="Mock-Up">
      </div>
      <div class="carousel-item container-fluid">
        <div class="row">
          <div class="col-lg-4 col-md-6">
            <img class="design-2" src="UI-Designs/Hiking.jpg" alt="Mock-Up">
          </div>
          <div class="col-lg-4 col-md-6">
            <img class="design-2" src="UI-Designs/Homescreen.jpg" alt="Mock-Up">
          </div>
          <div class="col-lg-4 col-md-6">
            <img class="design-2" src="UI-Designs/Cycling.jpg" alt="Mock-Up">
          </div>
        </div>
      </div>

      <div class="carousel-item container-fluid">
        <video width=100% controls>
          <source src="Echo.mp4" type="video/mp4">
        </video>
      </div>
    </div>

    <a class="carousel-control-prev" href="#ui-carousel" role="button" data-slide="prev">
      <span class="carousel-control-prev-icon"></span>
    </a>

    <a class="carousel-control-next" href="#ui-carousel" role="button" data-slide="next">
      <span class="carousel-control-next-icon"></span>
    </a>

  </div>
</div>```
</code>```

答:
```<code><div class="container">
  <h2>Carousel Example</h2>
  <div id="myCarousel" class="carousel slide" data-ride="carousel">
    <!-- Wrapper for slides -->
    <div class="carousel-inner">
      <div class="item active">
        <img src="la.jpg" alt="Los Angeles" style="width:100%;">
      </div>

      <div class="item">
        <img src="chicago.jpg" alt="Chicago" style="width:100%;">
      </div>

      <div class="item">
        <img src="ny.jpg" alt="New york" style="width:100%;">
      </div>
    </div>

    <!-- Left and right controls -->
    <a class="left carousel-control" href="#myCarousel" data-slide="prev">
      <span class="glyphicon glyphicon-chevron-left"></span>
      <span class="sr-only">Previous</span>
    </a>
    <a class="right carousel-control" href="#myCarousel" data-slide="next">
      <span class="glyphicon glyphicon-chevron-right"></span>
      <span class="sr-only">Next</span>
    </a>
  </div>
</div>
</code>```

Body:
I'm having trouble with containing responsive images inside a carousel slide and currently the carousel is not able to slide to either the next or previous one. Any help is appreciated, thanks.

 UI Snippets

 .

        <video width=100% controls>
          <source src="Echo.mp4" type="video/mp4">
        </video>

```


问:
Carbon Emacs does not paste Microsoft Word's copied contents
Not Sure if Stackoverflow is right site.

I'm using carbon emacs 22.0.971 on mac ox 10.6.7. And MS word 12.2.8. I have some text in MS word which i want to copy and paste into emacs. I do the normal procedure cmd C in word, C-y in emacs, but the text does not get copied in emacs, instead it looks a bitmap of the copied text is passed. One big image which can be deleted with one C-d. I can get around it: paste the text in mac ox' text editor. But for me it is new emacs behavior. Is there a way to force emacs to paste the clipboard as plain text?

regards,
Jeroen.

答:
That's because yank does not not paste from the clipboard, but from the kill ring. Try M-x clipboard-yank instead.

If you do not want to type that command every time, bind it to some keyboard shortcut, e.g. C-x y, by putting the following line into your .emacs file:

```<code>(global-set-key [(control x) (y)] 'clipboard-yank)
</code>```

Body:
That's because yank does not not paste from the clipboard, but from the kill ring. Try M-x clipboard-yank instead.

If you do not want to type that command every time, bind it to some keyboard shortcut, e.g. C-x y, by putting the following line into your .emacs file:

(global-set-key [(control x) (y)] 'clipboard-yank)


问:
adding data to the same set of properties in a class
I am trying to create a JSON file like so:

```<code>"payload": {
        "control": [
            {
                "option": "SUBSCRIBER_PREAMBLE",
                "value": "XXXX"
            },
            {
                "option": "SUBSCRIBER_OPERATOR_INITIAL",
                "value": "RR"
            }
]
}
</code>```

In order to achieve this, I created two classes like so:

```<code>public class control
{

    public string option { get; set; }
    public string value { get; set; }
}

  public class payloadData
    {
        public payloadData()
        {
            control = new List<control>();
        }
        public List<control> control { get; set; }
    }
</code>```

I put the values to the properties like so:

```<code>        payloadData pay = new payloadData();
        control con = new control();
        con.option= "SUBSCRIBER_PREAMBLE";
        con.value = "XXXX";
        pay.control.Add(con);
        id.payLoad.Add(pay);
        con.option = "SUBSCRIBER_OPERATOR_INITIAL";
        con.value = "RR";
        pay.control.Add(con);
</code>```

when the JSON is created, I am getting the SUBSCRIBER_OPERATOR_INITIAL option and RR value. Earlier value is overwritten by the next value. I want all the option and values to be added in the JSON. How can I achieve this.

Any help will be appreciated.

答:
You are not adding new controls to the list. In your case the below code will help:

```<code>payloadData pay = new payloadData();
pay.control.Add(new control { option = "SUBSCRIBER_PREAMBLE", value = "XXXX" });
pay.control.Add(new control { option = "SUBSCRIBER_OPERATOR_INITIAL", value = "RR" });
id.payLoad.Add(pay);
</code>```

Body:
I am trying to create a JSON file like so:

"payload": {
        "control": [
            {
                "option": "SUBSCRIBER_PREAMBLE",
                "value": "XXXX"
            },
            {
                "option": "SUBSCRIBER_OPERATOR_INITIAL",
                "value": "RR"
            }
]
}

In order to achieve this, I created two classes like so:

public class control
{

    public string option { get; set; }
    public string value { get; set; }
}

  public class payloadData
    {
        public payloadData()
        {
            control = new List<control>();
        }
        public List<control> control { get; set; }
    }

I put the values to the properties like so:

        payloadData pay = new payloadData();
        control con = new control();
        con.option= "SUBSCRIBER_PREAMBLE";
        con.value = "XXXX";
        pay.control.Add(con);
        id.payLoad.Add(pay);
        con.option = "SUBSCRIBER_OPERATOR_INITIAL";
        con.value = "RR";
        pay.control.Add(con);

when the JSON is created, I am getting the SUBSCRIBER_OPERATOR_INITIAL option and RR value. Earlier value is overwritten by the next value. I want all the option and values to be added in the JSON. How can I achieve this.

Any help will be appreciated.

Body:
You are not adding new controls to the list. In your case the below code will help:

payloadData pay = new payloadData();
pay.control.Add(new control { option = "SUBSCRIBER_PREAMBLE", value = "XXXX" });
pay.control.Add(new control { option = "SUBSCRIBER_OPERATOR_INITIAL", value = "RR" });
id.payLoad.Add(pay);


问:
Data not updating from Event Bus
I'm trying to get a data from another component (A) to component (B).

Component A:

```<code>methods: {
    setTemplate(template) {
        bus.$emit("setEmailTemplate", template);
    }
}
</code>```

Here is where I want to fetch the data

Component B:

```<code><template>
<div>
    <p>{{ template }}</p>
</div>
</template>

<script>
import { bus } from "../app";

export default {

    data() {
        return {
            template: ''
        };
    },
    created: function() {
        bus.$on("setEmailTemplate", (data) => {
            this.template = data;
        })
    }
};
</script>
</code>```

However when I run the code, template returns empty string. It seems that template is not being updated.

答:
Your event name is different while emitting and listening.

It has to be same for event bus to work.

Change your methods in Component A like so :

```<code>methods: {
    setTemplate(template) {
        bus.$emit("setEmailTemplate", template);
    }
}
</code>```

AFTER EDIT

Without seeing more code, it would be hard to debug what problem you are facing.

I made a simple example of what you are trying. This might help you.

Working implementation attached.

Title: Data not updating from Event Bus

Body:
I'm trying to get a data from another component (A) to component (B).

Component A:

methods: {
    setTemplate(template) {
        bus.$emit("setEmailTemplate", template);
    }
}

Here is where I want to fetch the data

Component B:

<template>

{{ template }}

</template>

However when I run the code, template returns empty string. It seems that template is not being updated.

Body:
Your event name is different while emitting and listening.

It has to be same for event bus to work.

Change your methods in Component A like so :

methods: {
    setTemplate(template) {
        bus.$emit("setEmailTemplate", template);
    }
}

AFTER EDIT

Without seeing more code, it would be hard to debug what problem you are facing.

I made a simple example of what you are trying. This might help you.

Working implementation attached.


问:
Why require build tool 29.0.2 when 29.0.3 is present?
I created a flutter app. I run it and it builds fine and it runs.

Now I change the project structure to android in order to build signed apk. Gradle updates and now it says can't find build tool 29.0.2. I checked and found that 29.0.3 is installed. Why do we need different tools for the same platform? And for the same program?

答:
Since it is asking for build tool 29.0.2 when 29.0.3 present(you don't need to download 29.0.2 again), you can go to the project's build.gradle file in the 'app' module. Open the file and you can either add or update the Builds Tools version you want to use by either updating/adding the property in the android section:

```<code>android {
    buildToolsVersion "29.0.3"
    ....
}
</code>```

Hope it helps :)

Body:
Since it is asking for build tool 29.0.2 when 29.0.3 present(you don't need to download 29.0.2 again), you can go to the project's build.gradle file in the 'app' module. Open the file and you can either add or update the Builds Tools version you want to use by either updating/adding the property in the android section:

android {
    buildToolsVersion "29.0.3"
    ....
}

Hope it helps :)


问:
getting error "machineDefinition is undefined" I already follow steps?
I am using below package for demo application

https://www.npmjs.com/package/@opuscapita/fsm-workflow-core

I follow all steps whatever it is written in doc .But getting error
machineDefinition is undefined

here is my code
https://codesandbox.io/s/inspiring-banzai-xumr2?file=/src/index.js

```<code>var http = require("http");

let { MachineDefinition, Machine } = require("@opuscapita/fsm-workflow-core");

var machineDefinition = new MachineDefinition({
  schema: {
    initialState: "start",
    finalStates: ["finish"],
    transitions: [{ from: "start", event: "run", to: "finish" }]
  }
});

const object = { status: "none" };
const machine = new Machine(machineDefinition);
machine
  .start({ object })
  .then(({ object }) => {
    console.log(machine.currentState({ object }));
    // start
    return machine.sendEvent({ object, event: "start" });
  })
  .then(({ object }) => {
    console.log(machine.currentState({ object }));
    // finish
  });

//create a server object:
http
  .createServer(function(req, res) {
    res.write("Hello World!"); //write a response to the client
    res.end(); //end the response
  })
  .listen(8080); //the server object listens on port 8080
</code>```

could you please tell me where I am doing wrong .?

One more thing this package is Apache-2.0 licence .can I use this package in my real project ?

答: So, I played around with that package a bit and found it to be a bit buggy. I fixed the problem your having, however, I ended up running into another one. You're passing the correct argument into the Machine constructor function but there is a problem within the package. If you read into it you will see that there is a conditional that explicitly throws an error if it doesn't see the very object you're passing in. Sorry I couldn't help more but I hope this at least got you closer to the goal. </p>

Body:
I am using below package for demo application

https://www.npmjs.com/package/@opuscapita/fsm-workflow-core

I follow all steps whatever it is written in doc .But getting error
machineDefinition is undefined

here is my code
https://codesandbox.io/s/inspiring-banzai-xumr2?file=/src/index.js

var http = require("http");

let { MachineDefinition, Machine } = require("@opuscapita/fsm-workflow-core");

var machineDefinition = new MachineDefinition({
  schema: {
    initialState: "start",
    finalStates: ["finish"],
    transitions: [{ from: "start", event: "run", to: "finish" }]
  }
});

const object = { status: "none" };
const machine = new Machine(machineDefinition);
machine
  .start({ object })
  .then(({ object }) => {
    console.log(machine.currentState({ object }));
    // start
    return machine.sendEvent({ object, event: "start" });
  })
  .then(({ object }) => {
    console.log(machine.currentState({ object }));
    // finish
  });

//create a server object:
http
  .createServer(function(req, res) {
    res.write("Hello World!"); //write a response to the client
    res.end(); //end the response
  })
  .listen(8080); //the server object listens on port 8080

could you please tell me where I am doing wrong .?

One more thing this package is Apache-2.0 licence .can I use this package in my real project ?


问:
Test try catch with Mocha and Chai in Node + Express appp
I have nodeJS app with simple route as below:

```<code>const express = require('express')
const router = express.Router();
const logger = require('../logger');

router.use('/logMessage',(req, res)  => {
    try {
        logger.info(req.query.message);
        res.send({
            statusMessage: 'success'
        })
    } catch (err) {
        logger.error('error in logging');
        logger.error(err);
        res.send({
            statusMessage: 'failure'
        })
    }
});

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

I am able to successfully test the try block using below code, but how can I test the catch block ?

Test for try block:

```<code>describe('GET /logMessage', () => {
    it('should host logger api', (done) => {
        chai.request(server)
            .get('/logMessage?message=testMessage')
            .end((err, response) => {
                response.should.have.status(200);
                done();
            });
    });
});
</code>```

答:
You need to let the statement in the try block to throw an error. You can make this using sinonjs. For demonstration here, I will rewrite the implementation of console.info, when the message is "makeError", an error is thrown.

E.g.

router.js:

const express = require('express');
const router = express.Router();

const logger = console;

router.use('/logMessage', (req, res) => {
  try {
    logger.info(req.query.message);
    res.send({
      statusMessage: 'success',
    });
  } catch (err) {
    logger.error('error in logging');
    logger.error(err);
    res.send({
      statusMessage: 'failure',
    });
  }
});

module.exports = router;
```

<p><code>server.js</code>:</p>

<pre class="lang-js prettyprint-override"><code>const express = require('express');
const app = express();
const router = require('./router');

const port = 3000;
app.use(router);

if (require.main === module) {
  app.listen(port, () => console.log('server is listening on port:' + port));
}

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

server.test.js:

const server = require('./server');
const chai = require('chai');
const sinon = require('sinon');
const chaiHttp = require('chai-http');
chai.use(chaiHttp);
chai.should();

describe('62080151', () => {
  describe('GET /logMessage', () => {
    it('should host logger api', (done) => {
      chai
        .request(server)
        .get('/logMessage?message=testMessage')
        .end((err, response) => {
          response.should.have.status(200);
          done();
        });
    });

    it('should handle error', (done) => {
      sinon.stub(console, 'info').callsFake((message) => {
        if (message === 'makeError') {
          throw new Error('custom error');
        }
      });
      sinon.spy(console, 'error');
      chai
        .request(server)
        .get('/logMessage?message=makeError')
        .end((err, response) => {
          response.should.have.status(200);
          sinon.assert.match(console.error.firstCall.calledWithExactly('error in logging'), true);
          console.error.secondCall.args[0].should.be.instanceOf(Error);
          done();
        });
    });
  });
});
```

<p>integration test results with coverage report:</p>

<pre class="lang-sh prettyprint-override"><code>  62080151
    GET /logMessage
testMessage
      ✓ should host logger api
error in logging
Error: custom error
    at Console.sinon.stub.callsFake (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/src/stackoverflow/62080151/server.test.js:23:17)
    at Object.invoke (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/sinon/lib/sinon/behavior.js:163:32)
    at Console.functionStub (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/sinon/lib/sinon/stub.js:39:43)
    at Function.invoke (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/sinon/lib/sinon/proxy-invoke.js:47:47)
    at Console.bound consoleCall [as info] (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/sinon/lib/sinon/proxy.js:214:26)
    at router.use (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/src/stackoverflow/62080151/router.js:1:1894)
    at Layer.handle [as handle_request] (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:317:13)
    at /Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:275:10)
    at Function.handle (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:174:3)
    at router (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:47:12)
    at Layer.handle [as handle_request] (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:317:13)
    at /Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:275:10)
    at expressInit (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/middleware/init.js:40:5)
    at Layer.handle [as handle_request] (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:317:13)
    at /Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:275:10)
    at query (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/middleware/query.js:45:5)
    at Layer.handle [as handle_request] (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:317:13)
    at /Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:275:10)
    at Function.handle (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:174:3)
    at Function.handle (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/application.js:174:10)
    at Server.app (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/express.js:39:9)
    at Server.emit (events.js:198:13)
    at parserOnIncoming (_http_server.js:677:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:109:17)
      ✓ should handle error (43ms)

  2 passing (81ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files  |      90 |       50 |      50 |   94.74 |
 router.js |     100 |      100 |     100 |     100 |
 server.js |   77.78 |       50 |       0 |    87.5 | 9
-----------|---------|----------|---------|---------|-------------------
</code>```

Body:
I have nodeJS app with simple route as below:

const express = require('express')
const router = express.Router();
const logger = require('../logger');

router.use('/logMessage',(req, res)  => {
    try {
        logger.info(req.query.message);
        res.send({
            statusMessage: 'success'
        })
    } catch (err) {
        logger.error('error in logging');
        logger.error(err);
        res.send({
            statusMessage: 'failure'
        })
    }
});

module.exports = router;

I am able to successfully test the try block using below code, but how can I test the catch block ?

Test for try block:

describe('GET /logMessage', () => {
    it('should host logger api', (done) => {
        chai.request(server)
            .get('/logMessage?message=testMessage')
            .end((err, response) => {
                response.should.have.status(200);
                done();
            });
    });
});

Body:
You need to let the statement in the try block to throw an error. You can make this using sinonjs. For demonstration here, I will rewrite the implementation of console.info, when the message is "makeError", an error is thrown.

E.g.

router.js:

const express = require('express');
const router = express.Router();

const logger = console;

router.use('/logMessage', (req, res) => {
  try {
    logger.info(req.query.message);
    res.send({
      statusMessage: 'success',
    });
  } catch (err) {
    logger.error('error in logging');
    logger.error(err);
    res.send({
      statusMessage: 'failure',
    });
  }
});

module.exports = router;

server.js:

const express = require('express');
const app = express();
const router = require('./router');

const port = 3000;
app.use(router);

if (require.main === module) {
  app.listen(port, () => console.log('server is listening on port:' + port));
}

module.exports = app;

server.test.js:

const server = require('./server');
const chai = require('chai');
const sinon = require('sinon');
const chaiHttp = require('chai-http');
chai.use(chaiHttp);
chai.should();

describe('62080151', () => {
  describe('GET /logMessage', () => {
    it('should host logger api', (done) => {
      chai
        .request(server)
        .get('/logMessage?message=testMessage')
        .end((err, response) => {
          response.should.have.status(200);
          done();
        });
    });

    it('should handle error', (done) => {
      sinon.stub(console, 'info').callsFake((message) => {
        if (message === 'makeError') {
          throw new Error('custom error');
        }
      });
      sinon.spy(console, 'error');
      chai
        .request(server)
        .get('/logMessage?message=makeError')
        .end((err, response) => {
          response.should.have.status(200);
          sinon.assert.match(console.error.firstCall.calledWithExactly('error in logging'), true);
          console.error.secondCall.args[0].should.be.instanceOf(Error);
          done();
        });
    });
  });
});

integration test results with coverage report:

  62080151
    GET /logMessage
testMessage
      ✓ should host logger api
error in logging
Error: custom error
    at Console.sinon.stub.callsFake (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/src/stackoverflow/62080151/server.test.js:23:17)
    at Object.invoke (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/sinon/lib/sinon/behavior.js:163:32)
    at Console.functionStub (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/sinon/lib/sinon/stub.js:39:43)
    at Function.invoke (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/sinon/lib/sinon/proxy-invoke.js:47:47)
    at Console.bound consoleCall [as info] (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/sinon/lib/sinon/proxy.js:214:26)
    at router.use (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/src/stackoverflow/62080151/router.js:1:1894)
    at Layer.handle [as handle_request] (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:317:13)
    at /Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:275:10)
    at Function.handle (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:174:3)
    at router (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:47:12)
    at Layer.handle [as handle_request] (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:317:13)
    at /Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:275:10)
    at expressInit (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/middleware/init.js:40:5)
    at Layer.handle [as handle_request] (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:317:13)
    at /Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:275:10)
    at query (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/middleware/query.js:45:5)
    at Layer.handle [as handle_request] (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:317:13)
    at /Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:275:10)
    at Function.handle (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/router/index.js:174:3)
    at Function.handle (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/application.js:174:10)
    at Server.app (/Users/ldu020/workspace/github.com/mrdulin/expressjs-research/node_modules/express/lib/express.js:39:9)
    at Server.emit (events.js:198:13)
    at parserOnIncoming (_http_server.js:677:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:109:17)
      ✓ should handle error (43ms)

  2 passing (81ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files  |      90 |       50 |      50 |   94.74 |
 router.js |     100 |      100 |     100 |     100 |
 server.js |   77.78 |       50 |       0 |    87.5 | 9
-----------|---------|----------|---------|---------|-------------------


问:
How to do reverse for get_absolute_url with many to many field?
I have a model with many-to-many fields and I need to get an ID selected from a many to many field. I decorated a get_absolute_url method with permaling decorator. And it doesn't work. So I understand that I need to reverse the relation, it is obvious from the trace, but I do not really understand what should I do?

Model:

```<code>class MenuItems(models.Model):
    reference_value = models.CharField(max_length=255)
    filter_ids = models.ManyToManyField(Filter, blank = True)

    def __unicode__(self):
        return u'%s' % self.reference_value

    @models.permalink
    def get_absolute_url(self):
        return ('homepage_ids', None, {'ids': self.filter_ids })
</code>```

I tried to do with the reverse(), but I have the behavior of the method didn't changed.

```<code>    @models.permalink
    def get_absolute_url(self):
        return reverse('homepage_ids', kwargs={'ids': self.filter_ids })
</code>```

答:
You didn't post your url but something like this, should work

urls

```<code>url(r'^/something/(?P<var>\d+)/$', view_name, name="homepage_ids"),
</code>```

models

```<code>@permalink
def get_absolute_url(self):
    return ('homepage_ids', [str(self.filter_ids)])
</code>```

template

```<code><a href="{{ ids.get_absolute_url }}"> {{ ids }}</a>
</code>```

take a look into django tutorial

Body:
I have a model with many-to-many fields and I need to get an ID selected from a many to many field. I decorated a get_absolute_url method with permaling decorator. And it doesn't work. So I understand that I need to reverse the relation, it is obvious from the trace, but I do not really understand what should I do?

Model:

class MenuItems(models.Model):
    reference_value = models.CharField(max_length=255)
    filter_ids = models.ManyToManyField(Filter, blank = True)

    def __unicode__(self):
        return u'%s' % self.reference_value

    @models.permalink
    def get_absolute_url(self):
        return ('homepage_ids', None, {'ids': self.filter_ids })

I tried to do with the reverse(), but I have the behavior of the method didn't changed.

    @models.permalink
    def get_absolute_url(self):
        return reverse('homepage_ids', kwargs={'ids': self.filter_ids })

Body:
You didn't post your url but something like this, should work

urls

url(r'^/something/(?P<var>\d+)/$', view_name, name="homepage_ids"),

models

@permalink
def get_absolute_url(self):
    return ('homepage_ids', [str(self.filter_ids)])

template

<a href="{{ ids.get_absolute_url }}"> {{ ids }}</a>

take a look into django tutorial


问:
Split String every 2 characters with Zip in Python 3
I need to make a function that receives a String and a number and split this String every 2 characters but if the length of the String is not even I have to add the number. Here's what I got so far.

```<code>def splitString(string,number):
  if (len(string)%2 != 0):
    return list(map(''.join, zip(*[iter(string)]*2))) # I don't know how to add the number at the end
  else:
    return list(map(''.join, zip(*[iter(string)]*2)))
</code>```

As this is for homework I was told I can't create a list and then use .append() so I have to return the list ready.

答:
You were close:

```<code>def splitString(string,number):
  if (len(string)%2 != 0):
    return list(map(''.join, zip(*[iter(string + str(number))]*2)))
  else:
    return list(map(''.join, zip(*[iter(string)]*2)))
</code>```

Example:

```<code>>>> splitString("hellow", 4)
['he', 'll', 'ow']

>>> splitString("hello", 4)
['he', 'll', 'o4']
</code>```

Body:
I need to make a function that receives a String and a number and split this String every 2 characters but if the length of the String is not even I have to add the number. Here's what I got so far.

def splitString(string,number):
  if (len(string)%2 != 0):
    return list(map(''.join, zip(*[iter(string)]*2))) # I don't know how to add the number at the end
  else:
    return list(map(''.join, zip(*[iter(string)]*2)))

As this is for homework I was told I can't create a list and then use .append() so I have to return the list ready.

Body:
You were close:

def splitString(string,number):
  if (len(string)%2 != 0):
    return list(map(''.join, zip(*[iter(string + str(number))]*2)))
  else:
    return list(map(''.join, zip(*[iter(string)]*2)))

Example:

>>> splitString("hellow", 4)
['he', 'll', 'ow']

>>> splitString("hello", 4)
['he', 'll', 'o4']


问:
Storing pixels values from 50 images inside a vector
I need to extract features from specific points from an image. Currently im doing it for one image, but its to much work to go manually from frame to frame. To extract simple pixel intensity levels, im doing this:

```<code>print(img[45, 80])
print(img[45, 100])
print(img[50, 65])
print(img[50, 110])
print(img[40, 110])
print(img[35, 90])
print(img[25, 90])
print(img[25, 110])
print(img[64, 89])
print(img[25, 65])
print(img[40, 65])
print(img[65, 60])
print(img[65, 120])
print(img[82, 75])
print(img[82, 105])
print(img[78, 88])
print(img[110, 90])
print(img[90, 89])
print(img[100, 65])
print(img[100, 110])

values = [245, 247, 199, 199, 210, 213, 216, 196, 225, 199, 189, 189, 195, 221, 225, 201, 221, 201, 216, 222]
new_values = np.reshape(values,(20,1))
</code>```

Basically, i manually verify the pixels that are more useful to my application and store them inside a vector. Though, those coordinates are constant for all face images, what i want to do then, is to be able to load all 50 images at once, and print their values or/and store them inside a vector.

I am currently loading the images like this:

```<code>from os import listdir
from PIL import Image as PImage

def loadImages(path):

    imagesList = listdir(path)
    loadedImages = []
    for image in imagesList:
        img = PImage.open(path + image)
        loadedImages.append(img)

    return loadedImages

imgs = loadImages('C:/Dataset/Frames/')

for img in imgs:
    imgplot = plt.imshow(img)
    print(img[45, 100])
    plt.show()
</code>```

Not only, it does not work, it also gives me the error:

TypeError: 'TiffImageFile' object is not

subscriptable

答:
You may want to replace print(img[45, 100]) with print(img.getpixel((45, 100)))

Reference: https://pillow.readthedocs.io/en/stable/reference/Image.html

Body:
I need to extract features from specific points from an image. Currently im doing it for one image, but its to much work to go manually from frame to frame. To extract simple pixel intensity levels, im doing this:

print(img[45, 80])
print(img[45, 100])
print(img[50, 65])
print(img[50, 110])
print(img[40, 110])
print(img[35, 90])
print(img[25, 90])
print(img[25, 110])
print(img[64, 89])
print(img[25, 65])
print(img[40, 65])
print(img[65, 60])
print(img[65, 120])
print(img[82, 75])
print(img[82, 105])
print(img[78, 88])
print(img[110, 90])
print(img[90, 89])
print(img[100, 65])
print(img[100, 110])

values = [245, 247, 199, 199, 210, 213, 216, 196, 225, 199, 189, 189, 195, 221, 225, 201, 221, 201, 216, 222]
new_values = np.reshape(values,(20,1))

Basically, i manually verify the pixels that are more useful to my application and store them inside a vector. Though, those coordinates are constant for all face images, what i want to do then, is to be able to load all 50 images at once, and print their values or/and store them inside a vector.

I am currently loading the images like this:

from os import listdir
from PIL import Image as PImage

def loadImages(path):

    imagesList = listdir(path)
    loadedImages = []
    for image in imagesList:
        img = PImage.open(path + image)
        loadedImages.append(img)

    return loadedImages

imgs = loadImages('C:/Dataset/Frames/')

for img in imgs:
    imgplot = plt.imshow(img)
    print(img[45, 100])
    plt.show()

Not only, it does not work, it also gives me the error:

TypeError: 'TiffImageFile' object is not

subscriptable


问:
Parsing error: the type cast expression is expected to be wrapped in parentheses
Tried to create an object inside the "tracks" array under "You Give Love a Bad Name"    </p>

```<code>export default class Cart extends React.Component {
    render() {
      var collection = {
        "2548": {
          "album": "Slippery When Wet",
          "artist": "Bon Jovi",
          "tracks": [
            "Let It Rock", **
            "You Give Love a Bad Name": {
              "love": "bad",
              "you": "George"
            } **
          ]
        }
      };
      return ();
    }
}
</code>```

答:
I am not sure what you exactly want.

because this format looks not good.

```<code>var collection = {
        "2548": {
          "album": "Slippery When Wet",
          "artist": "Bon Jovi",
          "tracks": [
            "Let It Rock",
            {
              "You Give Love a Bad Name": {
                "love": "bad",
                "you": "George"
              }
            }
          ]
        }
      };
</code>```

Body:
Tried to create an object inside the "tracks" array under "You Give Love a Bad Name"

export default class Cart extends React.Component {
    render() {
      var collection = {
        "2548": {
          "album": "Slippery When Wet",
          "artist": "Bon Jovi",
          "tracks": [
            "Let It Rock", **
            "You Give Love a Bad Name": {
              "love": "bad",
              "you": "George"
            } **
          ]
        }
      };
      return ();
    }
}

Body:
I am not sure what you exactly want.

because this format looks not good.

var collection = {
        "2548": {
          "album": "Slippery When Wet",
          "artist": "Bon Jovi",
          "tracks": [
            "Let It Rock",
            {
              "You Give Love a Bad Name": {
                "love": "bad",
                "you": "George"
              }
            }
          ]
        }
      };


问:
Facebook Javascript SDK: Event auth.sessionChange and auto.logout firing only on page refresh
I have an implementation for my website to have facebook single sign on, using their javascript sdk.

The javascript adds the cookie and I deal with it fine.

The question is related to when an user logs out of facebook, I would expect the auth.sessionChange or auth.logout events to fire, but that only occurs when the page is refreshed.

As my implementation is done server-side, this means that after the user logs out of facebook they can access one secure page one more time before being properly logged out.

Is this the normal case or do these events usually fire up straight away and I'm maybe doing something incorrect in configuration of the facebook app?

答:
Almost 1/2 years later, i don't know if it's useful, but i try those things myself and observed that the subscribe solution doesn't work if i log in/out of facebook from their site(not from the current page that contains FB object, like using FB.login()).

Also by constantly polling getLoginStatus and getSession, nothing changes if i log in/out of facebook (!from their site).

My conclusion?! Their script is completely unsynchronized with the real events on facebook.
The only way that worked for me is to constantly do FB.ini(...).(it's like having a constant refresh)

I hope that it will be useful to other ppl having the same problem....?!?

ContentLicense: CC BY-SA 2.5


问:
State is not updating in react js
Below is my code snippet

```<code> this.setState({
  isConfirmationDialogOpen: false,
  progress: Progress.Saving
});

let state = { ...this.state };
</code>```

but it is not updating the state, can someone tell me what i am doing wrong.

答:
```<code> this.setState({
  isConfirmationDialogOpen: false,
  progress: Progress.Saving
});

let stateData = { ...this.state };
</code>```

Do not use the same name as state, also callback method in setState can be used to perform async activities.

UPDATE

If you don't want to use this callback, this is another way.

```<code>const state = {
    isConfirmationDialogOpen: false,
    progress: Progress.Saving
};

this.setState(state);
</code>```

And use the state object but this won't guarantee that you've the latest state i.e. this.state

Title: State is not updating in react js

Body:
Below is my code snippet

 this.setState({
  isConfirmationDialogOpen: false,
  progress: Progress.Saving
});

let state = { ...this.state };

but it is not updating the state, can someone tell me what i am doing wrong.

Body:
 this.setState({
  isConfirmationDialogOpen: false,
  progress: Progress.Saving
});

let stateData = { ...this.state };

Do not use the same name as state, also callback method in setState can be used to perform async activities.

UPDATE

If you don't want to use this callback, this is another way.

const state = {
    isConfirmationDialogOpen: false,
    progress: Progress.Saving
};

this.setState(state);

And use the state object but this won't guarantee that you've the latest state i.e. this.state


答:
Firstly, this.setState is async.

The second parameter to setState() is an optional callback function that will be executed once setState is completed and the component is re-rendered.

If you are trying to access state and want the updated state, then because it is async you "HAVE TO" access it inside the callback function to ensure you access the state only after it has been updated.

Title: State is not updating in react js


问:
How do I install a go module?
Usually, when i'm in a workspace, all I need to do is go install to install an executable into my pkg folder. However, let's say i'm creating a module outside of $GOPATH/src. I then have a folder called ModuleTest on my desktop that contains the go.mod file. How do I install the package I created so I can use it in other go programs.

I've tried running go get and go install while inside the ModuleTest folder but it doesn't install anything into $GOPATH/pkg or $GOPATH/bin.

EDIT: I guess what i'm asking is, how do I install a go module locally without first pushing it on github and then doing go get

答:
For it to reflect in $GOPATH/bin you need to do go get -u ....... instead of go get ........

Hope it helps :)

Title: How do I install a go module?


问:
I can't loop through a directory which has images
I have tried to loop through a directory which has images inside. There are 45 images inside that directory but when I executed the file the program gave me only one image and then it stopped the loop immediately. I don't know what I did wrong with it and also I have tried both for loops, one within the comment and another one is outside the command.

my code

```<code>import cv2
import argparse
import os
from imutils import paths

ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", required=True, help="path to not hong dataset")
ap.add_argument("-o", "--output", required=True, help="path to output directory")
args = vars(ap.parse_args())

haar_cascade = 'haarcascade_frontalface_default.xml'
detector = cv2.CascadeClassifier(haar_cascade)

print("\n[INFO] Working on image...")

"""
for imagePath in sorted(list(paths.list_images(args["dataset"]))):
    i = 0
    image = cv2.imread(imagePath)
    #image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    rects = detector.detectMultiScale(image, scaleFactor=1.1, minNeighbors=5,
                                    minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE)

    for (x, y, w, h) in rects:
        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
        sub_face = image[y:y + h, x:x + w]
        sub_face = cv2.cvtColor(sub_face, cv2.COLOR_BGR2GRAY)

        p = os.path.sep.join([args["output"], "{}.png".format(str(i).zfill(5))])
        sub_face = cv2.resize(sub_face, (64, 64))
        #sub_face = cv2.cvtColor(sub_face, cv2.COLOR_BGR2GRAY)
        cv2.imwrite(p, sub_face)
    i += 1
"""

for imagePath in os.listdir(args["dataset"]):
    i = 0
    image = cv2.imread(imagePath)
    rects = detector.detectMultiScale(image, scaleFactor=1.1, minNeighbors=5,
                                    minSize=(30, 30))

    for (x, y, w, h) in rects:
        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
        sub_face = image[y:y + h, x:x + w]
        sub_face = cv2.cvtColor(sub_face, cv2.COLOR_BGR2GRAY)

        p = os.path.sep.join([args["output"], "{}.png".format(str(i).zfill(5))])
        sub_face = cv2.resize(sub_face, (64, 64))
        #sub_face = cv2.cvtColor(sub_face, cv2.COLOR_BGR2GRAY)
        cv2.imwrite(p, sub_face)
    i += 1
</code>```

答: Your commented out code works fine. Just move the i = 0 statement outside the loop (since it reassigns it to 0 each time), and it should work.</p>

Body:
I have tried to loop through a directory which has images inside. There are 45 images inside that directory but when I executed the file the program gave me only one image and then it stopped the loop immediately. I don't know what I did wrong with it and also I have tried both for loops, one within the comment and another one is outside the command.

my code

import cv2
import argparse
import os
from imutils import paths

ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", required=True, help="path to not hong dataset")
ap.add_argument("-o", "--output", required=True, help="path to output directory")
args = vars(ap.parse_args())

haar_cascade = 'haarcascade_frontalface_default.xml'
detector = cv2.CascadeClassifier(haar_cascade)

print("\n[INFO] Working on image...")

"""
for imagePath in sorted(list(paths.list_images(args["dataset"]))):
    i = 0
    image = cv2.imread(imagePath)
    #image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    rects = detector.detectMultiScale(image, scaleFactor=1.1, minNeighbors=5,
                                    minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE)

    for (x, y, w, h) in rects:
        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
        sub_face = image[y:y + h, x:x + w]
        sub_face = cv2.cvtColor(sub_face, cv2.COLOR_BGR2GRAY)

        p = os.path.sep.join([args["output"], "{}.png".format(str(i).zfill(5))])
        sub_face = cv2.resize(sub_face, (64, 64))
        #sub_face = cv2.cvtColor(sub_face, cv2.COLOR_BGR2GRAY)
        cv2.imwrite(p, sub_face)
    i += 1
"""

for imagePath in os.listdir(args["dataset"]):
    i = 0
    image = cv2.imread(imagePath)
    rects = detector.detectMultiScale(image, scaleFactor=1.1, minNeighbors=5,
                                    minSize=(30, 30))

    for (x, y, w, h) in rects:
        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
        sub_face = image[y:y + h, x:x + w]
        sub_face = cv2.cvtColor(sub_face, cv2.COLOR_BGR2GRAY)

        p = os.path.sep.join([args["output"], "{}.png".format(str(i).zfill(5))])
        sub_face = cv2.resize(sub_face, (64, 64))
        #sub_face = cv2.cvtColor(sub_face, cv2.COLOR_BGR2GRAY)
        cv2.imwrite(p, sub_face)
    i += 1


问:
How do I fix my variables on my code as it does not appear
So when I ran this code below, I noticed that my variables myName and myAge didn't function at all. An I getting something wrong here?

This program says hello and asks for my name.

print ('Hello world!')

print ('What is your name?') # ask for their name

myName = input('Michael')

print ('It is good to meet you, ' + myName)

print('The length of your name is:')

print (len(myName))

print ('What is your age?') # ask for their age

myAge = input('16')

print('You will be " + str(int(myAge) + 1) + ' in a year.')
```

答:
This line "print('You will be " + str(int(myAge) + 1) + ' in a year.')", you are using two different types of quotes ' and ", you can only use one type at once.

This is a string: 'Michael'
Or like this: "Michael"

The items in quote above are valid strings in python.

"Michael' is an invalid string in python. Mixing two different types of quotation symbols.

Consider running my version of your code and see if it all makes sense.

```<code>print ('Hello world!')

myName = input('What is your name? ')  # ask for their name

print ('It is good to meet you, ' + myName) # Shows the name

print('The length of your name is:')

print (len(myName)) # Shows the length of the name

myAge = input('What is your age? ')  # ask for their age

print("You will be " + str(int(myAge) + 1) + " in a year.")  # Shows the age + 1
</code>```

Body:
This line "print('You will be " + str(int(myAge) + 1) + ' in a year.')", you are using two different types of quotes ' and ", you can only use one type at once.

This is a string: 'Michael'
Or like this: "Michael"

The items in quote above are valid strings in python.

"Michael' is an invalid string in python. Mixing two different types of quotation symbols.

Consider running my version of your code and see if it all makes sense.

print ('Hello world!')

myName = input('What is your name? ')  # ask for their name

print ('It is good to meet you, ' + myName) # Shows the name

print('The length of your name is:')

print (len(myName)) # Shows the length of the name

myAge = input('What is your age? ')  # ask for their age

print("You will be " + str(int(myAge) + 1) + " in a year.")  # Shows the age + 1


问:
Why am I getting result NONE in this simple python program?
I'm learning python 3. I expect this program to sum together a decreasing sequence of integers. Instead, I get NONE.

If this was throwing an error I might be able to figure out what I'm doing wrong, but in this case I am stumped.

```<code>def add_many_things(init_value):
    accumulator = 0
    while init_value > 0 :
        accumulator = accumulator + init_value
        init_value = init_value - 1

result = add_many_things(37)
print(f"{result}")
</code>```

答:
Add  return  accumulator to the function. You're trying to assign the result of the function:

result = add_many_things(37)

but your add_many_things() function doesn't return a value. Adding the return statement at the end of the function will pass the value of accumulator back to the caller.

Body:
I'm learning python 3. I expect this program to sum together a decreasing sequence of integers. Instead, I get NONE.

If this was throwing an error I might be able to figure out what I'm doing wrong, but in this case I am stumped.

def add_many_things(init_value):
    accumulator = 0
    while init_value > 0 :
        accumulator = accumulator + init_value
        init_value = init_value - 1

result = add_many_things(37)
print(f"{result}")


问:
How do I mass-delete channels on DIscord.js?
I'm making a bot that manages servers, and I would like to know how to delete all channels currently in a server with a single command</p>

答:
```<code>message.guild.channels.forEach(channel => channel.delete())
</code>```

Source: Discord.js - Deleting all channels in a server

Body:
message.guild.channels.forEach(channel => channel.delete())

Source: Discord.js - Deleting all channels in a server


问:
Docker run -p ?/? (what are this two port numbers and what they represents )
I used command "docker run -p 8080/8080 --name my_local_image ...." and it failed saying Unable to find image '8080/8080:latest' locally

8080/8080 = what this two port represents exactly ?

答:
The -p option is used to expose the ports that are used for the image instance. The first one is the hostport and the second parameter after the ":" fullcolon is the container port to which it should be mapped . For more details read doc.

The error that you received while launching the instance using docker run tells us that the image name that you provided with the command is not locally available on the machine that you are using, it might also be an issue with the way that you provided the ports using '/' instead of ":" .So , to be safe, use docker pull first to pull the latest image from repo and then run it with proper syntax.

--expose=[]: Expose a port or a range of ports inside the container.
                These are additional to those exposed by the EXPOSE instruction

-P         : Publish all exposed ports to the host interfaces

-p=[]      : Publish a container's port or a range of ports to the host
                 format: ip:hostPort:containerPort | ip::containerPort | hostPort:containerPort | containerPort
                 Both hostPort and containerPort can be specified as a
                 range of ports. When specifying ranges for both, the
                 number of container ports in the range must match the
                 number of host ports in the range, for example:
                     -p 1234-1236:1234-1236/tcp
                 When specifying a range for hostPort only, the
                 containerPort must not be a range.  In this case the
                 container port is published somewhere within the
                 specified hostPort range. (e.g., -p 1234-1236:1234/tcp)
                 (use 'docker port' to see the actual mapping)

--link=""  : Add link to another container (:alias or )


问:
SpringBoot upgrade RestTemplateBuilder from 1.5.14 to 2.1.5
I have this piece of code working fine on a project that uses RestTemplateBuilder 1.5.14

```<code>this.restTemplate = restTemplateBuilder
                .setConnectTimeout(connectTimeout)
                .setReadTimeout(readTimeout)
                .requestFactory(new MyHttpComponentFactoryBuilder()
                        .build())
                .build();
</code>```

After updating to  RestTemplateBuilder 2.1.5 I have this piece of code:

```<code>this.restTemplate = restTemplateBuilder
                .setConnectTimeout(Duration.ofMillis(connectTimeout))
                .setReadTimeout(Duration.ofMillis(readTimeout))
                .requestFactory(new MyHttpComponentFactoryBuilder().build().getClass())
                .build();
</code>```

but when running the code I have a  InvocationTargetException / NullPointerException that dissapears when deleting the line .requestFactory(new MyHttpComponentFactoryBuilder().build().getClass()) , but debugging new MyHttpComponentFactoryBuilder().build().getClass() is not null

I also tried with the solution proposed:

```<code>...
.requestFactory(new MyRequestFactorySupplier())
...

class MyRequestFactorySupplier implements Supplier<ClientHttpRequestFactory> {

        @Override
        public ClientHttpRequestFactory get() {

            // Using Apache HTTP client.
            HttpClientBuilder clientBuilder = HttpClientBuilder.create();
            HttpClient httpClient = clientBuilder.build();
            HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
            requestFactory.setBufferRequestBody(false); // When sending large amounts of data via POST or PUT, it is recommended to change this property to false, so as not to run out of memory.
            return requestFactory;
        }

    }
</code>```

but I have also a InvocationTargetException / NullPointerException

答:
I have wrote detail notes on my github wiki page , please check sure will be helpful

https://github.com/vaquarkhan/vaquarkhan/wiki/RestTemplate-vs-WebClient

Here is example :

```<code>        public String retrieveData(String id, String name) {

            HttpHeaders headers =createHeader();
            String requestJson = "{\"name\":\"" + name + "\"}";
            HttpEntity<String> request = new HttpEntity<String>(requestJson, headers);
            // external call time
            long startTime = System.currentTimeMillis();
            ResponseEntity<String> response = customRestTemplate().exchange(externalUrl, HttpMethod.POST, request,
                    String.class);
            long endTime = System.currentTimeMillis();
            long duration = (endTime - startTime); // divide by 1000000 to get milliseconds.
            log.info("{\"RestTemplateDemo\":{\"id\":\"" + id + "\",\"external call duration\":" + duration + "}}");
            ObjectMapper mapper = new ObjectMapper();
            return response.getBody();
        }
</code>```

Body:
I have this piece of code working fine on a project that uses RestTemplateBuilder 1.5.14

this.restTemplate = restTemplateBuilder
                .setConnectTimeout(connectTimeout)
                .setReadTimeout(readTimeout)
                .requestFactory(new MyHttpComponentFactoryBuilder()
                        .build())
                .build();

After updating to  RestTemplateBuilder 2.1.5 I have this piece of code:

this.restTemplate = restTemplateBuilder
                .setConnectTimeout(Duration.ofMillis(connectTimeout))
                .setReadTimeout(Duration.ofMillis(readTimeout))
                .requestFactory(new MyHttpComponentFactoryBuilder().build().getClass())
                .build();

but when running the code I have a  InvocationTargetException / NullPointerException that dissapears when deleting the line .requestFactory(new MyHttpComponentFactoryBuilder().build().getClass()) , but debugging new MyHttpComponentFactoryBuilder().build().getClass() is not null

I also tried with the solution proposed:

...
.requestFactory(new MyRequestFactorySupplier())
...

class MyRequestFactorySupplier implements Supplier<ClientHttpRequestFactory> {

        @Override
        public ClientHttpRequestFactory get() {

            // Using Apache HTTP client.
            HttpClientBuilder clientBuilder = HttpClientBuilder.create();
            HttpClient httpClient = clientBuilder.build();
            HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
            requestFactory.setBufferRequestBody(false); // When sending large amounts of data via POST or PUT, it is recommended to change this property to false, so as not to run out of memory.
            return requestFactory;
        }

    }

but I have also a InvocationTargetException / NullPointerException

Body:
I have wrote detail notes on my github wiki page , please check sure will be helpful

https://github.com/vaquarkhan/vaquarkhan/wiki/RestTemplate-vs-WebClient

Here is example :

        public String retrieveData(String id, String name) {

            HttpHeaders headers =createHeader();
            String requestJson = "{\"name\":\"" + name + "\"}";
            HttpEntity<String> request = new HttpEntity<String>(requestJson, headers);
            // external call time
            long startTime = System.currentTimeMillis();
            ResponseEntity<String> response = customRestTemplate().exchange(externalUrl, HttpMethod.POST, request,
                    String.class);
            long endTime = System.currentTimeMillis();
            long duration = (endTime - startTime); // divide by 1000000 to get milliseconds.
            log.info("{\"RestTemplateDemo\":{\"id\":\"" + id + "\",\"external call duration\":" + duration + "}}");
            ObjectMapper mapper = new ObjectMapper();
            return response.getBody();
        }


问:
How to insert arbitrary JSON response to mongodb collection in Laravel?
I have described the model in the following way:

```<code><?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Feed extends Model
{
    protected $collection = 'feeds';
    protected $connection = 'mongodb';
    protected $appends = ['id'];
    protected $hidden = ['_id'];
    protected $fillable = ['feed_content'];
    public $timestamps = true;
}
</code>```

I want to save the content of the API response in database logs:

```<code>    $feed_info = $driver->getAdvertiserFeed();
    $feed_id = new Feed;
    $feed_id->feed_content = $feed_info;
    $feed_id->save();
</code>```

The connection to MongoDB is configured in this way:

```<code>    'mongodb' => [
        'driver' => 'mongodb',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', 27017),
        'database' => env('DB_DATABASE', 'feeds'),
        'username' => env('DB_USERNAME', 'user'),
        'password' => env('DB_PASSWORD', 'test'),
        'options' => [
            'database' => env('DB_AUTHENTICATION_DATABASE', 'admin'),
        ],
    ],
</code>```

But when I try to execute the second piece of code, I get this error:

```<code>Symfony\Component\Debug\Exception\FatalThrowableError:
Argument 1 passed to Illuminate\Database\Grammar::parameterize()
must be of the type array, string given, called in
/home/pavel/Projects/axonite/vendor/laravel/framework/
  src/Illuminate/Database/Query/Grammars/Grammar.php on line 853

at /home/pavel/Projects/axonite/vendor/laravel/framework/src/Illuminate/Database/Grammar.php:138
    134|      *
    135|      * @param  array   $values
    136|      * @return string
    137|      */
  > 138|     public function parameterize(array $values)
    139|     {
    140|         return implode(', ', array_map([$this, 'parameter'], $values));
    141|     }
    142|
</code>```

What exactly do I do wrong? How to fill JSON in a collection in a more correct manner with getting a document id back? I want to save it in the relational database for retrieving it later. Thanks!

答:
Laravel doesn't support noSql database like mongodb and others..

You need to use PHP methods for the specific database or you can use this ORM package: https://github.com/jenssegers/laravel-mongodb

This package will enable all the ORM functionality same as RDBMS.

Body:
I have described the model in the following way:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Feed extends Model
{
    protected $collection = 'feeds';
    protected $connection = 'mongodb';
    protected $appends = ['id'];
    protected $hidden = ['_id'];
    protected $fillable = ['feed_content'];
    public $timestamps = true;
}

I want to save the content of the API response in database logs:

    $feed_info = $driver->getAdvertiserFeed();
    $feed_id = new Feed;
    $feed_id->feed_content = $feed_info;
    $feed_id->save();

The connection to MongoDB is configured in this way:

    'mongodb' => [
        'driver' => 'mongodb',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', 27017),
        'database' => env('DB_DATABASE', 'feeds'),
        'username' => env('DB_USERNAME', 'user'),
        'password' => env('DB_PASSWORD', 'test'),
        'options' => [
            'database' => env('DB_AUTHENTICATION_DATABASE', 'admin'),
        ],
    ],

But when I try to execute the second piece of code, I get this error:

Symfony\Component\Debug\Exception\FatalThrowableError:
Argument 1 passed to Illuminate\Database\Grammar::parameterize()
must be of the type array, string given, called in
/home/pavel/Projects/axonite/vendor/laravel/framework/
  src/Illuminate/Database/Query/Grammars/Grammar.php on line 853

at /home/pavel/Projects/axonite/vendor/laravel/framework/src/Illuminate/Database/Grammar.php:138
    134|      *
    135|      * @param  array   $values
    136|      * @return string
    137|      */
  > 138|     public function parameterize(array $values)
    139|     {
    140|         return implode(', ', array_map([$this, 'parameter'], $values));
    141|     }
    142|

What exactly do I do wrong? How to fill JSON in a collection in a more correct manner with getting a document id back? I want to save it in the relational database for retrieving it later. Thanks!


问:
NO alert received on elastalert-test-rule or while executing the rule
I have done setup on windows 10. Getting below output when executing elastalert-test-rule for my rule.

```<code>elastalert-test-rule example_rules\example_frequency.yaml --config config.yaml
Would have written the following documents to writeback index (default is elastalert_status):

elastalert_status - {'rule_name': 'Example frequency rule', 'endtime': datetime.datetime(2020, 4, 19, 18, 49, 10, 397745, tzinfo=tzutc()), 'starttime': datetime.datetime(2019, 4, 17, 3, 13, 10, 397745, tzinfo=tzutc()), 'matches': 4, 'hits': 4, '@timestamp': datetime.datetime(2020, 4, 19, 18, 55, 56, 314841, tzinfo=tzutc()), 'time_taken': 405.48910188674927}
</code>```

However, no alert is triggered.
Please find below contents of config.yaml and example_frequency.yaml

config.yaml

```<code># This is the folder that contains the rule yaml files
# Any .yaml file will be loaded as a rule
rules_folder: example_rules

# How often ElastAlert will query Elasticsearch
# The unit can be anything from weeks to seconds
run_every:
  seconds: 5

# ElastAlert will buffer results from the most recent
# period of time, in case some log sources are not in real time
buffer_time:
  minutes: 15

# The Elasticsearch hostname for metadata writeback
# Note that every rule can have its own Elasticsearch host
es_host: 127.0.0.1

# The Elasticsearch port
es_port: 9200

# The AWS region to use. Set this when using AWS-managed elasticsearch
#aws_region: us-east-1

# The AWS profile to use. Use this if you are using an aws-cli profile.
# See http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html
# for details
#profile: test

# Optional URL prefix for Elasticsearch
#es_url_prefix: elasticsearch

# Connect with TLS to Elasticsearch
#use_ssl: True

# Verify TLS certificates
#verify_certs: True

# GET request with body is the default option for Elasticsearch.
# If it fails for some reason, you can pass 'GET', 'POST' or 'source'.
# See http://elasticsearch-py.readthedocs.io/en/master/connection.html?highlight=send_get_body_as#transport
# for details
#es_send_get_body_as: GET

# Option basic-auth username and password for Elasticsearch
#es_username: someusername
#es_password: somepassword

# Use SSL authentication with client certificates client_cert must be
# a pem file containing both cert and key for client
#verify_certs: True
#ca_certs: /path/to/cacert.pem
#client_cert: /path/to/client_cert.pem
#client_key: /path/to/client_key.key

# The index on es_host which is used for metadata storage
# This can be a unmapped index, but it is recommended that you run
# elastalert-create-index to set a mapping
writeback_index: elastalert_status
writeback_alias: elastalert_alerts

# If an alert fails for some reason, ElastAlert will retry
# sending the alert until this time period has elapsed
alert_time_limit:
  days: 2

# Custom logging configuration
# If you want to setup your own logging configuration to log into
# files as well or to Logstash and/or modify log levels, use
# the configuration below and adjust to your needs.
# Note: if you run ElastAlert with --verbose/--debug, the log level of
# the "elastalert" logger is changed to INFO, if not already INFO/DEBUG.
#logging:
#  version: 1
#  incremental: false
#  disable_existing_loggers: false
#  formatters:
#    logline:
#      format: '%(asctime)s %(levelname)+8s %(name)+20s %(message)s'
#
#    handlers:
#      console:
#        class: logging.StreamHandler
#        formatter: logline
#        level: DEBUG
#        stream: ext://sys.stderr
#
#      file:
#        class : logging.FileHandler
#        formatter: logline
#        level: DEBUG
#        filename: elastalert.log
#
#    loggers:
#      elastalert:
#        level: WARN
#        handlers: []
#        propagate: true
#
#      elasticsearch:
#        level: WARN
#        handlers: []
#        propagate: true
#
#      elasticsearch.trace:
#        level: WARN
#        handlers: []
#        propagate: true
#
#      '':  # root logger
#        level: WARN
#          handlers:
#            - console
#            - file
#        propagate: false
</code>```

example_frequency.yaml

```<code># Alert when the rate of events exceeds a threshold

# (Optional)
# Elasticsearch host
# es_host: elasticsearch.example.com

# (Optional)
# Elasticsearch port
# es_port: 14900

# (OptionaL) Connect with SSL to Elasticsearch
#use_ssl: True

# (Optional) basic-auth username and password for Elasticsearch
#es_username: someusername
#es_password: somepassword

# (Required)
# Rule name, must be unique
name: Example frequency rule

# (Required)
# Type of alert.
# the frequency rule type alerts when num_events events occur with timeframe time
type: frequency

# (Required)
# Index to search, wildcard supported
index: com-*

# (Required, frequency specific)
# Alert when this many documents matching the query occur within a timeframe
num_events: 1

# (Required, frequency specific)
# num_events must occur within this amount of time to trigger an alert
timeframe:
  days: 365

# (Required)
# A list of Elasticsearch filters used for find events
# These filters are joined with AND and nested in a filtered query
# For more info: http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl.html
filter:
- term:
    "log_json.response.statusCode": "404"

# (Required)
# The alert is use when a match is found
alert:
- "email"

# (required, email specific)
# a list of email addresses to send alerts to
email:
- "username@mydomain.com"

realert:
  minutes: 0
</code>```

What is it that i am missing to receive alerts? Neither do i see any error on console.

答:
SMTP configuration in missing, so that is why no alert is being sent.

Please try to include the smtp_host,smtp_port,smtp_ssl and smtp_auth_file in your example_frequency.yaml.
Refer to the document for Email Alert

Body:
I have done setup on windows 10. Getting below output when executing elastalert-test-rule for my rule.

elastalert-test-rule example_rules\example_frequency.yaml --config config.yaml
Would have written the following documents to writeback index (default is elastalert_status):

elastalert_status - {'rule_name': 'Example frequency rule', 'endtime': datetime.datetime(2020, 4, 19, 18, 49, 10, 397745, tzinfo=tzutc()), 'starttime': datetime.datetime(2019, 4, 17, 3, 13, 10, 397745, tzinfo=tzutc()), 'matches': 4, 'hits': 4, '@timestamp': datetime.datetime(2020, 4, 19, 18, 55, 56, 314841, tzinfo=tzutc()), 'time_taken': 405.48910188674927}

However, no alert is triggered.
Please find below contents of config.yaml and example_frequency.yaml

config.yaml

# This is the folder that contains the rule yaml files
# Any .yaml file will be loaded as a rule
rules_folder: example_rules

# How often ElastAlert will query Elasticsearch
# The unit can be anything from weeks to seconds
run_every:
  seconds: 5

# ElastAlert will buffer results from the most recent
# period of time, in case some log sources are not in real time
buffer_time:
  minutes: 15

# The Elasticsearch hostname for metadata writeback
# Note that every rule can have its own Elasticsearch host
es_host: 127.0.0.1

# The Elasticsearch port
es_port: 9200

# The AWS region to use. Set this when using AWS-managed elasticsearch
#aws_region: us-east-1

# The AWS profile to use. Use this if you are using an aws-cli profile.
# See http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html
# for details
#profile: test

# Optional URL prefix for Elasticsearch
#es_url_prefix: elasticsearch

# Connect with TLS to Elasticsearch
#use_ssl: True

# Verify TLS certificates
#verify_certs: True

# GET request with body is the default option for Elasticsearch.
# If it fails for some reason, you can pass 'GET', 'POST' or 'source'.
# See http://elasticsearch-py.readthedocs.io/en/master/connection.html?highlight=send_get_body_as#transport
# for details
#es_send_get_body_as: GET

# Option basic-auth username and password for Elasticsearch
#es_username: someusername
#es_password: somepassword

# Use SSL authentication with client certificates client_cert must be
# a pem file containing both cert and key for client
#verify_certs: True
#ca_certs: /path/to/cacert.pem
#client_cert: /path/to/client_cert.pem
#client_key: /path/to/client_key.key

# The index on es_host which is used for metadata storage
# This can be a unmapped index, but it is recommended that you run
# elastalert-create-index to set a mapping
writeback_index: elastalert_status
writeback_alias: elastalert_alerts

# If an alert fails for some reason, ElastAlert will retry
# sending the alert until this time period has elapsed
alert_time_limit:
  days: 2

# Custom logging configuration
# If you want to setup your own logging configuration to log into
# files as well or to Logstash and/or modify log levels, use
# the configuration below and adjust to your needs.
# Note: if you run ElastAlert with --verbose/--debug, the log level of
# the "elastalert" logger is changed to INFO, if not already INFO/DEBUG.
#logging:
#  version: 1
#  incremental: false
#  disable_existing_loggers: false
#  formatters:
#    logline:
#      format: '%(asctime)s %(levelname)+8s %(name)+20s %(message)s'
#
#    handlers:
#      console:
#        class: logging.StreamHandler
#        formatter: logline
#        level: DEBUG
#        stream: ext://sys.stderr
#
#      file:
#        class : logging.FileHandler
#        formatter: logline
#        level: DEBUG
#        filename: elastalert.log
#
#    loggers:
#      elastalert:
#        level: WARN
#        handlers: []
#        propagate: true
#
#      elasticsearch:
#        level: WARN
#        handlers: []
#        propagate: true
#
#      elasticsearch.trace:
#        level: WARN
#        handlers: []
#        propagate: true
#
#      '':  # root logger
#        level: WARN
#          handlers:
#            - console
#            - file
#        propagate: false

example_frequency.yaml

# Alert when the rate of events exceeds a threshold

# (Optional)
# Elasticsearch host
# es_host: elasticsearch.example.com

# (Optional)
# Elasticsearch port
# es_port: 14900

# (OptionaL) Connect with SSL to Elasticsearch
#use_ssl: True

# (Optional) basic-auth username and password for Elasticsearch
#es_username: someusername
#es_password: somepassword

# (Required)
# Rule name, must be unique
name: Example frequency rule

# (Required)
# Type of alert.
# the frequency rule type alerts when num_events events occur with timeframe time
type: frequency

# (Required)
# Index to search, wildcard supported
index: com-*

# (Required, frequency specific)
# Alert when this many documents matching the query occur within a timeframe
num_events: 1

# (Required, frequency specific)
# num_events must occur within this amount of time to trigger an alert
timeframe:
  days: 365

# (Required)
# A list of Elasticsearch filters used for find events
# These filters are joined with AND and nested in a filtered query
# For more info: http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl.html
filter:
- term:
    "log_json.response.statusCode": "404"

# (Required)
# The alert is use when a match is found
alert:
- "email"

# (required, email specific)
# a list of email addresses to send alerts to
email:
- "username@mydomain.com"

realert:
  minutes: 0

What is it that i am missing to receive alerts? Neither do i see any error on console.