问:
Split a XML into multiple XMLs
I am looking for a batch/VBScript which can split a large XML with multiple tags into multiple XML files. Please see details below.

Input XML:

<Shipment>
----some data- say 001-------
</Shipment>
< Shipment>
---- Some data- say 002-------
</Shipment>
```

<p>****Output XML 1:****</p>

<pre class="lang-xml prettyprint-override"><code><Shipment>
---some data- say 001-------
</Shipment>
</code>```

Output XML 2:

<Shipment>
----some data- say 002-------
</Shipment>
```

<hr>

<p>My code below is not working for some reason. Can anyone help me with logic?
I was trying intitally to get data with input having only single <code><shipment></code> tag.</p>

<p><strong>Code:</strong></p>

<pre class="lang-batch prettyprint-override"><code>    ::Read Xml file
    set f_xml=input2.xml
    for %%i in (%f_xml%) do (
        set xmlfilename=%%~ni
    )

    ::Write XML file
    for /f "tokens=1* delims=]" %%b in ('type "!xmlfilename!" ^| find /n /v ""') do (
        if /i *%%c*==*[Shipment]* set inblock=1
        if !inblock!==1 (
            if *%%c*==** (echo.) else (echo %%c)
            if /i *%%c*==*[/Shipment]* set inblock=0
        )
    )
    echo.
) >> output.xml
</code>```

答:
It's better to parse and objectify XML and other such structured markup than to hack and scrape it as flat text. The cmd interpreter unfortunately doesn't offer much for parsing XML natively, but it's easy enough to borrow from other scripting engines that do.

PowerShell is particularly well-suited to handle XML. You can read an XML file as text, then cast that data as an XML object simply by prefacing it with the [xml] accelerator. Handy, right? From there, select all Shipment nodes using an XPath expression; then for each, clone to a fresh XML object and save.

Here's a hybrid Batch + PowerShell script demonstrating this. Save this with a .bat extension and salt to taste.

<# : Batch portion
@echo off & setlocal

set "xmlfile=test.xml"

powershell -noprofile "iex (${%~f0} | out-string)"
goto :EOF

: end Batch / begin PowerShell hybrid code #>

[xml]$xml = "<root>$(gc $env:xmlfile)</root>"

$xml.SelectNodes("//Shipment") | %{
    $x = new-object xml
    $x.AppendChild($x.ImportNode($_, $true))
    $x.Save("shipment{0:D3}.xml" -f ++$i)
}
```

The drawback to this method is that your large XML file must be loaded into memory before even the first chunk is saved.  Depending on how large "large" is, you might have to resort to a stream reader and flat text scraping to speed up execution (similar to what you originally intended, but with a more efficient reader than Batch for /f).  That flat text scraping should be avoided if possible (see this ugly example).  But if you're working with an XML file that can be measured in gigs, you might have no other choice.

Title: Split a XML into multiple XMLs

Body:
I am looking for a batch/VBScript which can split a large XML with multiple tags into multiple XML files. Please see details below.

Input XML:

<Shipment>
----some data- say 001-------
</Shipment>
< Shipment>
---- Some data- say 002-------
</Shipment>

****Output XML 1:****

<Shipment>
---some data- say 001-------
</Shipment>

Output XML 2:

<Shipment>
----some data- say 002-------
</Shipment>

My code below is not working for some reason. Can anyone help me with logic?
I was trying intitally to get data with input having only single <shipment> tag.

Code:

    ::Read Xml file
    set f_xml=input2.xml
    for %%i in (%f_xml%) do (
        set xmlfilename=%%~ni
    )

    ::Write XML file
    for /f "tokens=1* delims=]" %%b in ('type "!xmlfilename!" ^| find /n /v ""') do (
        if /i *%%c*==*[Shipment]* set inblock=1
        if !inblock!==1 (
            if *%%c*==** (echo.) else (echo %%c)
            if /i *%%c*==*[/Shipment]* set inblock=0
        )
    )
    echo.
) >> output.xml

Body:
It's better to parse and objectify XML and other such structured markup than to hack and scrape it as flat text. The cmd interpreter unfortunately doesn't offer much for parsing XML natively, but it's easy enough to borrow from other scripting engines that do.

PowerShell is particularly well-suited to handle XML. You can read an XML file as text, then cast that data as an XML object simply by prefacing it with the [xml] accelerator. Handy, right? From there, select all Shipment nodes using an XPath expression; then for each, clone to a fresh XML object and save.

Here's a hybrid Batch + PowerShell script demonstrating this. Save this with a .bat extension and salt to taste.

<# : Batch portion
@echo off & setlocal

set "xmlfile=test.xml"

powershell -noprofile "iex (${%~f0} | out-string)"
goto :EOF

: end Batch / begin PowerShell hybrid code #>

[xml]$xml = "<root>$(gc $env:xmlfile)</root>"

$xml.SelectNodes("//Shipment") | %{
    $x = new-object xml
    $x.AppendChild($x.ImportNode($_, $true))
    $x.Save("shipment{0:D3}.xml" -f ++$i)
}

The drawback to this method is that your large XML file must be loaded into memory before even the first chunk is saved.  Depending on how large "large" is, you might have to resort to a stream reader and flat text scraping to speed up execution (similar to what you originally intended, but with a more efficient reader than Batch for /f).  That flat text scraping should be avoided if possible (see this ugly example).  But if you're working with an XML file that can be measured in gigs, you might have no other choice.


来源: stackexchange

问:
$routeProvider not redirecting to templateUrl
I am creating some CRUD pages using AngularJS and on a list of Users page, I am trying redirect to edit page once the user click on "Edit" button. But for some reason $routeProvider is not working.

Here is my index.html showing list of users

```<code><tr ng-repeat="user in usersData">
    <td>{{ user.firstname }}</td>
    <td>{{ user.lastname }}</td>
    <td>{{ user.jobtitle }}</td>
    <td>{{ user.userprofile.sex }}</td>
    <td>{{ user.userprofile.maritalstatus }}</td>
    <td><a ng-click="editUser(user.id)" class="btn btn-small btn-primary">edit</a></td>
    <td><a ng-click="deleteUser(user.id)" class="btn btn-small btn-danger">delete</a></td>
</tr>
</code>```

My app.js

```<code>var app = angular.module('benefitApp', ['ngRoute']);
app.config(function($routeProvider){
    $routeProvider
        .when("/editUser/:userId", {
                templateUrl : "templates/editUser.html"
            });
});

app.controller('userController', ['$scope','$http','$location',function($scope, $http, $location) {
  $http.get("https://localhost:8443/benefits/v1/users/").then(function (response){
      $scope.usersData = response.data;
  });
  $scope.editUser = function(userId) {
      $location.path('/editUser/' + userId);
  }
}]);
</code>```

My directory structure is as below

```<code>src/main/resources/static/js/app.js
src/main/resources/static/css/bootstrap.css
src/main/resources/templates/index.html
src/main/resources/templates/editUser.html
</code>```

What am i missing? On click of "Edit" button, the url in the browser changes to https://localhost:8443/home#!/editUser/1, but it never gets routed to editUser.html

答: Try adding this and ng-view directive $location.path('editUser/' + userId);

ContentLicense: CC BY-SA 3.0

Body:
I am creating some CRUD pages using AngularJS and on a list of Users page, I am trying redirect to edit page once the user click on "Edit" button. But for some reason $routeProvider is not working.

Here is my index.html showing list of users

    {{ user.firstname }}
    {{ user.lastname }}
    {{ user.jobtitle }}
    {{ user.userprofile.sex }}
    {{ user.userprofile.maritalstatus }}
    edit
    delete

My app.js

var app = angular.module('benefitApp', ['ngRoute']);
app.config(function($routeProvider){
    $routeProvider
        .when("/editUser/:userId", {
                templateUrl : "templates/editUser.html"
            });
});

app.controller('userController', ['$scope','$http','$location',function($scope, $http, $location) {
  $http.get("https://localhost:8443/benefits/v1/users/").then(function (response){
      $scope.usersData = response.data;
  });
  $scope.editUser = function(userId) {
      $location.path('/editUser/' + userId);
  }
}]);

My directory structure is as below

src/main/resources/static/js/app.js
src/main/resources/static/css/bootstrap.css
src/main/resources/templates/index.html
src/main/resources/templates/editUser.html

What am i missing? On click of "Edit" button, the url in the browser changes to https://localhost:8443/home#!/editUser/1, but it never gets routed to editUser.html


问:
Cannot replace some html characters with str_replace()
From the database I receive the following text:

```<code><div onclick="alert('cÃ³digo inyectado');">Texto</div>

[img]http://www.hobbyconsolas.com/sites/hobbyconsolas.com/public/media/image/2015/07/503196-halo-5-guardians-nuevos-datos-campana-cooperativa.jpg[/img]

Y aquÃ una URL: [url]https://www.google.es/?gws_rd=ssl[/url]

Bueno pues vamos [b]a ver si esto funciona[/b] porque "todavÃa" no lo sÃ© [i][u]bien[/u][/i]
</code>```

This text is stored in a variable called $texto. Once htmlspecialchars() applied to the variable, I go through where I´m finding the problem:

```<code>$texto = str_replace(""","\"",$texto); //para comillas
$texto = str_replace("<","<",$texto); // para <
$texto = str_replace(">",">",$texto); // para >
</code>```

But no modification is done. If I remove the character & works, how can I fix this problem?

答:
I'd say don't do that htmlspecialchars() call, and only call str_replace() once:

Code: (Demo)

```<code>$texto="<div onclick="alert('cÃ³digo inyectado');">Texto</div>

[img]http://www.hobbyconsolas.com/sites/hobbyconsolas.com/public/media/image/2015/07/503196-halo-5-guardians-nuevos-datos-campana-cooperativa.jpg[/img]

Y aquÃ una URL: [url]https://www.google.es/?gws_rd=ssl[/url]

Bueno pues vamos [b]a ver si esto funciona[/b] porque "todavÃa" no lo sÃ© [i][u]bien[/u][/i]";
//$texto=htmlspecialchars($texto);

$texto = str_replace([""","<",">"],['"','<','>'],$texto);

var_export($texto);
</code>```

Output:

```<code>'<div onclick="alert(\'cÃ³digo inyectado\');">Texto</div>

[img]http://www.hobbyconsolas.com/sites/hobbyconsolas.com/public/media/image/2015/07/503196-halo-5-guardians-nuevos-datos-campana-cooperativa.jpg[/img]

Y aquÃ una URL: [url]https://www.google.es/?gws_rd=ssl[/url]

Bueno pues vamos [b]a ver si esto funciona[/b] porque "todavÃa" no lo sÃ© [i][u]bien[/u][/i]'
</code>```

fyrye's suggestion yields this -- if this is what you are shooting for:

```<code>'<div onclick="alert('cÃ³digo inyectado');">Texto</div>

[img]http://www.hobbyconsolas.com/sites/hobbyconsolas.com/public/media/image/2015/07/503196-halo-5-guardians-nuevos-datos-campana-cooperativa.jpg[/img]

Y aquÃ una URL: [url]https://www.google.es/?gws_rd=ssl[/url]

