问:
Sitecore 8 PowerShell Get-User Custom Properties
I need to return either a) a list of users with specific value in a profile field OR b) return the entirety of the users with the value of the profile field displayed in the results.

Currently, I am running the following but it has been running for an hour even though I only have one test user with this field set to this value.

```<code>Get-User -Filter * | Where-Object {Profile.GetCustomProperties("Subscribed") -eq "yup"}
</code>```

答:
I don't have Sitecore to verify this, but it looks like you are trying to filter on the objects you are retrieving from the Get-User cmdlet. So you'll need to use $_ or $psitem. Something like:

```<code>Get-User -Filter * | Where-Object {$_.Profile.GetCustomProperties("Subscribed") -eq "yup"}`
</code>```

I can't comment on the length this will take, but it looks like you pull every user with Get-User then run the GetCustomProperties() method on each one, so depending on how many users that may take a while.

Body:
I need to return either a) a list of users with specific value in a profile field OR b) return the entirety of the users with the value of the profile field displayed in the results.

Currently, I am running the following but it has been running for an hour even though I only have one test user with this field set to this value.

Get-User -Filter * | Where-Object {Profile.GetCustomProperties("Subscribed") -eq "yup"}

Body:
I don't have Sitecore to verify this, but it looks like you are trying to filter on the objects you are retrieving from the Get-User cmdlet. So you'll need to use $_ or $psitem. Something like:

Get-User -Filter * | Where-Object {$_.Profile.GetCustomProperties("Subscribed") -eq "yup"}`

I can't comment on the length this will take, but it looks like you pull every user with Get-User then run the GetCustomProperties() method on each one, so depending on how many users that may take a while.


来源: stackexchange

问:
How to set right spacing between inline-block elements
My example:

Its possilble to set same spacing between div inline elements. Because auto width is not working.
This is what i got so far:

HTML

```<code> <div id="frame">
      <div class="block">1</div>
      <div class="block">2</div>
      <div class="block">3</div>
      <div class="block">4</div>
    </div>
  </div>
</code>```

CSS

```<code>#frame div {
    background-color: brown;
    padding-left: 20%;
    padding-right: 20%;
    width: auto;
    margin: 5px;
    display: inline-block;
}
</code>```

答:
Width of frame is full screen and width of block have to fit inside this frame, its not that important.

In that case you can avoid the not yet that well supported flex and use percentages instead:

Give 20% width to each of the .block divs

Give 4% margin-right to each of the .block divs

Give either the first .block an additional 4% margin-left or set a padding-left of 4% on #frame

Of course, you can change these values as long as they add up to a maximum of 100% of #frame.

#frame {
    width: 100%;
    box-sizing: border-box;
    margin: 0;
    padding: 0 0 0 4%;
}

#frame div {
    display: inline-block;
    background-color: brown;
    width: 20%;
    margin: 1em 4% 1em 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div id="frame">
      <div class="block">1</div>
      <div class="block">2</div>
      <div class="block">3</div>
      <div class="block">4</div>
    </div>
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
My example:

Its possilble to set same spacing between div inline elements. Because auto width is not working.
This is what i got so far:

HTML

1

2

3

4

CSS

#frame div {
    background-color: brown;
    padding-left: 20%;
    padding-right: 20%;
    width: auto;
    margin: 5px;
    display: inline-block;
}

Body:
Width of frame is full screen and width of block have to fit inside this frame, its not that important.

In that case you can avoid the not yet that well supported flex and use percentages instead:

Give 20% width to each of the .block divs

Give 4% margin-right to each of the .block divs

Give either the first .block an additional 4% margin-left or set a padding-left of 4% on #frame

Of course, you can change these values as long as they add up to a maximum of 100% of #frame.

#frame {
    width: 100%;
    box-sizing: border-box;
    margin: 0;
    padding: 0 0 0 4%;
}

#frame div {
    display: inline-block;
    background-color: brown;
    width: 20%;
    margin: 1em 4% 1em 0;
}

 <div id="frame">
      <div class="block">1</div>
      <div class="block">2</div>
      <div class="block">3</div>
      <div class="block">4</div>
    </div>
</div>


问:
Left nav menu with show/hide

I am trying to build my Angular2 application which will have a left nav menu with show/hide feature. I tried looking for some bootstrap snippets and other third party libs but couldn't find one.

答:
You have a few options, however for this answer I will give you two.

First one is of course Angular 2 Material Navigation, the side nav does exactly what you are looking for, so check out there get started section.

The other one is Bootstrap unfortunately I couldn't find a solution on getbootstrap.com, but what I have found is this tutorial, also here's a link to their github page

Title: Left nav menu with show/hide


问:
How to replace numbers in a div?
With the following code, I'm getting the values of "id"(almost 35), and then add 1 to each "id", so 1 will be 2 and so on. Where I'm stock, it is on how to replace that id number in the html.

This is the code that use to get the values of each id, then I push them into an array, then I run another "for loop" to add 1 to each value, but I don't how to return them to the html.

var x = document.getElementsByClassName('p-divs');

var portfolio = new Array;

for (var i = 0; i < x.length; i++)
{
    var y = document.getElementsByClassName('p-divs')[i].getAttribute('id');
    portfolio.push(y);
}

console.log(portfolio);

var portfolio2 = new Array;

for (var i = 0; i<portfolio.length; i++)
{
    var newId;
    newId = parseInt(portfolio[i]) + 1;

    portfolio2.push(newId);
}

console.log(portfolio2);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-lg-3 col-md-3 col-sm-6 col-xs-12 p-divs" id="1">
  <div class="portfolio">
    <center>
      <img src="images/pace.png" width="230" height="190" alt="" class="img-responsive">
    </center>
  </div>
</div></code>```

答:
```<code>for(i=0;i<$('.p-divs').length;i++){
 newId= parseInt($($('.p-divs')[i]).attr('id'))+1;
 $($('.p-divs')[i]).attr('id',newId)
}
</code>```

Using Jquery attr

Title: How to replace numbers in a div?

Body:
for(i=0;i<$('.p-divs').length;i++){
 newId= parseInt($($('.p-divs')[i]).attr('id'))+1;
 $($('.p-divs')[i]).attr('id',newId)
}

Using Jquery attr


问:
Outputting JS variable into my PHP file
I'm trying to output a JS variable into my PHP-file. And then let the PHP send the variable value into my database.
But somehow it doesn't work..

Here I have a form that triggers the JS function:   (This file is called index.php)

```<code><form method="post" action="index.php" onsubmit="return phpFunction()" >
      <input type="hidden" name="submitted" value="true">
      <input type="text" id="nameInput" placeholder="your name" maxlength="12" name="name">
      <input type="submit" id="submitted" value="Submit your highscore">
      </form>
</code>```

Here we have the JS function:    ( This file is called main.js)

```<code>function phpFunction () {

var php = duck.highscore ;   // duck.highscore is a number that dynamically changes
window.location.href = "index.php?score=" + php;

};
</code>```

In the end we got the PHP file that sends the value to my localserver:  (This file is inside index.php)

```<code><?php

if (isset($_POST['submitted'])) {

// connect  to the database
include('connect.php');

$name = $_POST['name'] ;
$score = $_GET['score'] ;
$sqlinsert = "INSERT INTO leaderboard (name, score) VALUES ('$name','$score')" ;

if (!mysqli_query($conn, $sqlinsert)) {
    die('error inserting new record') ;
    } // end of my nested if statement

    $newrecord = "record added" ;

}
?>
</code>```

When I press the submit button I get a error message like this:

error 404

答: You should redirect from your script using header('Location: ' . $your_next_url);.

Title: Outputting JS variable into my PHP file

Body:
I'm trying to output a JS variable into my PHP-file. And then let the PHP send the variable value into my database.
But somehow it doesn't work..

Here I have a form that triggers the JS function:   (This file is called index.php)

<form method="post" action="index.php" onsubmit="return phpFunction()" >
      <input type="hidden" name="submitted" value="true">
      <input type="text" id="nameInput" placeholder="your name" maxlength="12" name="name">
      <input type="submit" id="submitted" value="Submit your highscore">
      </form>

Here we have the JS function:    ( This file is called main.js)

function phpFunction () {

var php = duck.highscore ;   // duck.highscore is a number that dynamically changes
window.location.href = "index.php?score=" + php;

};

In the end we got the PHP file that sends the value to my localserver:  (This file is inside index.php)

<?php

if (isset($_POST['submitted'])) {

// connect  to the database
include('connect.php');

$name = $_POST['name'] ;
$score = $_GET['score'] ;
$sqlinsert = "INSERT INTO leaderboard (name, score) VALUES ('$name','$score')" ;

if (!mysqli_query($conn, $sqlinsert)) {
    die('error inserting new record') ;
    } // end of my nested if statement

    $newrecord = "record added" ;

}
?>

When I press the submit button I get a error message like this:

error 404


问:
Why is User (as in User.Identity.Name) null in my abstract base controller?
I was asking a related question but messed the title up and no-one would understand it. Since I am able now to ask the question more precisely, I decided to reformulate it in a new question and close the old one. Sorry for that.

So what I want to do is passing data (my custom user's nickname as stored in the db) to the LoginUserControl. This login gets rendered from the master page via Html.RenderPartial(), so what I really need to do is making sure that, say ViewData["UserNickname"] is present on every call. But I don't want to populate ViewData["UserNickname"] in each and every action of every controller, so I decided to use this approach and create an abstract base controller which will do the work for me, like so:

```<code>public abstract class ApplicationController : Controller
    {
        private IUserRepository _repUser;

        public ApplicationController()
        {
            _repUser = RepositoryFactory.getUserRepository();
            var loggedInUser = _repUser.FindById(User.Identity.Name); //Problem!
            ViewData["LoggedInUser"] = loggedInUser;
        }
    }
</code>```

This way, whatever my deriving Controller does, the user information will already be present.

So far, so good. Now for the problem:

I can't call User.Identity.Name because User is already null. This is not the case in all of my deriving controllers, so this is specific for the abstract base controller.

I am setting the User.Identity.Name via FormsAuthentication at another place in the code, but I think this can't be the problem - afaik User.Identity.Name can be null, but not User itself.

It looks to me like the HttpContext is not available (since also null ;-) and that I am missing a simple yet important point here. Can anyone give me some hints? I would really appreciate it.

答:
My guess would be that the Controller's base constructor is not filling in the User, but that it is only known later when the ControllerContext is set for the Controller. You should check this in the documentation about the lifecycle of an MVC application, (the one here will probably do, although it might be a bit out of date since it's for the preview version), or just check the source code of MVC.

from the code that I have of MVC (also a preview version, but that should be fine):
(In Controller)

```<code> public IPrincipal User {
            get {
                return HttpContext == null ? null : HttpContext.User;
            }
        }
</code>```

...

```<code>public HttpContextBase HttpContext {
        get {
            return ControllerContext == null ? null : ControllerContext.HttpContext;
        }
    }
