问:
Sorting raw data from one sheet into separate tabs on a new sheet in Google App Script
I have a large data file that I want to be separated/filtered out into separate tabs on a new sheet. They need to be filtered by a certain column containing "BGT" within the string.

I am very new to using Google Apps Script so this is a work in progress. I am able to pull the data from one sheet into another, convert it to an array and assign the column I want to sort by. I just can't properly set up the filter.

```<code>function CreativeReport() {

  var ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
  var sheet = ss.getSheetByName(SHEET_NAME);

  var folder = getDriveFolderFromPath("Daily Creative Audit");

  var fileId = folder.getFiles().next().getId();

  var RawMM = SpreadsheetApp.openById(fileId);
  var ArrayRawData = RawMM.getRange(2,1,RawMM.getLastRow()-1,5).getValues();

  var ConceptName = RawMM.getRange('A:A').getValues();
  var BGTFilter = ConceptName.includes("BGT");
  var BGTFilteredData = ArrayRawData.filter(function(item){ return item [6] === BGTFilter;});

  Logger.log(BGTFilteredData);
</code>```

The column I want to sort buy contains cells formatted like this

```<code>2019_BGT_Bigsale_300x50
2019_SWT_Bigsale_300x50
2019_AI_Bigsale_300x50
2019_SWO_Bigsale_300x50
2019_DCO_Bigsale_300x50.
</code>```

The goal is to have the script filter this raw data, and sort it into separate sheets depending on the cells containing:

```<code>BGT
SWO
SWT
AI
DCO
</code>```

The code I how SHOULD log out just the concepts containing "BGT" in the string but I get

```<code>TypeError: Cannot find function includes in object ,concept_name,
</code>```

答:
You have values at "Sheet1" in the source Spreadsheet.

You want to separate the values by checking whether the column "A" has the values of BGT, SWO, SWT, AI, DCO.

You want to put the separated values to the sheet names of BGT, SWO, SWT, AI, DCO in the destination Spreadsheet.

I could understand like above. If my understanding is correct, how about this modification? Unfortunately, the modified script was largely changed from your original script. I apologize for this. I think that there are several answers for your situation. So please think of this as just one of them.

The flow of the modified script is as follows.

Retrieve values from the source sheet.

Create an object for retrieving values for each destination sheet.

The object is like  {"BGT": [values], "SWO": [values],,,}.

Put values for the destination sheets.

Modified script:

Before you run the script, please set srcSpreadsheetId, dstSpreadsheetId and srcSheetName.

```<code>function CreativeReport() {
  // Variables: Please set them for your situation.
  var srcSpreadsheetId = "###"; // Please set the source Spreadsheet ID. In your sample, the Spreadsheet name is "Sample Raw Data".
  var dstSpreadsheetId = "###"; // Please set the destination Spreadsheet ID. In your sample, the Spreadsheet name is "Sorted Data".
  var srcSheetName = "Sheet1"; // Please modify this. In this sample, it's the same with your sample Spreadsheet.
  var dstSheetNames = ["BGT", "SWO", "DCO", "AI", "SWT"];

  // Open Spreadsheets
  var srcSS = SpreadsheetApp.openById(srcSpreadsheetId);
  var dstSS = SpreadsheetApp.openById(dstSpreadsheetId);

  // Retrieve values from the source sheet.
  var srcSheet = srcSS.getSheetByName(srcSheetName);
  var srcValues = srcSheet.getRange(2, 1, srcSheet.getLastRow() - 1, 5).getValues();

  // Create an object for retrieving values for each destination sheet.
  var object = srcValues.reduce(function(obj, e) {
    dstSheetNames.forEach(function(f) {
      if (e[0].indexOf(f) > -1) obj[f] = obj[f] ? obj[f].concat([e]) : [e];
    });
    return obj;
  }, {});

  // Put values for the destination sheets.
  dstSheetNames.forEach(function(e) {
    var sheet = dstSS.getSheetByName(e);
    sheet.getRange(sheet.getLastRow() + 1, 1, object[e].length, object[e][0].length).setValues(object[e]);
  });
}
</code>```

Note:

As mentioned at my comment, the values retrieved by getValues() is 2 dimensional array. So if Array.includes() can be used at Google Apps Script, in your script, ConceptName.includes("BGT") is always false. And, unfortunately, Array.includes() cannot be used at Google Apps Script. Ref

This modified script was prepared using the sample Spreadsheets of "Sample Raw Data" and "Sorted Data" you shared. So if your actual Spreadsheet is different from these samples, please modify above script.

When the values of source Spreadsheet and the number of destination sheets are much increased, I recommend to use Sheets API for putting the values for each destination sheet.

References:

getValues()

Basic JavaScript features

includes()

indexOf()

reduce()

forEach()

Body:
I have a large data file that I want to be separated/filtered out into separate tabs on a new sheet. They need to be filtered by a certain column containing "BGT" within the string.

I am very new to using Google Apps Script so this is a work in progress. I am able to pull the data from one sheet into another, convert it to an array and assign the column I want to sort by. I just can't properly set up the filter.