Bueno pues vamos [b]a ver si esto funciona[/b] porque "todavÃa" no lo sÃ© [i][u]bien[/u][/i]'
</code>```

Body:
From the database I receive the following text:

Texto

[img]http://www.hobbyconsolas.com/sites/hobbyconsolas.com/public/media/image/2015/07/503196-halo-5-guardians-nuevos-datos-campana-cooperativa.jpg[/img]

Y aquÃ una URL: [url]https://www.google.es/?gws_rd=ssl[/url]

Bueno pues vamos [b]a ver si esto funciona[/b] porque "todavÃa" no lo sÃ© [i][u]bien[/u][/i]

This text is stored in a variable called $texto. Once htmlspecialchars() applied to the variable, I go through where I´m finding the problem:

$texto = str_replace(""","\"",$texto); //para comillas
$texto = str_replace("<","<",$texto); // para <
$texto = str_replace(">",">",$texto); // para >

But no modification is done. If I remove the character & works, how can I fix this problem?

Body:
I'd say don't do that htmlspecialchars() call, and only call str_replace() once:

Code: (Demo)

$texto="&lt;div onclick=&quot;alert('cÃ³digo inyectado');&quot;&gt;Texto&lt;/div&gt;

[img]http://www.hobbyconsolas.com/sites/hobbyconsolas.com/public/media/image/2015/07/503196-halo-5-guardians-nuevos-datos-campana-cooperativa.jpg[/img]

Y aquÃ una URL: [url]https://www.google.es/?gws_rd=ssl[/url]

Bueno pues vamos [b]a ver si esto funciona[/b] porque &quot;todavÃa&quot; no lo sÃ© [i][u]bien[/u][/i]";
//$texto=htmlspecialchars($texto);

$texto = str_replace(["&quot;","&lt;","&gt;"],['"','<','>'],$texto);

var_export($texto);

Output:

'<div onclick="alert(\'cÃ³digo inyectado\');">Texto</div>

[img]http://www.hobbyconsolas.com/sites/hobbyconsolas.com/public/media/image/2015/07/503196-halo-5-guardians-nuevos-datos-campana-cooperativa.jpg[/img]

Y aquÃ una URL: [url]https://www.google.es/?gws_rd=ssl[/url]

Bueno pues vamos [b]a ver si esto funciona[/b] porque "todavÃa" no lo sÃ© [i][u]bien[/u][/i]'

fyrye's suggestion yields this -- if this is what you are shooting for:

'<div onclick="alert(&#039;cÃ³digo inyectado&#039;);">Texto</div>

[img]http://www.hobbyconsolas.com/sites/hobbyconsolas.com/public/media/image/2015/07/503196-halo-5-guardians-nuevos-datos-campana-cooperativa.jpg[/img]

Y aquÃ una URL: [url]https://www.google.es/?gws_rd=ssl[/url]

Bueno pues vamos [b]a ver si esto funciona[/b] porque "todavÃa" no lo sÃ© [i][u]bien[/u][/i]'


问:
How to rotate SKLabelNode in company with its parent SKShapeNode?

When press the screen, balls created with the following codes:

```<code>var n = 1
func addBall(_ x:CGFloat){
    let numShape =  SKShapeNode(circleOfRadius: 30)
    numShape.name  = "ball"
    numShape.position = CGPoint(x: x, y: frame.maxY-40)
    numShape.physicsBody = SKPhysicsBody(circleOfRadius: 30)
    numShape.fillColor = SKColor.white
    numShape.physicsBody?.density = 0.1
    numShape.physicsBody?.affectedByGravity = true
    numShape.physicsBody?.friction = 0;
    numShape.physicsBody?.restitution = 0.6
    numShape.physicsBody?.allowsRotation = true
    numShape.physicsBody?.isDynamic = true

    let numLabel = SKLabelNode(fontNamed: "Helvetica")
    numLabel.text = "\(n)"
    numLabel.name = "\(n)"
    numLabel.fontColor = .red
    numLabel.position = CGPoint(x: 0, y: 0)
    numLabel.verticalAlignmentMode = .center

    numShape.addChild(numLabel)
    self.addChild(numShape)

    n += 1
}
</code>```

The balls can rotate, but their childNode numlabel don't rotate in company with them. I try to update their zRotation like below:

```<code>   override func update(_ currentTime: TimeInterval) {
        self.enumerateChildNodes(withName: "ball") {
            node, stop in
            if (node is SKShapeNode) {
                let ball = node as! SKShapeNode
                let num = ball.children[0]
                num.zRotation = ball.zRotation
            }
        }

    }
</code>```

They still refuse to rotate. If I change zRotation directly like num.zRotation = 2, they work.

How can I make them rotate in company with SKShapeNode?

Thx.

答:
You need to set your friction to a number other than 0.

Also, concerning the shape node performance:

look at the draw count at the bottom of 50 shapes:

```<code>for _ in 1...50 {
  let x = arc4random_uniform(UInt32(frame.maxX));
  let xx = CGFloat(x) - size.width/4

  let y = arc4random_uniform(UInt32(frame.maxY))
  let yy = CGFloat(y) - size.width/4

  let shape = SKShapeNode(circleOfRadius: 50)
  shape.strokeColor = .blue
  shape.lineWidth = 1
  shape.position = CGPoint(x: xx, y: yy)
  addChild(shape)
}
</code>```

But now compare that to this image of only 2 draws with only a few lines of refactoring:

```<code>func addFiftySprites() {

  let shape = SKShapeNode(circleOfRadius: 50)
  shape.strokeColor = .blue
  shape.lineWidth = 1

  let texture = SKView().texture(from: shape)

  for _ in 1...50 {
    let x = arc4random_uniform(UInt32(frame.maxX));
    let xx = CGFloat(x) - size.width/4

    let y = arc4random_uniform(UInt32(frame.maxY))
    let yy = CGFloat(y) - size.width/4

    let sprite = SKSpriteNode(texture: texture)
    sprite.position = CGPoint(x: xx, y: yy)

    addChild(sprite)
  }
}
</code>```

The magic here is using let texture = SKView().texture(from: <SKNode>) to convert the shape to a sprite :) let sprite = SKSpriteNode(texture: texture)

Body:
When press the screen, balls created with the following codes:

var n = 1
func addBall(_ x:CGFloat){
    let numShape =  SKShapeNode(circleOfRadius: 30)
    numShape.name  = "ball"
    numShape.position = CGPoint(x: x, y: frame.maxY-40)
    numShape.physicsBody = SKPhysicsBody(circleOfRadius: 30)
    numShape.fillColor = SKColor.white
    numShape.physicsBody?.density = 0.1
    numShape.physicsBody?.affectedByGravity = true
    numShape.physicsBody?.friction = 0;
    numShape.physicsBody?.restitution = 0.6
    numShape.physicsBody?.allowsRotation = true
    numShape.physicsBody?.isDynamic = true

    let numLabel = SKLabelNode(fontNamed: "Helvetica")
    numLabel.text = "\(n)"
    numLabel.name = "\(n)"
    numLabel.fontColor = .red
    numLabel.position = CGPoint(x: 0, y: 0)
    numLabel.verticalAlignmentMode = .center

    numShape.addChild(numLabel)
    self.addChild(numShape)

    n += 1
}

The balls can rotate, but their childNode numlabel don't rotate in company with them. I try to update their zRotation like below:

   override func update(_ currentTime: TimeInterval) {
        self.enumerateChildNodes(withName: "ball") {
            node, stop in
            if (node is SKShapeNode) {
                let ball = node as! SKShapeNode
                let num = ball.children[0]
                num.zRotation = ball.zRotation
            }
        }

    }

They still refuse to rotate. If I change zRotation directly like num.zRotation = 2, they work.

How can I make them rotate in company with SKShapeNode?

Thx.

Body:
You need to set your friction to a number other than 0.

Also, concerning the shape node performance:

look at the draw count at the bottom of 50 shapes:

for _ in 1...50 {
  let x = arc4random_uniform(UInt32(frame.maxX));
  let xx = CGFloat(x) - size.width/4

  let y = arc4random_uniform(UInt32(frame.maxY))
  let yy = CGFloat(y) - size.width/4

  let shape = SKShapeNode(circleOfRadius: 50)
  shape.strokeColor = .blue
  shape.lineWidth = 1
  shape.position = CGPoint(x: xx, y: yy)
  addChild(shape)
}

But now compare that to this image of only 2 draws with only a few lines of refactoring:

func addFiftySprites() {

  let shape = SKShapeNode(circleOfRadius: 50)
  shape.strokeColor = .blue
  shape.lineWidth = 1

  let texture = SKView().texture(from: shape)

  for _ in 1...50 {
    let x = arc4random_uniform(UInt32(frame.maxX));
    let xx = CGFloat(x) - size.width/4

    let y = arc4random_uniform(UInt32(frame.maxY))
    let yy = CGFloat(y) - size.width/4

    let sprite = SKSpriteNode(texture: texture)
    sprite.position = CGPoint(x: xx, y: yy)

    addChild(sprite)
  }
}

The magic here is using let texture = SKView().texture(from: <SKNode>) to convert the shape to a sprite :) let sprite = SKSpriteNode(texture: texture)


问:
How to format file in Visual Studio Code (hotkeys)?
How to format file | project folder | all project files (using hot keys AND using menu) in Visual Studio Code?</p>

答:
If you're on Windows use Shift + Alt + F to make your code "pretty".

(This is similar to Ctrl + K + D in Visual Studio)

You will have to do this for each individual file though.  I don't know of a way to format all files at once.


问:
F# Inline Function Specialization
My current project involves lexing and parsing script code, and as such I'm using fslex and fsyacc.  Fslex LexBuffers can come in either LexBuffer<char> and LexBuffer<byte> varieties, and I'd like to have the option to use both.

In order to user both, I need a lexeme function of type ^buf -> string.  Thus far, my attempts at specialization have looked like:

```<code>let inline lexeme (lexbuf: ^buf) : ^buf -> string where ^buf : (member Lexeme: char array) =
  new System.String(lexbuf.Lexeme)

let inline lexeme (lexbuf: ^buf) : ^buf -> string where ^buf : (member Lexeme: byte array) =
  System.Text.Encoding.UTF8.GetString(lexbuf.Lexeme)
</code>```

I'm getting a type error stating that the function body should be of type ^buf -> string, but the inferred type is just string.  Clearly, I'm doing something (majorly?) wrong.

Is what I'm attempting even possible in F#?  If so, can someone point me to the proper path?

Thanks!

答:
```<code>type LexBuffer<'a>(data : 'a []) =
  member this.Lexeme = data