</code>```

I don't see en an implementation of a default constructor in the code.
That would prove that the ControllerContext is null at the time of construction.

So you should execute your code somewhere else.

OwnerDisplayName: Masterfu

ContentLicense: CC BY-SA 2.5

Body:
I was asking a related question but messed the title up and no-one would understand it. Since I am able now to ask the question more precisely, I decided to reformulate it in a new question and close the old one. Sorry for that.

So what I want to do is passing data (my custom user's nickname as stored in the db) to the LoginUserControl. This login gets rendered from the master page via Html.RenderPartial(), so what I really need to do is making sure that, say ViewData["UserNickname"] is present on every call. But I don't want to populate ViewData["UserNickname"] in each and every action of every controller, so I decided to use this approach and create an abstract base controller which will do the work for me, like so:

public abstract class ApplicationController : Controller
    {
        private IUserRepository _repUser;

        public ApplicationController()
        {
            _repUser = RepositoryFactory.getUserRepository();
            var loggedInUser = _repUser.FindById(User.Identity.Name); //Problem!
            ViewData["LoggedInUser"] = loggedInUser;
        }
    }

This way, whatever my deriving Controller does, the user information will already be present.

So far, so good. Now for the problem:

I can't call User.Identity.Name because User is already null. This is not the case in all of my deriving controllers, so this is specific for the abstract base controller.

I am setting the User.Identity.Name via FormsAuthentication at another place in the code, but I think this can't be the problem - afaik User.Identity.Name can be null, but not User itself.

It looks to me like the HttpContext is not available (since also null ;-) and that I am missing a simple yet important point here. Can anyone give me some hints? I would really appreciate it.

Body:
My guess would be that the Controller's base constructor is not filling in the User, but that it is only known later when the ControllerContext is set for the Controller. You should check this in the documentation about the lifecycle of an MVC application, (the one here will probably do, although it might be a bit out of date since it's for the preview version), or just check the source code of MVC.

from the code that I have of MVC (also a preview version, but that should be fine):
(In Controller)

 public IPrincipal User {
            get {
                return HttpContext == null ? null : HttpContext.User;
            }
        }

...

public HttpContextBase HttpContext {
        get {
            return ControllerContext == null ? null : ControllerContext.HttpContext;
        }
    }

I don't see en an implementation of a default constructor in the code.
That would prove that the ControllerContext is null at the time of construction.

So you should execute your code somewhere else.

OwnerDisplayName: Raymond Roestenburg


问:
Mapbox Annotation Callout
I have recently decided to change from Mapkit to Mapbox. I have my annotations implemented within my map but for some reason my annotation callouts are not appearing when I click on the annotation. I am quite confused and unsure as to why this is not appearing. Hopefully somebody can help! The appropriate code is shown below:</p>

```<code>import UIKit
import Firebase
import Mapbox

class ViewController: UIViewController, SideBarDelegate, MGLMapViewDelegate {

@IBOutlet weak var mapView: MGLMapView!

//Filtering annotations for sidebar

func sideBarDidSelectButtonAtIndex(_ index: Int) {
   mapView.removeAnnotations(mapView.annotations!)

    for park in skateparks {

        if index == 0 {
            addAnnotation(park: park)
        }

        if index == 1 && park.type == .park {
            addAnnotation(park: park)
        }

        if index == 2 && park.type == .street {
            addAnnotation(park: park)
        }

    }

}

var sideBar: SideBar = SideBar()

var skateparks = [Skatepark]()

let locationsRef = FIRDatabase.database().reference(withPath: "locations")

override func viewDidLoad() {
    super.viewDidLoad()

    //Location

    mapView.delegate = self
    mapView.showsUserLocation = true

    //Sidebar

    sideBar = SideBar(sourceView: self.view, skateItems: ["All Skate Spots", "Skateparks", "Street Skating"])
    sideBar.delegate = self

    // Passing firebase annotation data

    locationsRef.observe(.value, with: { snapshot in
        self.skateparks.removeAll()

        for item in snapshot.children {
            guard let snapshot = item as? FIRDataSnapshot else { continue }

            let newSkatepark = Skatepark(snapshot: snapshot)

            self.skateparks.append(newSkatepark)

            self.addAnnotation(park: newSkatepark)
        }
    })
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    view.sendSubview(toBack: mapView)
}

func addAnnotation(park: Skatepark) {

    let point = MGLPointAnnotation()

    point.coordinate = park.coordinate

    point.title = park.name

    point.subtitle = park.subtitle

    mapView.addAnnotation(point)

    mapView.selectAnnotation(point, animated: true)

}
}

func mapView(mapView: MGLMapView, viewForAnnotation annotation: MGLAnnotation) -> MGLAnnotationView? {
return nil
}

func mapView(mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
return true
}
</code>```

答:
You may find this example helpful (if you have not already seen it)!
 It shows how to use the Mapbox callout delegate.</p>

Title: Mapbox Annotation Callout

Body:
I have recently decided to change from Mapkit to Mapbox. I have my annotations implemented within my map but for some reason my annotation callouts are not appearing when I click on the annotation. I am quite confused and unsure as to why this is not appearing. Hopefully somebody can help! The appropriate code is shown below:

import UIKit
import Firebase
import Mapbox

class ViewController: UIViewController, SideBarDelegate, MGLMapViewDelegate {

@IBOutlet weak var mapView: MGLMapView!

//Filtering annotations for sidebar

func sideBarDidSelectButtonAtIndex(_ index: Int) {
   mapView.removeAnnotations(mapView.annotations!)

    for park in skateparks {

        if index == 0 {
            addAnnotation(park: park)
        }

        if index == 1 && park.type == .park {
            addAnnotation(park: park)
        }

        if index == 2 && park.type == .street {
            addAnnotation(park: park)
        }

    }

}

var sideBar: SideBar = SideBar()

var skateparks = [Skatepark]()

let locationsRef = FIRDatabase.database().reference(withPath: "locations")

override func viewDidLoad() {
    super.viewDidLoad()

    //Location

    mapView.delegate = self
    mapView.showsUserLocation = true

    //Sidebar

    sideBar = SideBar(sourceView: self.view, skateItems: ["All Skate Spots", "Skateparks", "Street Skating"])
    sideBar.delegate = self

    // Passing firebase annotation data

    locationsRef.observe(.value, with: { snapshot in
        self.skateparks.removeAll()

        for item in snapshot.children {
            guard let snapshot = item as? FIRDataSnapshot else { continue }

            let newSkatepark = Skatepark(snapshot: snapshot)

            self.skateparks.append(newSkatepark)

            self.addAnnotation(park: newSkatepark)
        }
    })
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    view.sendSubview(toBack: mapView)
}

func addAnnotation(park: Skatepark) {

    let point = MGLPointAnnotation()

    point.coordinate = park.coordinate

    point.title = park.name

    point.subtitle = park.subtitle

    mapView.addAnnotation(point)

    mapView.selectAnnotation(point, animated: true)

}
}

func mapView(mapView: MGLMapView, viewForAnnotation annotation: MGLAnnotation) -> MGLAnnotationView? {
return nil
}

func mapView(mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
return true
}


问:
Angular 2 ng2-charts doughnut text in the middle?
I am using Doughnut chart from ng2-charts (http://valor-software.com/ng2-charts/) in angular 2.
I have been searching for an option to put a text in the middle without success.
I already searched in ng-chart options as in chart.js (dependency).
Do you know another way to achieve this in Angular 2 typescript? or there is something I am missing?</p>

答:
You can do the following to place text in the center of doughnut chart. It worked for me

HTML:

```<code> <div style="display: block">
  <canvas #mycanvas baseChart
              [data]="doughnutChartData"
              [labels]="doughnutChartLabels"
              [chartType]="doughnutChartType"
              (chartHover)="chartHovered($event)"
              (chartClick)="chartClicked($event)"></canvas>
</div>
</code>```

Typescript

```<code>import {Component, NgModule, ElementRef, Inject, ViewChild} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {ChartsModule, Color} from 'ng2-charts';

export class App{
   @ViewChild('mycanvas')
  canvas:ElementRef;

 ngOnInit(){
    var ctx = this.canvas.nativeElement.getContext("2d");

    let me = this;
    this.options = {

      circumference: Math.PI,
      rotation :  Math.PI,
      animation:{ onComplete: function() {
         me.doit(ctx);
       }}
    }

      }

     doit(ctx) {
         //   Chart.types.Doughnut.prototype.draw.apply(this, arguments);

            var width = this.canvas.nativeElement.clientWidth,
                height = this.canvas.nativeElement.clientHeight;

            var fontSize = (height / 250).toFixed(2);
            ctx.font = fontSize + "em Verdana";
            ctx.textBaseline = "middle";
            ctx.fillStyle = "blue";

            var text = "Pass Rate 82%",
                textX = Math.round((width - ctx.measureText(text).width) / 2),
                textY = height -10;

            ctx.fillText(text, textX, textY);
            ctx.restore();
        }
}
}
</code>```

Body:
You can do the following to place text in the center of doughnut chart. It worked for me

HTML:

 <div style="display: block">
  <canvas #mycanvas baseChart
              [data]="doughnutChartData"
              [labels]="doughnutChartLabels"
              [chartType]="doughnutChartType"
              (chartHover)="chartHovered($event)"
              (chartClick)="chartClicked($event)"></canvas>
</div>

Typescript

import {Component, NgModule, ElementRef, Inject, ViewChild} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {ChartsModule, Color} from 'ng2-charts';

export class App{
   @ViewChild('mycanvas')
  canvas:ElementRef;

 ngOnInit(){
    var ctx = this.canvas.nativeElement.getContext("2d");

    let me = this;
    this.options = {

      circumference: Math.PI,
      rotation :  Math.PI,
      animation:{ onComplete: function() {
         me.doit(ctx);
       }}
    }

      }

     doit(ctx) {
         //   Chart.types.Doughnut.prototype.draw.apply(this, arguments);

            var width = this.canvas.nativeElement.clientWidth,
                height = this.canvas.nativeElement.clientHeight;

            var fontSize = (height / 250).toFixed(2);
            ctx.font = fontSize + "em Verdana";
            ctx.textBaseline = "middle";
            ctx.fillStyle = "blue";

            var text = "Pass Rate 82%",
                textX = Math.round((width - ctx.measureText(text).width) / 2),
                textY = height -10;

            ctx.fillText(text, textX, textY);
            ctx.restore();
        }
}
}


问:
specifying a complete sub directory in webpack 2 entry
I have a webpack 2 configuration as follows:

```<code>module.exports = {
    context: __dirname,
    entry: [
        "./app.ts",
        "./tab.ts",
        "./client/clientService.ts",
        "./client/clientSearchComponent.ts",
        "./infrastructure/messageComponent.ts",
        "./infrastructure/typeaheadComponent.ts",
        "./url.ts"],
    output: {
        filename: "./wwwroot/js/admin/admin.js"
    },
    devtool: "source-map",
    module: {
        rules: [
            { test: /\.ts$/, use: 'ts-loader' }
        ]
    }
};
</code>```

This is imported into a gulp task as follows...

```<code>gulp.task("admin:js",
    function (done) {
        var configuration = require(path.join(__dirname, config.js, "admin/webpack.config.js").toString());
        webpack(configuration).run(reportWebpackResults(done));
    });