function CreativeReport() {

  var ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
  var sheet = ss.getSheetByName(SHEET_NAME);

  var folder = getDriveFolderFromPath("Daily Creative Audit");

  var fileId = folder.getFiles().next().getId();

  var RawMM = SpreadsheetApp.openById(fileId);
  var ArrayRawData = RawMM.getRange(2,1,RawMM.getLastRow()-1,5).getValues();

  var ConceptName = RawMM.getRange('A:A').getValues();
  var BGTFilter = ConceptName.includes("BGT");
  var BGTFilteredData = ArrayRawData.filter(function(item){ return item [6] === BGTFilter;});

  Logger.log(BGTFilteredData);

The column I want to sort buy contains cells formatted like this

2019_BGT_Bigsale_300x50
2019_SWT_Bigsale_300x50
2019_AI_Bigsale_300x50
2019_SWO_Bigsale_300x50
2019_DCO_Bigsale_300x50.

The goal is to have the script filter this raw data, and sort it into separate sheets depending on the cells containing:

BGT
SWO
SWT
AI
DCO

The code I how SHOULD log out just the concepts containing "BGT" in the string but I get

TypeError: Cannot find function includes in object ,concept_name,

Body:
You have values at "Sheet1" in the source Spreadsheet.

You want to separate the values by checking whether the column "A" has the values of BGT, SWO, SWT, AI, DCO.

You want to put the separated values to the sheet names of BGT, SWO, SWT, AI, DCO in the destination Spreadsheet.

I could understand like above. If my understanding is correct, how about this modification? Unfortunately, the modified script was largely changed from your original script. I apologize for this. I think that there are several answers for your situation. So please think of this as just one of them.

The flow of the modified script is as follows.

Retrieve values from the source sheet.

Create an object for retrieving values for each destination sheet.

The object is like  {"BGT": [values], "SWO": [values],,,}.

Put values for the destination sheets.

Modified script:

Before you run the script, please set srcSpreadsheetId, dstSpreadsheetId and srcSheetName.

function CreativeReport() {
  // Variables: Please set them for your situation.
  var srcSpreadsheetId = "###"; // Please set the source Spreadsheet ID. In your sample, the Spreadsheet name is "Sample Raw Data".
  var dstSpreadsheetId = "###"; // Please set the destination Spreadsheet ID. In your sample, the Spreadsheet name is "Sorted Data".
  var srcSheetName = "Sheet1"; // Please modify this. In this sample, it's the same with your sample Spreadsheet.
  var dstSheetNames = ["BGT", "SWO", "DCO", "AI", "SWT"];

  // Open Spreadsheets
  var srcSS = SpreadsheetApp.openById(srcSpreadsheetId);
  var dstSS = SpreadsheetApp.openById(dstSpreadsheetId);

  // Retrieve values from the source sheet.
  var srcSheet = srcSS.getSheetByName(srcSheetName);
  var srcValues = srcSheet.getRange(2, 1, srcSheet.getLastRow() - 1, 5).getValues();

  // Create an object for retrieving values for each destination sheet.
  var object = srcValues.reduce(function(obj, e) {
    dstSheetNames.forEach(function(f) {
      if (e[0].indexOf(f) > -1) obj[f] = obj[f] ? obj[f].concat([e]) : [e];
    });
    return obj;
  }, {});

  // Put values for the destination sheets.
  dstSheetNames.forEach(function(e) {
    var sheet = dstSS.getSheetByName(e);
    sheet.getRange(sheet.getLastRow() + 1, 1, object[e].length, object[e][0].length).setValues(object[e]);
  });
}

Note:

As mentioned at my comment, the values retrieved by getValues() is 2 dimensional array. So if Array.includes() can be used at Google Apps Script, in your script, ConceptName.includes("BGT") is always false. And, unfortunately, Array.includes() cannot be used at Google Apps Script. Ref

This modified script was prepared using the sample Spreadsheets of "Sample Raw Data" and "Sorted Data" you shared. So if your actual Spreadsheet is different from these samples, please modify above script.

When the values of source Spreadsheet and the number of destination sheets are much increased, I recommend to use Sheets API for putting the values for each destination sheet.

References:

getValues()

Basic JavaScript features

includes()

indexOf()

reduce()

forEach()


来源: stackexchange

问:
Java Swing Maven - How to load ImageIcon in jar file
Here is my current directory structure (contained inside a connect4 directory):

```<code>├── pom.xml
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       └── dv
│   │   │           └── app
│   │   │               ├── App.java
│   │   │               ├── Board.java
│   │   │
|   |   |
│   │   │
│   │   └── resources
│   │       ├── red-chip.png
│   │
│   └── test
│       ...
|
└── target
    ├── classes/com/dv/app/*.class
</code>```

Essentially from Board.java, I am trying to access red-chip.png.

I tried many variations for this to work, right now I just have:

ImageIcon redChip = new ImageIcon("red-chip.png");

I tried changing up the path to use /resources, used the getResource function, but nothing seemed to work.

When I generate the jar using mvn package and run the jar file, it does not show the image.

I perform unzip -l <jar file> and see that my red-chip.png has been moved to the root directory for some reason.

```<code>  Length      Date    Time    Name
---------  ---------- -----   ----
      126  2019-05-30 20:03   META-INF/MANIFEST.MF
        0  2019-05-30 20:03   META-INF/
        0  2019-05-30 19:19   com/
        0  2019-05-30 19:19   com/dv/
        0  2019-05-30 19:20   com/dv/app/
        0  2019-05-30 20:03   META-INF/maven/
        0  2019-05-30 20:03   META-INF/maven/com.dv.app/
        0  2019-05-30 20:03   META-INF/maven/com.dv.app/connect4/
     4190  2019-05-30 19:20   com/dv/app/App.class
     4975  2019-05-30 19:20   com/dv/app/Board.class
      110  2019-05-29 20:29   META-INF/maven/com.dv.app/connect4/pom.properties
     7856  2019-05-30 19:32   red-chip.png
</code>```

Here is my pom.xml. Main thing to look at is the build jar plugin.

(removed useless stuff like artifactID, etc)

```<code><project xmlns="...">
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.1.0</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>lib/</classpathPrefix>
                            <mainClass>com.dv.app.App</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

So my questions are as follows:

What is the proper way to reference my png file so it will be visible in the jar?

Why was the png file located in the root in the jar?

答:
If you need to load image as an icon for application your code should be like this. This will set the icon for your application.

```<code>this.setIconImage(new ImageIcon(getClass().getResource("/red-chip.png")).getImage());
</code>```

If you need to use setIcon method, you can use

```<code>ImageIcon IC = new ImageIcon(getClass().getResource("/red-chip.png"));
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here is my current directory structure (contained inside a connect4 directory):

├── pom.xml
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       └── dv
│   │   │           └── app
│   │   │               ├── App.java
│   │   │               ├── Board.java
│   │   │
|   |   |
│   │   │
│   │   └── resources
│   │       ├── red-chip.png
│   │
│   └── test
│       ...
|
└── target
    ├── classes/com/dv/app/*.class

Essentially from Board.java, I am trying to access red-chip.png.

I tried many variations for this to work, right now I just have:

ImageIcon redChip = new ImageIcon("red-chip.png");

I tried changing up the path to use /resources, used the getResource function, but nothing seemed to work.

When I generate the jar using mvn package and run the jar file, it does not show the image.

I perform unzip -l <jar file> and see that my red-chip.png has been moved to the root directory for some reason.

  Length      Date    Time    Name
---------  ---------- -----   ----
      126  2019-05-30 20:03   META-INF/MANIFEST.MF
        0  2019-05-30 20:03   META-INF/
        0  2019-05-30 19:19   com/
        0  2019-05-30 19:19   com/dv/
        0  2019-05-30 19:20   com/dv/app/
        0  2019-05-30 20:03   META-INF/maven/
        0  2019-05-30 20:03   META-INF/maven/com.dv.app/
        0  2019-05-30 20:03   META-INF/maven/com.dv.app/connect4/
     4190  2019-05-30 19:20   com/dv/app/App.class
     4975  2019-05-30 19:20   com/dv/app/Board.class
      110  2019-05-29 20:29   META-INF/maven/com.dv.app/connect4/pom.properties
     7856  2019-05-30 19:32   red-chip.png

Here is my pom.xml. Main thing to look at is the build jar plugin.

(removed useless stuff like artifactID, etc)

<project xmlns="...">
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.1.0</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>lib/</classpathPrefix>
                            <mainClass>com.dv.app.App</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

So my questions are as follows:

What is the proper way to reference my png file so it will be visible in the jar?

Why was the png file located in the root in the jar?

Body:
If you need to load image as an icon for application your code should be like this. This will set the icon for your application.

this.setIconImage(new ImageIcon(getClass().getResource("/red-chip.png")).getImage());

If you need to use setIcon method, you can use

ImageIcon IC = new ImageIcon(getClass().getResource("/red-chip.png"));


问:
How can I get or download the app built (exe file) from appveyor after finish building
I builded an electron app on appveyor, because it uses native node module dependencies.
I needed windows version of that app.
After finishing the build process successfully, I had no idea of getting the exe file.
I think there are some apis or need some cmd on appveyor.yml file to get that. What should I add more after build?
Here is my appveyor.yml file.

```<code>image: Visual Studio 2017

platform:
  - x64

cache:
  - node_modules
  - '%USERPROFILE%\.electron'

init:
  - git config --global core.autocrlf input

install:
  - ps: Install-Product node 8 x64
  - yarn

build_script:
  - ./node_modules/.bin/electron-builder

test: off
</code>```

please explain in detail as much as possible, I have really no idea of Appveyor.

答: You can package your file as an artifact and then download it from AppVeyor. However AppVeyor removes artifacts in 6 month after creation according to the retention policy . Therefore best approach is to deploy artifact to a storage of your choice.</p>

Body:
I builded an electron app on appveyor, because it uses native node module dependencies.
I needed windows version of that app.
After finishing the build process successfully, I had no idea of getting the exe file.
I think there are some apis or need some cmd on appveyor.yml file to get that. What should I add more after build?
Here is my appveyor.yml file.

image: Visual Studio 2017

platform:
  - x64

cache:
  - node_modules
  - '%USERPROFILE%\.electron'

init:
  - git config --global core.autocrlf input

install:
  - ps: Install-Product node 8 x64
  - yarn

build_script:
  - ./node_modules/.bin/electron-builder

test: off

please explain in detail as much as possible, I have really no idea of Appveyor.


问:
How to postpone to print an error until every execution
Currently I iterate through every .py file in / directory. For each iteration, I call pycodestyle and exit as soon as I see the error.

But I want to see all the error messages for every file even if any of file had an error before << This helps developer to see which lines he/she should change in order to pass the test (linting).

If no file prints an error, don't print error. << This will be useful for my Jenkins pipeline.

```<code>for file in $(find /-type d -name test -prune -o -type f -name '*.py' -print); do
    filename=$(basename $file)
    if [[ $filename != "__init__.py" ]] ; then
        echo "$file"
        pycodestyle "${file}" || exit 1 <<< This causes an error.
                   << If it passes the linting, it doesn't exit.
    fi
done
</code>```

My solution:

Somehow I need a boolean local variable to show whether it prints error. At the end I can check the variable and returns exit or not. But I don't know how to implement this... Thanks!

答:
Instead of exiting, set a variable, which you test at the end so you exit with the proper status.

```<code>status=0
for file in $(find /-type d -name test -prune -o -type f -name '*.py' ! -name '__init__.py' -print); do
    echo "$file"
    pycodestyle "${file}" || status=1
done
exit "$status"
</code>```

Also, you can filter out __init__.py in the find command, so you don't need the if (I showed you the same thing in Exclude a certain directory while (find command) - BASH).

Also, see Why is looping over find's output bad practice?

Body:
Currently I iterate through every .py file in / directory. For each iteration, I call pycodestyle and exit as soon as I see the error.

But I want to see all the error messages for every file even if any of file had an error before << This helps developer to see which lines he/she should change in order to pass the test (linting).

If no file prints an error, don't print error. << This will be useful for my Jenkins pipeline.

for file in $(find /-type d -name test -prune -o -type f -name '*.py' -print); do
    filename=$(basename $file)
    if [[ $filename != "__init__.py" ]] ; then
        echo "$file"
        pycodestyle "${file}" || exit 1 <<< This causes an error.
                   << If it passes the linting, it doesn't exit.
    fi
done

My solution:

Somehow I need a boolean local variable to show whether it prints error. At the end I can check the variable and returns exit or not. But I don't know how to implement this... Thanks!

Body:
Instead of exiting, set a variable, which you test at the end so you exit with the proper status.

status=0
for file in $(find /-type d -name test -prune -o -type f -name '*.py' ! -name '__init__.py' -print); do
    echo "$file"
    pycodestyle "${file}" || status=1
done
exit "$status"

Also, you can filter out __init__.py in the find command, so you don't need the if (I showed you the same thing in Exclude a certain directory while (find command) - BASH).

Also, see Why is looping over find's output bad practice?


问:
Using css columns for image grid, sometimes images stack
I'm using the technique described here and have a problem where sometimes the images arrange themselves in columns as intended, but sometimes they stack underneath each other which isn't what I want.

I tried adding white-space:nowrap which gets the images to display on the same line but it also removes the column-gap and makes the images align left instead of centred.

I've created a Codepen which illustrates the problem. Set 1 stacks (bad), Set 2 is in columns (good).

Anyone have an idea why the two sets of images behave differently and a way to solve it which doesn't also sacrifice the gap and alignment?

答:
Try adding float:left to img

.img-columns {
  column-gap: 1rem;
  column-count: 2;
  white-space: normal;
}

.img-columns img {
  float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://andersons.tyssendesign.com.au/assets/css/site.combined.min.css" rel="stylesheet" />
<div class="container mx-auto px-6">
  <div class="clearfix">
    <h1 class="px-6 mb-6">Set 1</h1>
    <div class="px-6 md:float-none md:w-full mb-4  mx-auto  text-center img-columns">
      <img class="img-content lazyloaded" src="https://andersons.tyssendesign.com.au/site/assets/files/1387/s-fold-blog-1.480x0.jpg">
      <img class="img-content  lazyloaded" src="https://andersons.tyssendesign.com.au/site/assets/files/1387/s-fold-blog-2.480x0.jpg">
    </div>

    <h1 class="px-6 mb-6">Set 2</h1>
    <div class="px-6 md:float-none md:w-full mb-4  mx-auto  text-center img-columns">
      <img class="img-content lazyloaded" src="https://andersons.tyssendesign.com.au/site/assets/files/1363/bauhaus.480x0.jpg">
      <img class="img-content lazyloaded" src="https://andersons.tyssendesign.com.au/site/assets/files/1363/matka.480x0.jpg">
      <img class="img-content lazyloaded" src="https://andersons.tyssendesign.com.au/site/assets/files/1363/yokun.480x0.jpg">
    </div>

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

Body:
Try adding float:left to img

.img-columns {
  column-gap: 1rem;
  column-count: 2;
  white-space: normal;
}

.img-columns img {
  float: left;
}

<link href="https://andersons.tyssendesign.com.au/assets/css/site.combined.min.css" rel="stylesheet" />
<div class="container mx-auto px-6">
  <div class="clearfix">
    <h1 class="px-6 mb-6">Set 1</h1>
    <div class="px-6 md:float-none md:w-full mb-4  mx-auto  text-center img-columns">
      <img class="img-content lazyloaded" src="https://andersons.tyssendesign.com.au/site/assets/files/1387/s-fold-blog-1.480x0.jpg">
      <img class="img-content  lazyloaded" src="https://andersons.tyssendesign.com.au/site/assets/files/1387/s-fold-blog-2.480x0.jpg">
    </div>

    <h1 class="px-6 mb-6">Set 2</h1>
    <div class="px-6 md:float-none md:w-full mb-4  mx-auto  text-center img-columns">
      <img class="img-content lazyloaded" src="https://andersons.tyssendesign.com.au/site/assets/files/1363/bauhaus.480x0.jpg">
      <img class="img-content lazyloaded" src="https://andersons.tyssendesign.com.au/site/assets/files/1363/matka.480x0.jpg">
      <img class="img-content lazyloaded" src="https://andersons.tyssendesign.com.au/site/assets/files/1363/yokun.480x0.jpg">
    </div>

  </div>
</div>


问:
Php datastore script fails on development server while runs as expected on production server
Have a look on the following datastore script:

```<code><?php
use google\appengine\datastore\v4\Mutation\Operation;
use google\appengine\datastore\v4\BeginTransactionRequest;
use google\appengine\datastore\v4\BeginTransactionResponse;
use google\appengine\datastore\v4\CommitRequest;
use google\appengine\datastore\v4\CommitRequest\Mode;
use google\appengine\datastore\v4\CommitResponse;
use google\appengine\datastore\v4\RollbackRequest;
use google\appengine\datastore\v4\RollbackResponse;
use google\appengine\runtime\ApiProxy;
use google\appengine\runtime\ApplicationError;

function beginTransaction(){
    global $request, $response;
    $request = new BeginTransactionRequest();
    $request->setCrossGroup(true);
    $response = new BeginTransactionResponse();
    try{
        ApiProxy::makeSyncCall('datastore_v4', 'BeginTransaction', $request, $response, 60);
    }
    catch(ApplicationError $e){
        echo $e->getMessage();
        exit();
    }

    $request = new CommitRequest();
    $request->setTransaction($response->transaction);
    $request->setMode(Mode::TRANSACTIONAL);
}

function prepareEntity($entity, $name, $author, $channel){
    global $projectId;
    $entity->mutableKey()->mutablePartitionId()->setDatasetId($projectId);
    $entity->mutableKey()->addPathElement()->setKind('Books');
    $entity->addProperty()->setName('Name')->mutableValue()->setStringValue($name);
    $entity->addProperty()->setName('Author')->mutableValue()->setStringValue($author);
    $entity->addProperty()->setName('Channel')->mutableValue()->setStringValue($channel);
}

function commit(){
    global $request, $response;
    $response = new CommitResponse();
    try{
        ApiProxy::makeSyncCall('datastore_v4', 'Commit', $request, $response, 60);
    }
    catch(ApplicationError $e){
        echo $e->getMessage();
        exit();
    }
}

$projectId = $_SERVER['APPLICATION_ID'];
beginTransaction();

prepareEntity(
    $request->addMutation()->setOp(Operation::INSERT)->mutableEntity(),
    'Contemporary Abstract Algebra',
    'J Gallian',
    'Mutation'
    );

prepareEntity(
    $request->addMutation()->setOp(Operation::INSERT)->mutableEntity(),
    'Principals of Mathematical Analysis',
    'Rudin',
    'Mutation'
    );
commit('Mutation Commit');
echo "<h2>Mutation Commit</h2>";
foreach($response->getMutationResultList() as $mutationResult){
    echo 'Book@'. end($mutationResult->getKey()->getPathElementList())->getId(). '<br/>';
}
echo '<hr/>';

beginTransaction();
prepareEntity(
    $request->mutableDeprecatedMutation()->addInsertAutOId(),
    'Contemporary Abstract Algebra',
    'J Gallian',
    'Deprecated Mutation'
    );

prepareEntity(
    $request->mutableDeprecatedMutation()->addInsertAutOId(),
    'Principals of Mathematical Analysis',
    'Rudin',
    'Deprecated Mutation'
    );

commit();
echo "<h2>Deprecated Mutation Commit</h2>";
foreach($response->getDeprecatedMutationResult()->getInsertAutoIdKeyList() as $key){
    echo 'Book@'. end($key->getPathElementList())->getId(). '<br/>';
}
echo '<hr/>';
</code>```

In this script the commits using mutation don't work on the development server. Neither they save the data nor they throw any error. Though they work as expected on the production server. The deprecated mutations work as expected on both development server and production server. I debugged and found that make_call function call in use google\appengine\runtime\RealApiProxy is unable to produce a response. Can someone please explain this behavior. Is that a bug in the development runtime?

答: I expect your problem is with the use google\appengine\datastore\v4\... lines, you should probably use the google-cloud-datastore libraries.  The getting started guide is at https://cloud.google.com/php/getting-started/using-cloud-datastore .

Body:
Have a look on the following datastore script:

<?php
use google\appengine\datastore\v4\Mutation\Operation;
use google\appengine\datastore\v4\BeginTransactionRequest;
use google\appengine\datastore\v4\BeginTransactionResponse;
use google\appengine\datastore\v4\CommitRequest;
use google\appengine\datastore\v4\CommitRequest\Mode;
use google\appengine\datastore\v4\CommitResponse;
use google\appengine\datastore\v4\RollbackRequest;
use google\appengine\datastore\v4\RollbackResponse;
use google\appengine\runtime\ApiProxy;
use google\appengine\runtime\ApplicationError;

function beginTransaction(){
    global $request, $response;
    $request = new BeginTransactionRequest();
    $request->setCrossGroup(true);
    $response = new BeginTransactionResponse();
    try{
        ApiProxy::makeSyncCall('datastore_v4', 'BeginTransaction', $request, $response, 60);
    }
    catch(ApplicationError $e){
        echo $e->getMessage();
        exit();
    }

    $request = new CommitRequest();
    $request->setTransaction($response->transaction);
    $request->setMode(Mode::TRANSACTIONAL);
}

function prepareEntity($entity, $name, $author, $channel){
    global $projectId;
    $entity->mutableKey()->mutablePartitionId()->setDatasetId($projectId);
    $entity->mutableKey()->addPathElement()->setKind('Books');
    $entity->addProperty()->setName('Name')->mutableValue()->setStringValue($name);
    $entity->addProperty()->setName('Author')->mutableValue()->setStringValue($author);
    $entity->addProperty()->setName('Channel')->mutableValue()->setStringValue($channel);
}

function commit(){
    global $request, $response;
    $response = new CommitResponse();
    try{
        ApiProxy::makeSyncCall('datastore_v4', 'Commit', $request, $response, 60);
    }
    catch(ApplicationError $e){
        echo $e->getMessage();
        exit();
    }
}

$projectId = $_SERVER['APPLICATION_ID'];
beginTransaction();

prepareEntity(
    $request->addMutation()->setOp(Operation::INSERT)->mutableEntity(),
    'Contemporary Abstract Algebra',
    'J Gallian',
    'Mutation'
    );

prepareEntity(
    $request->addMutation()->setOp(Operation::INSERT)->mutableEntity(),
    'Principals of Mathematical Analysis',
    'Rudin',
    'Mutation'
    );
commit('Mutation Commit');
echo "
Mutation Commit
";
foreach($response->getMutationResultList() as $mutationResult){
    echo 'Book@'. end($mutationResult->getKey()->getPathElementList())->getId(). '
';
}
echo '
';

beginTransaction();
prepareEntity(
    $request->mutableDeprecatedMutation()->addInsertAutOId(),
    'Contemporary Abstract Algebra',
    'J Gallian',
    'Deprecated Mutation'
    );

prepareEntity(
    $request->mutableDeprecatedMutation()->addInsertAutOId(),
    'Principals of Mathematical Analysis',
    'Rudin',
    'Deprecated Mutation'
    );

commit();
echo "
Deprecated Mutation Commit
";
foreach($response->getDeprecatedMutationResult()->getInsertAutoIdKeyList() as $key){
    echo 'Book@'. end($key->getPathElementList())->getId(). '
';
}
echo '
';

In this script the commits using mutation don't work on the development server. Neither they save the data nor they throw any error. Though they work as expected on the production server. The deprecated mutations work as expected on both development server and production server. I debugged and found that make_call function call in use google\appengine\runtime\RealApiProxy is unable to produce a response. Can someone please explain this behavior. Is that a bug in the development runtime?


问:
How does C++ placement delete work internally (C++ runtime)? How to overcome its limitation?
C++ is asymmetric of placement new and placement delete. We are allowed to overload placement new in almost arbitrary ways. However, the placement delete functions are only called from placement new expressions. In particular, they are called if the constructor of the object throws an exception. There's no way to invoke placement delete for application code at all.

I have following confusions and questions to be clarified:

1) Why can't C++ compiler simply reject a placement new method signature if there's no placement delete counterpart defined? Doing that could help kill the possibilities of memory leak in that context.

2) If I have multiple memory pools (managed by application code) and I want different placement new to allocate memory from different pools, there's simply no way to support that due to the the fact that there's no way to know which memory pool the pointer came from in operator delete? (operator delete only has void* info). Is there any way I can accomplish this in C++?

```<code>struct Node {
    void* operator new(size_t size, Strategy s) {
        // Depend on different strategy, allocate memory
        // from different Memory pool
    }

    void operator delete(void* memory, Strategy s) {
        // Return the memory to different Memory pool
        // depends on the Strategy
        // However this delete will only be invoked by
        // c++ runtime if Node constructor throws.
    }

    void operator delete(void* memory, size_t s) {
        // This delete doesn't have any clue about the
        // the strategy. Hence, it can't decide which
        // Memory pool to return to.
    }
}
</code>```

3) In the context of placement new, C++ runtime will invoke placement delete with same argument. How does C++ runtime accomplish this?

答:
Having looked it up: you're supposed to provide a Node::destroy that gets rid of the node and returns it to your local heap.

If these were generic new with for void* we would have the following destroy:

```<code>template<class T> void destroy (Strategy s, T* ptr)
{
    ptr->~T();
    // return to custom heap
 }
</code>```

You could use fancy tricks to get rid of strategy, like checking what heap ptr is in, or storing it at a negative offset in new.

Useless historical answer:

It's been a long time, but I remember the syntax being

```<code>delete (strategy) pointer;
</code>```

This appears to be vendor specific nonsense from BC4.5.

Body:
C++ is asymmetric of placement new and placement delete. We are allowed to overload placement new in almost arbitrary ways. However, the placement delete functions are only called from placement new expressions. In particular, they are called if the constructor of the object throws an exception. There's no way to invoke placement delete for application code at all.

I have following confusions and questions to be clarified:

1) Why can't C++ compiler simply reject a placement new method signature if there's no placement delete counterpart defined? Doing that could help kill the possibilities of memory leak in that context.

2) If I have multiple memory pools (managed by application code) and I want different placement new to allocate memory from different pools, there's simply no way to support that due to the the fact that there's no way to know which memory pool the pointer came from in operator delete? (operator delete only has void* info). Is there any way I can accomplish this in C++?

struct Node {
    void* operator new(size_t size, Strategy s) {
        // Depend on different strategy, allocate memory
        // from different Memory pool
    }

    void operator delete(void* memory, Strategy s) {
        // Return the memory to different Memory pool
        // depends on the Strategy
        // However this delete will only be invoked by
        // c++ runtime if Node constructor throws.
    }

    void operator delete(void* memory, size_t s) {
        // This delete doesn't have any clue about the
        // the strategy. Hence, it can't decide which
        // Memory pool to return to.
    }
}

3) In the context of placement new, C++ runtime will invoke placement delete with same argument. How does C++ runtime accomplish this?

Body:
Having looked it up: you're supposed to provide a Node::destroy that gets rid of the node and returns it to your local heap.

If these were generic new with for void* we would have the following destroy:

template<class T> void destroy (Strategy s, T* ptr)
{
    ptr->~T();
    // return to custom heap
 }

You could use fancy tricks to get rid of strategy, like checking what heap ptr is in, or storing it at a negative offset in new.

Useless historical answer:

It's been a long time, but I remember the syntax being

delete (strategy) pointer;

This appears to be vendor specific nonsense from BC4.5.


问:
Clear explanation of the "theta join" in relational algebra?
I'm looking for a clear, basic explanation of the concept of theta join in relational algebra and perhaps an example (using SQL perhaps) to illustrate its usage.

If I understand it correctly, the theta join is a natural join with a condition added in. So, whereas the natural join enforces equality between attributes of the same name (and removes the duplicate?), the theta join does the same thing but adds in a condition. Do I have this right? Any clear explanation, in simple terms (for a non-mathmetician) would be greatly appreciated.

Also (sorry to just throw this in at the end, but its sort of related), could someone explain the importance or idea of cartesian product? I think I'm missing something with regard to the basic concept, because to me it just seems like a restating of a basic fact, i.e that a set of 13 X a set of 4 = 52...

答:
All joins can be thought of as beginning with a cross product and then weeding out certain rows.  A natural join weeds out all rows in which columns of the same name in the two tables being joine have different values.  An equijoin weeds out all rows in which the specified columns have different values.  And a theta-join weeds out all rows in which the specified columns do not stand in the specified relationship (<, >, or whatever; in principle it could be is_prefix_of as a relationship beween strings).

Update: Note that outer joins cannot be understood this way, because they synthesize information (that is, nulls) out of nothing.

ContentLicense: CC BY-SA 3.0


问:
How can I paginate get_context_data choosing from among multiple context objects?
I am trying to paginate get_context_data from views.py, by selecting from among multiple context objects.  Only two choices are shown in the code example conditional statements, but I have several more choices which basically cover all choices from the form submission.  Only one context is returned, in the end however, passing the context to the template view for pagination.

I tried also setting pagination globally in settings.py, but it is not working.

I have viewed the article below, previously, as a guide to pagination on get-context-objects.

How to perform pagination for context object in django?

From views.py:

```<code>from django.shortcuts import render
import django.views.generic
from django.http import HttpResponse
from django.template import loader
from django.template import RequestContext
from ephemera.models import *
from ephemera.serializers import ItemSerializer
from rest_framework import generics
from ephemera.forms import SearchForm, AdvSearchForm
from itertools import chain
from django.core.paginator import Paginator
from django.core.paginator import EmptyPage
from django.core.paginator import PageNotAnInteger

class SearchResultsAdvancedView(django.views.generic.ListView):
    template_name = 'ephemera/searchresults_advanced.html'
    form = AdvSearchForm()
    paginate_by = 10
    model = Item

    def get_context_data(self, **kwargs):
        context = super(SearchResultsAdvancedView, self).get_context_data(**kwargs)

        choose_collection = self.request.GET.get('choose_collection')
        user_input = self.request.GET.get('user_input')
        choose_item = self.request.GET.get('choose_item')

        bookpage = False
        imagepage = False

        if choose_collection == 'All' and user_input == '' and choose_item == 'book':
            context['book_qs'] = Item.objects.raw('SELECT  * FROM   ephemera_item WHERE ephemera_item.material_type LIKE %s', ['book']);
            bookpage = True
        elif choose_collection == 'All' and user_input == '' and choose_item == 'image':
            context['image_qs'] = Item.objects.raw('SELECT  * FROM   ephemera_item WHERE ephemera_item.material_type LIKE %s', ['image']);
            imagepage = True

        if bookpage:
            paginator = Paginator(context, self.paginate_by)
            page = self.request.GET.get('page')
            try:
                book_qs = paginator.page(page)
            except PageNotAnInteger:
                book_qs = paginator.page(1)
            except EmptyPage:
                book_qs = paginator.page(paginator.num_pages)
            context['book_qs'] = book_qs

        elif imagepage:
            paginator = Paginator(context, self.paginate_by)
            page = self.request.GET.get('page')
            try:
                image_qs = paginator.page(page)
            except PageNotAnInteger:
                image_qs = paginator.page(1)
            except EmptyPage:
                image_qs = paginator.page(paginator.num_pages)
            context['image_qs'] = image_qs

        return context
</code>```

Errors returned include:

Exception Value:    unhashable type: 'slice'

Exception Location:     c:\users\administrator\appdata\local\programs\python\python36-32\lib\site-packages\django\core\paginator.py in page, line 70

答:
One problem in the original code example is the RawQuerySets do not work for the pagination code shown in get_context_data, and those should be model objects, with filters or else the pagination code will fail. Ex.

```<code>    mydata = self.model.objects.filter(material_type__icontains = 'book')

</code>```

In this case, however, the RawQuerySets, are needed and useful due to additional (not shown) queries with complex inner joins etc., difficult to accomplish with filters.

One solution for casting a raw query set as a list for pagination
 is answered in:

Also a django paginator module for RawQuerySet is available to help with this problem linked in that post.

django-paginator-rawqueryset

With the help of the module, the raw query sets can be used effectively with the given paginator code to utilize context objects for returning a context to be passed to the template.  The template then, along with typical code to show the page navigation, is also able to utilize the variables attached to the context in order to display the data as needed.

```<code>    {% if book_qs %}
    {% endif %}

    {% if image_qs %}
    {% endif %}
</code>```

The problem example shown, from views.py, is a bit 'brute force' and could be coded more compactly with the help of definitions within the class as shown in the first answer.  Another solution to the problem, using the module, is shown here:

```<code>    from rawpaginator.paginator import Paginator
    from django.core.paginator import EmptyPage
    from django.core.paginator import PageNotAnInteger

    class SearchResultsAdvancedView(django.views.generic.ListView):
        template_name = 'ephemera/searchresults_advanced.html'
        form = AdvSearchForm()
        paginate_by = 10
        model = Item

        def get_context_data(self, **kwargs):
            context = super(SearchResultsAdvancedView, self).get_context_data(**kwargs)

            choose_collection = self.request.GET.get('choose_collection')
            user_input = self.request.GET.get('user_input')
            choose_item = self.request.GET.get('choose_item')

            bookpage = False
            imagepage = False

            if choose_collection == 'All' and user_input == '' and choose_item == 'book':
                mydata = Item.objects.raw('SELECT  * FROM   ephemera_item WHERE ephemera_item.material_type LIKE %s', ['book']);
                bookpage = True
            elif choose_collection == 'All' and user_input == '' and choose_item == 'image':
                mydata = Item.objects.raw('SELECT  * FROM   ephemera_item WHERE ephemera_item.material_type LIKE %s', ['image']);
                imagepage = True

             paginator = Paginator(mydata, self.paginate_by)
             page = self.request.GET.get('page')

            if bookpage:
                try:
                    book_qs = paginator.page(page)
                except PageNotAnInteger:
                    book_qs = paginator.page(1)
                except EmptyPage:
                    book_qs = paginator.page(paginator.num_pages)
                context['book_qs'] = book_qs

            elif imagepage:
                try:
                    image_qs = paginator.page(page)
                except PageNotAnInteger:
                    image_qs = paginator.page(1)
                except EmptyPage:
                    image_qs = paginator.page(paginator.num_pages)
                context['image_qs'] = image_qs

            return context
</code>```

Body:
I am trying to paginate get_context_data from views.py, by selecting from among multiple context objects.  Only two choices are shown in the code example conditional statements, but I have several more choices which basically cover all choices from the form submission.  Only one context is returned, in the end however, passing the context to the template view for pagination.

I tried also setting pagination globally in settings.py, but it is not working.

I have viewed the article below, previously, as a guide to pagination on get-context-objects.

How to perform pagination for context object in django?

From views.py:

from django.shortcuts import render
import django.views.generic
from django.http import HttpResponse
from django.template import loader
from django.template import RequestContext
from ephemera.models import *
from ephemera.serializers import ItemSerializer
from rest_framework import generics
from ephemera.forms import SearchForm, AdvSearchForm
from itertools import chain
from django.core.paginator import Paginator
from django.core.paginator import EmptyPage
from django.core.paginator import PageNotAnInteger

class SearchResultsAdvancedView(django.views.generic.ListView):
    template_name = 'ephemera/searchresults_advanced.html'
    form = AdvSearchForm()
    paginate_by = 10
    model = Item

    def get_context_data(self, **kwargs):
        context = super(SearchResultsAdvancedView, self).get_context_data(**kwargs)

        choose_collection = self.request.GET.get('choose_collection')
        user_input = self.request.GET.get('user_input')
        choose_item = self.request.GET.get('choose_item')

        bookpage = False
        imagepage = False

        if choose_collection == 'All' and user_input == '' and choose_item == 'book':
            context['book_qs'] = Item.objects.raw('SELECT  * FROM   ephemera_item WHERE ephemera_item.material_type LIKE %s', ['book']);
            bookpage = True
        elif choose_collection == 'All' and user_input == '' and choose_item == 'image':
            context['image_qs'] = Item.objects.raw('SELECT  * FROM   ephemera_item WHERE ephemera_item.material_type LIKE %s', ['image']);
            imagepage = True

        if bookpage:
            paginator = Paginator(context, self.paginate_by)
            page = self.request.GET.get('page')
            try:
                book_qs = paginator.page(page)
            except PageNotAnInteger:
                book_qs = paginator.page(1)
            except EmptyPage:
                book_qs = paginator.page(paginator.num_pages)
            context['book_qs'] = book_qs

        elif imagepage:
            paginator = Paginator(context, self.paginate_by)
            page = self.request.GET.get('page')
            try:
                image_qs = paginator.page(page)
            except PageNotAnInteger:
                image_qs = paginator.page(1)
            except EmptyPage:
                image_qs = paginator.page(paginator.num_pages)
            context['image_qs'] = image_qs

        return context

Errors returned include:

Exception Value:    unhashable type: 'slice'

Exception Location:     c:\users\administrator\appdata\local\programs\python\python36-32\lib\site-packages\django\core\paginator.py in page, line 70

Body:
One problem in the original code example is the RawQuerySets do not work for the pagination code shown in get_context_data, and those should be model objects, with filters or else the pagination code will fail. Ex.

    mydata = self.model.objects.filter(material_type__icontains = 'book')

In this case, however, the RawQuerySets, are needed and useful due to additional (not shown) queries with complex inner joins etc., difficult to accomplish with filters.

One solution for casting a raw query set as a list for pagination
 is answered in:

Also a django paginator module for RawQuerySet is available to help with this problem linked in that post.

django-paginator-rawqueryset

With the help of the module, the raw query sets can be used effectively with the given paginator code to utilize context objects for returning a context to be passed to the template.  The template then, along with typical code to show the page navigation, is also able to utilize the variables attached to the context in order to display the data as needed.

    {% if book_qs %}
    {% endif %}

    {% if image_qs %}
    {% endif %}

The problem example shown, from views.py, is a bit 'brute force' and could be coded more compactly with the help of definitions within the class as shown in the first answer.  Another solution to the problem, using the module, is shown here:

    from rawpaginator.paginator import Paginator
    from django.core.paginator import EmptyPage
    from django.core.paginator import PageNotAnInteger

    class SearchResultsAdvancedView(django.views.generic.ListView):
        template_name = 'ephemera/searchresults_advanced.html'
        form = AdvSearchForm()
        paginate_by = 10
        model = Item

        def get_context_data(self, **kwargs):
            context = super(SearchResultsAdvancedView, self).get_context_data(**kwargs)

            choose_collection = self.request.GET.get('choose_collection')
            user_input = self.request.GET.get('user_input')
            choose_item = self.request.GET.get('choose_item')

            bookpage = False
            imagepage = False

            if choose_collection == 'All' and user_input == '' and choose_item == 'book':
                mydata = Item.objects.raw('SELECT  * FROM   ephemera_item WHERE ephemera_item.material_type LIKE %s', ['book']);
                bookpage = True
            elif choose_collection == 'All' and user_input == '' and choose_item == 'image':
                mydata = Item.objects.raw('SELECT  * FROM   ephemera_item WHERE ephemera_item.material_type LIKE %s', ['image']);
                imagepage = True

             paginator = Paginator(mydata, self.paginate_by)
             page = self.request.GET.get('page')

            if bookpage:
                try:
                    book_qs = paginator.page(page)
                except PageNotAnInteger:
                    book_qs = paginator.page(1)
                except EmptyPage:
                    book_qs = paginator.page(paginator.num_pages)
                context['book_qs'] = book_qs

            elif imagepage:
                try:
                    image_qs = paginator.page(page)
                except PageNotAnInteger:
                    image_qs = paginator.page(1)
                except EmptyPage:
                    image_qs = paginator.page(paginator.num_pages)
                context['image_qs'] = image_qs

            return context


问:
java.lang.ClassNotFoundException: Recorder when running Recorder.scala in IntelliJ
I am just getting started with Gatling. I followed the instructions on this page but I am stuck in the last part. I want to run Recorder.scala and/or Engine.scala directly from Intellij, but I get an error as following:

C:\jdk12\bin\java.exe "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2019.1.2\lib\idea_rt.jar=59109:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2019.1.2\bin" -Dfile.encoding=UTF-8 -classpath C:\etc\ws\Gatling\target\test-classes;C:\Users\PCUSER\.m2\repository\io\gatling\highcharts\gatling-charts-highcharts\3.1.2\gatling-charts-highcharts-3.1.2.jar;C:\Users\PCUSER\.m2\repository\org\scala-lang\scala-library\2.12.8\scala-library-2.12.8.jar;C:\Users\PCUSER\.m2\repository\io\gatling\gatling-charts\3.1.2\gatling-charts-3.1.2.jar;C:\Users\PCUSER\.m2\repository\com\tdunning\t-digest\3.1\t-digest-3.1.jar;C:\Users\PCUSER\.m2\repository\io\gatling\gatling-http-client\3.1.2\gatling-http-client-3.1.2.jar;C:\Users\PCUSER\.m2\repository\io\gatling\gatling-netty-util\3.1.2\gatling-netty-util-3.1.2.jar;C:\Users\PCUSER\.m2\repository\io\netty\netty-buffer\4.1.36.Final\netty-buffer-4.1.36.Final.jar;C:\Users\PCUSER\.m2\repository\io\netty\netty-handler\4.1.36.Final\netty-handler-4.1.36.Final.jar;C:\Users\PCUSER\.m2\repository\io\netty\netty-handler-proxy\4.1.36.Final\netty-handler-proxy-4.1.36.Final.jar;C:\Users\PCUSER\.m2\repository\io\netty\netty-codec-socks\4.1.36.Final\netty-codec-socks-4.1.36.Final.jar;C:\Users\PCUSER\.m2\repository\io\netty\netty-resolver-dns\4.1.36.Final\netty-resolver-dns-4.1.36.Final.jar;C:\Users\PCUSER\.m2\repository\io\netty\netty-resolver\4.1.36.Final\netty-resolver-4.1.36.Final.jar;C:\Users\PCUSER\.m2\repository\io\netty\netty-codec-dns\4.1.36.Final\netty-codec-dns-4.1.36.Final.jar;C:\Users\PCUSER\.m2\repository\io\netty\netty-transport-native-epoll\4.1.36.Final\netty-transport-native-epoll-4.1.36.Final-linux-x86_64.jar;C:\Users\PCUSER\.m2\repository\io\netty\netty-transport-native-unix-common\4.1.36.Final\netty-transport-native-unix-common-4.1.36.Final.jar;C:\Users\PCUSER\.m2\repository\io\netty\netty-codec-http2\4.1.36.Final\netty-codec-http2-4.1.36.Final.jar;C:\Users\PCUSER\.m2\repository\io\netty\netty-tcnative-boringssl-static\2.0.25.Final\netty-tcnative-boringssl-static-2.0.25.Final.jar;C:\Users\PCUSER\.m2\repository\com\sun\activation\javax.activation\1.2.0\javax.activation-1.2.0.jar;C:\Users\PCUSER\.m2\repository\org\slf4j\slf4j-api\1.7.26\slf4j-api-1.7.26.jar;C:\Users\PCUSER\.m2\repository\com\typesafe\scala-logging\scala-logging_2.12\3.9.2\scala-logging_2.12-3.9.2.jar;C:\Users\PCUSER\.m2\repository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;C:\Users\PCUSER\.m2\repository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;C:\Users\PCUSER\.m2\repository\io\gatling\gatling-commons\3.1.2\gatling-commons-3.1.2.jar;C:\Users\PCUSER\.m2\repository\org\scala-lang\scala-reflect\2.12.8\scala-reflect-2.12.8.jar;C:\Users\PCUSER\.m2\repository\com\typesafe\config\1.3.4\config-1.3.4.jar;C:\Users\PCUSER\.m2\repository\com\dongxiguo\fastring_2.12\1.0.0\fastring_2.12-1.0.0.jar;C:\Users\PCUSER\.m2\repository\io\suzaku\boopickle_2.12\1.3.1\boopickle_2.12-1.3.1.jar;C:\Users\PCUSER\.m2\repository\org\typelevel\spire-macros_2.12\0.16.1\spire-macros_2.12-0.16.1.jar;C:\Users\PCUSER\.m2\repository\org\scala-lang\modules\scala-collection-compat_2.12\0.3.0\scala-collection-compat_2.12-0.3.0.jar;C:\Users\PCUSER\.m2\repository\com\softwaremill\quicklens\quicklens_2.12\1.4.12\quicklens_2.12-1.4.12.jar;C:\Users\PCUSER\.m2\repository\org\scala-lang\modules\scala-java8-compat_2.12\0.9.0\scala-java8-compat_2.12-0.9.0.jar;C:\Users\PCUSER\.m2\repository\com\eatthepath\fast-uuid\0.1\fast-uuid-0.1.jar;C:\Users\PCUSER\.m2\repository\io\gatling\gatling-app\3.1.2\gatling-app-3.1.2.jar;C:\Users\PCUSER\.m2\repository\io\gatling\gatling-core\3.1.2\gatling-core-3.1.2.jar;C:\Users\PCUSER\.m2\repository\com\typesafe\akka\akka-slf4j_2.12\2.5.22\akka-slf4j_2.12-2.5.22.jar;C:\Users\PCUSER\.m2\repository\org\simpleflatmapper\lightning-csv\6.7.0\lightning-csv-6.7.0.jar;C:\Users\PCUSER\.m2\repository\org\simpleflatmapper\sfm-util\6.7.0\sfm-util-6.7.0.jar;C:\Users\PCUSER\.m2\repository\com\github\ben-manes\caffeine\caffeine\2.7.0\caffeine-2.7.0.jar;C:\Users\PCUSER\.m2\repository\org\checkerframework\checker-qual\2.6.0\checker-qual-2.6.0.jar;C:\Users\PCUSER\.m2\repository\com\google\errorprone\error_prone_annotations\2.3.3\error_prone_annotations-2.3.3.jar;C:\Users\PCUSER\.m2\repository\io\pebbletemplates\pebble\3.0.9\pebble-3.0.9.jar;C:\Users\PCUSER\.m2\repository\org\unbescape\unbescape\1.1.6.RELEASE\unbescape-1.1.6.RELEASE.jar;C:\Users\PCUSER\.m2\repository\org\scala-lang\modules\scala-parser-combinators_2.12\1.1.2\scala-parser-combinators_2.12-1.1.2.jar;C:\Users\PCUSER\.m2\repository\com\github\scopt\scopt_2.12\3.7.1\scopt_2.12-3.7.1.jar;C:\Users\PCUSER\.m2\repository\io\gatling\jsonpath_2.12\0.6.14\jsonpath_2.12-0.6.14.jar;C:\Users\PCUSER\.m2\repository\org\jodd\jodd-json\5.0.13\jodd-json-5.0.13.jar;C:\Users\PCUSER\.m2\repository\org\jodd\jodd-bean\5.0.13\jodd-bean-5.0.13.jar;C:\Users\PCUSER\.m2\repository\org\jodd\jodd-core\5.0.13\jodd-core-5.0.13.jar;C:\Users\PCUSER\.m2\repository\net\sf\saxon\Saxon-HE\9.9.1-2\Saxon-HE-9.9.1-2.jar;C:\Users\PCUSER\.m2\repository\com\ibm\icu\icu4j\63.1\icu4j-63.1.jar;C:\Users\PCUSER\.m2\repository\org\jodd\jodd-lagarto\5.0.13\jodd-lagarto-5.0.13.jar;C:\Users\PCUSER\.m2\repository\org\jodd\jodd-log\5.0.13\jodd-log-5.0.13.jar;C:\Users\PCUSER\.m2\repository\io\gatling\gatling-http\3.1.2\gatling-http-3.1.2.jar;C:\Users\PCUSER\.m2\repository\org\scala-lang\modules\scala-xml_2.12\1.2.0\scala-xml_2.12-1.2.0.jar;C:\Users\PCUSER\.m2\repository\io\gatling\gatling-jms\3.1.2\gatling-jms-3.1.2.jar;C:\Users\PCUSER\.m2\repository\org\apache\geronimo\specs\geronimo-jms_1.1_spec\1.1.1\geronimo-jms_1.1_spec-1.1.1.jar;C:\Users\PCUSER\.m2\repository\io\gatling\gatling-jdbc\3.1.2\gatling-jdbc-3.1.2.jar;C:\Users\PCUSER\.m2\repository\io\gatling\gatling-redis\3.1.2\gatling-redis-3.1.2.jar;C:\Users\PCUSER\.m2\repository\net\debasishg\redisclient_2.12\3.9\redisclient_2.12-3.9.jar;C:\Users\PCUSER\.m2\repository\org\apache\commons\commons-pool2\2.6.0\commons-pool2-2.6.0.jar;C:\Users\PCUSER\.m2\repository\io\gatling\gatling-graphite\3.1.2\gatling-graphite-3.1.2.jar;C:\Users\PCUSER\.m2\repository\org\hdrhistogram\HdrHistogram\2.1.11\HdrHistogram-2.1.11.jar;C:\Users\PCUSER\.m2\repository\io\gatling\gatling-recorder\3.1.2\gatling-recorder-3.1.2.jar;C:\Users\PCUSER\.m2\repository\org\scala-lang\modules\scala-swing_2.12\2.1.1\scala-swing_2.12-2.1.1.jar;C:\Users\PCUSER\.m2\repository\com\fasterxml\jackson\core\jackson-databind\2.9.8\jackson-databind-2.9.8.jar;C:\Users\PCUSER\.m2\repository\com\fasterxml\jackson\core\jackson-annotations\2.9.0\jackson-annotations-2.9.0.jar;C:\Users\PCUSER\.m2\repository\com\fasterxml\jackson\core\jackson-core\2.9.8\jackson-core-2.9.8.jar;C:\Users\PCUSER\.m2\repository\org\json4s\json4s-jackson_2.12\3.6.5\json4s-jackson_2.12-3.6.5.jar;C:\Users\PCUSER\.m2\repository\org\json4s\json4s-core_2.12\3.6.5\json4s-core_2.12-3.6.5.jar;C:\Users\PCUSER\.m2\repository\org\json4s\json4s-ast_2.12\3.6.5\json4s-ast_2.12-3.6.5.jar;C:\Users\PCUSER\.m2\repository\org\json4s\json4s-scalap_2.12\3.6.5\json4s-scalap_2.12-3.6.5.jar;C:\Users\PCUSER\.m2\repository\com\thoughtworks\paranamer\paranamer\2.8\paranamer-2.8.jar;C:\Users\PCUSER\.m2\repository\org\bouncycastle\bcpkix-jdk15on\1.61\bcpkix-jdk15on-1.61.jar;C:\Users\PCUSER\.m2\repository\org\bouncycastle\bcprov-jdk15on\1.61\bcprov-jdk15on-1.61.jar;C:\Users\PCUSER\.m2\repository\io\netty\netty-codec-http\4.1.36.Final\netty-codec-http-4.1.36.Final.jar;C:\Users\PCUSER\.m2\repository\io\netty\netty-common\4.1.36.Final\netty-common-4.1.36.Final.jar;C:\Users\PCUSER\.m2\repository\io\netty\netty-transport\4.1.36.Final\netty-transport-4.1.36.Final.jar;C:\Users\PCUSER\.m2\repository\io\netty\netty-codec\4.1.36.Final\netty-codec-4.1.36.Final.jar;C:\Users\PCUSER\.m2\repository\com\typesafe\akka\akka-actor_2.12\2.5.22\akka-actor_2.12-2.5.22.jar Recorder
Error: Could not find or load main class Recorder
Caused by: java.lang.ClassNotFoundException: Recorder
```

I have tried using JDK12, it does not work.
Running the standalone recorder.bat works just fine.

答:
This works now. I failed to add the following in POM.XML as described in https://gatling.io/docs/3.1/installation/#with-maven.</p>

```<code><build>
        <sourceDirectory>src/main/scala</sourceDirectory>
        <testSourceDirectory>src/test/scala</testSourceDirectory>
        <plugins>
                <plugin>
                        <groupId>net.alchim31.maven</groupId>
                        <artifactId>scala-maven-plugin</artifactId>
                        <version>MANUALLY_REPLACE_WITH_LATEST_VERSION</version>
<configuration>
  <args>
    <arg>-target:jvm-1.8</arg>
    <arg>-deprecation</arg>
    <arg>-feature</arg>
    <arg>-unchecked</arg>
    <arg>-language:implicitConversions</arg>
    <arg>-language:postfixOps</arg>
  </args>
</configuration>
                        <executions>
                                <execution>
                                        <goals>
                                                <goal>compile</goal>
                                                <goal>testCompile</goal>
                                        </goals>
                                </execution>
                        </executions>
                </plugin>
        </plugins>
</build>
</code>```

Body:
I am just getting started with Gatling. I followed the instructions on this page but I am stuck in the last part. I want to run Recorder.scala and/or Engine.scala directly from Intellij, but I get an error as following:

C:\jdk12\bin\java.exe "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2019.1.2\lib\idea_rt.jar=59109:C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2019.1.2\bin" -Dfile.encoding=UTF-8 -classpath C:\etc\ws\Gatling\target\test-classes;C:\Users\PCUSER\.m2\repository\io\gatling\highcharts\gatling-charts-highcharts\3.1.2\gatling-charts-highcharts-3.1.2.jar;C:\Users\PCUSER\.m2\repository\org\scala-lang\scala-library\2.12.8\scala-library-2.12.8.jar;C:\Users\PCUSER\.m2\repository\io\gatling\gatling-charts\3.1.2\gatling-charts-3.1.2.jar;C:\Users\PCUSER\.m2\repository\com\tdunning\t-digest\3.1\t-digest-3.1.jar;C:\Users\PCUSER\.m2\repository\io\gatling\gatling-http-client\3.1.2\gatling-http-client-3.1.2.jar;C:\Users\PCUSER\.m2\repository\io\gatling\gatling-netty-util\3.1.2\gatling-netty-util-3.1.2.jar;C:\Users\PCUSER\.m2\repository\io\netty\netty-buffer\4.1.36.Final\netty-buffer-4.1.36.Final.jar;C:\Users\PCUSER\.m2\repository\io\netty\netty-handler\4.1.36.Final\netty-handler-4.1.36.Final.jar;C:\Users\PCUSER\.m2\repository\io\netty\netty-handler-proxy\4.1.36.Final\netty-handler-proxy-4.1.36.Final.jar;C:\Users\PCUSER\.m2\repository\io\netty\netty-codec-socks\4.1.36.Final\netty-codec-socks-4.1.36.Final.jar;C:\Users\PCUSER\.m2\repository\io\netty\netty-resolver-dns\4.1.36.Final\netty-resolver-dns-4.1.36.Final.jar;C:\Users\PCUSER\.m2\repository\io\netty\netty-resolver\4.1.36.Final\netty-resolver-4.1.36.Final.jar;C:\Users\PCUSER\.m2\repository\io\netty\netty-codec-dns\4.1.36.Final\netty-codec-dns-4.1.36.Final.jar;C:\Users\PCUSER\.m2\repository\io\netty\netty-transport-native-epoll\4.1.36.Final\netty-transport-native-epoll-4.1.36.Final-linux-x86_64.jar;C:\Users\PCUSER\.m2\repository\io\netty\netty-transport-native-unix-common\4.1.36.Final\netty-transport-native-unix-common-4.1.36.Final.jar;C:\Users\PCUSER\.m2\repository\io\netty\netty-codec-http2\4.1.36.Final\netty-codec-http2-4.1.36.Final.jar;C:\Users\PCUSER\.m2\repository\io\netty\netty-tcnative-boringssl-static\2.0.25.Final\netty-tcnative-boringssl-static-2.0.25.Final.jar;C:\Users\PCUSER\.m2\repository\com\sun\activation\javax.activation\1.2.0\javax.activation-1.2.0.jar;C:\Users\PCUSER\.m2\repository\org\slf4j\slf4j-api\1.7.26\slf4j-api-1.7.26.jar;C:\Users\PCUSER\.m2\repository\com\typesafe\scala-logging\scala-logging_2.12\3.9.2\scala-logging_2.12-3.9.2.jar;C:\Users\PCUSER\.m2\repository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;C:\Users\PCUSER\.m2\repository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;C:\Users\PCUSER\.m2\repository\io\gatling\gatling-commons\3.1.2\gatling-commons-3.1.2.jar;C:\Users\PCUSER\.m2\repository\org\scala-lang\scala-reflect\2.12.8\scala-reflect-2.12.8.jar;C:\Users\PCUSER\.m2\repository\com\typesafe\config\1.3.4\config-1.3.4.jar;C:\Users\PCUSER\.m2\repository\com\dongxiguo\fastring_2.12\1.0.0\fastring_2.12-1.0.0.jar;C:\Users\PCUSER\.m2\repository\io\suzaku\boopickle_2.12\1.3.1\boopickle_2.12-1.3.1.jar;C:\Users\PCUSER\.m2\repository\org\typelevel\spire-macros_2.12\0.16.1\spire-macros_2.12-0.16.1.jar;C:\Users\PCUSER\.m2\repository\org\scala-lang\modules\scala-collection-compat_2.12\0.3.0\scala-collection-compat_2.12-0.3.0.jar;C:\Users\PCUSER\.m2\repository\com\softwaremill\quicklens\quicklens_2.12\1.4.12\quicklens_2.12-1.4.12.jar;C:\Users\PCUSER\.m2\repository\org\scala-lang\modules\scala-java8-compat_2.12\0.9.0\scala-java8-compat_2.12-0.9.0.jar;C:\Users\PCUSER\.m2\repository\com\eatthepath\fast-uuid\0.1\fast-uuid-0.1.jar;C:\Users\PCUSER\.m2\repository\io\gatling\gatling-app\3.1.2\gatling-app-3.1.2.jar;C:\Users\PCUSER\.m2\repository\io\gatling\gatling-core\3.1.2\gatling-core-3.1.2.jar;C:\Users\PCUSER\.m2\repository\com\typesafe\akka\akka-slf4j_2.12\2.5.22\akka-slf4j_2.12-2.5.22.jar;C:\Users\PCUSER\.m2\repository\org\simpleflatmapper\lightning-csv\6.7.0\lightning-csv-6.7.0.jar;C:\Users\PCUSER\.m2\repository\org\simpleflatmapper\sfm-util\6.7.0\sfm-util-6.7.0.jar;C:\Users\PCUSER\.m2\repository\com\github\ben-manes\caffeine\caffeine\2.7.0\caffeine-2.7.0.jar;C:\Users\PCUSER\.m2\repository\org\checkerframework\checker-qual\2.6.0\checker-qual-2.6.0.jar;C:\Users\PCUSER\.m2\repository\com\google\errorprone\error_prone_annotations\2.3.3\error_prone_annotations-2.3.3.jar;C:\Users\PCUSER\.m2\repository\io\pebbletemplates\pebble\3.0.9\pebble-3.0.9.jar;C:\Users\PCUSER\.m2\repository\org\unbescape\unbescape\1.1.6.RELEASE\unbescape-1.1.6.RELEASE.jar;C:\Users\PCUSER\.m2\repository\org\scala-lang\modules\scala-parser-combinators_2.12\1.1.2\scala-parser-combinators_2.12-1.1.2.jar;C:\Users\PCUSER\.m2\repository\com\github\scopt\scopt_2.12\3.7.1\scopt_2.12-3.7.1.jar;C:\Users\PCUSER\.m2\repository\io\gatling\jsonpath_2.12\0.6.14\jsonpath_2.12-0.6.14.jar;C:\Users\PCUSER\.m2\repository\org\jodd\jodd-json\5.0.13\jodd-json-5.0.13.jar;C:\Users\PCUSER\.m2\repository\org\jodd\jodd-bean\5.0.13\jodd-bean-5.0.13.jar;C:\Users\PCUSER\.m2\repository\org\jodd\jodd-core\5.0.13\jodd-core-5.0.13.jar;C:\Users\PCUSER\.m2\repository\net\sf\saxon\Saxon-HE\9.9.1-2\Saxon-HE-9.9.1-2.jar;C:\Users\PCUSER\.m2\repository\com\ibm\icu\icu4j\63.1\icu4j-63.1.jar;C:\Users\PCUSER\.m2\repository\org\jodd\jodd-lagarto\5.0.13\jodd-lagarto-5.0.13.jar;C:\Users\PCUSER\.m2\repository\org\jodd\jodd-log\5.0.13\jodd-log-5.0.13.jar;C:\Users\PCUSER\.m2\repository\io\gatling\gatling-http\3.1.2\gatling-http-3.1.2.jar;C:\Users\PCUSER\.m2\repository\org\scala-lang\modules\scala-xml_2.12\1.2.0\scala-xml_2.12-1.2.0.jar;C:\Users\PCUSER\.m2\repository\io\gatling\gatling-jms\3.1.2\gatling-jms-3.1.2.jar;C:\Users\PCUSER\.m2\repository\org\apache\geronimo\specs\geronimo-jms_1.1_spec\1.1.1\geronimo-jms_1.1_spec-1.1.1.jar;C:\Users\PCUSER\.m2\repository\io\gatling\gatling-jdbc\3.1.2\gatling-jdbc-3.1.2.jar;C:\Users\PCUSER\.m2\repository\io\gatling\gatling-redis\3.1.2\gatling-redis-3.1.2.jar;C:\Users\PCUSER\.m2\repository\net\debasishg\redisclient_2.12\3.9\redisclient_2.12-3.9.jar;C:\Users\PCUSER\.m2\repository\org\apache\commons\commons-pool2\2.6.0\commons-pool2-2.6.0.jar;C:\Users\PCUSER\.m2\repository\io\gatling\gatling-graphite\3.1.2\gatling-graphite-3.1.2.jar;C:\Users\PCUSER\.m2\repository\org\hdrhistogram\HdrHistogram\2.1.11\HdrHistogram-2.1.11.jar;C:\Users\PCUSER\.m2\repository\io\gatling\gatling-recorder\3.1.2\gatling-recorder-3.1.2.jar;C:\Users\PCUSER\.m2\repository\org\scala-lang\modules\scala-swing_2.12\2.1.1\scala-swing_2.12-2.1.1.jar;C:\Users\PCUSER\.m2\repository\com\fasterxml\jackson\core\jackson-databind\2.9.8\jackson-databind-2.9.8.jar;C:\Users\PCUSER\.m2\repository\com\fasterxml\jackson\core\jackson-annotations\2.9.0\jackson-annotations-2.9.0.jar;C:\Users\PCUSER\.m2\repository\com\fasterxml\jackson\core\jackson-core\2.9.8\jackson-core-2.9.8.jar;C:\Users\PCUSER\.m2\repository\org\json4s\json4s-jackson_2.12\3.6.5\json4s-jackson_2.12-3.6.5.jar;C:\Users\PCUSER\.m2\repository\org\json4s\json4s-core_2.12\3.6.5\json4s-core_2.12-3.6.5.jar;C:\Users\PCUSER\.m2\repository\org\json4s\json4s-ast_2.12\3.6.5\json4s-ast_2.12-3.6.5.jar;C:\Users\PCUSER\.m2\repository\org\json4s\json4s-scalap_2.12\3.6.5\json4s-scalap_2.12-3.6.5.jar;C:\Users\PCUSER\.m2\repository\com\thoughtworks\paranamer\paranamer\2.8\paranamer-2.8.jar;C:\Users\PCUSER\.m2\repository\org\bouncycastle\bcpkix-jdk15on\1.61\bcpkix-jdk15on-1.61.jar;C:\Users\PCUSER\.m2\repository\org\bouncycastle\bcprov-jdk15on\1.61\bcprov-jdk15on-1.61.jar;C:\Users\PCUSER\.m2\repository\io\netty\netty-codec-http\4.1.36.Final\netty-codec-http-4.1.36.Final.jar;C:\Users\PCUSER\.m2\repository\io\netty\netty-common\4.1.36.Final\netty-common-4.1.36.Final.jar;C:\Users\PCUSER\.m2\repository\io\netty\netty-transport\4.1.36.Final\netty-transport-4.1.36.Final.jar;C:\Users\PCUSER\.m2\repository\io\netty\netty-codec\4.1.36.Final\netty-codec-4.1.36.Final.jar;C:\Users\PCUSER\.m2\repository\com\typesafe\akka\akka-actor_2.12\2.5.22\akka-actor_2.12-2.5.22.jar Recorder
Error: Could not find or load main class Recorder
Caused by: java.lang.ClassNotFoundException: Recorder

I have tried using JDK12, it does not work.
Running the standalone recorder.bat works just fine.

Body:
This works now. I failed to add the following in POM.XML as described in https://gatling.io/docs/3.1/installation/#with-maven.

<build>
        <sourceDirectory>src/main/scala</sourceDirectory>
        <testSourceDirectory>src/test/scala</testSourceDirectory>
        <plugins>
                <plugin>
                        <groupId>net.alchim31.maven</groupId>
                        <artifactId>scala-maven-plugin</artifactId>
                        <version>MANUALLY_REPLACE_WITH_LATEST_VERSION</version>
<configuration>
  <args>
    <arg>-target:jvm-1.8</arg>
    <arg>-deprecation</arg>
    <arg>-feature</arg>
    <arg>-unchecked</arg>
    <arg>-language:implicitConversions</arg>
    <arg>-language:postfixOps</arg>
  </args>
</configuration>
                        <executions>
                                <execution>
                                        <goals>
                                                <goal>compile</goal>
                                                <goal>testCompile</goal>
                                        </goals>
                                </execution>
                        </executions>
                </plugin>
        </plugins>
</build>


问:
Value error when using decision tree classifier
I'm trying to run this decision tree classifier using the Iris data set but I keep getting the error: ValueError: could not convert string to float: 'sepal_length'

(screenshots of code https://drive.google.com/folderview?id=1WzOaIsdgoJaQ-OkExobP7Uo-ljtUoLMw)

```<code>import pandas as pd
from sklearn.tree import DecisionTreeClassifier # Import Decision Tree Classifier
from sklearn.model_selection import train_test_split # Import train_test_split function
from sklearn import metrics

import os
os.chdir('C:\\Users\\michael\\Documents')

col_names = ['sepal length', 'sepal width', 'petal length', 'petal width', 'species']

iris = pd.read_csv("iris.csv", header=None,names=col_names)
iris.head()

feature_cols = ['sepal length', 'sepal width', 'petal length', 'petal width']
X = iris[feature_cols] # Features
y = iris.species # Target variable

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1) # 70% training and 30% test

clf = DecisionTreeClassifier()

# Train Decision Tree Classifier
______> clf = clf.fit(X_train,y_train) --------- error occurs here(could not convert string to float:'sepal_length'...value error

#Predict the response for test dataset
y_pred = clf.predict(X_test)
</code>```

答: Header=0 that what should have been there, thanks everyone

Body:
I'm trying to run this decision tree classifier using the Iris data set but I keep getting the error: ValueError: could not convert string to float: 'sepal_length'

(screenshots of code https://drive.google.com/folderview?id=1WzOaIsdgoJaQ-OkExobP7Uo-ljtUoLMw)

import pandas as pd
from sklearn.tree import DecisionTreeClassifier # Import Decision Tree Classifier
from sklearn.model_selection import train_test_split # Import train_test_split function
from sklearn import metrics

import os
os.chdir('C:\\Users\\michael\\Documents')

col_names = ['sepal length', 'sepal width', 'petal length', 'petal width', 'species']

iris = pd.read_csv("iris.csv", header=None,names=col_names)
iris.head()

feature_cols = ['sepal length', 'sepal width', 'petal length', 'petal width']
X = iris[feature_cols] # Features
y = iris.species # Target variable

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1) # 70% training and 30% test

clf = DecisionTreeClassifier()

# Train Decision Tree Classifier
______> clf = clf.fit(X_train,y_train) --------- error occurs here(could not convert string to float:'sepal_length'...value error

#Predict the response for test dataset
y_pred = clf.predict(X_test)


问:
Line Passing Through Given Points

I am trying to find the angle of the outer line of the object in the green region of the image as shown in the image above…

For that, I have scanned the green region and get the points (dark blue points as shown in the image)...

As you can see, the points are not making straight line so I can’t find angle easily.

So I think I have to find a middle way and
that is to find the line so that the distance between each point and line remain as minimum as possible.

So how can I find the line so that each point exposes minimum distance to it……?

Is there any algorithm for this or is there any good way other than this?

答:
The hough transform might be also a good option:

http://en.wikipedia.org/wiki/Hough_transform

Title: Line Passing Through Given Points


问:
Better way to change background color based on element's property
I'm working on a project using Django, some JavaScript and Tachyons. I have the following in a template file:

```<code><tbody class="lh-copy">
    {% for alarm in alarm_list %}
        <tr>
            <td class="pv3 pr3 bb b--black-20 bg-light-green {{ alarm.id }}-td">{{ alarm.agent.name }}</td>
            <td class="pv3 pr3 bb b--black-20 bg-light-green {{ alarm.id }}-td">{{ alarm.profile_name }}</td>
            <td class="pv3 pr3 bb b--black-20 bg-light-green {{ alarm.id }}-td">{{ alarm.is_active }}</td>
            <td class="pv3 pr3 bb b--black-20 bg-light-green {{ alarm.id }}-td">{{ alarm.created }}</td>
            <td class="pv3 pr3 bb b--black-20 bg-light-green {{ alarm.id }}-td">{{ alarm.message }}</td>
            <td class="pv3 pr3 bb b--black-20 bg-light-green {{ alarm.id }}-td">{{ alarm.alrmtype }}</td>
            <td class="pv3 pr3 bb b--black-20 bg-light-green {{ alarm.id }}-td">{{ alarm.acknowledged }}</td>
            <td class="pv3 pr3 bb b--black-20 bg-light-green {{ alarm.id }}-td">{{ alarm.is_hidden }}</td>

            {% if alarm.is_active %}
                <script language="javascript">
                    const alarmValElementList{{ alarm.id }} = document.getElementsByClassName("{{ alarm.id }}-td");
                    for (let i=0; i < alarmValElementList{{ alarm.id }}.length; i ++) {
                        alarmValElementList{{ alarm.id }}[i].classList.remove("bg-light-green");
                        alarmValElementList{{ alarm.id }}[i].classList.add("bg-light-red");
                    };
                </script>
            {% endif %}
         </tr>
     {% endfor %}
 </tbody>
</code>```

I'm accessing the element alarm from alarm_list and using a template "if" to insert JavaScript code that tells the HTML element to remove the current background color and add another one. I'm not happy to use alarmValeElementList{{ alarm.id }} as a dynamic variable name but I can't think of another way to do this.

Is there a better way to implement this?

ETA:

This looks better I think as it got rid of the dynamic variable name:

```<code><script language="javascript">
    let alarmValElementList = [];
</script>
{% for alarm in alarm_list %}
    <tr>
        <td class="pv3 pr3 bb b--black-20 bg-light-green alarm-val-td">{{ alarm.agent.name }}</td>
        <td class="pv3 pr3 bb b--black-20 bg-light-green alarm-val-td">{{ alarm.profile_name }}</td>
        <td class="pv3 pr3 bb b--black-20 bg-light-green alarm-val-td">{{ alarm.is_active }}</td>
        <td class="pv3 pr3 bb b--black-20 bg-light-green alarm-val-td">{{ alarm.created }}</td>
        <td class="pv3 pr3 bb b--black-20 bg-light-green alarm-val-td">{{ alarm.message }}</td>
        <td class="pv3 pr3 bb b--black-20 bg-light-green alarm-val-td">{{ alarm.alrmtype }}</td>
        <td class="pv3 pr3 bb b--black-20 bg-light-green alarm-val-td">{{ alarm.acknowledged }}</td>
        <td class="pv3 pr3 bb b--black-20 bg-light-green alarm-val-td">{{ alarm.is_hidden }}</td>

        {% if alarm.is_active %}
            <script language="javascript">
                alarmValElementList = document.getElementsByClassName("alarm-val-td");
                for (let i=0; i < alarmValElementList.length; i ++) {
                    alarmValElementList[i].classList.remove("bg-light-green");
                    alarmValElementList[i].classList.add("bg-light-red");
                };
            </script>
        {% endif %}
    </tr>
{% endfor %}
</code>```

But, I am wondering if there is not a better way to do this possibly?

答:
I might be missing something else you are trying to do but would this work?

```<code>{% for alarm in alarm_list %}
<tr>
    <td class="pv3 pr3 bb b--black-20 {% if alarm.is_active %}bg-light-red{% else %} bg-light-green{% endif %} alarm-val-td">{{ alarm.agent.name }}</td>
    <td class="pv3 pr3 bb b--black-20 {% if alarm.is_active %}bg-light-red{% else %} bg-light-green{% endif %} alarm-val-td">{{ alarm.profile_name }}</td>
    <td class="pv3 pr3 bb b--black-20 {% if alarm.is_active %}bg-light-red{% else %} bg-light-green{% endif %} alarm-val-td">{{ alarm.is_active }}</td>
    <td class="pv3 pr3 bb b--black-20 {% if alarm.is_active %}bg-light-red{% else %} bg-light-green{% endif %} alarm-val-td">{{ alarm.created }}</td>
    <td class="pv3 pr3 bb b--black-20 {% if alarm.is_active %}bg-light-red{% else %} bg-light-green{% endif %} alarm-val-td">{{ alarm.message }}</td>
    <td class="pv3 pr3 bb b--black-20 {% if alarm.is_active %}bg-light-red{% else %} bg-light-green{% endif %} alarm-val-td">{{ alarm.alrmtype }}</td>
    <td class="pv3 pr3 bb b--black-20 {% if alarm.is_active %}bg-light-red{% else %} bg-light-green{% endif %} alarm-val-td">{{ alarm.acknowledged }}</td>
    <td class="pv3 pr3 bb b--black-20 {% if alarm.is_active %}bg-light-red{% else %} bg-light-green{% endif %} alarm-val-td">{{ alarm.is_hidden }}</td>

</tr>
{% endfor %}
</code>```

I'd personally probably have a property on the model for alarm which sets the colour class so you could just say:

```<code><td class="pv3 pr3 bb b--black-20 {{ alarm.css_class }} alarm-val-td">{{ alarm.agent.name }}</td>
</code>```

EDIT
if you are concerned with the unsightly visual of too many if's in your template (I'd say it is okay though) you could use the with statement combined with a yesno filter for a cleaner appearance. I haven't tested this but the following might work for your particular case. If you are concerned with performance which I think would be nearly indifferent between the one 'with' or multiple 'if's you should time it out. My bet would be on the multiple if's, however, the 'with' gives an edge on maintainability.

```<code>{% with tdalarm_cssclass=alarm.is_active|yesno:"bg-light-red,bg-light-green" %}
    <td class="pv3 pr3 bb b--black-20 {{ tdalarm_cssclass }} alarm-val-td">{{ alarm.agent.name }}</td>
    <td class="pv3 pr3 bb b--black-20 {{ tdalarm_cssclass }} alarm-val-td">{{ alarm.profile_name }}</td>
    <td class="pv3 pr3 bb b--black-20 {{ tdalarm_cssclass }} alarm-val-td">{{ alarm.is_active }}</td>
    <td class="pv3 pr3 bb b--black-20 {{ tdalarm_cssclass }} alarm-val-td">{{ alarm.created }}</td>
    <td class="pv3 pr3 bb b--black-20 {{ tdalarm_cssclass }} alarm-val-td">{{ alarm.message }}</td>
    <td class="pv3 pr3 bb b--black-20 {{ tdalarm_cssclass }} alarm-val-td">{{ alarm.alrmtype }}</td>
    <td class="pv3 pr3 bb b--black-20 {{ tdalarm_cssclass }} alarm-val-td">{{ alarm.acknowledged }}</td>
    <td class="pv3 pr3 bb b--black-20 {{ tdalarm_cssclass }} alarm-val-td">{{ alarm.is_hidden }}</td>
{% endwith %}
</code>```

Body:
I'm working on a project using Django, some JavaScript and Tachyons. I have the following in a template file:

    {% for alarm in alarm_list %}

            {{ alarm.agent.name }}
            {{ alarm.profile_name }}
            {{ alarm.is_active }}
            {{ alarm.created }}
            {{ alarm.message }}
            {{ alarm.alrmtype }}
            {{ alarm.acknowledged }}
            {{ alarm.is_hidden }}

            {% if alarm.is_active %}

            {% endif %}

     {% endfor %}

I'm accessing the element alarm from alarm_list and using a template "if" to insert JavaScript code that tells the HTML element to remove the current background color and add another one. I'm not happy to use alarmValeElementList{{ alarm.id }} as a dynamic variable name but I can't think of another way to do this.

Is there a better way to implement this?

ETA:

This looks better I think as it got rid of the dynamic variable name:

{% for alarm in alarm_list %}

        {{ alarm.agent.name }}
        {{ alarm.profile_name }}
        {{ alarm.is_active }}
        {{ alarm.created }}
        {{ alarm.message }}
        {{ alarm.alrmtype }}
        {{ alarm.acknowledged }}
        {{ alarm.is_hidden }}

        {% if alarm.is_active %}

        {% endif %}

{% endfor %}

But, I am wondering if there is not a better way to do this possibly?

Body:
I might be missing something else you are trying to do but would this work?

{% for alarm in alarm_list %}
<tr>
    <td class="pv3 pr3 bb b--black-20 {% if alarm.is_active %}bg-light-red{% else %} bg-light-green{% endif %} alarm-val-td">{{ alarm.agent.name }}</td>
    <td class="pv3 pr3 bb b--black-20 {% if alarm.is_active %}bg-light-red{% else %} bg-light-green{% endif %} alarm-val-td">{{ alarm.profile_name }}</td>
    <td class="pv3 pr3 bb b--black-20 {% if alarm.is_active %}bg-light-red{% else %} bg-light-green{% endif %} alarm-val-td">{{ alarm.is_active }}</td>
    <td class="pv3 pr3 bb b--black-20 {% if alarm.is_active %}bg-light-red{% else %} bg-light-green{% endif %} alarm-val-td">{{ alarm.created }}</td>
    <td class="pv3 pr3 bb b--black-20 {% if alarm.is_active %}bg-light-red{% else %} bg-light-green{% endif %} alarm-val-td">{{ alarm.message }}</td>
    <td class="pv3 pr3 bb b--black-20 {% if alarm.is_active %}bg-light-red{% else %} bg-light-green{% endif %} alarm-val-td">{{ alarm.alrmtype }}</td>
    <td class="pv3 pr3 bb b--black-20 {% if alarm.is_active %}bg-light-red{% else %} bg-light-green{% endif %} alarm-val-td">{{ alarm.acknowledged }}</td>
    <td class="pv3 pr3 bb b--black-20 {% if alarm.is_active %}bg-light-red{% else %} bg-light-green{% endif %} alarm-val-td">{{ alarm.is_hidden }}</td>

</tr>
{% endfor %}

I'd personally probably have a property on the model for alarm which sets the colour class so you could just say:

<td class="pv3 pr3 bb b--black-20 {{ alarm.css_class }} alarm-val-td">{{ alarm.agent.name }}</td>

EDIT
if you are concerned with the unsightly visual of too many if's in your template (I'd say it is okay though) you could use the with statement combined with a yesno filter for a cleaner appearance. I haven't tested this but the following might work for your particular case. If you are concerned with performance which I think would be nearly indifferent between the one 'with' or multiple 'if's you should time it out. My bet would be on the multiple if's, however, the 'with' gives an edge on maintainability.

{% with tdalarm_cssclass=alarm.is_active|yesno:"bg-light-red,bg-light-green" %}
    <td class="pv3 pr3 bb b--black-20 {{ tdalarm_cssclass }} alarm-val-td">{{ alarm.agent.name }}</td>
    <td class="pv3 pr3 bb b--black-20 {{ tdalarm_cssclass }} alarm-val-td">{{ alarm.profile_name }}</td>
    <td class="pv3 pr3 bb b--black-20 {{ tdalarm_cssclass }} alarm-val-td">{{ alarm.is_active }}</td>
    <td class="pv3 pr3 bb b--black-20 {{ tdalarm_cssclass }} alarm-val-td">{{ alarm.created }}</td>
    <td class="pv3 pr3 bb b--black-20 {{ tdalarm_cssclass }} alarm-val-td">{{ alarm.message }}</td>
    <td class="pv3 pr3 bb b--black-20 {{ tdalarm_cssclass }} alarm-val-td">{{ alarm.alrmtype }}</td>
    <td class="pv3 pr3 bb b--black-20 {{ tdalarm_cssclass }} alarm-val-td">{{ alarm.acknowledged }}</td>
    <td class="pv3 pr3 bb b--black-20 {{ tdalarm_cssclass }} alarm-val-td">{{ alarm.is_hidden }}</td>
{% endwith %}


问:
How to implement to a generic protocol, which has a function using the Type of associatedtype?
I am creating some class confirms to a generic protocol, this generic protocol has a method which accept a parameter of the Type of the associatedtype, I use Xcode to generate the stub for me:

```<code>
import UIKit

struct SomeObject: Codable {
    var id: String?
    var name: String?
}

protocol INetworkManager {
    associatedtype ResponseObject
    func get(url: String, ofType: ResponseObject.Type, completion: (ResponseObject?, Error?) -> Void)
}

class NetworkManager: INetworkManager {
    typealias ResponseObject = Codable

    func get(url: String, ofType: ResponseObject.Protocol, completion: (ResponseObject?, Error?) -> Void) {
        completion(SomeObject(id: "1", name: "hello"), nil)
    }
}

</code>```

Instead of ResponseObject.Type it generates ResponseObject.Protocol for me, I don't actually know what this ResponseObject.Protocol is, and I can not pass SomeObject.self as the parameter like this:

```<code>let networkManager = NetworkManager()
networkManager.get(url: "http://whatever.com", ofType: SomeObject.self) { (responseObject, error) in
    print("got response object named: \(responseObject.name)")
}
</code>```

compiler gave me this error:

```<code>error: Cannot convert value of type 'SomeObject.Type' to expected argument type 'NetworkManager.ResponseObject.Protocol' (aka '(Decodable & Encodable).Protocol')
</code>```

I think something wrong with my implementation, anyone can give me any ideas?

Thanks!

答:
This isn't how associated types work. get should be generic over its response type, but the network manager itself isn't generic over some specific response type. I believe what you meant to here is this:

```<code>protocol NetworkManager {
    func get<ResponseObject>(url: String,
                             ofType: ResponseObject.Type,
                             completion: (Result<ResponseObject, Error>) -> Void)
    where ResponseObject: Decodable
}

class TrivialNetworkManager: NetworkManager {
    func get<ResponseObject>(url: String,
                             ofType: ResponseObject.Type,
                             completion: (Result<ResponseObject, Error>) -> Void)
    where ResponseObject: Decodable {
        completion(.success(SomeObject(id: "1", name: "hello"))
    }
}
</code>```

For a more worked-out version of this specific problem you can read my protocol series, but the important concept here is that NetworkManager doesn't vary over its ResponseType, so there's no reason to make its ResponseType an associated type.

What you wrote is trying to say "some network managers will have a Codable ResponseType, and other network managers will have some other kind of ResponseType." Not "some other specific response type (like User)" but "some other protocol that its response types would have to conform to." While it's conceivable to build something like that, it's much more complex, and you'd need to explain your precise use case in order to design it. Specifically, you'd need to show several concrete implementations of your protocol in order to see what kind of shared code you're trying to extract.

Body:
I am creating some class confirms to a generic protocol, this generic protocol has a method which accept a parameter of the Type of the associatedtype, I use Xcode to generate the stub for me:

import UIKit

struct SomeObject: Codable {
    var id: String?
    var name: String?
}

protocol INetworkManager {
    associatedtype ResponseObject
    func get(url: String, ofType: ResponseObject.Type, completion: (ResponseObject?, Error?) -> Void)
}

class NetworkManager: INetworkManager {
    typealias ResponseObject = Codable

    func get(url: String, ofType: ResponseObject.Protocol, completion: (ResponseObject?, Error?) -> Void) {
        completion(SomeObject(id: "1", name: "hello"), nil)
    }
}

Instead of ResponseObject.Type it generates ResponseObject.Protocol for me, I don't actually know what this ResponseObject.Protocol is, and I can not pass SomeObject.self as the parameter like this:

let networkManager = NetworkManager()
networkManager.get(url: "http://whatever.com", ofType: SomeObject.self) { (responseObject, error) in
    print("got response object named: \(responseObject.name)")
}

compiler gave me this error:

error: Cannot convert value of type 'SomeObject.Type' to expected argument type 'NetworkManager.ResponseObject.Protocol' (aka '(Decodable & Encodable).Protocol')

I think something wrong with my implementation, anyone can give me any ideas?

Thanks!

Body:
This isn't how associated types work. get should be generic over its response type, but the network manager itself isn't generic over some specific response type. I believe what you meant to here is this:

protocol NetworkManager {
    func get<ResponseObject>(url: String,
                             ofType: ResponseObject.Type,
                             completion: (Result<ResponseObject, Error>) -> Void)
    where ResponseObject: Decodable
}

class TrivialNetworkManager: NetworkManager {
    func get<ResponseObject>(url: String,
                             ofType: ResponseObject.Type,
                             completion: (Result<ResponseObject, Error>) -> Void)
    where ResponseObject: Decodable {
        completion(.success(SomeObject(id: "1", name: "hello"))
    }
}

For a more worked-out version of this specific problem you can read my protocol series, but the important concept here is that NetworkManager doesn't vary over its ResponseType, so there's no reason to make its ResponseType an associated type.

What you wrote is trying to say "some network managers will have a Codable ResponseType, and other network managers will have some other kind of ResponseType." Not "some other specific response type (like User)" but "some other protocol that its response types would have to conform to." While it's conceivable to build something like that, it's much more complex, and you'd need to explain your precise use case in order to design it. Specifically, you'd need to show several concrete implementations of your protocol in order to see what kind of shared code you're trying to extract.


问:
Auto property initialization with anonymous function
I'm trying to get rid of some code with anonymous functions and classes.

I stuck on this:

```<code>public List<Object> Years { get; set; } = GetYears();

private static List<Object> GetYears()
{
    List<Object> retList = new List<Object>();

    retList.Add(new { Value = (byte)255, Name = "Any" });
    retList.Add(new { Value = (byte)254, Name = "None" });

    for (byte i = 0; i < 50; i++)
    {
        retList.Add(new { Value = i, Name = (2000 + i).ToString() });
    }
    return retList;
}
</code>```

Is it possible to get rid of static GetYears() method?

I mean something like this:

```<code>public List<Object> Years { get; set; } = () =>
{
    List<Object> retList = new List<Object>();
    for (byte i = 0; i < 50; i++)
    {
        retList.Add(new { Value = i, Name = (2000 + i).ToString() });
    }
    return retList;
}
</code>```

The problem is that the field initializer cannot reference non-static method.

Is it possible to get around this?

Edit: I added these 2 lines of code:

```<code>retList.Add(new { Value = (byte)255, Name = "None" });
retList.Add(new { Value = (byte)254, Name = "Any" });
</code>```

答:
As mentioned you can't do this by design, an initializer cannot reference the nonstatic field, method, or property 'field', and an anonymous method is not this.

You can put it in the constructor, other options would be to make it a Lazy<T>

```<code>public Lazy<List<Object>> Years { get; set; } = new Lazy<List<object>>(() =>
{
   List<object> retList = new List<object>();
   for (byte i = 0; i < 50; i++)
   {
      retList.Add(new { Value = i, Name = (2000 + i).ToString() });
   }
   return retList;
});
</code>```

or hack it a little with Enumerable.Range

```<code>private List<Object> Years { get; set; }
   = Enumerable.Range(0, 50)
               .Select(i => (object)new { Value = i, Name = (2000 + i).ToString() })
               .ToList();
</code>```

 Note : The whole List<object> seems a little suspicious anyway

Or maybe a little more succinct would be a Value Tuple

```<code>private List<(int Value, string Name)> Years { get; set; }
   = Enumerable.Range(0, 50)
               .Select(i => (i, (2000 + i).ToString()))
               .ToList();
</code>```

Body:
I'm trying to get rid of some code with anonymous functions and classes.

I stuck on this:

public List<Object> Years { get; set; } = GetYears();

private static List<Object> GetYears()
{
    List<Object> retList = new List<Object>();

    retList.Add(new { Value = (byte)255, Name = "Any" });
    retList.Add(new { Value = (byte)254, Name = "None" });

    for (byte i = 0; i < 50; i++)
    {
        retList.Add(new { Value = i, Name = (2000 + i).ToString() });
    }
    return retList;
}

Is it possible to get rid of static GetYears() method?

I mean something like this:

public List<Object> Years { get; set; } = () =>
{
    List<Object> retList = new List<Object>();
    for (byte i = 0; i < 50; i++)
    {
        retList.Add(new { Value = i, Name = (2000 + i).ToString() });
    }
    return retList;
}

The problem is that the field initializer cannot reference non-static method.

Is it possible to get around this?

Edit: I added these 2 lines of code:

retList.Add(new { Value = (byte)255, Name = "None" });
retList.Add(new { Value = (byte)254, Name = "Any" });

Body:
As mentioned you can't do this by design, an initializer cannot reference the nonstatic field, method, or property 'field', and an anonymous method is not this.

You can put it in the constructor, other options would be to make it a Lazy<T>

public Lazy<List<Object>> Years { get; set; } = new Lazy<List<object>>(() =>
{
   List<object> retList = new List<object>();
   for (byte i = 0; i < 50; i++)
   {
      retList.Add(new { Value = i, Name = (2000 + i).ToString() });
   }
   return retList;
});

or hack it a little with Enumerable.Range

private List<Object> Years { get; set; }
   = Enumerable.Range(0, 50)
               .Select(i => (object)new { Value = i, Name = (2000 + i).ToString() })
               .ToList();

 Note : The whole List<object> seems a little suspicious anyway

Or maybe a little more succinct would be a Value Tuple

private List<(int Value, string Name)> Years { get; set; }
   = Enumerable.Range(0, 50)
               .Select(i => (i, (2000 + i).ToString()))
               .ToList();


问:
Firestore runTransaction never runs
I am having the strangest problem. One day, out of the blue, runTransaction simply stopped running completely. no errors. no messages. any print statements i put there never runs. nothing. like as if the runTransaction statement is not there at all.

My code is exactly like the example code on the pub. if i just run update or set or add without the transaction it works perfectly.

```<code>final DocumentReference postRef = Firestore.instance.document('all_tokens/123');
Firestore.instance.runTransaction((Transaction tx) async {
                  DocumentSnapshot postSnapshot = await tx.get(postRef);
                  if (postSnapshot.exists) {
                    await tx.update(postRef, <String, dynamic>{'likesCount': postSnapshot.data['likesCount'] + 1});
                  }else{
                    await tx.set(postRef, <String, dynamic>{'likesCount': postSnapshot.data['likesCount'] + 1});
                  }
                });
</code>```

No error messages at all. nothing in the catch, nothing in then. The entire thing never runs. its like its being skipped

here is my pubspeck.yaml :

```<code>dependencies:
  flutter:
    sdk: flutter
  http: ^0.12.0
  font_awesome_flutter: ^8.2.0
  fluttertoast: ^3.0.4
  datetime_picker_formfield: ^0.1.7
  flutter_image_compress: ^0.4.0
  cloud_firestore: ^0.11.0+2
  firebase_auth: ^0.11.1
  google_sign_in: ^4.0.1+3
  firebase_messaging: ^4.0.0+3
  shared_preferences: ^0.5.2
  firebase_storage: ^3.0.0
  flutter_rating: ^0.0.2
  flutter_typeahead: ^1.4.0
  url_launcher: ^4.0.3
  flutter_facebook_login: ^2.0.0
  algolia: ^0.1.5
  geolocator: ^4.0.3
  provider: ^2.0.1
</code>```

答:
I conclude it is a recent version of Flutter that has caused this issue.  I recently upgraded to the latest in the master channel and I started having the same problems.  Once I downgraded to latest build in the Stable channel, the problem went away.

Thanks to crushman1 for reporting this and updating that a downgrade worked for him.  Downgrading to latest stable build fixed it for me as well.

Steps to downgrade can be found HERE

Title: Firestore runTransaction never runs

Body:
I am having the strangest problem. One day, out of the blue, runTransaction simply stopped running completely. no errors. no messages. any print statements i put there never runs. nothing. like as if the runTransaction statement is not there at all.

My code is exactly like the example code on the pub. if i just run update or set or add without the transaction it works perfectly.

final DocumentReference postRef = Firestore.instance.document('all_tokens/123');
Firestore.instance.runTransaction((Transaction tx) async {
                  DocumentSnapshot postSnapshot = await tx.get(postRef);
                  if (postSnapshot.exists) {
                    await tx.update(postRef, <String, dynamic>{'likesCount': postSnapshot.data['likesCount'] + 1});
                  }else{
                    await tx.set(postRef, <String, dynamic>{'likesCount': postSnapshot.data['likesCount'] + 1});
                  }
                });

No error messages at all. nothing in the catch, nothing in then. The entire thing never runs. its like its being skipped

here is my pubspeck.yaml :

dependencies:
  flutter:
    sdk: flutter
  http: ^0.12.0
  font_awesome_flutter: ^8.2.0
  fluttertoast: ^3.0.4
  datetime_picker_formfield: ^0.1.7
  flutter_image_compress: ^0.4.0
  cloud_firestore: ^0.11.0+2
  firebase_auth: ^0.11.1
  google_sign_in: ^4.0.1+3
  firebase_messaging: ^4.0.0+3
  shared_preferences: ^0.5.2
  firebase_storage: ^3.0.0
  flutter_rating: ^0.0.2
  flutter_typeahead: ^1.4.0
  url_launcher: ^4.0.3
  flutter_facebook_login: ^2.0.0
  algolia: ^0.1.5
  geolocator: ^4.0.3
  provider: ^2.0.1