let lexeme (buf : LexBuffer<'a>) =
  match box buf.Lexeme with
  | :? (char array) as chArr ->
      new System.String(chArr)
  | :? (byte array) as byArr ->
      System.Text.Encoding.UTF8.GetString(byArr)
  | _ -> invalidArg "buf" "must be either char or byte LexBuffer"

new LexBuffer<byte>([| 97uy; 98uy; 99uy |])
|> lexeme
|> printfn "%A"

new LexBuffer<char>([| 'a'; 'b'; 'c' |])
|> lexeme
|> printfn "%A"
</code>```

ContentLicense: CC BY-SA 2.5

Title: F# Inline Function Specialization

Body:
My current project involves lexing and parsing script code, and as such I'm using fslex and fsyacc.  Fslex LexBuffers can come in either LexBuffer<char> and LexBuffer<byte> varieties, and I'd like to have the option to use both.

In order to user both, I need a lexeme function of type ^buf -> string.  Thus far, my attempts at specialization have looked like:

let inline lexeme (lexbuf: ^buf) : ^buf -> string where ^buf : (member Lexeme: char array) =
  new System.String(lexbuf.Lexeme)

let inline lexeme (lexbuf: ^buf) : ^buf -> string where ^buf : (member Lexeme: byte array) =
  System.Text.Encoding.UTF8.GetString(lexbuf.Lexeme)

I'm getting a type error stating that the function body should be of type ^buf -> string, but the inferred type is just string.  Clearly, I'm doing something (majorly?) wrong.

Is what I'm attempting even possible in F#?  If so, can someone point me to the proper path?

Thanks!


问:
Creating Android Chart using MPAndroid Chart Library
I am currently working on implementing the MpAndroid Chart Library from Philip Jay GitHub account.
Following some tutorials, I have done its implementation. But I am having a very simple issue in adjusting the weight of the bar.

I am implementing it in such a way that its layout height would be 1/3 of my Screen and so the width. I tried different method using my layout but couldn't resolve the issue.

Is there any workaround I can do to change or adjust the weight of each bars preferably, a quarter of whats implemented is all I need. Also how can I change the background of the chart.

Would be glad if I can get a guideline on how to do it. Appreciate your response in advance

答:
```<code>    chart=(BarChart)findViewById(R.id.chart);
    ArrayList<String> xAxis=new ArrayList<>();
    ArrayList<IBarDataSet> dataSets=null;
    ArrayList<BarEntry> valueSet=new ArrayList<>();

    xAxis.add("Mozilla Firefox");
    xAxis.add("Google Chrome");
    xAxis.add("Internet Explorer");
    xAxis.add("Safari");

    valueSet.add(new BarEntry(25,0));
    valueSet.add(new BarEntry(20,1));
    valueSet.add(new BarEntry(40,2));
    valueSet.add(new BarEntry(30,3));

    BarDataSet barDataSet=new BarDataSet(valueSet,"Browser");
    barDataSet.setColors(new int[] {Color.RED,Color.GREEN,Color.MAGENTA,Color.BLUE});

    dataSets=new ArrayList<>();
    dataSets.add(barDataSet);

    YAxis yAxisRight=chart.getAxisRight();
    yAxisRight.setEnabled(false);

    BarData data=new BarData(xAxis,dataSets);
    chart.setExtraOffsets(0,0,0,20);
    chart.setData(data);
    chart.animateXY(2000,2000);
    chart.invalidate();
</code>```


问:
Prime Number Generator Optimisation (Project Euler #7)
I want to optimize this code so that the time to complete this task is shorter (I do want to keep printing all the prime numbers along the way):

(Getting 10001st prime number)

counter = 10001
target_num = 1          #because if we add 1 to it the first time, it will become 2
input('This may take a while, press Enter to continue; you can stop the program any time by pressing CTRL + C.')
while counter <= 10001 and counter > 0:
    target_num = target_num + 1
    for x in range(1, target_num + 1):
        if target_num % x == 0:
            if x == 1:
                pass
            elif x != target_num:
                break
            elif x == target_num:
                counter = counter - 1
                print (target_num)  #prints prime number so user knows if program is actually crunching numbers
print ('10001st prime number is: ' + str(target_num))
```

答:
I timed your code. This is how long it takes:

```<code>Over 72 seconds (%timeit died, sorry!)
</code>```

The glaring issue is the fact that you run your loop from 1 to target_num to find primes. That's not necessary.

Proof of that can be seen here.

Here's a version that runs upto the square root. You can remove those redundant ifs too.

```<code>def foo():
    counter = 10001
    target_num = 1          #because if we add 1 to it the first time, it will become 2
    while counter <= 10001 and counter > 0:
        target_num = target_num + 1
        for x in range(2, int(target_num ** 0.5) + 1 ):
            if target_num % x == 0:
                if x != target_num:
                    break
        else:
            counter -= 1

    print ('10001st prime number is: ' + str(target_num))
</code>```

Timing:

```<code>1 loop, best of 3: 442 ms per loop
</code>```

Further speedups may be achieved by stepping range by 2, so you skip checks for even numbers:

```<code>def foo():
    counter = 10000
    target_num = 1
    while counter <= 10001 and counter > 0:
        target_num = target_num + 2
        ...
</code>```

Timing:

```<code>1 loop, best of 3: 378 ms per loop
</code>```

Footnote: This answer explains the inadequacies of your current approach. However, for a completely new approach, check out Sieve of Eratosthenes - Finding Primes Python, or @AChampion's answer.

Body:
I timed your code. This is how long it takes:

Over 72 seconds (%timeit died, sorry!)

The glaring issue is the fact that you run your loop from 1 to target_num to find primes. That's not necessary.

Proof of that can be seen here.

Here's a version that runs upto the square root. You can remove those redundant ifs too.

def foo():
    counter = 10001
    target_num = 1          #because if we add 1 to it the first time, it will become 2
    while counter <= 10001 and counter > 0:
        target_num = target_num + 1
        for x in range(2, int(target_num ** 0.5) + 1 ):
            if target_num % x == 0:
                if x != target_num:
                    break
        else:
            counter -= 1

    print ('10001st prime number is: ' + str(target_num))

Timing:

1 loop, best of 3: 442 ms per loop

Further speedups may be achieved by stepping range by 2, so you skip checks for even numbers:

def foo():
    counter = 10000
    target_num = 1
    while counter <= 10001 and counter > 0:
        target_num = target_num + 2
        ...

Timing:

1 loop, best of 3: 378 ms per loop

Footnote: This answer explains the inadequacies of your current approach. However, for a completely new approach, check out Sieve of Eratosthenes - Finding Primes Python, or @AChampion's answer.


问:
ng-repeat not listing different json values, instead it just displays the entire json file content in single list item
ng-repeat is not listing different json values, instead it just displays the entire json file content in single list item

codepen

html:

```<code>      <div ng-app="myApp">

    <div ng-controller="myCtrl" class="container">

        <h2>Basic List</h2>

        <ul class="list-group">
            <li class="list-group-item" ng-reapeat="student">
                {{student}}
            </li>

        </ul>

    </div>

</div>
</code>```

All the json file content is in here. I just need the specific data to display on each list item.
For Example,

Student One

Student Two

Student Three

Student Four

Student Five

 See image for issue

JS

```<code><script>

var app = angular.module('myApp', []);
//$.ajax({url: app, crossDomain:true, dataType: 'json', type: 'GET'})
app.controller('myCtrl', function($scope, $http){
  $http.get("student.json")
 // $http.get("stud.json")
  .then(function(response) {
      $scope.student = response.data;
  });

});

</script>
</code>```

json

```<code>[

{
    "name" : "Student One"
},

{
    "name" : "Student Two"
},

{
    "name" : "Student Three"
},

{
    "name" : "Student Four"
},

{
    "name" : "Student Five"
}
</code>```

]

答:
Your ng-repeat should be look like, to be more on that, you are missing the proper syntax and its ng-repeat not ng-reapeat

```<code><li class="list-group-item" ng-repeat="stu in student" >
     {{stu.name}}
 </li>
</code>```

DEMO

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.student =
[
  {
    "name": "Student One"
  },
  {
    "name": "Student Two"
  },
  {
    "name": "Student Three"
  },
  {
    "name": "Student Four"
  },
  {
    "name": "Student Five"
  }
];
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
</head>
<body >
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp"  ng-controller="myCtrl" >
<div class="container">
<h2>Basic List</h2>
 <ul class="list-group">
  <li    ng-repeat="stu in student"  >
    {{stu.name}}
</li>
</ul>
</div>
</div>
</body>
 </code>```

Body:
ng-repeat is not listing different json values, instead it just displays the entire json file content in single list item

codepen

html:

Basic List

                {{student}}

All the json file content is in here. I just need the specific data to display on each list item.
For Example,

Student One

Student Two

Student Three

Student Four

Student Five

 See image for issue

JS

json

[

{
    "name" : "Student One"
},

{
    "name" : "Student Two"
},

{
    "name" : "Student Three"
},

{
    "name" : "Student Four"
},

{
    "name" : "Student Five"
}

]

Body:
Your ng-repeat should be look like, to be more on that, you are missing the proper syntax and its ng-repeat not ng-reapeat

<li class="list-group-item" ng-repeat="stu in student" >
     {{stu.name}}
 </li>

DEMO

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.student =
[
  {
    "name": "Student One"
  },
  {
    "name": "Student Two"
  },
  {
    "name": "Student Three"
  },
  {
    "name": "Student Four"
  },
  {
    "name": "Student Five"
  }
];
});

<!DOCTYPE html>
<html>
<head>
</head>
<body >
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp"  ng-controller="myCtrl" >
<div class="container">
<h2>Basic List</h2>
 <ul class="list-group">
  <li    ng-repeat="stu in student"  >
    {{stu.name}}
</li>
</ul>
</div>
</div>
</body>


问:
My python codes in general are very slow, is this normal?
I recently began self-learning python, and have been using this language for an online course in algorithms. For some reason, many of my codes I created for this course are very slow (relatively to C/C++ Matlab codes I have created in the past), and I'm starting to worry that I am not using python properly.

Here is a simple python and matlab code to compare their speed.

MATLAB

```<code>   for i = 1:100000000
        a = 1 + 1
   end
</code>```

Python

```<code>   for i in list(range(0, 100000000)):
        a=1 + 1
</code>```

The matlab code takes about 0.3 second, and the python code takes about 7 seconds. Is this normal? My python codes for much complex problems are very slow. For example, as a HW assignment, I'm running depth first search on a graph with about 900000 nodes, and this is taking forever. Thank you.

答:
Try using xrange instead of range.

The difference between them is that **xrange** generates the values as you use them instead of range, which tries to generate a static list at runtime.

Body:
I recently began self-learning python, and have been using this language for an online course in algorithms. For some reason, many of my codes I created for this course are very slow (relatively to C/C++ Matlab codes I have created in the past), and I'm starting to worry that I am not using python properly.

Here is a simple python and matlab code to compare their speed.

MATLAB

   for i = 1:100000000
        a = 1 + 1
   end

Python

   for i in list(range(0, 100000000)):
        a=1 + 1

The matlab code takes about 0.3 second, and the python code takes about 7 seconds. Is this normal? My python codes for much complex problems are very slow. For example, as a HW assignment, I'm running depth first search on a graph with about 900000 nodes, and this is taking forever. Thank you.


问:
Where is the repository of material.angular.io (the website) located?
In the official website of Material, it says

material.angular.io - We build our own documentation with Angular Material!

But where is the repository located (I mean the source code of the website)? I guess it is on Github but couldn't find it.

答:
The repository of material.angular.io website isn't this ?

https://github.com/angular/material.angular.io


问:
Open word using vba Mac - OS X
I am trying to open automatically an excel document on a Mac OS X, but it doesn't work. My code is:

```<code>Sub Button81_Click()
    Dim objWord
    Dim objDoc
    Set objWord = CreateObject("Word.Application")
    Set objDoc = objWord.Documents.Open("/Users/ricardo/Miniman/miniman_uti.docx")
    objWord.Visible = True
End Sub
</code>```

Will the path be wrong? For this path "/Users/ricardo/Miniman/miniman_uti.docx" it opens excel files. Why not word files?

Can someone please help me?

答:
Code to safely open a word doc from a file.
Handles the case where you already have word open.</p>

```<code>Dim w As Object
' If word is already open get ahold of the running instance
' Otherwise create a new instance
On Error Resume Next
Set w = GetObject(, "Word.Application")
If w Is Nothing Then Set w = CreateObject("Word.Application")
On Error GoTo 0
' Close all open files and shutdown Word
' Loop through any open documents and close them
Do Until w.Documents.Count = 0
    w.Documents(1).Close