</code>```

I am finding that I have to specify each component in entry[...].

How do I specify globs, they don't seem to work out of the box.

```<code>entry: [
    "./client/**/*.ts", // module not found...
</code>```

答:
You can use a glob library like globule. globule.find returns an array of the files. So you can use it as the entry:

```<code>entry: globule.find("./client/**/*.ts")
</code>```

If you want to include other entry points as well you can combine them by spreading the returned array:

```<code>entry: [
    './other/entry.js'
    ...globule.find("./client/**/*.ts")
]
</code>```

Or use any other way of combining the arrays (e.g. Array.prototype.concat).

Alternatively you can use a single entry that imports everything you need with the help of require.context as shown in the question webpack require every file in directory.

```<code>const req = require.context('./client/', true, /\.ts$/);
req.keys().forEach(req);
</code>```

Body:
I have a webpack 2 configuration as follows:

module.exports = {
    context: __dirname,
    entry: [
        "./app.ts",
        "./tab.ts",
        "./client/clientService.ts",
        "./client/clientSearchComponent.ts",
        "./infrastructure/messageComponent.ts",
        "./infrastructure/typeaheadComponent.ts",
        "./url.ts"],
    output: {
        filename: "./wwwroot/js/admin/admin.js"
    },
    devtool: "source-map",
    module: {
        rules: [
            { test: /\.ts$/, use: 'ts-loader' }
        ]
    }
};

This is imported into a gulp task as follows...

gulp.task("admin:js",
    function (done) {
        var configuration = require(path.join(__dirname, config.js, "admin/webpack.config.js").toString());
        webpack(configuration).run(reportWebpackResults(done));
    });

I am finding that I have to specify each component in entry[...].

How do I specify globs, they don't seem to work out of the box.

entry: [
    "./client/**/*.ts", // module not found...

Body:
You can use a glob library like globule. globule.find returns an array of the files. So you can use it as the entry:

entry: globule.find("./client/**/*.ts")

If you want to include other entry points as well you can combine them by spreading the returned array:

entry: [
    './other/entry.js'
    ...globule.find("./client/**/*.ts")
]

Or use any other way of combining the arrays (e.g. Array.prototype.concat).

Alternatively you can use a single entry that imports everything you need with the help of require.context as shown in the question webpack require every file in directory.

const req = require.context('./client/', true, /\.ts$/);
req.keys().forEach(req);


问:
Sort an array of associative arrays by column value
Given this array:

```<code>$inventory = array(

   array("type"=>"fruit", "price"=>3.50),
   array("type"=>"milk", "price"=>2.90),
   array("type"=>"pork", "price"=>5.43),

);
</code>```

I would like to sort $inventory's elements by price to get:

```<code>$inventory = array(

   array("type"=>"pork", "price"=>5.43),
   array("type"=>"fruit", "price"=>3.50),
   array("type"=>"milk", "price"=>2.90),

);
</code>```

How can I do this?

答:
While others have correctly suggested the use of array_multisort(), for some reason no answer seems to acknowledge the existence of array_column(), which can greatly simplify the solution. So my suggestion would be:

```<code>array_multisort(array_column($inventory, 'price'), SORT_DESC, $inventory);
</code>```

If you want Case Insensitive Sort on strings, you can use SORT_NATURAL|SORT_FLAG_CASE

```<code>array_multisort(array_column($inventory, 'key_name'), SORT_DESC, SORT_NATURAL|SORT_FLAG_CASE, $inventory);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Given this array:

$inventory = array(

   array("type"=>"fruit", "price"=>3.50),
   array("type"=>"milk", "price"=>2.90),
   array("type"=>"pork", "price"=>5.43),

);

I would like to sort $inventory's elements by price to get:

$inventory = array(

   array("type"=>"pork", "price"=>5.43),
   array("type"=>"fruit", "price"=>3.50),
   array("type"=>"milk", "price"=>2.90),

);

How can I do this?

Body:
While others have correctly suggested the use of array_multisort(), for some reason no answer seems to acknowledge the existence of array_column(), which can greatly simplify the solution. So my suggestion would be:

array_multisort(array_column($inventory, 'price'), SORT_DESC, $inventory);

If you want Case Insensitive Sort on strings, you can use SORT_NATURAL|SORT_FLAG_CASE

array_multisort(array_column($inventory, 'key_name'), SORT_DESC, SORT_NATURAL|SORT_FLAG_CASE, $inventory);


问:
drupal 8 and link to file
I installed drupal 8.2.7, no extra plugins or themes.
I have added in the "base page" (structure / type) a field (file1) to upload files.

If I add a new page (drupal / node / add / page) and also load a file in file1 (test.txt), the new page displays me the link to the file.

Then I add a new field called file2 as entity reference (file type).
If I add a new page (drupal / node / add / page) and put in file2 a reference to the test.txt, I see the new page, but with only the label name of the file, not its link

you can test the error on:

https://r20kx.ply.st/node/1

https://r20kx.ply.st/node/2

答: You can edit the fields of the content type and from Manage display tab change the Format settings for the field file2 to URL to file. Check this screen: http://prnt.sc/epnh4n

Title: drupal 8 and link to file


问:
Is there any shortcut for array size / length in C?
Is there any way to speed up getting an array size in C?

Typing out sizeof(array)/sizeof(int) every time gets old.  Do any C libraries have something like .length or is there some way I can define sizeof(array)/sizeof(int) as a shorter constant of some sort (possible also using dot notation)?

答:
All solutions in C boil down to a macro:</p>

```<code>#define ARRAY_LENGTH(array) (sizeof((array))/sizeof((array)[0]))
</code>```

Body:
All solutions in C boil down to a macro:

#define ARRAY_LENGTH(array) (sizeof((array))/sizeof((array)[0]))


问:
Load pretrained word embedding into Tensorflow model
I'm trying to modify this Tensorflow LSTM model to load this pre-trained GoogleNews word ebmedding GoogleNews-vectors-negative300.bin (or a tensorflow Word2Vec embedding would be just as good).

I've been reading examples on how to load a pre-trained word embedding into tensorflow (eg. 1: here, 2: here, 3: here and 4: here).

In the first linked example they can easily assign the embedding to the graph:

```<code>sess.run(cnn.W.assign(initW))
</code>```

In the second linked example they create an embedding-wrapper variable:

```<code>with tf.variable_scope("embedding_rnn_seq2seq/rnn/embedding_wrapper", reuse=True):
        em_in = tf.get_variable("embedding")
</code>```

then they initialize the embedding wrapper:

```<code>sess.run(em_in.assign(initW))
</code>```

Both those examples make sense, but it's not obvious to me how I can assign the unpacked embedding initW to the TF graph in my case. (I'm a TF beginner).

I can prepare initW like the first two examples:

```<code>def loadEmbedding(self, word_to_id):
    # New model, we load the pre-trained word2vec data and initialize embeddings
    with open(os.path.join('GoogleNews-vectors-negative300.bin'), "rb", 0) as f:
        header = f.readline()
        vocab_size, vector_size = map(int, header.split())
        binary_len = np.dtype('float32').itemsize * vector_size
        initW = np.random.uniform(-0.25,0.25,(len(word_to_id), vector_size))
        for line in range(vocab_size):
            word = []
            while True:
                ch = f.read(1)
                if ch == b' ':
                    word = b''.join(word).decode('utf-8')
                    break
                if ch != b'\n':
                    word.append(ch)
            if word in word_to_id:
                initW[word_to_id[word]] = np.fromstring(f.read(binary_len), dtype='float32')
            else:
                f.read(binary_len)
    return initW
</code>```

From the solution in example 4, I thought I should be able to do something like

```<code>session.run(tf.assign(embedding, initW)).
</code>```

If I try to add the line here like this when the session is initialized :

```<code>with sv.managed_session() as session:
        initializer = tf.random_uniform_initializer(-config.init_scale,
                                                    config.init_scale)
        session.run(tf.assign(m.embedding, initW))
</code>```

I get the following error:

```<code>ValueError: Fetch argument <tf.Tensor 'Assign:0' shape=(10000, 300) dtype=float32_ref> cannot be interpreted as a Tensor. (Tensor Tensor("Assign:0", shape=(10000, 300), dtype=float32_ref, device=/device:CPU:0) is not an element of this graph.)
</code>```

Update: I updated the code following Nilesh Birari's suggestion: Full code. It results in no improvement in validation or test set perplexity, it only improves training set perplexity.

答:
Correct me if I am wrong, trying to answer with my limited understanding of tensorflow.

```<code>ValueError: Fetch argument <tf.Tensor 'Assign:0' shape=(10000, 300) dtype=float32_ref> cannot be interpreted as a Tensor. (Tensor Tensor("Assign:0", shape=(10000, 300), dtype=float32_ref, device=/device:CPU:0) is not an element of this graph.)
</code>```

This simply states you are trying to initialize element of different graph, so I guess you need to be in same scope in which your graph is define. Just adjusting your embedding initialization code in same scope can solve the problem.

```<code>with tf.Graph().as_default():
    initializer = tf.random_uniform_initializer(-config.init_scale,
                                                config.init_scale)
    with tf.name_scope("Train"):
        train_input = PTBInput(config=config, data=train_data, name="TrainInput")
        with tf.variable_scope("Model", reuse=None, initializer=initializer):
            m = PTBModel(is_training=True, config=config, input_=train_input)
        tf.summary.scalar("Training Loss", m.cost)
        tf.summary.scalar("Learning Rate", m.lr)

    with tf.name_scope("Valid"):
        valid_input = PTBInput(config=config, data=valid_data, name="ValidInput")
        with tf.variable_scope("Model", reuse=True, initializer=initializer):
            mvalid = PTBModel(is_training=False, config=config, input_=valid_input)
        tf.summary.scalar("Validation Loss", mvalid.cost)

    with tf.name_scope("Test"):
        test_input = PTBInput(config=eval_config, data=test_data, name="TestInput")
        with tf.variable_scope("Model", reuse=True, initializer=initializer):
            mtest = PTBModel(is_training=False, config=eval_config,
                             input_=test_input)

    sv = tf.train.Supervisor(logdir=FLAGS.save_path)
    with sv.managed_session() as session:
        word2vec = loadEmbedding(word_to_id)
        session.run(tf.assign(m.embedding, word2vec))
        print("WORKED!!!")
</code>```

I guess this should be only problem, as you can see in your first example, initialization are under same scope.

Body:
I'm trying to modify this Tensorflow LSTM model to load this pre-trained GoogleNews word ebmedding GoogleNews-vectors-negative300.bin (or a tensorflow Word2Vec embedding would be just as good).

I've been reading examples on how to load a pre-trained word embedding into tensorflow (eg. 1: here, 2: here, 3: here and 4: here).

In the first linked example they can easily assign the embedding to the graph:

sess.run(cnn.W.assign(initW))

In the second linked example they create an embedding-wrapper variable:

with tf.variable_scope("embedding_rnn_seq2seq/rnn/embedding_wrapper", reuse=True):
        em_in = tf.get_variable("embedding")

then they initialize the embedding wrapper:

sess.run(em_in.assign(initW))

Both those examples make sense, but it's not obvious to me how I can assign the unpacked embedding initW to the TF graph in my case. (I'm a TF beginner).

I can prepare initW like the first two examples:

def loadEmbedding(self, word_to_id):
    # New model, we load the pre-trained word2vec data and initialize embeddings
    with open(os.path.join('GoogleNews-vectors-negative300.bin'), "rb", 0) as f:
        header = f.readline()
        vocab_size, vector_size = map(int, header.split())
        binary_len = np.dtype('float32').itemsize * vector_size
        initW = np.random.uniform(-0.25,0.25,(len(word_to_id), vector_size))
        for line in range(vocab_size):
            word = []
            while True:
                ch = f.read(1)
                if ch == b' ':
                    word = b''.join(word).decode('utf-8')
                    break
                if ch != b'\n':
                    word.append(ch)
            if word in word_to_id:
                initW[word_to_id[word]] = np.fromstring(f.read(binary_len), dtype='float32')
            else:
                f.read(binary_len)
    return initW