Loop
w.Quit False
Set w = Nothing

' Now that all instances of word are closed, open the template
Dim wdApp As Object
Dim wdDoc As Object
Set wdApp = CreateObject("Word.application")
wdApp.Visible = True
wdApp.DisplayAlerts = False
Set wdDoc = wdApp.Documents.Open(Filename:="MYPATH")
</code>```

Title: Open word using vba Mac - OS X

Body:
I am trying to open automatically an excel document on a Mac OS X, but it doesn't work. My code is:

Sub Button81_Click()
    Dim objWord
    Dim objDoc
    Set objWord = CreateObject("Word.Application")
    Set objDoc = objWord.Documents.Open("/Users/ricardo/Miniman/miniman_uti.docx")
    objWord.Visible = True
End Sub

Will the path be wrong? For this path "/Users/ricardo/Miniman/miniman_uti.docx" it opens excel files. Why not word files?

Can someone please help me?

Body:
Code to safely open a word doc from a file.
Handles the case where you already have word open.

Dim w As Object
' If word is already open get ahold of the running instance
' Otherwise create a new instance
On Error Resume Next
Set w = GetObject(, "Word.Application")
If w Is Nothing Then Set w = CreateObject("Word.Application")
On Error GoTo 0
' Close all open files and shutdown Word
' Loop through any open documents and close them
Do Until w.Documents.Count = 0
    w.Documents(1).Close
Loop
w.Quit False
Set w = Nothing

' Now that all instances of word are closed, open the template
Dim wdApp As Object
Dim wdDoc As Object
Set wdApp = CreateObject("Word.application")
wdApp.Visible = True
wdApp.DisplayAlerts = False
Set wdDoc = wdApp.Documents.Open(Filename:="MYPATH")


问:
How do prototypes work under the hood?

"Put functions on a prototype object when you're going to create lots
  of copies of a particular kind of object and they all need to share
  common behaviors. By doing so, you'll save some memory by having just
  one copy of each function, but that's only the simplest benefit."

How exactly does this work under the hood?

答:
This is not as simple as it used to be, before the introduction of property getters and setters.

JavaScript Objects (and null)

A javascript object is some kind of collection of object properties and their values in memory.  A javascript object value is a some kind of reference to such a data collection. The javascript null value is used to represent the absence of an object. Although the "typeof" operator returns "object" when applied to null, this is an early language design flaw that is entrenched and cannot be changed: "null" is a datatype of its own and null is not an object.

The memory structure used to store object data is not defined in language standards. Some discussion of how different implementations handle and store object data is available such as this answer on V8's object data storage.

Private Properties and slots

Private internal properties are defined in language standards for various types of of objects, but are not generally accessible from JavaScript code. Internal properties are usually called "slots" in language documentation and written inside double square back notation. For example the internal [[Callable]] slot of an object is set true for function objects but can only be checked from code by seeing if the typeof operator returns "function" when applied to an object.

[[Prototype]] slot

One such internal slot is [[prototype]], which is an object reference to the next object in a prototype chain, or null if the end of the chain has been reached and there are no further objects in the chain. Its value can be accessed using the non-enumerable __proto__ getter/setter property of an object in Netscape flavored browsers (Microsoft did not implement it when they initially cloned JavaScript into Jscript) or using Object.getPrototypeOf  introduced in ECMAScript 5.1. The [[prototype]] property is mutable, but changing it on an existing object is discouraged in `Object.setPrototypeOf' documentation.

Named Object Properties

Named object properties can be implemented as key-value pairs stored in an object, or as a combination of getter/setter functions supplied for the property using Object.defineProperty (or associated Object.defineProperties method for multiple properties).

Local or "own" properties

Property values may be located in the data collection of an object reference, or accessed by searching the [[prototype]] pointer chain (the "inheritance chain") set up for the object. Checking that a property is local to the object being referenced can be achieved using  the .hasOwnProperty method of an objects.

How property access works

Getters and setters for an object property take precedence over the use of key-value pairs. If a property of an object was defined using a setter/getter pair, the setter or getter function will be called to read or write the property even if the property is inherited. Superficially this suggests the prototype chain must be searched for setters when an object property being written does not already exist as a local property. How this might be optimized or not would depend on the JavaScript Engine and is not covered here.

For an ordinary key-value object property, reading the property will search the object and its prototype chain, in order of object and [[prototype]] linkages, to see if the property already exists. If it does its value is returned from where it was found. If it is not found before reaching the end of the prototype chain, undefined is returned as the property value.

Writing a key-value type property, without a setter or getter, simply writes the value as a local property of the object being written to, creating a new property if the name of property being written does not exist already.

Locally writing a key-value property means that when reading it back, the local value will returned without searching the inheritance chain. So writing the value of an inherited property on one instance object does not affect the value inherited by another object of the same class.

The delete operator only removes local properties from an object. If an inherited property that has been written to is deleted, its value reverts to the inherited value. Attempting to delete an object property that is being inherited has no effect.

Where does the prototype chain come from.

Objects in Javascipt are created by constructor functions. Each constructor function (object) has a property called prototype. When an object is constructed, its internal [[prototype]] slot is set to the object value held in the prototype property of its constructor, at the time the object was created. If you need to go there, this means that changing the value of a constructor's prototype property does not affect objects previously created by the constructor.

Class declarations set up a constructor function with the same name as the class name. Methods defined within a class declaration are added as properties of the prototype property of the constructor with effect that they are inherited by class instance objects.

A big difference between constructors declared using class and function is that theprototype property of class constructors is read only and cannot be changed (noting properties of the prototype are not read only and can be changed). This mechanism protects the prototype chain of classes and extensions from being updated after declaration of class structures.

See also Inheritance and the prototype chain on MDN, or a web search for "how does prototypal inheritance work in javascript".

Title: How do prototypes work under the hood?


问:
How to display and loop record from database to label one by one with timer
I am developing windows form project with C# where I need to display record from access database to label, but it should not show entire record at a time rather it should show record from database one at a time and so on looping one by one with timer say 5 seconds. Any kind of suggestion will be helpful and will be highly appreciable.
Below is the code I was trying but gave up:</p>

```<code>   private void BindLabel()
   {
        string constring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\LicensedDB.accdb;
        Persist Security Info=True;Jet OLEDB:Database Password=abc123";
        using (OleDbConnection con = new OleDbConnection(constring))
        {
            using (OleDbCommand cmd = new OleDbCommand("SELECT TaskDetails FROM TaskReminder ", con))
            {
                cmd.CommandType = CommandType.Text;
                using (OleDbDataAdapter sda = new OleDbDataAdapter(cmd))
                {
                    using (DataTable dt = new DataTable())
                    {
                        sda.Fill(dt);

                       //label1
                        // Please guide me, any suggestion will be higly helpful and appreciable.

                    }
                }
            }
        }
    }
</code>```

答:
Make DataTable global to form and then use timer

```<code>DataTable dtReminders = null;
int i = 0;
private void BindLabel()
   {
        string constring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\LicensedDB.accdb;
        Persist Security Info=True;Jet OLEDB:Database Password=abc123";
        using (OleDbConnection con = new OleDbConnection(constring))
        {
            using (OleDbCommand cmd = new OleDbCommand("SELECT TaskDetails FROM TaskReminder ", con))
            {
                cmd.CommandType = CommandType.Text;
                using (OleDbDataAdapter sda = new OleDbDataAdapter(cmd))
                {
                        sda.Fill(dtReminders);
                        if(dtReminders.Rows.Count > 0)
                          timer.Start();
                }
            }
        }
    }
</code>```

In timer tick event add below lines

```<code>if(i >= dtReminders.Rows.Count)
    i = 0;
if(dtReminders.Rows[i]["columnName"] != null)
     lblRemider.Text = dtReminders.Rows[i]["columnName"].ToString();
     i++;
</code>```

Body:
I am developing windows form project with C# where I need to display record from access database to label, but it should not show entire record at a time rather it should show record from database one at a time and so on looping one by one with timer say 5 seconds. Any kind of suggestion will be helpful and will be highly appreciable.
Below is the code I was trying but gave up:

   private void BindLabel()
   {
        string constring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\LicensedDB.accdb;
        Persist Security Info=True;Jet OLEDB:Database Password=abc123";
        using (OleDbConnection con = new OleDbConnection(constring))
        {
            using (OleDbCommand cmd = new OleDbCommand("SELECT TaskDetails FROM TaskReminder ", con))
            {
                cmd.CommandType = CommandType.Text;
                using (OleDbDataAdapter sda = new OleDbDataAdapter(cmd))
                {
                    using (DataTable dt = new DataTable())
                    {
                        sda.Fill(dt);

                       //label1
                        // Please guide me, any suggestion will be higly helpful and appreciable.

                    }
                }
            }
        }
    }

Body:
Make DataTable global to form and then use timer

DataTable dtReminders = null;
int i = 0;
private void BindLabel()
   {
        string constring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\LicensedDB.accdb;
        Persist Security Info=True;Jet OLEDB:Database Password=abc123";
        using (OleDbConnection con = new OleDbConnection(constring))
        {
            using (OleDbCommand cmd = new OleDbCommand("SELECT TaskDetails FROM TaskReminder ", con))
            {
                cmd.CommandType = CommandType.Text;
                using (OleDbDataAdapter sda = new OleDbDataAdapter(cmd))
                {
                        sda.Fill(dtReminders);
                        if(dtReminders.Rows.Count > 0)
                          timer.Start();
                }
            }
        }
    }

In timer tick event add below lines

if(i >= dtReminders.Rows.Count)
    i = 0;
if(dtReminders.Rows[i]["columnName"] != null)
     lblRemider.Text = dtReminders.Rows[i]["columnName"].ToString();
     i++;


问:
Create custom LocalChangeInterceptor
I am writing an application using Spring Boot. In my application I am going to use localized URL smth like http://localhost:8080/School/**en**/xxx/... . I try to implement Custom Locale Interceptor. In listing below the first variant works fine. I would like to use the second variant but instead of France or Germany locale doesn't change and remains en_US. Can anybody please suggest me anything ?

```<code>@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter {

1 VARIANT

@Bean
public LocaleResolver localeResolver() {
    SessionLocaleResolver slr = new SessionLocaleResolver();
    slr.setDefaultLocale(Locale.GERMANY);
    return slr;
}

@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
    LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
    lci.setParamName("lang");
    return lci;
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(localeChangeInterceptor());
}

2 VARIANT

@Bean
public LangInterceptor langInterceptor() {
    return new LangInterceptor();
}

    @Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor( langInterceptor());
}

@Bean
public SessionLocaleResolver sessionLocaleResolver() {
    SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
    sessionLocaleResolver.setDefaultLocale(Locale.GERMANY);
    return sessionLocaleResolver;
}
}
</code>```

And my custom Interceptor:

```<code>public class LangInterceptor extends HandlerInterceptorAdapter {

@Autowired
LocaleResolver sessionLocaleResolver;
Locale locale;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    if (StringUtils.startsWithIgnoreCase(request.getServletPath(), "/it/")) {
        locale = new Locale("it");
    } else {
        locale = new Locale("en");
    }
    sessionLocaleResolver.setLocale(request, response, Locale.FRENCH);
    return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

}
}
</code>```

答:
You can't throw in a random HandlerInterceptorAdapter to change the locale. Spring uses AcceptHeaderLocaleResolver by default and you want to resolve based on path segment. Extend WebMvcConfigurerAdapter, then do the following:

```<code>@Bean
public LocaleResolver localeResolver() {
   // return custom LocaleResolver
}
</code>```

However, I'm cautioning you that you're going against the HTTP spec. The Accept-Language header is meant for this purpose, which is what the AcceptHeaderLocaleResolver uses.

You don't need a LocaleChangeInterceptor because it operates on a query parameter.

Title: Create custom LocalChangeInterceptor

Body:
I am writing an application using Spring Boot. In my application I am going to use localized URL smth like http://localhost:8080/School/**en**/xxx/... . I try to implement Custom Locale Interceptor. In listing below the first variant works fine. I would like to use the second variant but instead of France or Germany locale doesn't change and remains en_US. Can anybody please suggest me anything ?

@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter {

1 VARIANT

@Bean
public LocaleResolver localeResolver() {
    SessionLocaleResolver slr = new SessionLocaleResolver();
    slr.setDefaultLocale(Locale.GERMANY);
    return slr;
}

@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
    LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
    lci.setParamName("lang");
    return lci;
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(localeChangeInterceptor());
}

2 VARIANT

@Bean
public LangInterceptor langInterceptor() {
    return new LangInterceptor();
}

    @Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor( langInterceptor());
}

@Bean
public SessionLocaleResolver sessionLocaleResolver() {
    SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
    sessionLocaleResolver.setDefaultLocale(Locale.GERMANY);
    return sessionLocaleResolver;
}
}

And my custom Interceptor:

public class LangInterceptor extends HandlerInterceptorAdapter {

@Autowired
LocaleResolver sessionLocaleResolver;
Locale locale;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    if (StringUtils.startsWithIgnoreCase(request.getServletPath(), "/it/")) {
        locale = new Locale("it");
    } else {
        locale = new Locale("en");
    }
    sessionLocaleResolver.setLocale(request, response, Locale.FRENCH);
    return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

}
}

Body:
You can't throw in a random HandlerInterceptorAdapter to change the locale. Spring uses AcceptHeaderLocaleResolver by default and you want to resolve based on path segment. Extend WebMvcConfigurerAdapter, then do the following:

@Bean
public LocaleResolver localeResolver() {
   // return custom LocaleResolver
}

However, I'm cautioning you that you're going against the HTTP spec. The Accept-Language header is meant for this purpose, which is what the AcceptHeaderLocaleResolver uses.

You don't need a LocaleChangeInterceptor because it operates on a query parameter.


问:
Using a string argument to represent an object
If I have the following code:

```<code>TextBox txtUsername = new TextBox();
void setEnabled(string str, bool enable)
{
    // use str to find the TextBox object
    // str.Enabled = enable;
}
</code>```

Is this kinda thing even possible?

I want to be passing in 'Username' and then be prepending it with 'txt'.

答:
One way to do this is to store all your text fields in a dictionary with an identifier:</p>

```<code>Dictionary<string,TextBox> index = new Dictionary<string,TextBox>();
index.add("Username",txtUsername);

void setEnabled(string str, bool enable)
{
    index[str].Enabled = enable;
}
</code>```

Body:
If I have the following code:

TextBox txtUsername = new TextBox();
void setEnabled(string str, bool enable)
{
    // use str to find the TextBox object
    // str.Enabled = enable;
}

Is this kinda thing even possible?

I want to be passing in 'Username' and then be prepending it with 'txt'.

Body:
One way to do this is to store all your text fields in a dictionary with an identifier:

Dictionary<string,TextBox> index = new Dictionary<string,TextBox>();
index.add("Username",txtUsername);

void setEnabled(string str, bool enable)
{
    index[str].Enabled = enable;
}


答:
There a many resources for fast prime number generators.

For example, you could install primesieve which provides:

```<code>In []:
import primesieve
primesieve.nth_prime(10001)

Out[]:
104743

In []:
%timeit primesieve.nth_prime(10001)

Out[]:
28.3 µs ± 549 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
</code>```

A native python implementation of a simple sieve:

```<code>In []:
import itertools as it

def primes():
    yield 2
    sieve = {}
    for n in it.count(3, 2):
        if n not in sieve:
            sieve[n*n] = 2*n
            yield n
            continue
        a = sieve.pop(n)
        x = n + a
        while x in sieve:
            x += a
        sieve[x] = a

def nth_prime(n):
    return next(it.islice(primes(), n-1, None))

nth_prime(10001)

Out[]:
104743

In []:
%timeit nth_prime(10001)

Out[]:
26.3 ms ± 629 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
</code>```

Title: Prime Number Generator Optimisation (Project Euler #7)

Body:
I want to optimize this code so that the time to complete this task is shorter (I do want to keep printing all the prime numbers along the way):

(Getting 10001st prime number)

counter = 10001
target_num = 1          #because if we add 1 to it the first time, it will become 2
input('This may take a while, press Enter to continue; you can stop the program any time by pressing CTRL + C.')
while counter <= 10001 and counter > 0:
    target_num = target_num + 1
    for x in range(1, target_num + 1):
        if target_num % x == 0:
            if x == 1:
                pass
            elif x != target_num:
                break
            elif x == target_num:
                counter = counter - 1
                print (target_num)  #prints prime number so user knows if program is actually crunching numbers
print ('10001st prime number is: ' + str(target_num))

Body:
There a many resources for fast prime number generators.

For example, you could install primesieve which provides:

In []:
import primesieve
primesieve.nth_prime(10001)

Out[]:
104743

In []:
%timeit primesieve.nth_prime(10001)

Out[]:
28.3 µs ± 549 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

A native python implementation of a simple sieve:

In []:
import itertools as it

def primes():
    yield 2
    sieve = {}
    for n in it.count(3, 2):
        if n not in sieve:
            sieve[n*n] = 2*n
            yield n
            continue
        a = sieve.pop(n)
        x = n + a
        while x in sieve:
            x += a
        sieve[x] = a

def nth_prime(n):
    return next(it.islice(primes(), n-1, None))

nth_prime(10001)

Out[]:
104743

In []:
%timeit nth_prime(10001)

Out[]:
26.3 ms ± 629 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)


答:
Unfortunately, python's amazing flexibility and ease comes at the cost of being slow. And also, for such large values of iteration, I suggest using itertools module as it has faster caching.

The xrange is a good solution however if you want to iterate over dictionaries and such, it's better to use itertools as in that, you can iterate over any type of sequence object.

Title: My python codes in general are very slow, is this normal?


答:
If you are just trying to remove duplicates, you can try this:</p>

```<code>tosort = [ 5, 6, 7, 21, 5, 9, 6, 9]
seen = []
for num in tosort:
    if not (num in seen):
         seen.append(num)
print(seen)
</code>```

Title: Removing similar elements but leaving unique ones by looping

Body:
I have to remove similar elements from a list which is not sorted, looks like this.

[(579, 271, 97, 114), (580, 271, 97, 114), (578, 272, 97, 114), (579, 272, 97, 114), (580, 272, 97, 114), (581, 272, 97, 114), (577, 273, 97, 114), (578, 273, 97, 114), (579, 273, 97, 114), (580, 273, 97, 114), (581, 273, 97, 114), (582, 273, 97, 114), (577, 274, 97, 114), (578, 274, 97, 114), (579, 274, 97, 114), (580, 274, 97, 114), (581, 274, 97, 114), (582, 274, 97, 114), (577, 275, 97, 114), (578, 275, 97, 114), (579, 275, 97, 114), (580, 275, 97, 114), (581, 275, 97, 114), (578, 276, 97, 114), (579, 276, 97, 114), (580, 276, 97, 114), (581, 276, 97, 114), (579, 277, 97, 114), (22, 460, 97, 114), (23, 460, 97, 114), (133, 460, 97, 114), (134, 460, 97, 114), (21, 461, 97, 114), (22, 461, 97, 114), (23, 461, 97, 114), (24, 461, 97, 114), (132, 461, 97, 114), (133, 461, 97, 114), (134, 461, 97, 114), (135, 461, 97, 114), (20, 462, 97, 114), (21, 462, 97, 114), (22, 462, 97, 114), (23, 462, 97, 114), (24, 462, 97, 114), (131, 462, 97, 114), (132, 462, 97, 114), (133, 462, 97, 114), (134, 462, 97, 114), (135, 462, 97, 114), (136, 462, 97, 114), (20, 463, 97, 114), (21, 463, 97, 114), (22, 463, 97, 114), (23, 463, 97, 114), (24, 463, 97, 114), (131, 463, 97, 114), (132, 463, 97, 114), (133, 463, 97, 114), (134, 463, 97, 114), (135, 463, 97, 114), (136, 463, 97, 114), (20, 464, 97, 114), (21, 464, 97, 114), (22, 464, 97, 114), (23, 464, 97, 114), (24, 464, 97, 114), (131, 464, 97, 114), (132, 464, 97, 114), (133, 464, 97, 114), (134, 464, 97, 114), (135, 464, 97, 114), (136, 464, 97, 114), (21, 465, 97, 114), (22, 465, 97, 114), (23, 465, 97, 114), (132, 465, 97, 114), (133, 465, 97, 114), (134, 465, 97, 114), (135, 465, 97, 114), (22, 466, 97, 114), (133, 466, 97, 114), (134, 466, 97, 114)]

i want to leave unique elements from comes up first in the head, but remove elements within the difference of 5.

I've coded a function compare difference between each element, but it keeps getting large.

def compare_remove(input_list):
    cnt = 0
    glob_cnt = 0
    output_list = [input_list[0]]

    while True:

        for i in range(len(input_list)):
            if i <= cnt:
                print 'jump || '
                continue

            if abs(output_list[cnt][0] - input_list[i][0]) <= 5:
                if abs(output_list[cnt][0] - input_list[i][0]) == 0:
                    continue

                print 'skip ||' + str(output_list[cnt]) +' || ' + str(input_list[i])
                continue
            else:
                print 'append || ' + str(input_list[i])
                output_list.append(input_list[i])

        print 'loop out || '
        input_list = output_list
        cnt+=1

        if cnt == 100:
            break
        try:
            output_list[cnt]
        except:
            break

    return output_list

it compares the first element of elements, and the difference between previous one, remove it.

Body:
If you are just trying to remove duplicates, you can try this:

tosort = [ 5, 6, 7, 21, 5, 9, 6, 9]
seen = []
for num in tosort:
    if not (num in seen):
         seen.append(num)
print(seen)


问:
Factory Pattern implementation in C#
I'm implementing a factory pattern that looks as follows.

```<code>public class FeedFactory
{
    #region Singleton Pattern
    //..
    #endregion

    private static Feed[] _factory = new Feed[(int)FeedType.Total];

    public void RegisterFeed(FeedType feedType,Feed feed)
    {
        if (_factory[(int)feedType] == null)
        {
            _factory[(int)feedType] = feed;
        }
        else
        {
            // already registered
        }
    }

    public Feed GetFeed(FeedType feedType)
    {
        return _factory[(int)feedType];
    }
}
</code>```

Here, Feed is an abstract class from which the different classes inherit. How can I register the different classes? Is it possible to do it from their constructor?

答:
This is not a factory pattern. A factory will always have some constructor logic in it, at least one new. That's the idea of a factory: the caller doesn't have to worry about how objects are created. This is a singleton repository.

So first of all, instead of using an array, you should be having a type indexed dictionary.

```<code>private static Dictionary<Type, Feed> _singletons = new Dictionary<Type, Feed>();
</code>```