From the solution in example 4, I thought I should be able to do something like

session.run(tf.assign(embedding, initW)).

If I try to add the line here like this when the session is initialized :

with sv.managed_session() as session:
        initializer = tf.random_uniform_initializer(-config.init_scale,
                                                    config.init_scale)
        session.run(tf.assign(m.embedding, initW))

I get the following error:

ValueError: Fetch argument <tf.Tensor 'Assign:0' shape=(10000, 300) dtype=float32_ref> cannot be interpreted as a Tensor. (Tensor Tensor("Assign:0", shape=(10000, 300), dtype=float32_ref, device=/device:CPU:0) is not an element of this graph.)

Update: I updated the code following Nilesh Birari's suggestion: Full code. It results in no improvement in validation or test set perplexity, it only improves training set perplexity.

Body:
Correct me if I am wrong, trying to answer with my limited understanding of tensorflow.

ValueError: Fetch argument <tf.Tensor 'Assign:0' shape=(10000, 300) dtype=float32_ref> cannot be interpreted as a Tensor. (Tensor Tensor("Assign:0", shape=(10000, 300), dtype=float32_ref, device=/device:CPU:0) is not an element of this graph.)

This simply states you are trying to initialize element of different graph, so I guess you need to be in same scope in which your graph is define. Just adjusting your embedding initialization code in same scope can solve the problem.

with tf.Graph().as_default():
    initializer = tf.random_uniform_initializer(-config.init_scale,
                                                config.init_scale)
    with tf.name_scope("Train"):
        train_input = PTBInput(config=config, data=train_data, name="TrainInput")
        with tf.variable_scope("Model", reuse=None, initializer=initializer):
            m = PTBModel(is_training=True, config=config, input_=train_input)
        tf.summary.scalar("Training Loss", m.cost)
        tf.summary.scalar("Learning Rate", m.lr)

    with tf.name_scope("Valid"):
        valid_input = PTBInput(config=config, data=valid_data, name="ValidInput")
        with tf.variable_scope("Model", reuse=True, initializer=initializer):
            mvalid = PTBModel(is_training=False, config=config, input_=valid_input)
        tf.summary.scalar("Validation Loss", mvalid.cost)

    with tf.name_scope("Test"):
        test_input = PTBInput(config=eval_config, data=test_data, name="TestInput")
        with tf.variable_scope("Model", reuse=True, initializer=initializer):
            mtest = PTBModel(is_training=False, config=eval_config,
                             input_=test_input)

    sv = tf.train.Supervisor(logdir=FLAGS.save_path)
    with sv.managed_session() as session:
        word2vec = loadEmbedding(word_to_id)
        session.run(tf.assign(m.embedding, word2vec))
        print("WORKED!!!")

I guess this should be only problem, as you can see in your first example, initialization are under same scope.


问:
Django: Query which excludes all children if the parent is included in the query
```<code>class Person(TimeStampedModel):
    name = models.CharField(max_length=32)
    parent = models.ForeignKey('self', null=True, blank=True, related_name='children')
    is_child = models.BooleanField(default=False,)
</code>```

I am trying to form a query which excludes all children if their parent is present. Children, represent a 30% of the model's entries -for the time being- in my PostgreSQL.

My approach would be to use a nested query. However, I am not sure that it would be the most efficient solution.

I would appreciate your help.

Update

The python solution I came up with is the following:

```<code>a = Person.objects.filter(...)
ids = [i.id for i in a]
result = [x for x in a if any((not x.is_child, x.parent_id not in ids))]
</code>```

答:
Try this:</p>

```<code>qs0 = Person.objects.filter(...)
qs = qs0.exclude(is_child=True, parent__in=qs0)
</code>```

Body:
class Person(TimeStampedModel):
    name = models.CharField(max_length=32)
    parent = models.ForeignKey('self', null=True, blank=True, related_name='children')
    is_child = models.BooleanField(default=False,)

I am trying to form a query which excludes all children if their parent is present. Children, represent a 30% of the model's entries -for the time being- in my PostgreSQL.

My approach would be to use a nested query. However, I am not sure that it would be the most efficient solution.

I would appreciate your help.

Update

The python solution I came up with is the following:

a = Person.objects.filter(...)
ids = [i.id for i in a]
result = [x for x in a if any((not x.is_child, x.parent_id not in ids))]

Body:
Try this:

qs0 = Person.objects.filter(...)
qs = qs0.exclude(is_child=True, parent__in=qs0)


问:
Need to loop through & modify cells in an Excel sheet... Where do I start?
What I'm working with

I need to modify a file (exported from salesforce) where rows have a unique ID, a name, and a column with the unique ID of another row from this table, identifying it as a "child" of that item.

ID  (columnA)

Name  (columnB)

ParentID  (columnC)

Image of unaffected data:

What I need to accomplish

My goal is to loop through the entire spreadsheet (55,000 rows) and change the ParentID to the value from the parent's Name column.

My pseudo-code solution

```<code>foreach row starting from the top {
    varA = [current row number for this loop];
    varX = [value in varA:columnC];
    if (varX == [regex value]) {
        foreach row starting from the top {
            varB = [current row number for this loop];
            if ([value in varB:columnA] == varX) {
                foreach row starting from the top {
                    varC = [current row number for this loop];
                    if (varC:columnC = varB:columnA) {
                        [varC:columnC] = [varB:columnB];
                    }
                }
                break second foreach loop;
            }
        }
    }
}
</code>```

Image of data after manual fix:

Research I've done so far

I am working with excel, and I found resources discussing how to create a new macro, and some that even have examples, but I'm not confident that's going to be the right place for this. I also have a friend who is suggesting that it would be better to modify the file using Pandas, but that isn't something I'm familiar with either.

My question:

Where do I start? ...What is the proper tool to write a script to modify all of this?

Also, if possible, can you suggest a resource for me to use as reference when using the proper tool for this job?

答:
Change this,

.. with this code,

```<code>Option Explicit

Sub wqweqrteq()
    Dim d As Long, dict As Object, vals As Variant

    Set dict = CreateObject("Scripting.Dictionary")

    With Worksheets("salesforce")
        With .Range(.Cells(2, "A"), .Cells(.Rows.Count, "C").End(xlUp))
            vals = .Value2
        End With

        For d = LBound(vals, 1) To UBound(vals, 1)
            dict.Item(vals(d, 1)) = vals(d, 2)
        Next d

        For d = LBound(vals, 1) To UBound(vals, 1)
            If dict.exists(vals(d, 3)) Then
                vals(d, 3) = dict.Item(vals(d, 3))
            End If
        Next d

        With .Range(.Cells(2, "A"), .Cells(.Rows.Count, "C").End(xlUp))
            .Value = vals
        End With
    End With

End Sub
</code>```

.. into this.

Body:
What I'm working with

I need to modify a file (exported from salesforce) where rows have a unique ID, a name, and a column with the unique ID of another row from this table, identifying it as a "child" of that item.

ID  (columnA)

Name  (columnB)

ParentID  (columnC)

Image of unaffected data:

What I need to accomplish

My goal is to loop through the entire spreadsheet (55,000 rows) and change the ParentID to the value from the parent's Name column.

My pseudo-code solution

foreach row starting from the top {
    varA = [current row number for this loop];
    varX = [value in varA:columnC];
    if (varX == [regex value]) {
        foreach row starting from the top {
            varB = [current row number for this loop];
            if ([value in varB:columnA] == varX) {
                foreach row starting from the top {
                    varC = [current row number for this loop];
                    if (varC:columnC = varB:columnA) {
                        [varC:columnC] = [varB:columnB];
                    }
                }
                break second foreach loop;
            }
        }
    }
}

Image of data after manual fix:

Research I've done so far

I am working with excel, and I found resources discussing how to create a new macro, and some that even have examples, but I'm not confident that's going to be the right place for this. I also have a friend who is suggesting that it would be better to modify the file using Pandas, but that isn't something I'm familiar with either.

My question:

Where do I start? ...What is the proper tool to write a script to modify all of this?

Also, if possible, can you suggest a resource for me to use as reference when using the proper tool for this job?

Body:
Change this,

.. with this code,

Option Explicit

Sub wqweqrteq()
    Dim d As Long, dict As Object, vals As Variant

    Set dict = CreateObject("Scripting.Dictionary")

    With Worksheets("salesforce")
        With .Range(.Cells(2, "A"), .Cells(.Rows.Count, "C").End(xlUp))
            vals = .Value2
        End With

        For d = LBound(vals, 1) To UBound(vals, 1)
            dict.Item(vals(d, 1)) = vals(d, 2)
        Next d

        For d = LBound(vals, 1) To UBound(vals, 1)
            If dict.exists(vals(d, 3)) Then
                vals(d, 3) = dict.Item(vals(d, 3))
            End If
        Next d

        With .Range(.Cells(2, "A"), .Cells(.Rows.Count, "C").End(xlUp))
            .Value = vals
        End With
    End With

End Sub

.. into this.


问:
Can I use glmnet with caret and sparse matrices?
One of the big perks to using glmnet for me is the ability to work with sparse matrices directly without having to convert them. Posts here seem to indicate that caret's train function can only take in data frames for the training set, and ?caret::train suggests the same. Is this actually the case?</p>

Body:
@Noobie This works with glmnet, for example:

library(glmnet)
set.seed(1)
X <- sparseMatrix(i=sample(1:20,20), j=sample(1:20,20), x=sample(1:100,20),
                                       dims=c(20,20)) # some random sparse training data
X
# [1,] .  .  . 64  .  .  . .  . .  .  .  .  .  .  .  .  .  .  .
# [2,] .  .  .  .  .  .  . .  . .  .  .  .  . 98  .  .  .  .  .
# [3,] .  .  .  .  .  .  . .  . .  .  . 43  .  .  .  .  .  .  .
# [4,] .  .  .  .  .  .  . .  . .  .  .  .  .  .  .  .  .  . 51
# [5,] .  .  .  .  .  .  . .  . 7  .  .  .  .  .  .  .  .  .  .
# [6,] .  .  .  .  .  .  . .  . .  .  .  .  .  .  .  .  . 83  .
# [7,] .  .  .  .  .  .  . 9  . .  .  .  .  .  .  .  .  .  .  .
# [8,] .  .  .  . 65  .  . .  . .  .  .  .  .  .  .  .  .  .  .
# [9,] .  .  .  .  .  .  . .  . .  .  .  .  .  . 45  .  .  .  .
#[10,] . 22  .  .  .  .  . .  . .  .  .  .  .  .  .  .  .  .  .
#[11,] .  .  .  .  .  .  . .  . .  . 77  .  .  .  .  .  .  .  .
#[12,] .  .  .  .  .  .  . . 27 .  .  .  .  .  .  .  .  .  .  .
#[13,] .  .  .  .  .  .  . .  . .  .  .  .  .  .  . 33  .  .  .
#[14,] .  .  .  .  . 75  . .  . .  .  .  .  .  .  .  .  .  .  .
#[15,] 3  .  .  .  .  .  . .  . .  .  .  .  .  .  .  .  .  .  .
#[16,] .  . 54  .  .  .  . .  . .  .  .  .  .  .  .  .  .  .  .
#[17,] .  .  .  .  .  .  . .  . .  .  .  . 44  .  .  .  .  .  .
#[18,] .  .  .  .  .  . 55 .  . .  .  .  .  .  .  .  .  .  .  .
#[19,] .  .  .  .  .  .  . .  . . 68  .  .  .  .  .  .  .  .  .
#[20,] .  .  .  .  .  .  . .  . .  .  .  .  .  .  .  . 39  .  .