After that, you don't need a register method. The dictionary should be filled automatically when you retrieve singletons.

Now I suppose your Feed class has a default constructor without arguments. In that case, you can implement a factory method directly from the abstract class Feed. We're going to use some generics here, because it allows you to control inheritance:

```<code>public abstract class Feed
{
    public static T GetInstance<T>() where T:Feed, new()
    {
        T instance = new T();
        // TODO: Implement here other initializing behaviour
        return instance;
    }
}
</code>```

Now back to your singleton repository.

```<code>public class FeedSingletonRepository
{
    private static readonly object _padlock = new object();
    private static Dictionary<Type, Feed> _singletons = new Dictionary<Type, Feed>();

    public static T GetFeed<T>() where T:Feed
    {
        lock(_padlock)
        {
             if (!_singletons.ContainsKey(typeof(T))
             {
                 _singletons[typeof(T)] = Feed.GetInstance<T>();
             }
             return (T)_singletons[typeof(T)];
        }
    }
}
</code>```

Note that I included a threadsafe behaviour which is a good thing to do when you work with singletons.

Now if you want to get the singleton for a given type inheriting from Feed (let's call it SpecializedFeedType), all you have to do is:

```<code>var singleton = FeedSingletonRepository.GetFeed<SpecializedFeedType>();
</code>```

or

```<code>SpecializedFeedType singleton = FeedSingletonRepository.GetFeed();
</code>```

which is the same line with a slightly different syntax.

Edit2: changed some syntax errors.

Title: Factory Pattern implementation in C#

Body:
I'm implementing a factory pattern that looks as follows.

public class FeedFactory
{
    #region Singleton Pattern
    //..
    #endregion

    private static Feed[] _factory = new Feed[(int)FeedType.Total];

    public void RegisterFeed(FeedType feedType,Feed feed)
    {
        if (_factory[(int)feedType] == null)
        {
            _factory[(int)feedType] = feed;
        }
        else
        {
            // already registered
        }
    }

    public Feed GetFeed(FeedType feedType)
    {
        return _factory[(int)feedType];
    }
}

Here, Feed is an abstract class from which the different classes inherit. How can I register the different classes? Is it possible to do it from their constructor?

Body:
This is not a factory pattern. A factory will always have some constructor logic in it, at least one new. That's the idea of a factory: the caller doesn't have to worry about how objects are created. This is a singleton repository.

So first of all, instead of using an array, you should be having a type indexed dictionary.

private static Dictionary<Type, Feed> _singletons = new Dictionary<Type, Feed>();

After that, you don't need a register method. The dictionary should be filled automatically when you retrieve singletons.

Now I suppose your Feed class has a default constructor without arguments. In that case, you can implement a factory method directly from the abstract class Feed. We're going to use some generics here, because it allows you to control inheritance:

public abstract class Feed
{
    public static T GetInstance<T>() where T:Feed, new()
    {
        T instance = new T();
        // TODO: Implement here other initializing behaviour
        return instance;
    }
}

Now back to your singleton repository.

public class FeedSingletonRepository
{
    private static readonly object _padlock = new object();
    private static Dictionary<Type, Feed> _singletons = new Dictionary<Type, Feed>();

    public static T GetFeed<T>() where T:Feed
    {
        lock(_padlock)
        {
             if (!_singletons.ContainsKey(typeof(T))
             {
                 _singletons[typeof(T)] = Feed.GetInstance<T>();
             }
             return (T)_singletons[typeof(T)];
        }
    }
}

Note that I included a threadsafe behaviour which is a good thing to do when you work with singletons.

Now if you want to get the singleton for a given type inheriting from Feed (let's call it SpecializedFeedType), all you have to do is:

var singleton = FeedSingletonRepository.GetFeed<SpecializedFeedType>();

or

SpecializedFeedType singleton = FeedSingletonRepository.GetFeed();

which is the same line with a slightly different syntax.

Edit2: changed some syntax errors.


问:
cordova build for Android fails from VS but not from console
I am developing a Cordova app for Android and iOS with Visual Studio 2015 Update 3 and recently I am having some problems building for Android (iOS builds work fine).

When I build from Visual Studio I get the following error (I am using diagnostic MSBuild output, but this is all that is shown related to the error, towards the end of the log).

```<code>1>                     No scripts found for hook "before_compile". (TaskId:25)
1>                     ANDROID_HOME=C:\Program Files (x86)\Android\android-sdk (TaskId:25)
1>                     JAVA_HOME=c:\Program Files\Java\jdk1.8.0_131\ (TaskId:25)
1>                     Reading build config file: C:\apprep\build.json (TaskId:25)
1>16:58:37.536     1>
1>MSBUILD : cordova-build error : TypeError: undefined is not a function
1>                     TypeError undefined is not a function (TaskId:25)
1>                   Done executing task "MdaVsCli" -- FAILED. (TaskId:25)
</code>```

However, if I run the command cordova build android from the command prompt it works well.

I am using Cordova 7.0.1, Node 6.11.0, npm 3.10.10, Java 1.8.0.131.

I have tried countless solutions to this problem (uninstalling and reinstalling tools and modules, cache cleaning, etc. etc.). I cannot figure what is wrong with the Visual Studio tools for Cordova. Can I find additional logging somewhere that could help me realize where is this undefine is not a function error coming from?

答:
I believe the root cause is that your version of Node is too low. I hit this trying to run through a MSVC Cordova tutorial on push notifications. MSVC defaults to an ancient Node release like v0.11.16. But one of the plugins they tell you use in the tutorial has been updated and now requires a higher version of the Android platform, which required a newer version of Node (the default LTS release v6.11.0 worked fine for me).

Uninstall any old versions of Node.

Install the LTS version of Node (v6.11.0 when I wrote this) at https://nodejs.org/en/download/.

Restart Windows (really, I encountered one situation where a process or daemon was hanging onto a cached proxy version of node somehow that would have prevented it from being deleted like it was supposed to).

Open cmd.exe and type where node.exe, ensure that the path to your v6.11.0 release comes first. If not modify your PATH and restart.

In MSVC under Options -> Projects and Solutions -> External Web Tools add the path to your 6.11.0 version of node.exe to the top of
the list. (all docs tell you to do this but it may not be necessary, at least mine built fine without it).

In MSVC under Options -> Tools for Apache Cordova -> Cordova Tools disable "Use a sandboxed version of NodeJS".

In MSVC under Options -> Tools for Apache Cordova -> Cordova Tools choose "Clear Cordova Cache".

NOTE: instructions 8-11 are recommended if you update from v5 to v6 of Cordova (see https://stackoverflow.com/a/29990937/2448947)

In the console type npm install -g cordova@X.Y.Z to install (where X.Y.Z is the cordova CLI version you chose in your project's config.xml) to ensure the new version of Node has Cordova installed.

Update your platform with cordova platform update android.

In the directory of your project, run cordova plugin list.

For each plugin listed in (10), run cordova plugin remove <X> AND cordova plugin add <X> to reinstall the plugin.

Ensure you see "BUILD SUCCESSFUL" running cordova build android from the console.

Verify the build works in MSVC as well.

You can now easily repro the "TypeError undefined is not a function" bug by turning "Use a sandboxed version of NodeJS" back on in the MSVC settings and rebuilding. Therefore the root cause must be due to an obsolete release of NodeJS.

My favorite thing about this is how the software community attempted to solve the DLL Hell problem with half a dozen different incompatible package managers that are now constantly conflicting with each other.

Body:
I am developing a Cordova app for Android and iOS with Visual Studio 2015 Update 3 and recently I am having some problems building for Android (iOS builds work fine).

When I build from Visual Studio I get the following error (I am using diagnostic MSBuild output, but this is all that is shown related to the error, towards the end of the log).

1>                     No scripts found for hook "before_compile". (TaskId:25)
1>                     ANDROID_HOME=C:\Program Files (x86)\Android\android-sdk (TaskId:25)
1>                     JAVA_HOME=c:\Program Files\Java\jdk1.8.0_131\ (TaskId:25)
1>                     Reading build config file: C:\apprep\build.json (TaskId:25)
1>16:58:37.536     1>
1>MSBUILD : cordova-build error : TypeError: undefined is not a function
1>                     TypeError undefined is not a function (TaskId:25)
1>                   Done executing task "MdaVsCli" -- FAILED. (TaskId:25)

However, if I run the command cordova build android from the command prompt it works well.

I am using Cordova 7.0.1, Node 6.11.0, npm 3.10.10, Java 1.8.0.131.

I have tried countless solutions to this problem (uninstalling and reinstalling tools and modules, cache cleaning, etc. etc.). I cannot figure what is wrong with the Visual Studio tools for Cordova. Can I find additional logging somewhere that could help me realize where is this undefine is not a function error coming from?


问:
Cannot resolve method putExtra
I am working through an app in Android Studio that passes data using intent for school. I have created my object to pass the data through and started the Intent but I keep getting a warning that my putExtra method cannot be resolved. Any ideas?
Thanks in advance.

```<code>public class MainActivity extends AppCompatActivity {

private ContactInfo contactobject;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Bundle extra = getIntent().getExtras();
    contactobject = (ContactInfo)extra.get("contact");
    if (contactobject == null )
        contactobject = new ContactInfo();

    TextView name1 = (TextView) findViewById(R.id.Name1);
    name1.setText(contactobject.getOneName());

    TextView phone1 = (TextView) findViewById(R.id.Phone1);
    phone1.setText(contactobject.getOnePhone());

    TextView email1 = (TextView) findViewById(R.id.Email1);
    email1.setText(contactobject.getOneEmail());

    TextView kin1 = (TextView) findViewById(R.id.Kin1);
    kin1.setText(contactobject.getOneKin());

    TextView name2 = (TextView) findViewById(R.id.Name2);
    name2.setText(contactobject.getTwoName());

    TextView phone2 = (TextView) findViewById(R.id.Phone2);
    phone2.setText(contactobject.getTwoPhone());

    TextView email2 = (TextView) findViewById(R.id.Email2);
    email2.setText(contactobject.getTwoEmail());

    TextView kin2 = (TextView) findViewById(R.id.Kin2);
    kin2.setText(contactobject.getTwoEmail());

}

public void EditPrimary(View view)
{
    Intent intent1 = new Intent(getApplicationContext(), Edit1.class);
    Intent intent = intent1.putExtra("contact", contactobject);
    startActivity(intent1);
}

}
</code>```

答:
You can't assign the putExtra call to a new intent variable:</p>

```<code>public void EditPrimary(View view)
{
    Intent intent1 = new Intent(getApplicationContext(), Edit1.class);
    intent1.putExtra("contact", contactobject);
    startActivity(intent1);
}
</code>```

Title: Cannot resolve method putExtra

Body:
I am working through an app in Android Studio that passes data using intent for school. I have created my object to pass the data through and started the Intent but I keep getting a warning that my putExtra method cannot be resolved. Any ideas?
Thanks in advance.

public class MainActivity extends AppCompatActivity {

private ContactInfo contactobject;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Bundle extra = getIntent().getExtras();
    contactobject = (ContactInfo)extra.get("contact");
    if (contactobject == null )
        contactobject = new ContactInfo();

    TextView name1 = (TextView) findViewById(R.id.Name1);
    name1.setText(contactobject.getOneName());

    TextView phone1 = (TextView) findViewById(R.id.Phone1);
    phone1.setText(contactobject.getOnePhone());

    TextView email1 = (TextView) findViewById(R.id.Email1);
    email1.setText(contactobject.getOneEmail());

    TextView kin1 = (TextView) findViewById(R.id.Kin1);
    kin1.setText(contactobject.getOneKin());

    TextView name2 = (TextView) findViewById(R.id.Name2);
    name2.setText(contactobject.getTwoName());

    TextView phone2 = (TextView) findViewById(R.id.Phone2);
    phone2.setText(contactobject.getTwoPhone());

    TextView email2 = (TextView) findViewById(R.id.Email2);
    email2.setText(contactobject.getTwoEmail());

    TextView kin2 = (TextView) findViewById(R.id.Kin2);
    kin2.setText(contactobject.getTwoEmail());

}

public void EditPrimary(View view)
{
    Intent intent1 = new Intent(getApplicationContext(), Edit1.class);
    Intent intent = intent1.putExtra("contact", contactobject);
    startActivity(intent1);
}

}

Body:
You can't assign the putExtra call to a new intent variable:

public void EditPrimary(View view)
{
    Intent intent1 = new Intent(getApplicationContext(), Edit1.class);
    intent1.putExtra("contact", contactobject);
    startActivity(intent1);
}


问:
what is the best way to transform a java Class into a php class?
I'd like to transform my java Class file intp a php class file. Do you know a good open source tool to do this?

Thanks you very much,

Bat

答: Using a conversion script will result in bad or garbage code. To achieve a usable result you should read Java class carefully and implement in PHP.</p>


问:
Why this while loop does not work?
Thanks everyone! I changed my code, and it still gives the error:

list index out of range.

Why?

```<code>M  = []
B = [1, 3, 5]
C = [2, 4, 6]
while (B and C):
    if B[0] <= C[0]:
        M.append(B.pop(0))
    if C[0] <= B[0]:
        M.append(C.pop(0))

print('Updated list: ', M)
</code>```

`

答:
B and C converge to:

```<code>B = [4, 5]
C = [2, 3, 6]
</code>```

C[0] (2) is clearly not greater or equal to than B[0] (4)

so your branch to pop B stops being hit, and you get stuck in an infinite loop

Title: Why this while loop does not work?

Body:
Thanks everyone! I changed my code, and it still gives the error:

list index out of range.

Why?

M  = []
B = [1, 3, 5]
C = [2, 4, 6]
while (B and C):
    if B[0] <= C[0]:
        M.append(B.pop(0))
    if C[0] <= B[0]:
        M.append(C.pop(0))

print('Updated list: ', M)

`

Body:
B and C converge to:

B = [4, 5]
C = [2, 3, 6]

C[0] (2) is clearly not greater or equal to than B[0] (4)

so your branch to pop B stops being hit, and you get stuck in an infinite loop


问:
Pyramid: resource tree in URL Dispatch(hybrid) application
I am trying to implement dynamic ACLs(including row-level security) in URL Dispatch app.
Defining Root factory only doesn't seem to be sufficient as I need to perform individual authz checks for each secured endpoint. My setup looks as follows(I was using pyramid docs and mmerickel's tutorials as a guide):

config.py

```<code>...
settings = config.registry.settings
config = Configurator(settings=settings, root_factory=RootPermissionFactory)
config.set_authentication_policy(CustomAuthenticationPolicy(settings))
config.set_authorization_policy(ACLAuthorizationPolicy())
...
</code>```

views.py

```<code>#import ...

@view_defaults(renderer='json', permission='secured')
class RecordsView(object):
    ...

   @view_config(request_method='GET', route_name='records_by_id')
   def get(self):
        record = self.request.context.data
        if not record:
            return HTTPNotFound()
        return record

    @view_config(request_method='GET', route_name='records')
    def get_by_owners(self):
        owner_uids = self.request.params.mixed()['owner_uids']
        return records_service.get_records(owner_uids=owner_uids)

def includeme(config):
    config.add_route('records', '/records', factory=RecordsResource)
    config.add_route('records_by_id', 'records/{record_id}', factory=RecordFactory, traverse='{record_id}')
</code>```

authorization.py

```<code>class RootPermissionFactory(object):
    __name__ = None
    __parent__ = None

    def __acl__(self):
        return [
            (Allow, 'authenticated_principal', 'secured'),
        ]

    def __init__(self, request):
        self.request = request

class RecordFactory(object):
    def __init__(self, request):
        self.request = request

    def __getitem__(self, key):
        record_data = records_service.get_record(key)
        owner = record_data.get('owner_uid')
        return RecordContext(self.request, owner, record_data)

class RecordContext(object):
    def __acl__(self):
        owner_principal = 'u:{owner}'.format(owner=self.owner)
        return [
            (Allow, owner_principal, 'secured'),
        ]

    def __init__(self, request, owner, record_data):
        self.request = request
        self.owner = owner
        self.data = record_data

class RecordsResource(object):
    def __acl__(self):
        request_params = self.request.params.mixed()
        request_owner_uids = request_params['owner_uids']
        authorized_owner_uids = owners_api_service.get_authorized_owners(self.request.user['auth_data'])
        return [(Allow, 'authenticated_principal', 'secured')]\
            if set(authorized_owner_uids) == set(request_owner_uids) else []

    def __init__(self, request):
        self.request = request
</code>```

My questions are following:

is it acceptable to utilize row-level security checks without having Model layer? i.e. there is no ORM set up for Records data and there is also no plain Model to put persisted data into, so I have to use 'fake' RecordContext class to attach __acl__ rules and pass data to the view

is it acceptable to treat /records endpoint as a Resource despite the fact it is not a resource from Traversal perspective and relies on query parameters rather than path sections?

答:
I think the answer to both of your question is: if it works for you then it's totally acceptable. I've found a lot of success treating URLs as resources as a general pattern to the extent that I have a some tooling to avoid using route_name. For example:

```<code>config.add_route('records', '/records', factory=RecordsResource, use_global_views=True)
config.add_route('records_by_id', 'records/{record_id}', factory=RecordFactory, traverse='{record_id}', use_global_views=True)

@view_config(context=RecordsResource, renderer='json')
def records_view(request):
    return {}

@view_config(context=RecordContext, renderer='json')
def record_view(request):
    return {}
</code>```

Body:
I am trying to implement dynamic ACLs(including row-level security) in URL Dispatch app.
Defining Root factory only doesn't seem to be sufficient as I need to perform individual authz checks for each secured endpoint. My setup looks as follows(I was using pyramid docs and mmerickel's tutorials as a guide):

config.py

...
settings = config.registry.settings
config = Configurator(settings=settings, root_factory=RootPermissionFactory)
config.set_authentication_policy(CustomAuthenticationPolicy(settings))
config.set_authorization_policy(ACLAuthorizationPolicy())
...

views.py

#import ...

@view_defaults(renderer='json', permission='secured')
class RecordsView(object):
    ...

   @view_config(request_method='GET', route_name='records_by_id')
   def get(self):
        record = self.request.context.data
        if not record:
            return HTTPNotFound()
        return record

    @view_config(request_method='GET', route_name='records')
    def get_by_owners(self):
        owner_uids = self.request.params.mixed()['owner_uids']
        return records_service.get_records(owner_uids=owner_uids)

def includeme(config):
    config.add_route('records', '/records', factory=RecordsResource)
    config.add_route('records_by_id', 'records/{record_id}', factory=RecordFactory, traverse='{record_id}')

authorization.py

class RootPermissionFactory(object):
    __name__ = None
    __parent__ = None

    def __acl__(self):
        return [
            (Allow, 'authenticated_principal', 'secured'),
        ]

    def __init__(self, request):
        self.request = request

class RecordFactory(object):
    def __init__(self, request):
        self.request = request

    def __getitem__(self, key):
        record_data = records_service.get_record(key)
        owner = record_data.get('owner_uid')
        return RecordContext(self.request, owner, record_data)

class RecordContext(object):
    def __acl__(self):
        owner_principal = 'u:{owner}'.format(owner=self.owner)
        return [
            (Allow, owner_principal, 'secured'),
        ]

    def __init__(self, request, owner, record_data):
        self.request = request
        self.owner = owner
        self.data = record_data

class RecordsResource(object):
    def __acl__(self):
        request_params = self.request.params.mixed()
        request_owner_uids = request_params['owner_uids']
        authorized_owner_uids = owners_api_service.get_authorized_owners(self.request.user['auth_data'])
        return [(Allow, 'authenticated_principal', 'secured')]\
            if set(authorized_owner_uids) == set(request_owner_uids) else []

    def __init__(self, request):
        self.request = request

My questions are following:

is it acceptable to utilize row-level security checks without having Model layer? i.e. there is no ORM set up for Records data and there is also no plain Model to put persisted data into, so I have to use 'fake' RecordContext class to attach __acl__ rules and pass data to the view

is it acceptable to treat /records endpoint as a Resource despite the fact it is not a resource from Traversal perspective and relies on query parameters rather than path sections?

Body:
I think the answer to both of your question is: if it works for you then it's totally acceptable. I've found a lot of success treating URLs as resources as a general pattern to the extent that I have a some tooling to avoid using route_name. For example:

config.add_route('records', '/records', factory=RecordsResource, use_global_views=True)
config.add_route('records_by_id', 'records/{record_id}', factory=RecordFactory, traverse='{record_id}', use_global_views=True)

@view_config(context=RecordsResource, renderer='json')
def records_view(request):
    return {}

@view_config(context=RecordContext, renderer='json')
def record_view(request):
    return {}


问:
What is a nested loop and how do I use it in example below?
I was given the following problem for my beginning python coding class. I have reached out to the professor, but he hasn't gotten back to me and this is due in 3.5 hours. If someone has a tutorial/guidance of how to start, that would be amazing. I do NOT expect anyone to write this code! I just need a bit of guidance! Thanks :)

Write a program in Python to prompt user to enter an integer between 10 and 3 inclusive and also a character. Then use these two values to display a box using the character entered with size of box determined by the number entered.

Here is a sample output:

```<code>Enter size of box:  4

Enter a character: %

%%%%

%%%%

%%%%

%%%%
</code>```

Here is another possible output:

```<code>Enter size of box:  3

Enter a character: &

&&&

&&&

&&&
</code>```

Your program will run only once but you must used repetition construct to draw the box using values entered.

Hint: It should be a nested loop. Each line printed is a loop so you will have loop inside loop construct; nested loop.

As before, you must test for invalid values and if so, display an error message and proceed to get a valid number.

Use your own test values here.

答:
A nested loop is a loop within a loop.

But how does it work?

The outer loop statement gets executed, which triggers the inner statement. The inner loop then executes till its completed..

So the inner statement will keep on going until it has satisfied the statement you have set it to.

Then, the outer loop triggers the inner loop again...and it will keep on triggering the inner loop forever until the outer loop's statement is satisfied.

Body:
I was given the following problem for my beginning python coding class. I have reached out to the professor, but he hasn't gotten back to me and this is due in 3.5 hours. If someone has a tutorial/guidance of how to start, that would be amazing. I do NOT expect anyone to write this code! I just need a bit of guidance! Thanks :)

Write a program in Python to prompt user to enter an integer between 10 and 3 inclusive and also a character. Then use these two values to display a box using the character entered with size of box determined by the number entered.

Here is a sample output:

Enter size of box:  4

Enter a character: %

%%%%

%%%%

%%%%

%%%%

Here is another possible output:

Enter size of box:  3

Enter a character: &

&&&

&&&

&&&

Your program will run only once but you must used repetition construct to draw the box using values entered.

Hint: It should be a nested loop. Each line printed is a loop so you will have loop inside loop construct; nested loop.

As before, you must test for invalid values and if so, display an error message and proceed to get a valid number.

Use your own test values here.


问:
Undefined variable error in laravel
i have a trouble about views in laravel
.here is Controller

```<code>public function transactions()
    {
        $transactions = Transaction::all();

        return view('admin.transaction', compact('transactions'));
    }
</code>```

here is view

```<code>@foreach($transactions as $transaction)
    <tr>
        <td>{{$transaction->bank_number}}</td>
        <td>{{$transaction->transaction_id}}</td>
        <td>{{$transaction->amount}}</td>
        <td>{{$transaction->description}}</td>
        <td>{{$transaction->made_on}}</td>
    </tr>
    @endforeach
</code>```

and error is

Undefined variable: transactions in view.

Please help me! thanks

答:
Use like below</p>

```<code>   return view('admin.transaction')->with('transactions', $transactions);
</code>```

Title: Undefined variable error in laravel

Body:
i have a trouble about views in laravel
.here is Controller

public function transactions()
    {
        $transactions = Transaction::all();

        return view('admin.transaction', compact('transactions'));
    }

here is view

@foreach($transactions as $transaction)

        {{$transaction->bank_number}}
        {{$transaction->transaction_id}}
        {{$transaction->amount}}
        {{$transaction->description}}
        {{$transaction->made_on}}

    @endforeach

and error is

Undefined variable: transactions in view.

Please help me! thanks

Body:
Use like below

   return view('admin.transaction')->with('transactions', $transactions);


答:
A nested loop is a loop within a loop. For example:</p>

```<code>import sys

def main():
    size_of_box = 4
    character = "%"
    for i in range(0, size_of_box):
        for j in range(0, size_of_box):
            sys.stdout.write(character)
        sys.stdout.write("\n")

if __name__ == "__main__":
    main()
</code>```

Title: What is a nested loop and how do I use it in example below?

Body:
A nested loop is a loop within a loop. For example:

import sys

def main():
    size_of_box = 4
    character = "%"
    for i in range(0, size_of_box):
        for j in range(0, size_of_box):
            sys.stdout.write(character)
        sys.stdout.write("\n")

if __name__ == "__main__":
    main()


问:
Align Check Boxes CSS
I want to align some check boxes with labels such that the check boxes are in a vertical row to the right side and the labels are aligned with the starting edges in a vertical row on the left side.</p>

答:
I believe this is what you're looking for:

label {
    display: inline-block;
    padding-left: 15px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
    <div>
        <label>Label text</label><input type="checkbox" />
        <label>Label text</label><input type="checkbox" />
        <label>Label text</label><input type="checkbox" />
    </div>
<form></code>```

Working Example: JSFiddle

Title: Align Check Boxes CSS

Body:
I believe this is what you're looking for:

label {
    display: inline-block;
    padding-left: 15px;
}

<form>
    <div>
        <label>Label text</label><input type="checkbox" />
        <label>Label text</label><input type="checkbox" />
        <label>Label text</label><input type="checkbox" />
    </div>
<form>

Working Example: JSFiddle


问:
Java mail : receiving email body as .htm file attachment along with attachment and body
Dears,

Facing an issue mail body duplicating in mobile when sending email using java mail (Microsoft Exchange server). Sending email body and pdf as attachment but when it customer receives the mail in inbox the email body content is duplicating (twice), also its sending PDF and one .htm file as attachment. Due to .htm file the email body is coming as twice. How to avoid this duplication body in mail. Below is the code used to send an email.  This issue not happening in browser based email clients, Its happening only in mobile.

Setting email body (html content) as below

```<code>import javax.mail.Message;
Message  msg = new SMTPMessage(session);
MimeMultipart mp = new MimeMultipart();
MimeBodyPart mbp = null;
mbp = new MimeBodyPart();
mbp.setContent("Hi, This is a test.", "text/html; charset=utf-8");
mp.addBodyPart(mbp);
</code>```

setting pdf as attachment

```<code> MimeBodyPart mbp = null;
 ByteArrayDataSource xfds3 = null;
 mbp = new MimeBodyPart();
 byte[] b = //PDF byte array
 xfds3 = new ByteArrayDataSource(b, "application/pdf");
 mbp.setDataHandler(new DataHandler(xfds3));
 String maskName = maskingNo(fileName, prop);
 mbp.setFileName(maskName);
 mp.addBodyPart(mbp);
 msg.setContent(mp);
 transport.sendMessage(msg, msg.getAllRecipients());
</code>```

Can anyone help how to solve this issue?

Output is coming in mail body:

Hi,
This is a test.

Hi,
This is a test

答:
Instead of this line:

mbp.setContent("Hi, This is a test.", "text/html; charset=utf-8");

Write this:

mbp.setContent("Hi, This is a test.", "text/plain; charset=utf-8");

Body:
Dears,

Facing an issue mail body duplicating in mobile when sending email using java mail (Microsoft Exchange server). Sending email body and pdf as attachment but when it customer receives the mail in inbox the email body content is duplicating (twice), also its sending PDF and one .htm file as attachment. Due to .htm file the email body is coming as twice. How to avoid this duplication body in mail. Below is the code used to send an email.  This issue not happening in browser based email clients, Its happening only in mobile.

Setting email body (html content) as below

import javax.mail.Message;
Message  msg = new SMTPMessage(session);
MimeMultipart mp = new MimeMultipart();
MimeBodyPart mbp = null;
mbp = new MimeBodyPart();
mbp.setContent("Hi, This is a test.", "text/html; charset=utf-8");
mp.addBodyPart(mbp);

setting pdf as attachment

 MimeBodyPart mbp = null;
 ByteArrayDataSource xfds3 = null;
 mbp = new MimeBodyPart();
 byte[] b = //PDF byte array
 xfds3 = new ByteArrayDataSource(b, "application/pdf");
 mbp.setDataHandler(new DataHandler(xfds3));
 String maskName = maskingNo(fileName, prop);
 mbp.setFileName(maskName);
 mp.addBodyPart(mbp);
 msg.setContent(mp);
 transport.sendMessage(msg, msg.getAllRecipients());

Can anyone help how to solve this issue?

Output is coming in mail body:

Hi,
This is a test.

Hi,
This is a test


答:
For ASP.Net cotrols try Control.FindControl Method

and for winforms use Controls.Find()

Title: Using a string argument to represent an object

Body:
If I have the following code:

TextBox txtUsername = new TextBox();
void setEnabled(string str, bool enable)
{
    // use str to find the TextBox object
    // str.Enabled = enable;
}

Is this kinda thing even possible?

I want to be passing in 'Username' and then be prepending it with 'txt'.


问:
How to publish apps to Apple app store?
I am a beginner in developing iOS apps. I am currently building one simple app for personal organization use and I want to publish the app. But all tutorials did not lead me to be able to publish the apps.

For example, image number did not show the "View details" (as the most tutorial showing that "view details".
And for image number 2, after I log into app developer account, I cannot see the certificate, etc. option (as most tutorial shown).

I just build the app using simulator since I don't have iPhone/iPad device. I got error

failed to create provisioning profile.

Is that possible to publish the apps without running it on the real device first?

答: Have you created and downloaded a provisioning profile on your developer account? Have you created a cert that allows you to do that ^ ? Have you registered your device on itunes connect so you can build on device? These are all things you have to do. After you do these things, you have to select Product > Archive for Generic iOS Devices. After it's done archiving, you can upload to the iTunes Store. Make sure your version number matches the app that you create on iTunesConnect. Build Numbers must also increase or the app store will reject your build. </p>

Title: How to publish apps to Apple app store?


答:
Css File:

```<code>.badgebox
{
    opacity: 0;
}

.badgebox + .badge
{
    /* Move the check mark away when unchecked */
    text-indent: -999999px;
    /* Makes the badge's width stay the same checked and unchecked */
    width: 27px;
}

.badgebox:focus + .badge
{
    /* Set something to make the badge looks focused */
    /* This really depends on the application, in my case it was: */

    /* Adding a light border */
    box-shadow: inset 0px 0px 5px;
    /* Taking the difference out of the padding */
}

.badgebox:checked + .badge
{
    /* Move the check mark back when checked */
    text-indent: 0;
}
</code>```

HTML File:

```<code><div class="container">
    <div class="row text-center">
        <br>
        <br>
        <h1>Badgebox: CSS only checkbox badge!</h1>
        <h2>Works on Bootstrap 2.3.2 and up</h2>
        <br>
        <label for="default" class="btn btn-default">Default <input type="checkbox" id="default" class="badgebox"><span class="badge">✓</span></label>
        <label for="primary" class="btn btn-primary">Primary <input type="checkbox" id="primary" class="badgebox"><span class="badge">✓</span></label>
        <label for="info" class="btn btn-info">Info <input type="checkbox" id="info" class="badgebox"><span class="badge">✓</span></label>
        <label for="success" class="btn btn-success">Success <input type="checkbox" id="success" class="badgebox"><span class="badge">✓</span></label>
        <label for="warning" class="btn btn-warning">Warning <input type="checkbox" id="warning" class="badgebox"><span class="badge">✓</span></label>
        <label for="danger" class="btn btn-danger">Danger <input type="checkbox" id="danger" class="badgebox"><span class="badge">✓</span></label>
    </div>
</div>
</code>```

Or

Refer this Link:

https://bootsnipp.com/snippets/featured/badgebox-css-checkbox-badge

Title: Align Check Boxes CSS

Body: I want to align some check boxes with labels such that the check boxes are in a vertical row to the right side and the labels are aligned with the starting edges in a vertical row on the left side.

Body:
Css File:

.badgebox
{
    opacity: 0;
}

.badgebox + .badge
{
    /* Move the check mark away when unchecked */
    text-indent: -999999px;
    /* Makes the badge's width stay the same checked and unchecked */
    width: 27px;
}

.badgebox:focus + .badge
{
    /* Set something to make the badge looks focused */
    /* This really depends on the application, in my case it was: */

    /* Adding a light border */
    box-shadow: inset 0px 0px 5px;
    /* Taking the difference out of the padding */
}

.badgebox:checked + .badge
{
    /* Move the check mark back when checked */
    text-indent: 0;
}

HTML File:

<div class="container">
    <div class="row text-center">
        <br>
        <br>
        <h1>Badgebox: CSS only checkbox badge!</h1>
        <h2>Works on Bootstrap 2.3.2 and up</h2>
        <br>
        <label for="default" class="btn btn-default">Default <input type="checkbox" id="default" class="badgebox"><span class="badge">&check;</span></label>
        <label for="primary" class="btn btn-primary">Primary <input type="checkbox" id="primary" class="badgebox"><span class="badge">&check;</span></label>
        <label for="info" class="btn btn-info">Info <input type="checkbox" id="info" class="badgebox"><span class="badge">&check;</span></label>
        <label for="success" class="btn btn-success">Success <input type="checkbox" id="success" class="badgebox"><span class="badge">&check;</span></label>
        <label for="warning" class="btn btn-warning">Warning <input type="checkbox" id="warning" class="badgebox"><span class="badge">&check;</span></label>
        <label for="danger" class="btn btn-danger">Danger <input type="checkbox" id="danger" class="badgebox"><span class="badge">&check;</span></label>
    </div>
</div>

Or

Refer this Link:

https://bootsnipp.com/snippets/featured/badgebox-css-checkbox-badge