y <- as.factor(sample(0:1, 20, replace=TRUE))

enet.fit <- glmnet(X, y, family='binomial')

Xtest <- sparseMatrix(i=sample(1:10,10), j=sample(1:20,10), x=sample(1:100,10),
                                     dims=c(10,20)) # some random sparse test data

# [1,] .  . . .  . 45  . . .  . .  .  .  .  . . .  . . .
# [2,] .  . . .  .  .  . . .  . .  .  .  .  . . . 21 . .
# [3,] .  . . .  .  .  . . .  . .  .  .  . 97 . .  . . .
# [4,] .  . . .  .  .  . . .  . . 27  .  .  . . .  . . .
# [5,] .  . . . 66  .  . . .  . .  .  .  .  . . .  . . .
# [6,] .  . . .  .  .  . . .  . .  .  . 55  . . .  . . .
# [7,] . 35 . .  .  .  . . .  . .  .  .  .  . . .  . . .
# [8,] .  . . .  .  .  . . . 86 .  .  .  .  . . .  . . .
# [9,] .  . . .  .  . 13 . .  . .  .  .  .  . . .  . . .
# [10,] .  . . .  .  .  . . .  . .  . 61  .  . . .  . . .

predict(enet.fit, newx=Xtest, type='class',s=0.01)
#      1
# [1,] "0"
# [2,] "1"
# [3,] "0"
# [4,] "0"
# [5,] "1"
# [6,] "1"
# [7,] "1"
# [8,] "1"
# [9,] "0"
#[10,] "0"


问:
stable parameters in jsp page
I build a web application using jsp. I send parameters from servlet to jsp in get method to display them in jsp page when I request it. the problem is : when I submit the form to servlet and then return to jsp I have to send these parameter with the request.
How can I make a stable parameters so, I have to send them once (in get method only) and maintain them in jsp.</p>

答:
You could access request parameters by ${param}.

```<code><input name="foo" value="${param.foo}">
</code>```

...

```<code><input type="radio" name="bar" value="a" ${param.bar == 'a' ? 'checked' : ''}>
</code>```

...

```<code><select name="baz">
<option value="b" ${param.baz == 'b' ? 'selected' : ''}>label</option>
</code>```

...

```<code> <textarea name="boo">${param.boo}</textarea>
</code>```

This basically prints request.getParameter("foo") as input value. This way the submitted value will be retained in the input elements.

same question here
How can I retain HTML form field values in JSP after submitting form to Servlet?

Title: stable parameters in jsp page

Body:
You could access request parameters by ${param}.

<input name="foo" value="${param.foo}">

...

<input type="radio" name="bar" value="a" ${param.bar == 'a' ? 'checked' : ''}>

...

<select name="baz">
<option value="b" ${param.baz == 'b' ? 'selected' : ''}>label</option>

...

 <textarea name="boo">${param.boo}</textarea>

This basically prints request.getParameter("foo") as input value. This way the submitted value will be retained in the input elements.

same question here
How can I retain HTML form field values in JSP after submitting form to Servlet?


问:
Why is thing displaying to the page with this code?
My JSON is good.  I've followed a very simple example from the json2html site ... nothing displays.

 ```

答:
Firstly if you could paste the actual JSON in your question that would go along way to helping figure out the issue.

This is probably where you're going wrong

```<code>stories: [
    {'<>':'ul','class':'stories','html':function() {
        return($.json2html(this.groups,transforms.group));
    }}
 ],
</code>```

Let me run though how this works

First

```<code>$('#stories').json2html(data, transforms.stories);
</code>```

Transforms the data object(s) into stories

```<code>stories: [
    {'<>':'ul','class':'stories','html':function() {
        return($.json2html(this.groups,transforms.group));
    }}  ],
</code>```

Stories transforms the objects under the "groups" property into a group

```<code>group: [
  {"<>": "li", "id":"id", "html":[
    {"<>": "span", "html": "${AUTHOR} ${HEADLINE}"}
    ]}
 ]
</code>```

Group transforms the group object into a list item with a span.

So you're json object better look something like

```<code>[{"groups":[{"AUTHOR":"Someone","HEADLINE":"Someheadline"},..]}]
</code>```

Though since groups was just used as an example I would suspect your json object looks more like this (best to paste that actual JSON in your question)

```<code>[{"AUTHOR":"Someone","HEADLINE":"Someheadline"},..]
</code>```

In that case just use the following code snipet should work. Keep in mind that the transform is just a representation of the html (template) that you want for each object in the JSON array from your $.getJSON

```<code>var data = [{"AUTHOR":"Someone","HEADLINE":"Someheadline"}];

var transforms = {
 story: [
  {"<>": "li", "id":"id", "html":[
    {"<>": "span", "html": "${AUTHOR} ${HEADLINE}"}
    ]}
 ]};

$("#stories").json2html(data,transforms.story);

//OR using getJSON
$.getJSON( "news/list/category/news/format/json",  function(data) {
    $('#stories').json2html(data, transforms.story);
});
</code>```

Body:
Firstly if you could paste the actual JSON in your question that would go along way to helping figure out the issue.

This is probably where you're going wrong

stories: [
    {'<>':'ul','class':'stories','html':function() {
        return($.json2html(this.groups,transforms.group));
    }}
 ],

Let me run though how this works

First

$('#stories').json2html(data, transforms.stories);

Transforms the data object(s) into stories

stories: [
    {'<>':'ul','class':'stories','html':function() {
        return($.json2html(this.groups,transforms.group));
    }}  ],

Stories transforms the objects under the "groups" property into a group

group: [
  {"<>": "li", "id":"id", "html":[
    {"<>": "span", "html": "${AUTHOR} ${HEADLINE}"}
    ]}
 ]

Group transforms the group object into a list item with a span.

So you're json object better look something like

[{"groups":[{"AUTHOR":"Someone","HEADLINE":"Someheadline"},..]}]

Though since groups was just used as an example I would suspect your json object looks more like this (best to paste that actual JSON in your question)

[{"AUTHOR":"Someone","HEADLINE":"Someheadline"},..]

In that case just use the following code snipet should work. Keep in mind that the transform is just a representation of the html (template) that you want for each object in the JSON array from your $.getJSON

var data = [{"AUTHOR":"Someone","HEADLINE":"Someheadline"}];

var transforms = {
 story: [
  {"<>": "li", "id":"id", "html":[
    {"<>": "span", "html": "${AUTHOR} ${HEADLINE}"}
    ]}
 ]};

$("#stories").json2html(data,transforms.story);

//OR using getJSON
$.getJSON( "news/list/category/news/format/json",  function(data) {
    $('#stories').json2html(data, transforms.story);
});


问:
Rails - Updating a value through rails seed for a given user
Apologies for the question, I'm still learning rails. Trying to update a specific user's home cities through a drop down. I followed all the steps as outlined in this question How to have a drop down <select> field in a rails form? and I'm not getting any errors. However, when I go to my rails console and do User.first - the homecities_id is still set as nil. Thank you guys so much for your help.

edit.html.erb

```<code><div class="field">
  <%= f.label :homecity %><br>
  <%= f.collection_select :homecities_id, Homecity.all, :id, :Hometown %>
</div>
</code>```

User.rb

```<code>class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
  :recoverable, :rememberable, :trackable,
  :validatable, :omniauthable, omniauth_providers: [:facebook]

  cattr_accessor :current_user

  belongs_to :homecity, optional: true
end
</code>```

Homecity.rb

```<code>class Homecity < ApplicationRecord
  has_many :users
end
</code>```

Application_controller.rb

```<code>class ApplicationController < ActionController::Base
  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:username, :name, :avatar, :homecities])
    devise_parameter_sanitizer.permit(:account_update, keys: [:username,:name, :avatar, :homecities])
  end
end
</code>```

Migrations

```<code>class CreateHomecities < ActiveRecord::Migration[5.0]
  def change
    create_table :homecities do |t|
      t.string :Hometown
      t.timestamps
    end
  end
end

class AddHomecitiesRefToUsers < ActiveRecord::Migration[5.0]
  def change
    add_reference :users, :homecities, foreign_key: true
  end
end
</code>```

seed.rb

```<code>Homecity.destroy_all
bigapple = Homecity.create!(Hometown:"New York City")
techhub = Homecity.create!(Hometown:"San Francisco")
longhorns = Homecity.create!(Hometown:"Austin")
angels = Homecity.create!(Hometown:"Los Angeles")
windycity = Homecity.create!(Hometown:"Chicago")
hcards = Homecity.create!(Hometown:"Washington DC")
amazon = Homecity.create!(Hometown:"Seattle")
</code>```

答:
add_reference :users, :homecity, foreign_key: true

In the migration, only the first argument should be plural. Take a look here.

That is why you have homecitied_id instead of homecity_id in your database, which is not correct.

Also in the view you need to change to homecity_id.

```<code><%= f.collection_select :homecity_id, Homecity.all, :id, :Hometown %>
</code>```

Body:
Apologies for the question, I'm still learning rails. Trying to update a specific user's home cities through a drop down. I followed all the steps as outlined in this question How to have a drop down <select> field in a rails form? and I'm not getting any errors. However, when I go to my rails console and do User.first - the homecities_id is still set as nil. Thank you guys so much for your help.

edit.html.erb

  <%= f.label :homecity %>

  <%= f.collection_select :homecities_id, Homecity.all, :id, :Hometown %>

User.rb

class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
  :recoverable, :rememberable, :trackable,
  :validatable, :omniauthable, omniauth_providers: [:facebook]

  cattr_accessor :current_user

  belongs_to :homecity, optional: true
end

Homecity.rb

class Homecity < ApplicationRecord
  has_many :users
end

Application_controller.rb

class ApplicationController < ActionController::Base
  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:username, :name, :avatar, :homecities])
    devise_parameter_sanitizer.permit(:account_update, keys: [:username,:name, :avatar, :homecities])
  end
end

Migrations

class CreateHomecities < ActiveRecord::Migration[5.0]
  def change
    create_table :homecities do |t|
      t.string :Hometown
      t.timestamps
    end
  end
end

class AddHomecitiesRefToUsers < ActiveRecord::Migration[5.0]
  def change
    add_reference :users, :homecities, foreign_key: true
  end
end

seed.rb

Homecity.destroy_all
bigapple = Homecity.create!(Hometown:"New York City")
techhub = Homecity.create!(Hometown:"San Francisco")
longhorns = Homecity.create!(Hometown:"Austin")
angels = Homecity.create!(Hometown:"Los Angeles")
windycity = Homecity.create!(Hometown:"Chicago")
hcards = Homecity.create!(Hometown:"Washington DC")
amazon = Homecity.create!(Hometown:"Seattle")

Body:
add_reference :users, :homecity, foreign_key: true

In the migration, only the first argument should be plural. Take a look here.

That is why you have homecitied_id instead of homecity_id in your database, which is not correct.

Also in the view you need to change to homecity_id.

<%= f.collection_select :homecity_id, Homecity.all, :id, :Hometown %>


问:
Reset Bootstrap modal when clicking outside modal window
I'm having some problems with reseting my bootstrap modal whenever the user clicks outside the modal window to dismiss instead of pressing the dismiss button. My datetimepicker stops working whenever the modal window doesnt reset properly.

This is what my modal should do whenever it opens:

But this is what happens if I open the window just after dismissing my window by hitting the gray area outside the modal window:

Whenever I dismiss using the Avbryt (dismiss) button it works just fine.
I get no errors and this is the code I use for my modal

```<code>$scope.show = function() {
    ModalService.showModal({
            templateUrl: 'newProject.html',
            controller: "NewProjectModalController"
        }).then(function(modal) {
            modal.element.modal();
            modal.close.then(function(result) {
                $('#newProjectModal').modal('hide');
                $('body').removeClass('modal-open');
                $('.modal-backdrop').remove();
            }
        });
    });
}
$scope.dismiss = function () {
    close(false, 500)
}
</code>```

The modal service can be found on JSfiddle.

I discovered that its not really the backdrop that is triggering the dismiss but the edges of the modal window. If I hit the outside of the modal within the small square, its dismisses, but not if I hit the backdrop outside.

答:
Try triggering a click event on the Avbryt button when a user clicks on the modal backdrop. Something like this:

```<code>$('.modal-backdrop').click(function(){
  $('.avbryt').trigger('click');
});
</code>```

That should bypass whatever the underlying problem is.

For reference: http://api.jquery.com/trigger/

Body:
I'm having some problems with reseting my bootstrap modal whenever the user clicks outside the modal window to dismiss instead of pressing the dismiss button. My datetimepicker stops working whenever the modal window doesnt reset properly.

This is what my modal should do whenever it opens:

But this is what happens if I open the window just after dismissing my window by hitting the gray area outside the modal window:

Whenever I dismiss using the Avbryt (dismiss) button it works just fine.
I get no errors and this is the code I use for my modal

$scope.show = function() {
    ModalService.showModal({
            templateUrl: 'newProject.html',
            controller: "NewProjectModalController"
        }).then(function(modal) {
            modal.element.modal();
            modal.close.then(function(result) {
                $('#newProjectModal').modal('hide');
                $('body').removeClass('modal-open');
                $('.modal-backdrop').remove();
            }
        });
    });
}
$scope.dismiss = function () {
    close(false, 500)
}

The modal service can be found on JSfiddle.

I discovered that its not really the backdrop that is triggering the dismiss but the edges of the modal window. If I hit the outside of the modal within the small square, its dismisses, but not if I hit the backdrop outside.

Body:
Try triggering a click event on the Avbryt button when a user clicks on the modal backdrop. Something like this:

$('.modal-backdrop').click(function(){
  $('.avbryt').trigger('click');
});

That should bypass whatever the underlying problem is.

For reference: http://api.jquery.com/trigger/


问:
Java-based Config that creates Parameterized Singleton Spring Bean
I have the following list of bean definitions in XML:

```<code><bean id="version201627" class="predicate.ClientVersionPredicate">
    <property name="year" value="2016"/>
    <property name="week" value="27"/>
</bean>

<bean id="version201628" class="predicate.ClientVersionPredicate">
    <property name="year" value="2016"/>
    <property name="week" value="28"/>
</bean>

... // the list goes on
</code>```

Is there a way to convert this to Java-based @Configuration, and not creating so many methods?

something like:

```<code>@Bean
public ClientVersionPredicate somePredicate(String year, String week) {
    return new ClientVersionPredicate(year, week);
}
</code>```

but I can specify the args somewhere? Thanks.

答:
You can use GenericBeanDefintion (look here for more details) which helps to define & register the beans dynamically.

The following code uses GenericBeanDefintion & helps you define the beans which you need through a single method during application start up.

Basically, you need a List of objects (List<YearAndWeek> yearAndWeeks) which contain years and weeks or you can use any other collection/array which contain the data & then iterate over it to register the beans with the bean registry.

```<code>@Component
public class MyProjectSpringUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
           throws BeansException {
           MyProjectSpringUtil.applicationContext = applicationContext;
    }

    @PostConstruct
    public void addNewBeans() {
        AutowireCapableBeanFactory factory =
                 applicationContext.getAutowireCapableBeanFactory();
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) factory;

       //Get your years and weeks data here through objects or array
        List<YearAndWeek> yearAndWeeks = new ArrayList<>();

        for(int i=0;i<yearAndWeeks.size();i++) {
             YearAndWeek yearAndWeek = yearAndWeeks.get(i);

             GenericBeanDefinition clientVersionPredicate =
                                      new GenericBeanDefinition();
             clientVersionPredicate.setBeanClass(ClientVersionPredicate.class);
             clientVersionPredicate.setScope(
                GenericBeanDefinition.SCOPE_SINGLETON);
             MutablePropertyValues props = new MutablePropertyValues();
             props.add("year", yearAndWeeks.getYear());
             props.add("week", yearAndWeeks.getWeek());
             clientVersionPredicate.setPropertyValues();

             //register your bean with id & object
             registry.registerBeanDefinition(
                      "version"+yearAndWeek,getYear()+yearAndWeek,getMonth(),
                      clientVersionPredicate);
        }
    }
}
</code>```

YearAndWeek class:

```<code>public class YearAndWeek {
    private int year;

    private int week;

   //getters and setters
}
</code>```

Body:
I have the following list of bean definitions in XML:

<bean id="version201627" class="predicate.ClientVersionPredicate">
    <property name="year" value="2016"/>
    <property name="week" value="27"/>
</bean>

<bean id="version201628" class="predicate.ClientVersionPredicate">
    <property name="year" value="2016"/>
    <property name="week" value="28"/>
</bean>

... // the list goes on

Is there a way to convert this to Java-based @Configuration, and not creating so many methods?

something like:

@Bean
public ClientVersionPredicate somePredicate(String year, String week) {
    return new ClientVersionPredicate(year, week);
}

but I can specify the args somewhere? Thanks.

Body:
You can use GenericBeanDefintion (look here for more details) which helps to define & register the beans dynamically.

The following code uses GenericBeanDefintion & helps you define the beans which you need through a single method during application start up.

Basically, you need a List of objects (List<YearAndWeek> yearAndWeeks) which contain years and weeks or you can use any other collection/array which contain the data & then iterate over it to register the beans with the bean registry.

@Component
public class MyProjectSpringUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
           throws BeansException {
           MyProjectSpringUtil.applicationContext = applicationContext;
    }

    @PostConstruct
    public void addNewBeans() {
        AutowireCapableBeanFactory factory =
                 applicationContext.getAutowireCapableBeanFactory();
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) factory;

       //Get your years and weeks data here through objects or array
        List<YearAndWeek> yearAndWeeks = new ArrayList<>();

        for(int i=0;i<yearAndWeeks.size();i++) {
             YearAndWeek yearAndWeek = yearAndWeeks.get(i);

             GenericBeanDefinition clientVersionPredicate =
                                      new GenericBeanDefinition();
             clientVersionPredicate.setBeanClass(ClientVersionPredicate.class);
             clientVersionPredicate.setScope(
                GenericBeanDefinition.SCOPE_SINGLETON);
             MutablePropertyValues props = new MutablePropertyValues();
             props.add("year", yearAndWeeks.getYear());
             props.add("week", yearAndWeeks.getWeek());
             clientVersionPredicate.setPropertyValues();

             //register your bean with id & object
             registry.registerBeanDefinition(
                      "version"+yearAndWeek,getYear()+yearAndWeek,getMonth(),
                      clientVersionPredicate);
        }
    }
}

YearAndWeek class:

public class YearAndWeek {
    private int year;

    private int week;

   //getters and setters
}


问:
Swift Console input not case sensitive
i just started learning Swift3. For the beginning i write a console program for converting units. I have a console input stream

```<code>let typ = readLine()
</code>```

and of cause i get the exact same string back but i use this in a if statement. Now my Problem i don't want to check it case sensitive i only want the plain string.
This is the if construct i use:

```<code>if typ == unitA {
    print("foo")
    //Some Code
}else if typ == unitB{
    print("super foo")
    //Some Code
}else{
    print("Invalid input :/")
}
</code>```

Thank you :D

答: If you want to compare the string based case insensitive you can use caseInsensitiveCompare see this answer

Title: Swift Console input not case sensitive

Body:
i just started learning Swift3. For the beginning i write a console program for converting units. I have a console input stream

let typ = readLine()

and of cause i get the exact same string back but i use this in a if statement. Now my Problem i don't want to check it case sensitive i only want the plain string.
This is the if construct i use:

if typ == unitA {
    print("foo")
    //Some Code
}else if typ == unitB{
    print("super foo")
    //Some Code
}else{
    print("Invalid input :/")
}

Thank you :D


问:
Magento: Layout Changes using LOCAL XML ONLY
I'm pretty new to magento and I would like to customize the store front-end.

I'm using Magento 1.4.1 and I'm planning to do all design modifications on the local.xml of my new template.

My doubt is if it is possible to change the layout structure only using the local.xml. I mean without changing the phtml files.

A simple example of what I would like to be able is:
I want to put the catalog search in another part of my html and not inside the , as it is today. So I would like to remove it from top-bar and put it inside another div.

```<code><div class="top-bar">
<div class="breadcrumbs">
    <ul>
                    <li class="home">
                            <a href="http://www.domain.com/magento/" title="Ir para página principal">Principal</a>
                                        <span>/ </span>
                        </li>
                    <li class="category9">
                            <strong>Product Category</strong>
                                    </li>
            </ul>
</div><!--breadcrumbs-->
<form id="search_mini_form" action="http://www.domain.com/magento/catalogsearch/result/" method="get">
    <div class="form-search">
        <label for="search">Pesquisar</label>
        <input id="search" type="text" name="q" value="" class="input-text" />
        <button type="submit" title="Ir" class="button"><span><span>Ir</span></span></button>
        <div id="search_autocomplete" class="search-autocomplete"></div>
        <script type="text/javascript">
        //<![CDATA[
            var searchForm = new Varien.searchForm('search_mini_form', 'search', 'Procurar em toda a loja...');
            searchForm.initAutocomplete('http://www.domain.com/magento/catalogsearch/ajax/suggest/', 'search_autocomplete');
        //]]>
        </script>
    </div>
</form>
</div>   <!--top bar-->
</code>```

How do I accomplish this? Is it possible to use only local.xml?

Thanks in advance and best regards

答:
The practical answer is "No, you can't do that".

What you want to do is theoretically possible, although the amount of work that would need to be done and the value of it would be questionable.

You use local.xml to add, remove, and interact with Blocks.  Each phtml file has a parent block that corresponds to something in your layout.  You can't change how a phtml block is rendered via the Layout XML, unless the Block and phtml contain logic to allow this.

In theory, you could

Identify the class responsible for rendering a particular template

Create a new Block class that extends this class (not override)

Change add code in local.xml to replace the block class

In your new block class override the view rendering method so it calls the parent view rendering method, and then attempts to alter the results of the returned string before returning its value

Again, all possible, but of questionable value.

Why the hesitancy to replace a phtml file from the default theme with a phtml file in your own theme(s)?

Body:
I'm pretty new to magento and I would like to customize the store front-end.

I'm using Magento 1.4.1 and I'm planning to do all design modifications on the local.xml of my new template.

My doubt is if it is possible to change the layout structure only using the local.xml. I mean without changing the phtml files.

A simple example of what I would like to be able is:
I want to put the catalog search in another part of my html and not inside the , as it is today. So I would like to remove it from top-bar and put it inside another div.

                            Principal
                                        /

                            Product Category

<form id="search_mini_form" action="http://www.domain.com/magento/catalogsearch/result/" method="get">

        Pesquisar
        <input id="search" type="text" name="q" value="" class="input-text" />
        <button type="submit" title="Ir" class="button">Ir</button>

</form>

How do I accomplish this? Is it possible to use only local.xml?

Thanks in advance and best regards


问:
Create Thumbnails on Amazon S3 Bucket with Lambda function
I have two buckets on S3. campaignfotos and campaignfotosresized.

The Permissions for those two looks like this:

Created the ThumbnailCreatorRole ( I think I'm missing here something):

I have created a Lambda function an used the Code from here changed the file name form "CreateThumbnail.js" to "index.js".

Set the trigger, on create - so the thumbnails should be created when a user of my App uploads an image to the bucket:

When I test the function, it works for the first time (with the Test button on the lambda website on amazon) but it doesn't work when a User uploads an image from my app nor it works when I upload an image on the s3 bucket on amazons website.

When I try to test the function for the second time with the "Test" button, I get this error (yes I deleted the old resized-HappyFace.jpg from the thumbnails bucket):

What have I forgotten?

答:
The solution for this problem was the policy. The timout error for the testing above could be solved by increasing the timeout limit to 25sec.

How to set the policy:

Go to IAM => Roles => Create a new Role => Role Type => AWS Lambda => in Attach Policy select "AmazonS3FullAccess"

Now go to Lambda => select your Lambda function => in Configuration tab => Role: choose an existing Role => Select the just created Role

And finish, now it works. :)

Create thumbnails for already existing images:

You may have existing images in your bucket, which you want to create thumbnails for them?  Solution: Create a new bucket - go to the old bucket and select all images => cut. go to the new temporary created bucket and paste. Now select all those newly pasted images again in the temporary bucket => cut - go back to the old bucket and paste the images => this triggers your lambda function and will create for every image a new thumbnail. now you can delete the temporary created bucket. you are done. :)


问:
installfest rake db:migrate the system cannot find the path specified
I am going through the installfest process to get started with Ruby on Rails for the odin project, but I'm falling short at the final stage. I've installed everything they asked exactly as instructed, but when I run 'rake db:migrate' i get the message 'The system cannot find the path specified.'
I cant find anything for this on the internet, the solutions I've found all say the target file has the wrong code but when I correct as advised I still get the same message.

I am doing this for a windows system.

```<code>C:\Users\Olaoluwa>rails -v
Rails 5.0.2

C:\Users\Olaoluwa>cd c:\Sites

c:\Sites>mkdir railsbridge
A subdirectory or file railsbridge already exists.

c:\Sites>cd railsbridge

c:\Sites\railsbridge>cd test_app

c:\Sites\railsbridge\test_app>rails s
=> Booting Puma
=> Rails 5.0.2 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
*** SIGUSR2 not implemented, signal based restart unavailable!
*** SIGUSR1 not implemented, signal based restart unavailable!
*** SIGHUP not implemented, signal based logs reopening unavailable!
Puma starting in single mode...
* Version 3.7.1 (ruby 2.3.3-p222), codename: Snowy Sagebrush
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://localhost:3000
Use Ctrl-C to stop
Exiting
Terminate batch job (Y/N)? y

c:\Sites\railsbridge\test_app>rake db:migrate
The system cannot find the path specified.

c:\Sites\railsbridge\test_app>

Edit:
my gemfile.lock shows
GEM
remote: https://rubygems.org/
specs:
codeclimate-test-reporter (0.3.0)
  simplecov (>= 0.7.1, < 1.0.0)
diff-lcs (1.2.3)
docile (1.1.3)
multi_json (1.9.0)
rack (1.5.2)
rack-protection (1.5.0)
  rack
rake (10.0.4)
rspec (2.13.0)
  rspec-core (~> 2.13.0)
  rspec-expectations (~> 2.13.0)
  rspec-mocks (~> 2.13.0)
rspec-core (2.13.1)
rspec-expectations (2.13.0)
  diff-lcs (>= 1.1.3, < 2.0)
rspec-mocks (2.13.1)
simplecov (0.8.2)
  docile (~> 1.1.0)
  multi_json
  simplecov-html (~> 0.8.0)
simplecov-html (0.8.0)
sinatra (1.4.2)
  rack (~> 1.5, >= 1.5.2)
  rack-protection (~> 1.4)
  tilt (~> 1.3, >= 1.3.4)
tilt (1.3.7)

PLATFORMS
java
ruby

DEPENDENCIES
codeclimate-test-reporter
rack
rake
rspec
sinatra
</code>```

答:
If you haven't figured this out yet, it looks like running rails db:migrate should be the way it's done in Rails5 instead of rake db:migrate.

This is based off of this thread:
https://www.reddit.com/r/rails/comments/60gjx3/help_when_using_rake_dbmigrate_i_get_return_error/

Body:
I am going through the installfest process to get started with Ruby on Rails for the odin project, but I'm falling short at the final stage. I've installed everything they asked exactly as instructed, but when I run 'rake db:migrate' i get the message 'The system cannot find the path specified.'
I cant find anything for this on the internet, the solutions I've found all say the target file has the wrong code but when I correct as advised I still get the same message.

I am doing this for a windows system.

C:\Users\Olaoluwa>rails -v
Rails 5.0.2

C:\Users\Olaoluwa>cd c:\Sites

c:\Sites>mkdir railsbridge
A subdirectory or file railsbridge already exists.

c:\Sites>cd railsbridge

c:\Sites\railsbridge>cd test_app

c:\Sites\railsbridge\test_app>rails s
=> Booting Puma
=> Rails 5.0.2 application starting in development on http://localhost:3000
=> Run `rails server -h` for more startup options
*** SIGUSR2 not implemented, signal based restart unavailable!
*** SIGUSR1 not implemented, signal based restart unavailable!
*** SIGHUP not implemented, signal based logs reopening unavailable!
Puma starting in single mode...
* Version 3.7.1 (ruby 2.3.3-p222), codename: Snowy Sagebrush
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://localhost:3000
Use Ctrl-C to stop
Exiting
Terminate batch job (Y/N)? y

c:\Sites\railsbridge\test_app>rake db:migrate
The system cannot find the path specified.

c:\Sites\railsbridge\test_app>

Edit:
my gemfile.lock shows
GEM
remote: https://rubygems.org/
specs:
codeclimate-test-reporter (0.3.0)
  simplecov (>= 0.7.1, < 1.0.0)
diff-lcs (1.2.3)
docile (1.1.3)
multi_json (1.9.0)
rack (1.5.2)
rack-protection (1.5.0)
  rack
rake (10.0.4)
rspec (2.13.0)
  rspec-core (~> 2.13.0)
  rspec-expectations (~> 2.13.0)
  rspec-mocks (~> 2.13.0)
rspec-core (2.13.1)
rspec-expectations (2.13.0)
  diff-lcs (>= 1.1.3, < 2.0)
rspec-mocks (2.13.1)
simplecov (0.8.2)
  docile (~> 1.1.0)
  multi_json
  simplecov-html (~> 0.8.0)
simplecov-html (0.8.0)
sinatra (1.4.2)
  rack (~> 1.5, >= 1.5.2)
  rack-protection (~> 1.4)
  tilt (~> 1.3, >= 1.3.4)
tilt (1.3.7)

PLATFORMS
java
ruby

DEPENDENCIES
codeclimate-test-reporter
rack
rake
rspec
sinatra


问:
Python/Selenium Click on an element in a ul
I am new to Python/Selenium (< 3 days). I am trying to click on the "grades" item of an unordered list (Please see image). I have tried find_element_by_link_text, find_element_by_css_selector but am unable to find it.

Image from inspect element

Thanks.

答:
As per the HTML it is pretty clear that the desired field is within an  so you have to:

Induce WebDriverWait for the desired frame to be available and switch to it.

Induce WebDriverWait for the desired element to be clickable.

You can use either of the following Locator Strategies:

Using CSS_SELECTOR:

```<code>WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.ID,"frameDetail")))
element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a#grades")))
</code>```

Using XPATH:

```<code>WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.ID,"frameDetail")))
element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@id='grades']")))
</code>```

Note : You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Reference

You can find a couple of relevant discussions in:

Ways to deal with #document under iframe

Switch to an iframe through Selenium and python

Body:
As per the HTML it is pretty clear that the desired field is within an <iframe> so you have to:

Induce WebDriverWait for the desired frame to be available and switch to it.

Induce WebDriverWait for the desired element to be clickable.

You can use either of the following Locator Strategies:

Using CSS_SELECTOR:

WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.ID,"frameDetail")))
element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a#grades")))

Using XPATH:

WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.ID,"frameDetail")))
element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@id='grades']")))

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Reference

You can find a couple of relevant discussions in:

Ways to deal with #document under iframe

Switch to an iframe through Selenium and python


问:
write to file in foreach %dopar% loop
I have this code which I want to make parallel however I can't seem to get it to work.
The idea is that for each value chr, snp_sel(geno_data,k, bl) gives me back a matrix of k columns these columns are subsequently written one by one to a file.
How can I %dopar% this loop?</p>

```<code>foreach(chr=1:length(chrs_raw)) %dopar%
{
    start = Sys.time()
    print(start)

    print(chr)

    # get .raw file name + path
    rawfile = paste(RAWfolder, chrs_raw[chr],sep="/")
    # get .bim file name + path
    bimfile = paste(RAWfolder, chrs_bim[chr],sep="/")

    # Read in genetype data in raw format
    geno_data = fread(rawfile, data.table=FALSE, showProgress = FALSE)
    # Remove first 7 columns
    geno_data = as.matrix(geno_data[,c(7:ncol(geno_data))])

    # Apply LD subsetting function Lubke et al 2012
    LDsubset = snp_sel(geno_data,k, bl)
    rm(geno_data)

    snp_data = fread(bimfile, data.table=FALSE, showProgress = FALSE)

    for(subsets in 1:ncol(LDsubset))
    {
            dataout = snp_data[LDsubset[,subsets][LDsubset[,subsets] != 0],2]
            outfile = paste(gsub(".bim","",basename(chrs_bim[chr])), "S",subsets, sep="")
            pathout = paste("folderOut/Data/Subsets/",outfile, sep="")

            write.table(dataout, pathout, col.names=FALSE, row.names=F)
    }
    rm(snp_data); rm(LDsubset)
    stop = Sys.time()
    print(stop-start)
}
</code>```

答:
The line:

```<code>pathout = paste(folderOut/Data/Subsets/",outfile, sep="")
</code>```

is missing an opening double quote. It should be:

```<code>pathout = paste("folderOut/Data/Subsets/", outfile, sep="")
</code>```

I'm not sure if that fixes your problem entirely but that should help.

Title: write to file in foreach %dopar% loop

Body:
I have this code which I want to make parallel however I can't seem to get it to work.
The idea is that for each value chr, snp_sel(geno_data,k, bl) gives me back a matrix of k columns these columns are subsequently written one by one to a file.
How can I %dopar% this loop?

foreach(chr=1:length(chrs_raw)) %dopar%
{
    start = Sys.time()
    print(start)

    print(chr)

    # get .raw file name + path
    rawfile = paste(RAWfolder, chrs_raw[chr],sep="/")
    # get .bim file name + path
    bimfile = paste(RAWfolder, chrs_bim[chr],sep="/")

    # Read in genetype data in raw format
    geno_data = fread(rawfile, data.table=FALSE, showProgress = FALSE)
    # Remove first 7 columns
    geno_data = as.matrix(geno_data[,c(7:ncol(geno_data))])

    # Apply LD subsetting function Lubke et al 2012
    LDsubset = snp_sel(geno_data,k, bl)
    rm(geno_data)

    snp_data = fread(bimfile, data.table=FALSE, showProgress = FALSE)

    for(subsets in 1:ncol(LDsubset))
    {
            dataout = snp_data[LDsubset[,subsets][LDsubset[,subsets] != 0],2]
            outfile = paste(gsub(".bim","",basename(chrs_bim[chr])), "S",subsets, sep="")
            pathout = paste("folderOut/Data/Subsets/",outfile, sep="")

            write.table(dataout, pathout, col.names=FALSE, row.names=F)
    }
    rm(snp_data); rm(LDsubset)
    stop = Sys.time()
    print(stop-start)
}

Body:
The line:

pathout = paste(folderOut/Data/Subsets/",outfile, sep="")

is missing an opening double quote. It should be:

pathout = paste("folderOut/Data/Subsets/", outfile, sep="")

I'm not sure if that fixes your problem entirely but that should help.


问:
Need help in running this for Loop
Please be as simple as possible in explanation as I am a beginner.
Receives an integer n and returns the smallest integer that is greater than
    n and in which the sum of the digits is divisible by 11.
For example, nextCRC(100) = 119 because 119 is the first integer greater than
    100 and the sum of its digits 1+1+9 = 11 is divisible by 11.

1) The first thing which i cant understand is that why is there a "true" in the for loop at the start.

2) How do I compute the next number which is larger than and divisible by 11.

3)How do I do this for negative numbers, numbers < 0 .

```<code>public static int nextCRC(int n)
{
    try
    {
        **for (int i = n + 1; true; i++)**
        {
            String number = String.valueOf(Math.abs(i));

            int count = 0;
            for (int j = 0; j < number.length(); j++)
            {
                count += Integer.parseInt(String.valueOf(number.charAt(j)));
            }

            if (count > 0 && count % 11 == 0) return  i;
        }
    }
    catch (Exception e)
    {
        return 0;
    }
}

public static void main(String[] args)
{
    System.out.println(nextCRC(100));
    System.out.println(nextCRC(-100));
}
</code>```

}

答:
I added comments to the code explaining what each part of the code does:</p>

```<code>public static int nextCRC(int n)
{
try
{
    for (int i = n + 1; true; i++) // the for loop will loop as long as the boolean is true. i starts at the inputted value and increments by 1 each iteration
//Since the value is "true" it will loop forever or until a value is returned
    {
        String number = String.valueOf(Math.abs(i)); // convert the number to string

        int count = 0;
        for (int j = 0; j < number.length(); j++) //iterate through each digit in the number
        {
            count += Integer.parseInt(String.valueOf(number.charAt(j))); // add the value of each digit to cout variable
        }

        if (count > 0 && count % 11 == 0) return  i; //return the number that was checked if the sum of its digits is divisible by 11
    }
}
catch (Exception e) // return a value of 0 if there is an exception
{
    return 0;
}
}

public static void main(String[] args)
{
System.out.println(nextCRC(100));
System.out.println(nextCRC(-100));
}
}
</code>```

Title: Need help in running this for Loop

Body:
Please be as simple as possible in explanation as I am a beginner.
Receives an integer n and returns the smallest integer that is greater than
    n and in which the sum of the digits is divisible by 11.
For example, nextCRC(100) = 119 because 119 is the first integer greater than
    100 and the sum of its digits 1+1+9 = 11 is divisible by 11.

1) The first thing which i cant understand is that why is there a "true" in the for loop at the start.

2) How do I compute the next number which is larger than and divisible by 11.

3)How do I do this for negative numbers, numbers < 0 .

public static int nextCRC(int n)
{
    try
    {
        **for (int i = n + 1; true; i++)**
        {
            String number = String.valueOf(Math.abs(i));

            int count = 0;
            for (int j = 0; j < number.length(); j++)
            {
                count += Integer.parseInt(String.valueOf(number.charAt(j)));
            }

            if (count > 0 && count % 11 == 0) return  i;
        }
    }
    catch (Exception e)
    {
        return 0;
    }
}

public static void main(String[] args)
{
    System.out.println(nextCRC(100));
    System.out.println(nextCRC(-100));
}

}

Body:
I added comments to the code explaining what each part of the code does:

public static int nextCRC(int n)
{
try
{
    for (int i = n + 1; true; i++) // the for loop will loop as long as the boolean is true. i starts at the inputted value and increments by 1 each iteration
//Since the value is "true" it will loop forever or until a value is returned
    {
        String number = String.valueOf(Math.abs(i)); // convert the number to string

        int count = 0;
        for (int j = 0; j < number.length(); j++) //iterate through each digit in the number
        {
            count += Integer.parseInt(String.valueOf(number.charAt(j))); // add the value of each digit to cout variable
        }

        if (count > 0 && count % 11 == 0) return  i; //return the number that was checked if the sum of its digits is divisible by 11
    }
}
catch (Exception e) // return a value of 0 if there is an exception
{
    return 0;
}
}

public static void main(String[] args)
{
System.out.println(nextCRC(100));
System.out.println(nextCRC(-100));
}
}


问:
reverse printing on python 3.x function
```<code>import time
def close_garage_dors():
        a= '_ _ _'
        for i in range(5):
            time.sleep(1)
            print(a)

        return 'Doors are closed'
</code>```

Now my question is: How to open this doors :) Basically how to reverse this function, how to delete 5 lines of _ _ _ ? Any ideas?

答:
You should be able to use VT100 tools:

```<code>CURSOR_UP_ONE = '\x1b[1A' # Cursor up one line
ERASE_LINE = '\x1b[2K' # Erase current line
print(CURSOR_UP_ONE + ERASE_LINE)
</code>```

or ANSI escape sequence:

```<code>CURSOR_UP_ONE = '\033[F' # Cursor up one line
ERASE_LINE = '\033[K' # Clear to the end of line (not erase)
</code>```

Tested and working:

```<code>import time
CURSOR_UP_ONE = '\x1b[1A' # <--Replace with '\033[F' if you don't have VT100
ERASE_LINE = '\x1b[2K' # <--Replace with '\033[K' if you don't have VT100
def close_garage_dors():
    a = '_ _ _'
    for i in range(5):
        time.sleep(.5)
        print(a)
    for b in range(5):
        time.sleep(.5)
        print(CURSOR_UP_ONE + ERASE_LINE + CURSOR_UP_ONE)
close_garage_dors()
</code>```

Depending on your console you may need to use the ANSI code instead of VT100 tools.

Title: reverse printing on python 3.x function

Body:
import time
def close_garage_dors():
        a= '_ _ _'
        for i in range(5):
            time.sleep(1)
            print(a)

        return 'Doors are closed'

Now my question is: How to open this doors :) Basically how to reverse this function, how to delete 5 lines of _ _ _ ? Any ideas?

Body:
You should be able to use VT100 tools:

CURSOR_UP_ONE = '\x1b[1A' # Cursor up one line
ERASE_LINE = '\x1b[2K' # Erase current line
print(CURSOR_UP_ONE + ERASE_LINE)

or ANSI escape sequence:

CURSOR_UP_ONE = '\033[F' # Cursor up one line
ERASE_LINE = '\033[K' # Clear to the end of line (not erase)

Tested and working:

import time
CURSOR_UP_ONE = '\x1b[1A' # <--Replace with '\033[F' if you don't have VT100
ERASE_LINE = '\x1b[2K' # <--Replace with '\033[K' if you don't have VT100
def close_garage_dors():
    a = '_ _ _'
    for i in range(5):
        time.sleep(.5)
        print(a)
    for b in range(5):
        time.sleep(.5)
        print(CURSOR_UP_ONE + ERASE_LINE + CURSOR_UP_ONE)
close_garage_dors()

Depending on your console you may need to use the ANSI code instead of VT100 tools.


问:
Retrieve certain amount of children from Firebase
I am trying to create a tableView that loads only a certain amount of values, let's say like 30 or so from my database.

I've looked at other tutorials for this, but they are in Objective-C or some other language. Swift would be great!

答:
For Reference to the FireBase Documentation see:
https://www.firebase.com/docs/ios/guide/retrieving-data.html#section-queries

There is Objective-C and Swift Code referenced.

In short: you can make use of two functions:

```<code>open func queryLimitedToLast(limit: UInt) -> FIRDatabaseQuery
open func queryLimitedToFirst(limit: UInt) -> FIRDatabaseQuery
</code>```

UInt is a data type "unsigned int". Means: pass a positive number to the function :-)

Don't forget, to observe the results of the query by calling the "observeEventType" on it - this function contains a block, in which you can make use of your items (e.g. you could add them to an array of items. The array could be used for your tableview's datasource. Finally, reload the tableview

An Example to call it, could look like this (for your 30 entries) (e.g. in your viewDidLoad):

DataSource Array Declaration as Class Variable

```<code>var objects = [MyObjects]()
</code>```

Perform your Query:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    let ref = Firebase(url:"https://dinosaur-facts.firebaseio.com/dinosaurs")
    ref.queryLimitedToLast(30)
       .observeEventType(.ChildAdded, withBlock: { snapshot in
        println(snapshot.key)
        var newItems: [MyObject] = []
        for item in snapshot.children {
            let myObject = MyObject(snapshot: item as! FIRDataSnapshot)
            newItems.append(myObject)
        }
        self.objects = newItems
        self.tableView.reloadData()
    })
}
</code>```

And the interesting table view DataSource method could look like this:

```<code>override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return objects.count
    }
</code>```

Body:
For Reference to the FireBase Documentation see:
https://www.firebase.com/docs/ios/guide/retrieving-data.html#section-queries

There is Objective-C and Swift Code referenced.

In short: you can make use of two functions:

open func queryLimitedToLast(limit: UInt) -> FIRDatabaseQuery
open func queryLimitedToFirst(limit: UInt) -> FIRDatabaseQuery

UInt is a data type "unsigned int". Means: pass a positive number to the function :-)

Don't forget, to observe the results of the query by calling the "observeEventType" on it - this function contains a block, in which you can make use of your items (e.g. you could add them to an array of items. The array could be used for your tableview's datasource. Finally, reload the tableview

An Example to call it, could look like this (for your 30 entries) (e.g. in your viewDidLoad):

DataSource Array Declaration as Class Variable

var objects = [MyObjects]()

Perform your Query:

override func viewDidLoad() {
    super.viewDidLoad()

    let ref = Firebase(url:"https://dinosaur-facts.firebaseio.com/dinosaurs")
    ref.queryLimitedToLast(30)
       .observeEventType(.ChildAdded, withBlock: { snapshot in
        println(snapshot.key)
        var newItems: [MyObject] = []
        for item in snapshot.children {
            let myObject = MyObject(snapshot: item as! FIRDataSnapshot)
            newItems.append(myObject)
        }
        self.objects = newItems
        self.tableView.reloadData()
    })
}

And the interesting table view DataSource method could look like this:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return objects.count
    }