问:
Xcode, swift: SIGABRT error on performsegue
I am new to swift and I just started working on this project. It is a login app for ios. Here is the code for the "Log In" button. "Parola" means "password" by the way.

```<code>@IBAction func loginButton(_ sender: Any) {
    let Email = emailText.text;
    let Parola = parolaText.text;

    if((Email?.isEmpty)! || (Parola?.isEmpty)!){
        print("Empty field!")
    } else {

    let myUrl = NSURL(string: "http://my.url/webservice.php");
    let request = NSMutableURLRequest(url:myUrl! as URL);
    request.httpMethod = "POST";

    let postString = "email=\(String(describing: Email!))&password=\(String(describing: Parola!))";
    request.httpBody = postString.data(using: String.Encoding.utf8);

    let task = URLSession.shared.dataTask(with: request as URLRequest){
        data, response, error in

        if error != nil {
            print("error=\(String(describing: error))")
            return
        }

        var err: NSError?
        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

            if let parseJSON = json {
                var resultValue:String = parseJSON["status"] as! String;
                print("result: \(resultValue)");

                if(resultValue == "Success"){
                    self.performSegue(withIdentifier: "LogPers", sender: nil)
                }
            }

        } catch let error as NSError {
            err = error
        }
    }

    task.resume()

}
}
</code>```

It connects to a external database by using a web service to verify the inputed user information. All of that works fine.

My problem is the SIGABRT error I get when the app tries to execute the segue. I tried searching this problem online and all of the sources said that this error is caused by buggy outlets and connections, but all of my outlets are ok.

If I take the segue outside of the "let task = URLSession.shared.dataTask(with: request as URLRequest){" structure it can execute without the SIGABRT error, but I need it inside so it transfers to the second view only if the user input is correct.

How do i fix this? Thanks in advance.

Keep in mind that i am a beginner to xcode and swift, so sorry if this is a dumb question.

答:
The crash is because you're attempting to perform a segue on a background thread (because the performSegue call is in a URLSession callback). Any code that does things with views needs to run on the main thread.

Try wrapping your performSegue call in a DispatchQueue block, like this:

```<code>DispatchQueue.main.async {
    self.performSegue(withIdentifier: "LogPers", sender: nil)
}
</code>```

Body:
I am new to swift and I just started working on this project. It is a login app for ios. Here is the code for the "Log In" button. "Parola" means "password" by the way.

@IBAction func loginButton(_ sender: Any) {
    let Email = emailText.text;
    let Parola = parolaText.text;

    if((Email?.isEmpty)! || (Parola?.isEmpty)!){
        print("Empty field!")
    } else {

    let myUrl = NSURL(string: "http://my.url/webservice.php");
    let request = NSMutableURLRequest(url:myUrl! as URL);
    request.httpMethod = "POST";

    let postString = "email=\(String(describing: Email!))&password=\(String(describing: Parola!))";
    request.httpBody = postString.data(using: String.Encoding.utf8);

    let task = URLSession.shared.dataTask(with: request as URLRequest){
        data, response, error in

        if error != nil {
            print("error=\(String(describing: error))")
            return
        }

        var err: NSError?
        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

            if let parseJSON = json {
                var resultValue:String = parseJSON["status"] as! String;
                print("result: \(resultValue)");

                if(resultValue == "Success"){
                    self.performSegue(withIdentifier: "LogPers", sender: nil)
                }
            }

        } catch let error as NSError {
            err = error
        }
    }

    task.resume()

}
}

It connects to a external database by using a web service to verify the inputed user information. All of that works fine.

My problem is the SIGABRT error I get when the app tries to execute the segue. I tried searching this problem online and all of the sources said that this error is caused by buggy outlets and connections, but all of my outlets are ok.

If I take the segue outside of the "let task = URLSession.shared.dataTask(with: request as URLRequest){" structure it can execute without the SIGABRT error, but I need it inside so it transfers to the second view only if the user input is correct.

How do i fix this? Thanks in advance.

Keep in mind that i am a beginner to xcode and swift, so sorry if this is a dumb question.

Body:
The crash is because you're attempting to perform a segue on a background thread (because the performSegue call is in a URLSession callback). Any code that does things with views needs to run on the main thread.

Try wrapping your performSegue call in a DispatchQueue block, like this:

DispatchQueue.main.async {
    self.performSegue(withIdentifier: "LogPers", sender: nil)
}


来源: stackexchange

问:
Meteor: ArrayBuffer (FileReader result) is not passed to Meteor.method()
I have this event (upload of an image file using <input type="file">):

```<code>       "change .logoBusinessBig-upload":function(event, template){

            var reader = new FileReader()

            reader.addEventListener("load", function(evt){

                var x = reader.result

                console.log(x)

                Meteor.call("saveFile", x)

            })

            reader.readAsArrayBuffer(event.currentTarget.files[0])

        }
</code>```

and this Meteor.method()

```<code>       saveFile:function(file){

            console.log(file)

            var fs = Npm.require("fs")

            fs.writeFile('../../../../../public/jow.txt', file, function (err) {

                console.log("file saved")

            });

        }
</code>```

The console.log(x) in the event outputs an ArrayBuffer object, while the console.log(file) in the Meteor.method() shows and empty {} object.

Why is that? The ArrayBuffer should have been passed to the Meteor.method()

答:
Seeing that EJSON will encode typed arrays as base64 strings it doesn't matter if using EJSON or DateURL - they are equally inefficient (increasing bandwidth use by 30%).

So this:

```<code>reader.onload = function(event){
  var buffer = new Uint8Array(reader.result) // convert to binary
  Meteor.call('saveFile',buffer); // will convert to EJSON/base64
}

reader.readAsArrayBuffer(file); //read the file as arraybuffer
</code>```

is equivalent to

```<code>reader.onload = function(event){
  Meteor.call('saveFile',reader.result);
}

reader.readAsDataURL(file); //read the file DataURL (base 64)
</code>```

The last version is a line shorter on the client side, but will add a line on the server side when you unpack the file to trim it of the mime-type prefix, typically something like

```<code>new Buffer(dataURI.replace(/^data:.{1,20}\/.{1,30};base64,/, ''), 'base64');
</code>```

The alternative: XHR

So neither is really more efficient. If you want to to save on bandwidth, try doing this bit using XHR, which natively suppports all the binary types (File, ArrayBuffer, Blob). You might need to handle it outside of Meteor, perhaps as a small Express app with a route handled by a front-end proxy like NginX.

ContentLicense: CC BY-SA 3.0

Body:
I have this event (upload of an image file using <input type="file">):

       "change .logoBusinessBig-upload":function(event, template){

            var reader = new FileReader()

            reader.addEventListener("load", function(evt){

                var x = reader.result

                console.log(x)

                Meteor.call("saveFile", x)

            })

            reader.readAsArrayBuffer(event.currentTarget.files[0])

        }

and this Meteor.method()

       saveFile:function(file){

            console.log(file)

            var fs = Npm.require("fs")

            fs.writeFile('../../../../../public/jow.txt', file, function (err) {

                console.log("file saved")

            });

        }

The console.log(x) in the event outputs an ArrayBuffer object, while the console.log(file) in the Meteor.method() shows and empty {} object.

Why is that? The ArrayBuffer should have been passed to the Meteor.method()

Body:
Seeing that EJSON will encode typed arrays as base64 strings it doesn't matter if using EJSON or DateURL - they are equally inefficient (increasing bandwidth use by 30%).

So this:

reader.onload = function(event){
  var buffer = new Uint8Array(reader.result) // convert to binary
  Meteor.call('saveFile',buffer); // will convert to EJSON/base64
}

reader.readAsArrayBuffer(file); //read the file as arraybuffer

is equivalent to

reader.onload = function(event){
  Meteor.call('saveFile',reader.result);
}

reader.readAsDataURL(file); //read the file DataURL (base 64)

The last version is a line shorter on the client side, but will add a line on the server side when you unpack the file to trim it of the mime-type prefix, typically something like

new Buffer(dataURI.replace(/^data:.{1,20}\/.{1,30};base64,/, ''), 'base64');

The alternative: XHR

So neither is really more efficient. If you want to to save on bandwidth, try doing this bit using XHR, which natively suppports all the binary types (File, ArrayBuffer, Blob). You might need to handle it outside of Meteor, perhaps as a small Express app with a route handled by a front-end proxy like NginX.


问:
How add npm Configuration file template to my Visual Studio
Im doing a video tutorial to setup Angular 2 on VS 2017. During the setup process he search for "npm" and one template show. But in my VS doesn't. What I have to install to have those templates?

Of course I could just create "package.json" file myself but just wondering if I missing a package to do things easier.

This is my General Tab

答:
I had the same problem and, after much searching and testing many things, I found a solution.

It seems that in some cases the installation of Visual Studio is a mess and does not place the templates in the correct folder.

In my case I could find the templates in the folder

C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\ItemTemplates

and

C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\ProjectTemplates

My installation of Visual Studio 2017 uses the path

C:\Users\[myUser]\Documents\Visual Studio 2017\Templates\ItemTemplates

and

C:\Users\[myUser]\Documents\Visual Studio 2017\Templates\ProjectTemplates

What you have to do is replace the content of the first two folders inside the two second folders.

And now it is possible to use the npm template and others that were also missing.


问:
Why doing someVar in someArray in an If always give false value
I was just working on something in AngularJS. I noticed that by using the attached style of if condition, I always get a false result. Why so? Am I missing something? I tried to google it but didn't find anything.

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    var allowedExtensions = [".jpg",".pdf", ".png"];
    var testExt = ".jpg";

    if(testExt in allowedExtensions){
       $scope.isAllowed = true;
    }else{
       //will always go here why?
       $scope.isAllowed = false;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head></head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="MyCtrl">
  Is Extension Allowed : {{isAllowed}}
</div>
</body>
</html></code>```

I am from .NET background so we use LINQ in that kinda same like that. Is this type of syntax not supported in JS?

EDIT
I know about index of and other ways to find if it is in the array. But I was confused why in operator is not working.

Thank you for your time and help.

答:
You should use Array.prototype.indexOf() for arrays, in is for objects

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    var allowedExtensions = [".jpg",".pdf", ".png"];
    var testExt = ".jpg";

    if(allowedExtensions.indexOf(testExt) !== -1){
       $scope.isAllowed = true;
    }else{
       //will always go here why?
       $scope.isAllowed = false;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head></head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="MyCtrl">
  Is Extension Allowed : {{isAllowed}}
</div>
</body>
</html></code>```

Body:
I was just working on something in AngularJS. I noticed that by using the attached style of if condition, I always get a false result. Why so? Am I missing something? I tried to google it but didn't find anything.

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    var allowedExtensions = [".jpg",".pdf", ".png"];
    var testExt = ".jpg";

    if(testExt in allowedExtensions){
       $scope.isAllowed = true;
    }else{
       //will always go here why?
       $scope.isAllowed = false;
    }
}

  Is Extension Allowed : {{isAllowed}}

I am from .NET background so we use LINQ in that kinda same like that. Is this type of syntax not supported in JS?

EDIT
I know about index of and other ways to find if it is in the array. But I was confused why in operator is not working.

Thank you for your time and help.

Body:
You should use Array.prototype.indexOf() for arrays, in is for objects

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    var allowedExtensions = [".jpg",".pdf", ".png"];
    var testExt = ".jpg";

    if(allowedExtensions.indexOf(testExt) !== -1){
       $scope.isAllowed = true;
    }else{
       //will always go here why?
       $scope.isAllowed = false;
    }
}

<html>
<head></head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="MyCtrl">
  Is Extension Allowed : {{isAllowed}}
</div>
</body>
</html>


问:
Can't pull first $key from CSV using foreach
I am trying to pull data out of a foreach loop but I'm running into a strange phenomenon that I haven't encountered yet.

The first row of the CSV looks like this:

```<code>Part Number,Description,List Price
</code>```

Then Data so on and so forth.

What I have:

```<code>ini_set('auto_detect_line_endings', TRUE);
if (($openItems = fopen($uploadFile, 'r')) !== FALSE) {
   foreach (fgetcsv($openItems) as $key => $value) {
        $value = preg_replace('/\h+/', '', strtolower($value));
        echo $value;
        echo ' = ' . $key . " ";
        switch ($value) {
            case "partnumber":
                $pn = $key;
                break;
            case "description":
                $des = $key;
                break;
            case "listprice":
                $lp = $key;
                break;
        }
    }
    print_r("\npn: " . $pn . " des: " . $des . " lp: " . $lp);
}
</code>```

Print:

```<code>partnumber = 0 description = 1 listprice = 2
pn:  des: 1 lp: 2
</code>```

As you can see the first column is falsey so it is not assigned the proper value.

Alternative Print:

```<code>test = 0 partnumber = 1 description = 2 listprice = 3
pn: 1 des: 2 lp: 3
</code>```

Type check:

```<code>echo "I'm of Type ". gettype($value) . ". ";
</code>```

returns:

```<code>partnumber = 0 I'm of Type string. description = 1 I'm of Type string. listprice = 2 I'm of Type string.
</code>```

Side Note:

```<code>case "partnumber":
    $pn = $key;
    break;
</code>```

is never accessed

```<code>case "partnumber":
    $pn = $key;
    echo "I Worked!";
    break;
</code>```

This returns without any result.

Any Suggestions?

This Scenario is thanks to @azjezz

```<code>$csv = [];
ini_set('auto_detect_line_endings', TRUE);
if (($openItems = fopen($uploadFile, 'r')) !== FALSE) {
    foreach (fgetcsv($openItems) as $key => $value) {
        $value = preg_replace('/\h+/', '', strtolower($value));
        $csv[$value] = (Int) $key;
        echo $value;
        echo ' = ' . $key . " ";
        switch ($csv[$value]) {
            case "partnumber":
                $pn = $key;
                break;
            case "description":
                $des = $key;
                break;
            case "listprice":
                $lp = $key;
                break;
        }
    }
    print_r("\npn: " . $pn . " des: " . $des . " lp: " . $lp);
}
</code>```

Results in:

```<code>partnumber = 0 description = 1 listprice = 2
pn: 0 des:  lp:
</code>```

Another weird scinario:

```<code>    switch ((int) $value) {
        case "partnumber":
            $pn = $key;
            break;
        case "description":
            $des = $key;
            break;
        case "listprice":
            $lp = $key;
            break;
    }
</code>```

Returns:

```<code>partnumber = 0 description = 1 listprice = 2
pn: 2 des:  lp:
</code>```

答:
When I ran:

```<code>var_dump($value);
</code>```

I got:

```<code>string(13) "partnumber"
string(11) "description"
string(9) "listprice"
</code>```

But partnumber has 10 characters in it so that means hidden characters are getting through. so I changed my regular expression to this:

```<code>$value = trim(preg_replace('/[^a-z]+/', '', strtolower($value)));
</code>```

Body:
I am trying to pull data out of a foreach loop but I'm running into a strange phenomenon that I haven't encountered yet.

The first row of the CSV looks like this:

Part Number,Description,List Price

Then Data so on and so forth.

What I have:

ini_set('auto_detect_line_endings', TRUE);
if (($openItems = fopen($uploadFile, 'r')) !== FALSE) {
   foreach (fgetcsv($openItems) as $key => $value) {
        $value = preg_replace('/\h+/', '', strtolower($value));
        echo $value;
        echo ' = ' . $key . " ";
        switch ($value) {
            case "partnumber":
                $pn = $key;
                break;
            case "description":
                $des = $key;
                break;
            case "listprice":
                $lp = $key;
                break;
        }
    }
    print_r("\npn: " . $pn . " des: " . $des . " lp: " . $lp);
}

Print:

partnumber = 0 description = 1 listprice = 2
pn:  des: 1 lp: 2

As you can see the first column is falsey so it is not assigned the proper value.

Alternative Print:

test = 0 partnumber = 1 description = 2 listprice = 3
pn: 1 des: 2 lp: 3

Type check:

echo "I'm of Type ". gettype($value) . ". ";

returns:

partnumber = 0 I'm of Type string. description = 1 I'm of Type string. listprice = 2 I'm of Type string.

Side Note:

case "partnumber":
    $pn = $key;
    break;

is never accessed

case "partnumber":
    $pn = $key;
    echo "I Worked!";
    break;

This returns without any result.

Any Suggestions?

This Scenario is thanks to @azjezz

$csv = [];
ini_set('auto_detect_line_endings', TRUE);
if (($openItems = fopen($uploadFile, 'r')) !== FALSE) {
    foreach (fgetcsv($openItems) as $key => $value) {
        $value = preg_replace('/\h+/', '', strtolower($value));
        $csv[$value] = (Int) $key;
        echo $value;
        echo ' = ' . $key . " ";
        switch ($csv[$value]) {
            case "partnumber":
                $pn = $key;
                break;
            case "description":
                $des = $key;
                break;
            case "listprice":
                $lp = $key;
                break;
        }
    }
    print_r("\npn: " . $pn . " des: " . $des . " lp: " . $lp);
}

Results in:

partnumber = 0 description = 1 listprice = 2
pn: 0 des:  lp:

Another weird scinario:

    switch ((int) $value) {
        case "partnumber":
            $pn = $key;
            break;
        case "description":
            $des = $key;
            break;
        case "listprice":
            $lp = $key;
            break;
    }

Returns:

partnumber = 0 description = 1 listprice = 2
pn: 2 des:  lp:

Body:
When I ran:

var_dump($value);

I got:

string(13) "partnumber"
string(11) "description"
string(9) "listprice"

But partnumber has 10 characters in it so that means hidden characters are getting through. so I changed my regular expression to this:

$value = trim(preg_replace('/[^a-z]+/', '', strtolower($value)));


问:
Setting number in list that's less than 1% to 1% while keeping total 100%
I'm running into a logic issue with my web application.

Background: There will be a bunch of div's in a row across the page. Their CSS width: percentage is equal to the percentage the item's int value divided by the list's total int value.

The problem: I don't want any of the widths to be less than 1%.  This means I have to increase the width of items lower than 1% to 1%, and reduce the widths of all of the other items so the percentage total adds back up to 100% exactly.

This creates an issue where an item that was already exactly 1% gets reduced to less than 1%.

I've tried so many ways to do this, but this is my current iteration.  I made it simple for myself and you guys by putting it into a console application.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PercentageOfTotal
{
    public class Item
    {
        public int Value { get; set; }
        public double Percent { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var items = new List<Item>();

            items.Add(new Item { Value = 26 });
            items.Add(new Item { Value = 31 });
            items.Add(new Item { Value = 47 });
            items.Add(new Item { Value = 175 });
            items.Add(new Item { Value = 50 });
            items.Add(new Item { Value = 1 });
            items.Add(new Item { Value = 74 });
            items.Add(new Item { Value = 8 });
            items.Add(new Item { Value = 219 });
            items.Add(new Item { Value = 169 });

            int sum = items.Sum(x => x.Value);
            double minPercentage = 0.01;

            System.Console.WriteLine("Value - Percent");

            foreach (var item in items)
            {
                item.Percent = item.Value / (double)sum;
                System.Console.WriteLine(item.Value + " - " + item.Percent);
            }

            System.Console.WriteLine("---------");
            System.Console.WriteLine(items.Sum(x => x.Value) + " - " + items.Sum(x => x.Percent));
            System.Console.WriteLine("\n");

            var itemsLessThanOnePercent = items.Where(x => x.Percent < minPercentage).ToList();
            var itemsGreaterThanOrEqualToOnePercent = items.Where(x => x.Percent >= minPercentage).ToList();
            double totalPercentageLessThanOne = itemsLessThanOnePercent.Sum(x => x.Percent);
            double reduceEachGreaterThanOneBy = ((itemsLessThanOnePercent.Count() * minPercentage) - totalPercentageLessThanOne) / itemsGreaterThanOrEqualToOnePercent.Count();

            foreach (var item in itemsGreaterThanOrEqualToOnePercent)
            {
                item.Percent = item.Percent - reduceEachGreaterThanOneBy;
            }

            foreach (var item in itemsLessThanOnePercent)
            {
                item.Percent = minPercentage;
            }

            System.Console.WriteLine("Value - Percent");

            foreach (var item in items)
            {
                System.Console.WriteLine(item.Value + " - " + item.Percent);
            }

            System.Console.WriteLine("---------");
            System.Console.WriteLine(items.Sum(x => x.Value) + " - " + items.Sum(x => x.Percent));
            System.Console.ReadLine();
        }
    }
}
</code>```

As you can see, this case it reduces the item with Value = 8 to less than 1% (0.009) because the item.Value was already 1% in the first place.

Basically, I want the item's percentage to be relative to the overall sum of item.Value without having any percentages less than 1% and the total of percentages equaling 100%.

Any help would be appreciated.

答:
You should calculate the items as iteration until expected percentages performed. And you can do it recursively. I modified your code like this;</p>

```<code>    static void Main()
    {

        var items = new List<Item>();

        items.Add(new Item { Value = 26 });
        items.Add(new Item { Value = 31 });
        items.Add(new Item { Value = 47 });
        items.Add(new Item { Value = 175 });
        items.Add(new Item { Value = 50 });
        items.Add(new Item { Value = 1 });
        items.Add(new Item { Value = 74 });
        items.Add(new Item { Value = 8 });
        items.Add(new Item { Value = 219 });
        items.Add(new Item { Value = 169 });

        int sum = items.Sum(x => x.Value);
        double minPercentage = 0.01;

        System.Console.WriteLine("Value - Percent");

        foreach (var item in items)
        {
            item.Percent = item.Value / (double)sum;
            System.Console.WriteLine(item.Value + " - " + item.Percent);
        }

        System.Console.WriteLine("---------");
        System.Console.WriteLine(items.Sum(x => x.Value) + " - " + items.Sum(x => x.Percent));
        System.Console.WriteLine("\n");
        CalculatePercents(items,minPercentage);

        System.Console.WriteLine("Value - Percent");

        foreach (var item in items)
        {
            System.Console.WriteLine(item.Value + " - " + item.Percent);
        }

        System.Console.WriteLine("---------");
        System.Console.WriteLine(items.Sum(x => x.Value) + " - " + items.Sum(x => x.Percent));
        System.Console.ReadLine();

        Console.ReadLine();
    }

    private static void CalculatePercents(List<Item> items,double minPercentage)
    {

        var itemsLessThanOnePercent = items.Where(x => x.Percent < minPercentage).ToList();
        var itemsGreaterThanOrEqualToOnePercent = items.Where(x => x.Percent >= minPercentage).ToList();
        double totalPercentageLessThanOne = itemsLessThanOnePercent.Sum(x => x.Percent);
        double reduceEachGreaterThanOneBy = ((itemsLessThanOnePercent.Count() * minPercentage) - totalPercentageLessThanOne) / itemsGreaterThanOrEqualToOnePercent.Count();

        foreach (var item in itemsGreaterThanOrEqualToOnePercent)
        {
            item.Percent = item.Percent - reduceEachGreaterThanOneBy;
        }

        foreach (var item in itemsLessThanOnePercent)
        {
            item.Percent = minPercentage;
        }
        var minPercentagesItems = items.Where(x => x.Percent < minPercentage).ToList();
        if (minPercentagesItems.Count == 0)
        {
            return;
        }
        CalculatePercents(minPercentagesItems,minPercentage);
    }
</code>```

Body:
I'm running into a logic issue with my web application.

Background: There will be a bunch of div's in a row across the page. Their CSS width: percentage is equal to the percentage the item's int value divided by the list's total int value.

The problem: I don't want any of the widths to be less than 1%.  This means I have to increase the width of items lower than 1% to 1%, and reduce the widths of all of the other items so the percentage total adds back up to 100% exactly.

This creates an issue where an item that was already exactly 1% gets reduced to less than 1%.

I've tried so many ways to do this, but this is my current iteration.  I made it simple for myself and you guys by putting it into a console application.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PercentageOfTotal
{
    public class Item
    {
        public int Value { get; set; }
        public double Percent { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var items = new List<Item>();

            items.Add(new Item { Value = 26 });
            items.Add(new Item { Value = 31 });
            items.Add(new Item { Value = 47 });
            items.Add(new Item { Value = 175 });
            items.Add(new Item { Value = 50 });
            items.Add(new Item { Value = 1 });
            items.Add(new Item { Value = 74 });
            items.Add(new Item { Value = 8 });
            items.Add(new Item { Value = 219 });
            items.Add(new Item { Value = 169 });

            int sum = items.Sum(x => x.Value);
            double minPercentage = 0.01;

            System.Console.WriteLine("Value - Percent");

            foreach (var item in items)
            {
                item.Percent = item.Value / (double)sum;
                System.Console.WriteLine(item.Value + " - " + item.Percent);
            }

            System.Console.WriteLine("---------");
            System.Console.WriteLine(items.Sum(x => x.Value) + " - " + items.Sum(x => x.Percent));
            System.Console.WriteLine("\n");

            var itemsLessThanOnePercent = items.Where(x => x.Percent < minPercentage).ToList();
            var itemsGreaterThanOrEqualToOnePercent = items.Where(x => x.Percent >= minPercentage).ToList();
            double totalPercentageLessThanOne = itemsLessThanOnePercent.Sum(x => x.Percent);
            double reduceEachGreaterThanOneBy = ((itemsLessThanOnePercent.Count() * minPercentage) - totalPercentageLessThanOne) / itemsGreaterThanOrEqualToOnePercent.Count();

            foreach (var item in itemsGreaterThanOrEqualToOnePercent)
            {
                item.Percent = item.Percent - reduceEachGreaterThanOneBy;
            }

            foreach (var item in itemsLessThanOnePercent)
            {
                item.Percent = minPercentage;
            }

            System.Console.WriteLine("Value - Percent");

            foreach (var item in items)
            {
                System.Console.WriteLine(item.Value + " - " + item.Percent);
            }

            System.Console.WriteLine("---------");
            System.Console.WriteLine(items.Sum(x => x.Value) + " - " + items.Sum(x => x.Percent));
            System.Console.ReadLine();
        }
    }
}

As you can see, this case it reduces the item with Value = 8 to less than 1% (0.009) because the item.Value was already 1% in the first place.

Basically, I want the item's percentage to be relative to the overall sum of item.Value without having any percentages less than 1% and the total of percentages equaling 100%.

Any help would be appreciated.

Body:
You should calculate the items as iteration until expected percentages performed. And you can do it recursively. I modified your code like this;

    static void Main()
    {

        var items = new List<Item>();

        items.Add(new Item { Value = 26 });
        items.Add(new Item { Value = 31 });
        items.Add(new Item { Value = 47 });
        items.Add(new Item { Value = 175 });
        items.Add(new Item { Value = 50 });
        items.Add(new Item { Value = 1 });
        items.Add(new Item { Value = 74 });
        items.Add(new Item { Value = 8 });
        items.Add(new Item { Value = 219 });
        items.Add(new Item { Value = 169 });

        int sum = items.Sum(x => x.Value);
        double minPercentage = 0.01;

        System.Console.WriteLine("Value - Percent");

        foreach (var item in items)
        {
            item.Percent = item.Value / (double)sum;
            System.Console.WriteLine(item.Value + " - " + item.Percent);
        }

        System.Console.WriteLine("---------");
        System.Console.WriteLine(items.Sum(x => x.Value) + " - " + items.Sum(x => x.Percent));
        System.Console.WriteLine("\n");
        CalculatePercents(items,minPercentage);

        System.Console.WriteLine("Value - Percent");

        foreach (var item in items)
        {
            System.Console.WriteLine(item.Value + " - " + item.Percent);
        }

        System.Console.WriteLine("---------");
        System.Console.WriteLine(items.Sum(x => x.Value) + " - " + items.Sum(x => x.Percent));
        System.Console.ReadLine();

        Console.ReadLine();
    }

    private static void CalculatePercents(List<Item> items,double minPercentage)
    {

        var itemsLessThanOnePercent = items.Where(x => x.Percent < minPercentage).ToList();
        var itemsGreaterThanOrEqualToOnePercent = items.Where(x => x.Percent >= minPercentage).ToList();
        double totalPercentageLessThanOne = itemsLessThanOnePercent.Sum(x => x.Percent);
        double reduceEachGreaterThanOneBy = ((itemsLessThanOnePercent.Count() * minPercentage) - totalPercentageLessThanOne) / itemsGreaterThanOrEqualToOnePercent.Count();

        foreach (var item in itemsGreaterThanOrEqualToOnePercent)
        {
            item.Percent = item.Percent - reduceEachGreaterThanOneBy;
        }

        foreach (var item in itemsLessThanOnePercent)
        {
            item.Percent = minPercentage;
        }
        var minPercentagesItems = items.Where(x => x.Percent < minPercentage).ToList();
        if (minPercentagesItems.Count == 0)
        {
            return;
        }
        CalculatePercents(minPercentagesItems,minPercentage);
    }


问:
Symfony validation as comments in entity: what is misssing?
Validation is not reacting and blocks the submitting.
Could someone tell me what is missing or what am I doing wrong?
Apparently, when the method isValid is called, the validator blocks the validation.
 In entity, this variable is validated as follows:
    /**
     * @var string
     * @Assert\NotBlank()
     */
    private $pGaWeeks;

The submission is blocked what ever is given to the variable pGaWeeks and also when left empty.
There does not appear any error message. The submission works fine when "@Assert\NotBlank()" is taken away from the code.

I have also a DataHomeController.php

```<code>public function newAction(Request $request){

        if(!$this->hasFuAccess() || !$this->isAdmin()){
            throw new AccessDeniedException("You do not have permission to access");
        }

        $newrecord =array();

        $dataA = new DataAPatient();
        array_push($newrecord,$dataA);
        $appendForm = $this->createNewForm($dataA);

        $appendForm->handleRequest($request);

        if($appendForm->isSubmitted()){//Save
            if($appendForm->isValid()){
             $tmp_pKpPatientid = $this->storeDataAPatient($dataA);
             $records = $this->getStepByStepSearch($dataA);
             return $this->render('GeneralCommonBundle:DataHome:show.html.twig', array(
                'records'=> $records,
                'isNew' => false,
                'newrecord' => $newrecord
                ));
         }
       //   }
        }

        return $this->render('DataLiveBundle:DataAPatient:new.html.twig', array(
            'form'   => $appendForm->createView(),
        ));

    }
</code>```

And in config.yaml:

```<code>validation:      { enabled: true, enable_annotations: true }
</code>```

And an html.twig:

```<code>{% extends '::base.html.twig' %}

{% block body %}
{{ form_start(form, {attr: {novalidate: 'novalidate'}}) }}
{% form_theme form 'bootstrap_3_horizontal_layout.html.twig' %}

    <h1 style="margin-top:60px"><img src="{{ asset('public/images/icons/icon_data_gross.gif') }}"> Create a New Patient Dataset</h1>

          <div role="tabpanel" class="tab-pane active" id="PatientInfo">
              <div class="panel panel-default">
                  <div class="panel-body">
                     {% include 'DataLiveBundle:DataAPatient:form.html.twig' with {
                    'form':form, 'isNew': true  } only %}
                  </div>
              </div>
          </div>

    {{ form_row(form._token) }}
    {{ form_end(form) }}

{% endblock %}
</code>```

EDIT:

DataLiveBundle:DataAPatient:form.html.twig:

```<code>{% block body %}

            <div class="row" style='margin-bottom: 5px'>
                <div style='white-space: nowrap'>
                  <div class='col-xs-5'>
                    <div class='col-xs-5'>{{ form_label(form.pSnnid, 'SNN-ID (if known)', {'label_attr':{'style':'margin-top:3px'}})}}</div>
                   <div class='col-xs-2'>{{ form_widget(form.pSnnid, {'attr':{'style':'width:105px'}})}}</div>
                  </div>
                    <div class='col-xs-5'>
                  <div class='col-xs-5'>{{ form_label(form.pPlaceOfBirth, 'Place of birth', {'label_attr':{'style':'margin-top:3px' }})}}</div>
                  <div class='col-xs-2'>{{ form_widget(form.pPlaceOfBirth , {'attr': {'style':'width:200px' }})}}</div>
                  </div>
                </div>
            </div>

            <div class="row" style='margin-bottom: 5px'>
                <div style='white-space: nowrap'>
                  <div class='col-xs-5'>
                    <div class='col-xs-5'>{{ form_label(form.pDateOfBirth, 'Date of birth', {'label_attr':{'style':'margin-top:3px'}})}}</div>
                    <div class='col-xs-2'> {{ form_widget(form.pDateOfBirth, {'id': 'P_Date_of_birth','attr':{'style':'width:100px', }})}}</div>
                  </div>
                  <div class='col-xs-5'>
                    <div class='col-xs-5'>{{ form_label(form.pPatientNo, 'Patient ID / Nr. NEO', {'label_attr':{'style':'margin-top:5px'}})}}</div>
                    <div class='col-xs-2'>{{ form_widget(form.pPatientNo, {'attr':{'style':'width:105px' }})}}</div>
                  </div>
                </div>
            </div>

            <div class="row" style='margin-bottom: 5px'>
                <div style='white-space: nowrap'>
                  <div class='col-xs-5'>
                    <div class='col-xs-5'>{{ form_label(form.pGaWeeks, 'Gestational age', {'label_attr':{'style':'margin-top:3px'}})}}</div>
                    <div class='col-xs-2'> <div class="input-group">{{ form_widget(form.pGaWeeks, {'id': 'P_GA_weeks', 'attr':{'style':'width:45px'}})}}<div class="input-group-addon">w</div></div>
                <div class="input-group">{{ form_widget(form.pGaDays, {'id': 'P_GA_days','attr':{'style':'width:45px' }})}}<div class="input-group-addon">d</div></div></div>
                  </div>
                  <div class='col-xs-5'>
                    <div class='col-xs-5'>{{ form_label(form.pBirthWeight, 'Birth weight', {'label_attr':{'style':'margin-top:3px'}})}}</div>
                    <div class='col-xs-2'><div class="input-group">{{ form_widget(form.pBirthWeight, {'attr':{'style':'width:60px'}})}}<div class="input-group-addon">g</div></div></div>
                  </div>
                </div>
            </div>

            <div class="row" style='margin-bottom: 5px'>
                <div style='white-space:nowrap'>
                  <div class='col-xs-5'>
                    <div class='col-xs-5'>{{ form_label(form.pSex, 'Sex/Gender', {'label_attr':{'style':'margin-top:3px'}})}}</div>
                    <div class='col-xs-2' style='margin-top: 5px'>{{ form_widget(form.pSex, {'attr':{'style':'text-indent:10px'}})}}</div>
                  </div>
                  <div class='col-xs-5'>
                    <div class='col-xs-5'>{{ form_label(form.pNumberOfInfants, 'No. of infants in birth', {'label_attr':{'style':'margin-top:5px'}})}}</div>
                    <div class='col-xs-2'>{{ form_widget(form.pNumberOfInfants, {'attr':{'style':'width:35px'}})}}</div>
                  </div>
                </div>
            </div>

            <div class="row" style='margin-bottom: 5px'>
                <div style='white-space: nowrap'>
                  <div class='col-xs-5'>
                   {#<div class='col-xs-5'>{{ form_label(form.pEpoStudy, 'Child in EPO study')}}</div>#}
                   {# <div class='col-xs-2'>{{ form_widget(form.pEpoStudy, {'attr':{'style':'text-indent:10px'}})}}</div>#}
                  </div>
                  <div class='col-xs-5'>
                    <div class='col-xs-5'>{{ form_label(form.pRank, 'Rank (if >1)', {'label_attr':{'style':'margin-top:5px'}})}}</div>
                    <div class='col-xs-2'>{{ form_widget(form.pRank, {'attr':{'style':'width:35px'}})}}</div>
                    <div style='padding-right: 80px; margin-top: 8px'> (A/B/C/D..)</div>
                  </div>
                </div>
                <div  style= 'padding-left:40px ; margin-top:50px;'> (<font color=red>*</font> = input necessary)</div>
                {% if isNew == true %}
                  <div class='col-xs-2'>{{ form_widget(form.submit_new, {'attr':{'style':'width:160px ; color:red; margin-left:900px'}})}}</div>
                {% else %}
                <div style="padding-left:1000px"> <a class='btn btn-default btnNext'><font color=red>Continue »</font></a></div>
                {% endif %}
            </div>

{% endblock %}
</code>```

And the code for createNewForm:

```<code> /**
     * Creates a form to create a new DataAPatient entity.
     *
     * @param DataAPatient $entity The entity
     *
     * @return \Symfony\Component\Form\Form
     *
     */
    private function createNewForm(DataAPatient $entity)
    {
        $form = $this->createForm($this->get('data_livebundle.form.dataapatienttype'), $entity, array(
            'action' => $this->generateUrl('dataapatient_new'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));
        return $form;
    }
</code>```

And here is the methode stroeDataAPatient:

```<code>private function storeDataAPatient($dataA){

   if (!$dataA) {
        throw $this->createNotFoundException('Unable to find DataEFu2 entity.');
    }

    $em = $this->getDoctrine()->getManager();
    $session = $this->getRequest()->getSession();
    $em->persist($dataA);
    $em->flush();
    $tmp_pKpPatientid= $dataA->getpKpPatientid();

}
</code>```

storeDataAPatient:

```<code>private function storeDataAPatient($dataA){

   if (!$dataA) {
        throw $this->createNotFoundException('Unable to find DataEFu2 entity.');
    }

    $em = $this->getDoctrine()->getManager();
    $session = $this->getRequest()->getSession();
    $em->persist($dataA);
    $em->flush();
    $tmp_pKpPatientid= $dataA->getpKpPatientid();

}
</code>```

答:
I can tell you, you can put in your condition if the valid and submit, for better performance:

```<code> $form = $this->createForm(yourPathType, yourObject);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $this->getDoctrine()->getManager()->flush();
        }
</code>```

Is a short code

Body:
Validation is not reacting and blocks the submitting.
Could someone tell me what is missing or what am I doing wrong?
Apparently, when the method isValid is called, the validator blocks the validation.
 In entity, this variable is validated as follows:
    /**
     * @var string
     * @Assert\NotBlank()
     */
    private $pGaWeeks;

The submission is blocked what ever is given to the variable pGaWeeks and also when left empty.
There does not appear any error message. The submission works fine when "@Assert\NotBlank()" is taken away from the code.

I have also a DataHomeController.php

public function newAction(Request $request){

        if(!$this->hasFuAccess() || !$this->isAdmin()){
            throw new AccessDeniedException("You do not have permission to access");
        }

        $newrecord =array();

        $dataA = new DataAPatient();
        array_push($newrecord,$dataA);
        $appendForm = $this->createNewForm($dataA);

        $appendForm->handleRequest($request);

        if($appendForm->isSubmitted()){//Save
            if($appendForm->isValid()){
             $tmp_pKpPatientid = $this->storeDataAPatient($dataA);
             $records = $this->getStepByStepSearch($dataA);
             return $this->render('GeneralCommonBundle:DataHome:show.html.twig', array(
                'records'=> $records,
                'isNew' => false,
                'newrecord' => $newrecord
                ));
         }
       //   }
        }

        return $this->render('DataLiveBundle:DataAPatient:new.html.twig', array(
            'form'   => $appendForm->createView(),
        ));

    }

And in config.yaml:

validation:      { enabled: true, enable_annotations: true }

And an html.twig:

{% extends '::base.html.twig' %}

{% block body %}
{{ form_start(form, {attr: {novalidate: 'novalidate'}}) }}
{% form_theme form 'bootstrap_3_horizontal_layout.html.twig' %}

 Create a New Patient Dataset

                     {% include 'DataLiveBundle:DataAPatient:form.html.twig' with {
                    'form':form, 'isNew': true  } only %}

    {{ form_row(form._token) }}
    {{ form_end(form) }}

{% endblock %}

EDIT:

DataLiveBundle:DataAPatient:form.html.twig:

{% block body %}

{{ form_label(form.pSnnid, 'SNN-ID (if known)', {'label_attr':{'style':'margin-top:3px'}})}}

{{ form_widget(form.pSnnid, {'attr':{'style':'width:105px'}})}}

{{ form_label(form.pPlaceOfBirth, 'Place of birth', {'label_attr':{'style':'margin-top:3px' }})}}

{{ form_widget(form.pPlaceOfBirth , {'attr': {'style':'width:200px' }})}}

{{ form_label(form.pDateOfBirth, 'Date of birth', {'label_attr':{'style':'margin-top:3px'}})}}

 {{ form_widget(form.pDateOfBirth, {'id': 'P_Date_of_birth','attr':{'style':'width:100px', }})}}

{{ form_label(form.pPatientNo, 'Patient ID / Nr. NEO', {'label_attr':{'style':'margin-top:5px'}})}}

{{ form_widget(form.pPatientNo, {'attr':{'style':'width:105px' }})}}

{{ form_label(form.pGaWeeks, 'Gestational age', {'label_attr':{'style':'margin-top:3px'}})}}

{{ form_widget(form.pGaWeeks, {'id': 'P_GA_weeks', 'attr':{'style':'width:45px'}})}}
w

{{ form_widget(form.pGaDays, {'id': 'P_GA_days','attr':{'style':'width:45px' }})}}
d

{{ form_label(form.pBirthWeight, 'Birth weight', {'label_attr':{'style':'margin-top:3px'}})}}

{{ form_widget(form.pBirthWeight, {'attr':{'style':'width:60px'}})}}
g

{{ form_label(form.pSex, 'Sex/Gender', {'label_attr':{'style':'margin-top:3px'}})}}

{{ form_widget(form.pSex, {'attr':{'style':'text-indent:10px'}})}}

{{ form_label(form.pNumberOfInfants, 'No. of infants in birth', {'label_attr':{'style':'margin-top:5px'}})}}

{{ form_widget(form.pNumberOfInfants, {'attr':{'style':'width:35px'}})}}

                   {#
{{ form_label(form.pEpoStudy, 'Child in EPO study')}}
#}
                   {#
{{ form_widget(form.pEpoStudy, {'attr':{'style':'text-indent:10px'}})}}
#}

{{ form_label(form.pRank, 'Rank (if >1)', {'label_attr':{'style':'margin-top:5px'}})}}

{{ form_widget(form.pRank, {'attr':{'style':'width:35px'}})}}

 (A/B/C/D..)

 (* = input necessary)

                {% if isNew == true %}

{{ form_widget(form.submit_new, {'attr':{'style':'width:160px ; color:red; margin-left:900px'}})}}

                {% else %}

 Continue »

                {% endif %}

{% endblock %}

And the code for createNewForm:

 /**
     * Creates a form to create a new DataAPatient entity.
     *
     * @param DataAPatient $entity The entity
     *
     * @return \Symfony\Component\Form\Form
     *
     */
    private function createNewForm(DataAPatient $entity)
    {
        $form = $this->createForm($this->get('data_livebundle.form.dataapatienttype'), $entity, array(
            'action' => $this->generateUrl('dataapatient_new'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));
        return $form;
    }

And here is the methode stroeDataAPatient:

private function storeDataAPatient($dataA){

   if (!$dataA) {
        throw $this->createNotFoundException('Unable to find DataEFu2 entity.');
    }

    $em = $this->getDoctrine()->getManager();
    $session = $this->getRequest()->getSession();
    $em->persist($dataA);
    $em->flush();
    $tmp_pKpPatientid= $dataA->getpKpPatientid();

}

storeDataAPatient:

private function storeDataAPatient($dataA){

   if (!$dataA) {
        throw $this->createNotFoundException('Unable to find DataEFu2 entity.');
    }

    $em = $this->getDoctrine()->getManager();
    $session = $this->getRequest()->getSession();
    $em->persist($dataA);
    $em->flush();
    $tmp_pKpPatientid= $dataA->getpKpPatientid();

}

Body:
I can tell you, you can put in your condition if the valid and submit, for better performance:

 $form = $this->createForm(yourPathType, yourObject);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $this->getDoctrine()->getManager()->flush();
        }

Is a short code


问:
Owl Carousel, show child absolute div, over parent overflow hidden div
I am using owl carousel 2, I am facing following problem.

I have parent div with a name owl-stage-outer, it has overflow:hidden as per requirement of the carousel.

I have another child div name: ribbon (showing 'New Arrival' and 'Big Sale') which is position: absolute Now the problem which I am facing, on first item of carousel, ribbon is hiding because of overflow: hidden

reference image

Link on which I am working

I have tried solution provided in this link, but it will only work on immediate child.

Thanks in Advance.

答:
Try this solution</p>

```<code>.owl-carousel .owl-stage-outer {
  margin: -25px;
  padding: 25px;
}
</code>```

Body:
Try this solution

.owl-carousel .owl-stage-outer {
  margin: -25px;
  padding: 25px;
}


问:
Why does C# array not have Count property?

Possible Duplicate:

  count vs length vs size in a collection

Really strange:

C# arrays such as the following

```<code>double[] test = new double[1];
</code>```

support the Length property to get the size of the array. But arrays also implement an IList interface:

```<code>IList<double> list = test;
</code>```

However, the IList interface provides also a Count property. How come the array ("test" in this case) doesn't?

Edit: Thanks to all of you who pointed out that it is in fact the ICollection interface (not IList) which provides the Count property, and also that this is due to explicit implementation of the interface.

答:
Types inheriting from Array obtain implementations of IList<T> at run-time (how this is possible, don't ask me):

In the .NET Framework version 2.0, the
  Array class implements the
  System.Collections.Generic.IList<T>,
  System.Collections.Generic.ICollection<T>,
  and
  System.Collections.Generic.IEnumerable<T>
  generic interfaces. The
  implementations are provided to arrays
  at run time, and therefore are not
  visible to the documentation build
  tools. As a result, the generic
  interfaces do not appear in the
  declaration syntax for the Array
  class, and there are no reference
  topics for interface members that are
  accessible only by casting an array to
  the generic interface type (explicit
  interface implementations). The key
  thing to be aware of when you cast an
  array to one of these interfaces is
  that members which add, insert, or
  remove elements throw
  NotSupportedException.

In effect the IList<T> implementation acts like an explicit implementation, as Marc explained in his answer. This is why you can access certain members of IList<T> from the result of a cast but not from a variable typed as T[] specifically.

ContentLicense: CC BY-SA 2.5

Body:
Possible Duplicate:

  count vs length vs size in a collection

Really strange:

C# arrays such as the following

double[] test = new double[1];

support the Length property to get the size of the array. But arrays also implement an IList interface:

IList<double> list = test;

However, the IList interface provides also a Count property. How come the array ("test" in this case) doesn't?

Edit: Thanks to all of you who pointed out that it is in fact the ICollection interface (not IList) which provides the Count property, and also that this is due to explicit implementation of the interface.


问:
Creating image upload facility in php on one.com
I am trying to create a simple file upload facility for my website using php, I believe most of the code is fine. I'm using one.com and I have an assets folder which then has an image folder inside this is where I want the images to be uploaded to. I am unsure of what to put for the file image path though.When I try and upload an image the 'Done' is echoed to the page but my image doesn't appear in the folder.</p>

```<code>if(isset($_POST['submit'])){

// GETTING INFO FROM FILE WE'VE UPLOADED
$file = $_FILES['image'];
$fileName = $_FILES['image']['name'];
$fileTmpName = $_FILES['image']['tmp_name'];
$fileSize = $_FILES['image']['size'];
$fileError = $_FILES['image']['error'];
$fileType = $_FILES['image']['type'];
//Splitting the filename on the extension
$fileExt= explode ('.', $fileName);
//Getting the extension from the file and tolower so we can find out if it is an allowed file type
$fileActualExt = strtolower(end($fileExt));
//File types that we are going to allow
$allowed = array('jpg','jpeg','png');

if(in_array($fileActualExt, $allowed)){
    if($fileError === 0){
        $fileNameNew = uniqid('', true).".".$fileActualExt;

        $fileDestination = '/assets/images/'.$fileName;   //PROBLEM??

        move_uploaded_file($FileTmpName, $fileDestination);
        echo"Done?";
    }else{
        echo "There was an error?";
    }}
    else {
    echo "You cannot upload files of this type";
}}
</code>```

答:
The path your using is wrong. You need either the full path or the path relative to the location of the file your running from. try either

```<code>$fileDestination = getcwd().'/assets/images/'.$fileName;
</code>```

for the full path, or just

```<code>$fileDestination = './assets/images/'.$fileName;
</code>```

for the path relative to the current directory. This assumes that the file your running is in the same directory that contains the assets folder.

Body:
I am trying to create a simple file upload facility for my website using php, I believe most of the code is fine. I'm using one.com and I have an assets folder which then has an image folder inside this is where I want the images to be uploaded to. I am unsure of what to put for the file image path though.When I try and upload an image the 'Done' is echoed to the page but my image doesn't appear in the folder.

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

// GETTING INFO FROM FILE WE'VE UPLOADED
$file = $_FILES['image'];
$fileName = $_FILES['image']['name'];
$fileTmpName = $_FILES['image']['tmp_name'];
$fileSize = $_FILES['image']['size'];
$fileError = $_FILES['image']['error'];
$fileType = $_FILES['image']['type'];
//Splitting the filename on the extension
$fileExt= explode ('.', $fileName);
//Getting the extension from the file and tolower so we can find out if it is an allowed file type
$fileActualExt = strtolower(end($fileExt));
//File types that we are going to allow
$allowed = array('jpg','jpeg','png');

if(in_array($fileActualExt, $allowed)){
    if($fileError === 0){
        $fileNameNew = uniqid('', true).".".$fileActualExt;

        $fileDestination = '/assets/images/'.$fileName;   //PROBLEM??

        move_uploaded_file($FileTmpName, $fileDestination);
        echo"Done?";
    }else{
        echo "There was an error?";
    }}
    else {
    echo "You cannot upload files of this type";
}}

Body:
The path your using is wrong. You need either the full path or the path relative to the location of the file your running from. try either

$fileDestination = getcwd().'/assets/images/'.$fileName;

for the full path, or just

$fileDestination = './assets/images/'.$fileName;

for the path relative to the current directory. This assumes that the file your running is in the same directory that contains the assets folder.


问:
Cookie path always gets quoted using Apache Tomcat 7 but not Tomcat 9
I was implementing (using Apache Wicket 8.0.0-M6, JDK 1.8.0_20) a web application with some cookies running on Apache Tomcat 7.0.23 and all my cookies were being written with double quotes around their path whatever I did (no path ie default, /, /myapp/mysubdomain). This is preventing me from passing cookies betwseen my various webapps.

Eventually, I installed Apache Tomcat 9 (9.0.0.M26) and with JDK 1.8.0_141, this behaviour has gone away and the cookies are written correctly without the double quotes.

This is great and was without any config changes, but I am at a loss as to what in the upgrade has been responsible as I'd rather stick with Tomcat 7 for now if possible. Is it the change from the servlet 2 to 4 ? Anyone know?

答:
Did you refer to tomcat's migration guide? Here is tomcat's migration guide on cookies.

Tomcat's migration guide on Cookies

It says,

The default CookieProcessor is now the Rfc6265CookieProcessor. The
  CookieProcessor is configurable per Context and the
  LegacyCookieProcessor may be used to obtain the 8.0.x behaviour.

Try changing to LegacyCookieProcessor by adding following line in your  element.

```<code><CookieProcessor className="org.apache.tomcat.util.http.LegacyCookieProcessor"/>
</code>```

Body:
Did you refer to tomcat's migration guide? Here is tomcat's migration guide on cookies.

Tomcat's migration guide on Cookies

It says,

The default CookieProcessor is now the Rfc6265CookieProcessor. The
  CookieProcessor is configurable per Context and the
  LegacyCookieProcessor may be used to obtain the 8.0.x behaviour.

Try changing to LegacyCookieProcessor by adding following line in your  element.

<CookieProcessor className="org.apache.tomcat.util.http.LegacyCookieProcessor"/>


问:
XML::LibXML findvalue for an attribute with a namespace prefix

I am having some issues using
XML::LibXML
with namespaces. I have parsed files with namespaces before but this one is a bit different because it is defined with xlmns:abc rather then just xlmns.

I can't extract the 893 value of abc:id from this element

<element name='THEFIELD' type='string' abc:id='893' minOccurs='0' maxOccurs='1'>
```

<p>Sample data</p>

<pre class="lang-xml prettyprint-override"><code><schema
    xmlns:abc="http://www.example.com/schemas/abc"
    targetNamespace="http://example.com/schemas/product"
    elementFormDefault="qualified">

  <TheType name='MyName'>
    <sequence>
      <element name='THEFIELD' type='string' abc:id='893' minOccurs='0' maxOccurs='1'>
        <annotation><documentation>Identifier - Realtime</documentation></annotation>
      </element>
</code>```

My code returns all values correctly (the name and type attributes) but not abc:id

#!/usr/bin/perl

use 5.010;
use strict;
use warnings;

use XML::LibXML;
use XML::LibXML::XPathContext;

my $filename = '/schema.xml';
my $dom = XML::LibXML->load_xml( location => $filename );

my $xpc = XML::LibXML::XPathContext->new( $dom );
$xpc->registerNs( 'ns', 'abc:http://www.example.com/schemas/abc' );

foreach my $title ( $xpc->findnodes( '//schema' ) ) {

    foreach my $title ( $xpc->findnodes( '//TheType[@name="MyName"]/sequence/element' ) ) {

        say $title->findvalue( './@name' ), '|', $title->findvalue( '??????' ), '|', $title->findvalue( './@type' );
    }
}
```

My thoughts are

$xpc->registerNs( 'ns',  'abc:http://www.example.com/schemas/abc' ); is wrong

Every possibility I tried for the findvalue for abc:id—where the ???? is in the code—was wrong.

I tried many things here including things like ns:/@id to  *[local-name()="id"]

答:
XML::LibXML::XPathContext doesn't have to be used (in the recent years), it's loaded with XML::LibXML.

The correct usage of the registerNs function is to give it a prefix and URI.

Using the same variable for a nested loop makes no sense, especially if you don't use the outer variable anywhere.

You can use join to avoid repeating the call to findvalue.

```<code>#!/usr/bin/perl
use strict;
use warnings;
use feature qw{ say };

use XML::LibXML;

my $filename = shift;
my $dom = 'XML::LibXML'->load_xml(location => $filename);

my $xpc = 'XML::LibXML::XPathContext'->new($dom);
$xpc->registerNs(abc => 'http://www.example.com/schemas/abc');

for my $title ($xpc->findnodes('//TheType[@name="MyName"]/sequence/element')) {
    say join '|', map $title->findvalue($_), '@name', '@abc:id', '@type';
}
</code>```

Body:
I am having some issues using
XML::LibXML
with namespaces. I have parsed files with namespaces before but this one is a bit different because it is defined with xlmns:abc rather then just xlmns.

I can't extract the 893 value of abc:id from this element

<element name='THEFIELD' type='string' abc:id='893' minOccurs='0' maxOccurs='1'>

Sample data

<schema
    xmlns:abc="http://www.example.com/schemas/abc"
    targetNamespace="http://example.com/schemas/product"
    elementFormDefault="qualified">

  <TheType name='MyName'>
    <sequence>
      <element name='THEFIELD' type='string' abc:id='893' minOccurs='0' maxOccurs='1'>
        <annotation><documentation>Identifier - Realtime</documentation></annotation>
      </element>

My code returns all values correctly (the name and type attributes) but not abc:id

#!/usr/bin/perl

use 5.010;
use strict;
use warnings;

use XML::LibXML;
use XML::LibXML::XPathContext;

my $filename = '/schema.xml';
my $dom = XML::LibXML->load_xml( location => $filename );

my $xpc = XML::LibXML::XPathContext->new( $dom );
$xpc->registerNs( 'ns', 'abc:http://www.example.com/schemas/abc' );

foreach my $title ( $xpc->findnodes( '//schema' ) ) {

    foreach my $title ( $xpc->findnodes( '//TheType[@name="MyName"]/sequence/element' ) ) {

        say $title->findvalue( './@name' ), '|', $title->findvalue( '??????' ), '|', $title->findvalue( './@type' );
    }
}

My thoughts are

$xpc->registerNs( 'ns',  'abc:http://www.example.com/schemas/abc' ); is wrong

Every possibility I tried for the findvalue for abc:id—where the ???? is in the code—was wrong.

I tried many things here including things like ns:/@id to  *[local-name()="id"]

Body:
XML::LibXML::XPathContext doesn't have to be used (in the recent years), it's loaded with XML::LibXML.

The correct usage of the registerNs function is to give it a prefix and URI.

Using the same variable for a nested loop makes no sense, especially if you don't use the outer variable anywhere.

You can use join to avoid repeating the call to findvalue.

#!/usr/bin/perl
use strict;
use warnings;
use feature qw{ say };

use XML::LibXML;

my $filename = shift;
my $dom = 'XML::LibXML'->load_xml(location => $filename);

my $xpc = 'XML::LibXML::XPathContext'->new($dom);
$xpc->registerNs(abc => 'http://www.example.com/schemas/abc');

for my $title ($xpc->findnodes('//TheType[@name="MyName"]/sequence/element')) {
    say join '|', map $title->findvalue($_), '@name', '@abc:id', '@type';
}


Title: Inline SVG in react 16

Body:
I have a SVG file that I want to use as an icon in my react component.

<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 409.6 405.76"><defs><clipPath id="clip-path" transform="translate(-478 -181.08)"><rect class="cls-1" x="478" y="181" width="409.92" height="406.8"/></clipPath></defs><title>test</title><g class="cls-2"><path class="ofj" d="M682.8,396.06c50.72,0,91.84-48.13,91.84-107.49,0-82.33-41.12-107.49-91.84-107.49S591,206.24,591,288.57c0,59.36,41.12,107.49,91.84,107.49Zm0,0" transform="translate(-478 -181.08)"/><path d="M885.6,554.28,839.27,449.9a23.3,23.3,0,0,0-10.48-11.15l-71.91-37.43a4.66,4.66,0,0,0-4.93.41,113.41,113.41,0,0,1-138.3,0,4.67,4.67,0,0,0-4.94-.41l-71.9,37.43a23.24,23.24,0,0,0-10.47,11.15L480,554.28a23.16,23.16,0,0,0,21.18,32.56H864.42a23.17,23.17,0,0,0,21.18-32.56Zm0,0" transform="translate(-478 -181.08)"/></g></svg>

I want to be able to change the fill color dynamically. I've read that it's best to use SVG 'inline' and I tried to reference it with a <use> but it does not work (it's not showing...)

<svg className="icon-avator">
  <use xlinkHref="./assets/avatar.svg" />
</svg>

How can I achieve this?

Body:
React JSX can produce SVG, the same way it does with HTML. Write the SVG as the component's "markup", and use props to control the fill attribute (you can also change the style):

const Icon = ({ fill }) => (
  <svg viewBox="0 0 409.6 405.76" fill={ fill }>
      <path d="M682.8,396.06c50.72,0,91.84-48.13,91.84-107.49,0-82.33-41.12-107.49-91.84-107.49S591,206.24,591,288.57c0,59.36,41.12,107.49,91.84,107.49Zm0,0" transform="translate(-478 -181.08)"/>
      <path d="M885.6,554.28,839.27,449.9a23.3,23.3,0,0,0-10.48-11.15l-71.91-37.43a4.66,4.66,0,0,0-4.93.41,113.41,113.41,0,0,1-138.3,0,4.67,4.67,0,0,0-4.94-.41l-71.9,37.43a23.24,23.24,0,0,0-10.47,11.15L480,554.28a23.16,23.16,0,0,0,21.18,32.56H864.42a23.17,23.17,0,0,0,21.18-32.56Zm0,0" transform="translate(-478 -181.08)"/>
  </svg>
);

ReactDOM.render(
  <Icon fill="red" />,
  demo
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="demo"></div>


问:
Modal UIViewController can't receive NSNotifications
I have a modal UIViewController:

```<code>let rVC = RecoveryViewController()
rVC.modalPresentationStyle = .overFullScreen
self.present(rVC, animated: true, completion: nil)
</code>```

In viewDownload of this ViewController I have a function user.checkUserData() that would send NSNotifications when the job is done.

And, of course, observers for any of these notifications:

```<code>NotificationCenter.default.addObserver(self, selector: #selector(RecoveryViewController.userVIP), name: userDataIsHere, object: nil)
</code>```

But it seems that my modal ViewController is not able to receive any notifications, because nothing is happening. At the same time if I tried to add such observer to the parent UIViewController (non-modal), it'd work like a charm (actually, I checked).

My notifications are quite simple, and

```<code>let userDataIsHere = Notification.Name("userDataIsHere")
NotificationCenter.default.post(name: userDataIsHere, object: nil)
</code>```

What am I doing wrong here?

答:
Make sure you completed below things:

```<code>1) Notification Registered before use
2) Notification identifier must be same.
</code>```

Here is my code for notification:

1) Registered Notification in viewDidLoad:

```<code>let notificationName = Notification.Name("NotificationIdentifier")
NotificationCenter.default.addObserver(self, selector: #selector(yourFunctionName), name: notificationName, object: nil)

@objc func yourFunctionName(notification: NSNotification){
    //do stuff
    print("Called..")
}
</code>```

2) Post notification when you required:

```<code>    // Post notification
    let notificationName = Notification.Name("NotificationIdentifier")
    NotificationCenter.default.post(name: notificationName, object: nil)
</code>```

Body:
I have a modal UIViewController:

let rVC = RecoveryViewController()
rVC.modalPresentationStyle = .overFullScreen
self.present(rVC, animated: true, completion: nil)

In viewDownload of this ViewController I have a function user.checkUserData() that would send NSNotifications when the job is done.

And, of course, observers for any of these notifications:

NotificationCenter.default.addObserver(self, selector: #selector(RecoveryViewController.userVIP), name: userDataIsHere, object: nil)

But it seems that my modal ViewController is not able to receive any notifications, because nothing is happening. At the same time if I tried to add such observer to the parent UIViewController (non-modal), it'd work like a charm (actually, I checked).

My notifications are quite simple, and

let userDataIsHere = Notification.Name("userDataIsHere")
NotificationCenter.default.post(name: userDataIsHere, object: nil)

What am I doing wrong here?

Body:
Make sure you completed below things:

1) Notification Registered before use
2) Notification identifier must be same.

Here is my code for notification:

1) Registered Notification in viewDidLoad:

let notificationName = Notification.Name("NotificationIdentifier")
NotificationCenter.default.addObserver(self, selector: #selector(yourFunctionName), name: notificationName, object: nil)

@objc func yourFunctionName(notification: NSNotification){
    //do stuff
    print("Called..")
}

2) Post notification when you required:

    // Post notification
    let notificationName = Notification.Name("NotificationIdentifier")
    NotificationCenter.default.post(name: notificationName, object: nil)


问:
Android: Reverse geocoding - getFromLocation
I am trying to get an address based on the long/lat. it appears that something like this should work?

```<code>Geocoder myLocation = Geocoder(Locale.getDefault());
    List myList = myLocation.getFromLocation(latPoint,lngPoint,1);
</code>```

The issue is that I keep getting : The method Geocoder(Locale) is undefined for the type savemaplocation

Any assistance would be helpful. Thank you.

Thanks, I tried the context, locale one first, and that failed and was looking at some of the other constructors (I had seen one that had mentioned just locale). Regardless,

It did not work, as I am still getting : The method Geocoder(Context, Locale) is undefined for the type savemaplocation

I do have : import android.location.Geocoder;

答:
The following code snippet is doing it for me (lat and lng are doubles declared above this bit):</p>

```<code>Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
</code>```

OwnerDisplayName: Chrispix

Body:
I am trying to get an address based on the long/lat. it appears that something like this should work?

Geocoder myLocation = Geocoder(Locale.getDefault());
    List myList = myLocation.getFromLocation(latPoint,lngPoint,1);

The issue is that I keep getting : The method Geocoder(Locale) is undefined for the type savemaplocation

Any assistance would be helpful. Thank you.

Thanks, I tried the context, locale one first, and that failed and was looking at some of the other constructors (I had seen one that had mentioned just locale). Regardless,

It did not work, as I am still getting : The method Geocoder(Context, Locale) is undefined for the type savemaplocation

I do have : import android.location.Geocoder;

LastEditorDisplayName: Reto Meier

Body:
The following code snippet is doing it for me (lat and lng are doubles declared above this bit):

Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);

OwnerDisplayName: Wilfred Knievel


问:
How can I convert XML type to integer?
```<code>CREATE OR REPLACE FUNCTION j_f_sync_from_xml_2()
RETURNS boolean AS
$BODY$
DECLARE
myxml    xml;
datafile text := 'ABBATE_EMANUELE_Lvl1F2Va_20160418-1759_3.xml';
BEGIN

myxml := pg_read_file(datafile, 0, 100000000);

CREATE TABLE public.james_2 AS
SELECT unnest(xpath('//@OPERATORE', t)) as Operatore,
unnest(xpath('//@DATA', t)) as Data, unnest(xpath('//ObjectSelect/@NOME',
t)) as Nome, unnest(xpath('//ObjectSelect/@TEMPO', t)) as Tempo,
unnest(xpath('//ObjectSelect/@X', t)) as X,
unnest(xpath('//ObjectSelect/@Y', t)) as Y,
unnest(xpath('//ObjectSelect/@Z', t)) as Z
FROM   unnest(xpath('/root/level', myxml)) x(t);
RETURN TRUE;
END;
$BODY$ language plpgsql;
</code>```

This programme creates columns as XML type.
How convert XML type to integer format?
I tried this code:

```<code>select  Tempo::text::int
from    james_2
cross join lateral
unnest(xpath('//ObjectSelect/@TEMPO', Tempo)) xp(T)
</code>```

but give me an error: < not found

答:
You are trying to cast the complete xml that goes into your xpath call instead of the final output you aliased as xp(T). I would expect

```<code>select  T::text::int
from    james_2
cross join lateral
unnest(xpath('//ObjectSelect/@TEMPO', Tempo)) xp(T)
</code>```

to work. The ::text::int cast is the right idea I have used it my self in similar situations.

Title: How can I convert XML type to integer?

Body:
CREATE OR REPLACE FUNCTION j_f_sync_from_xml_2()
RETURNS boolean AS
$BODY$
DECLARE
myxml    xml;
datafile text := 'ABBATE_EMANUELE_Lvl1F2Va_20160418-1759_3.xml';
BEGIN

myxml := pg_read_file(datafile, 0, 100000000);

CREATE TABLE public.james_2 AS
SELECT unnest(xpath('//@OPERATORE', t)) as Operatore,
unnest(xpath('//@DATA', t)) as Data, unnest(xpath('//ObjectSelect/@NOME',
t)) as Nome, unnest(xpath('//ObjectSelect/@TEMPO', t)) as Tempo,
unnest(xpath('//ObjectSelect/@X', t)) as X,
unnest(xpath('//ObjectSelect/@Y', t)) as Y,
unnest(xpath('//ObjectSelect/@Z', t)) as Z
FROM   unnest(xpath('/root/level', myxml)) x(t);
RETURN TRUE;
END;
$BODY$ language plpgsql;

This programme creates columns as XML type.
How convert XML type to integer format?
I tried this code:

select  Tempo::text::int
from    james_2
cross join lateral
unnest(xpath('//ObjectSelect/@TEMPO', Tempo)) xp(T)

but give me an error: < not found

Body:
You are trying to cast the complete xml that goes into your xpath call instead of the final output you aliased as xp(T). I would expect

select  T::text::int
from    james_2
cross join lateral
unnest(xpath('//ObjectSelect/@TEMPO', Tempo)) xp(T)

to work. The ::text::int cast is the right idea I have used it my self in similar situations.


问:
How to require/import .less file in typescript file
I am trying to import a .less file in .ts file but I am not able to do that.
I am using webpack2 as bundler & webstorm IDE

Here snippet for less loader in a webpack.config.js file

```<code>{
  test: /\.less$/,      //less loader
  loader: ExtractTextPlugin.extract({
    fallbackLoader: 'style-loader',
    //loader: 'css-loader!less-loader'
    loader: 'raw-loader!less-loader'
  })
}, {
  test: /\.ts$/,    //typescript loader
  //include: path.resolve(__dirname, "ts-src"),
  include: path.resolve(__dirname, "js"),
  loader: "ts-loader"
}
//rest of code
resolve: {
  extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js", ".css", ".less"],
}
</code>```

As mentioned in link I tried by creating a global.d.ts file but no luck

Also i tried to require the file in the main.ts but in this case I am not seeing any option to requires a less file.
My question is how to load a .less file in a typescript files

[

答:
If your style.less file is in root of project, src folder you can use it as follows.

```<code>import "style.less";
</code>```

webpack.config.js should have properly configured style-loader and less-loader as mentioned in here
I have it like this:

```<code>module: {
   rules: [
      ...
      { test: /\.less$/i, use: ['style-loader', 'css-loader', 'less-loader'], issuer: /\.[tj]s$/i},
      { test: /\.less$/i, use: ['css-loader', 'less-loader'], issuer: /\.html?$/i },
   ]
}
</code>```

I have two, one for imports in ts/js files, the other one is for require in html templates

```<code><require from="style.less"></require>
</code>```

Body:
I am trying to import a .less file in .ts file but I am not able to do that.
I am using webpack2 as bundler & webstorm IDE

Here snippet for less loader in a webpack.config.js file

{
  test: /\.less$/,      //less loader
  loader: ExtractTextPlugin.extract({
    fallbackLoader: 'style-loader',
    //loader: 'css-loader!less-loader'
    loader: 'raw-loader!less-loader'
  })
}, {
  test: /\.ts$/,    //typescript loader
  //include: path.resolve(__dirname, "ts-src"),
  include: path.resolve(__dirname, "js"),
  loader: "ts-loader"
}
//rest of code
resolve: {
  extensions: [".webpack.js", ".web.js", ".ts", ".tsx", ".js", ".css", ".less"],
}

As mentioned in link I tried by creating a global.d.ts file but no luck

Also i tried to require the file in the main.ts but in this case I am not seeing any option to requires a less file.
My question is how to load a .less file in a typescript files

[

Body:
If your style.less file is in root of project, src folder you can use it as follows.

import "style.less";

webpack.config.js should have properly configured style-loader and less-loader as mentioned in here
I have it like this:

module: {
   rules: [
      ...
      { test: /\.less$/i, use: ['style-loader', 'css-loader', 'less-loader'], issuer: /\.[tj]s$/i},
      { test: /\.less$/i, use: ['css-loader', 'less-loader'], issuer: /\.html?$/i },
   ]
}

I have two, one for imports in ts/js files, the other one is for require in html templates

<require from="style.less"></require>


问:
Bash preserve whitespaces and newlines from file content to variable
I have this code

```<code>TOKEN=$(cat ./config/token)

echo "$TOKEN"

cat > variables.env <<EOF
TOKEN=`echo "$TOKEN"`
EOF
</code>```

I am trying to get the content of a file and output it in a new file prefixed by some text. The first echo in the console echoes the output I want, keeping the whitespaces and newlines.

However, in the new file the output is just the first line of the original string, while I'd like the same output I can see in the console with the first echo.

答:
You can do:

```<code>echo "TOKEN=" > newfile && cat ./config/token >> newfile
</code>```

>> appends to a file.

Body:
I have this code

TOKEN=$(cat ./config/token)

echo "$TOKEN"

cat > variables.env <<EOF
TOKEN=`echo "$TOKEN"`
EOF

I am trying to get the content of a file and output it in a new file prefixed by some text. The first echo in the console echoes the output I want, keeping the whitespaces and newlines.

However, in the new file the output is just the first line of the original string, while I'd like the same output I can see in the console with the first echo.

Body:
You can do:

echo "TOKEN=" > newfile && cat ./config/token >> newfile

>> appends to a file.


问:
iOS Simulator - how to test older (32-bit) devices?
Easy question. Is it possible to test 32-bit devices (iPhone 5/5c, iPad 2, etc.) on the iOS Simulator since the latest (11) iOS/SDK has been released? Since my budget is about $2, just buying a used one isn't currently an option (unfortunately). Are there options out there for the simulator?

Thanks for putting up with the noob question,

E

答: XCode --> Preferences --> Components will allow you do download simulator images for older versions of iOS</p>


问:
C++ cross-compiler from Windows to Linux
Are there any user friendly tools out there to cross-compile from Windows to Linux?</p>

答:
Are you asking for something that can take code written to run on Windows and make it run on linux?  There's not really a compiler that does that - but maybe you're looking for Wine ( http://www.winehq.org/ ) which lets you run Windows apps on linux (if they use APIs Wine has thunked out).

Edit: I'm assuming your code is using Windows APIs (Win32, etc.) in this answer.  If you're only using Standard C++ and libraries available cross-platform, then there's lots of other answers.


问:
Using JSQMessagesViewController without pod
I am trying to use JSQMessagesViewController in my swift project without using pod.

I downloaded the library from github and trying to run the Swift Example

in Swift Example project, I have added the JSQMessagesViewController folder.

I have a briding header with #import "JSQMessages.h" in it.

I have -ObjC other linker flag

My library search paths is empty

I am getting follwoing errors:

ld: warning: directory not found for option
  '-F/Users/Kashif/Library/Developer/Xcode/DerivedData/SwiftExample-ervbzkaxwylnjiabtkvejlktxmtv/Build/Products/Debug-iphonesimulator/JSQMessagesViewController'

ld: framework not found JSQMessagesViewController

clang: error: linker command failed with exit code 1 (use -v to see
  invocation)

What do you think I am missing?

Alternatively, if someone knows another library to achieve chat bubbles? as JSQMessagesViewController is now deprecated anyway.

答: Ya you want to check out MessageKit It is the next version of the project but more focused on being all swift. Its still relatively new but version 0.11.0 just shipped and it has most of the features that JSQMessagesViewController had. Let me know if you need more help they have an active slack group you can join


问:
Elasticsearch Id Inference 5.x
I'm configuring the ConnectionSettings object like so:

```<code>ConnectionSettings = new ConnectionSettings(settings.EndPointUrl)
    .DefaultIndex("myindex")
    .BasicAuthentication(settings.Username, settings.Password)
    .PrettyJson()
    .InferMappingFor<MyObject>(l => l
        .IdProperty(p => p.UserId)
    );
</code>```

When I index MyObject, it is not honoring the InferMappingFor setting. I've had to index single objects like so, explicitly setting the Id field:

```<code>var response = Elasticsearch.Client.Index(model, i => i
    .Id(model.UserId)
);
</code>```

Any idea why InferMappingFor isn't working? Am I missing something?

答:
Instead of using InferMapping you should use attribute decorations on your MyObject class.  Example:

```<code>[ElasticsearchType(Name = "myObject", Id=nameof(MyObject.UserID)]
public class MyObject {
   public String UserID {get;set;}

   //more properties
}
</code>```

Title: Elasticsearch Id Inference 5.x

Body:
I'm configuring the ConnectionSettings object like so:

ConnectionSettings = new ConnectionSettings(settings.EndPointUrl)
    .DefaultIndex("myindex")
    .BasicAuthentication(settings.Username, settings.Password)
    .PrettyJson()
    .InferMappingFor<MyObject>(l => l
        .IdProperty(p => p.UserId)
    );

When I index MyObject, it is not honoring the InferMappingFor setting. I've had to index single objects like so, explicitly setting the Id field:

var response = Elasticsearch.Client.Index(model, i => i
    .Id(model.UserId)
);

Any idea why InferMappingFor isn't working? Am I missing something?

Body:
Instead of using InferMapping you should use attribute decorations on your MyObject class.  Example:

[ElasticsearchType(Name = "myObject", Id=nameof(MyObject.UserID)]
public class MyObject {
   public String UserID {get;set;}

   //more properties
}


问:
'Microsoft.AspNet.SignalR.Hubs.IHubCallerConnectionContext<object>' does not contain a definition for 'Group'
I'am a newbie with signalR in ASP.NET C#.
the problem , I uses state management instead of Group property in Person class.

```<code> public class Person
{
   public string Name { get; set; }
    public string Message { get; set; }

  //  public string Group { get; set; }
}
</code>```

Client Code to Pass the State

```<code><script src="scripts/jquery-1.6.4.min.js"></script>

<script src="scripts/jquery.signalR-2.2.2.min.js"></script>

<script src="/signalr/hubs" type="text/javascript"></script>

<script type="text/javascript">
    $(function () {
        var broadcaster = $.connection.firstHub;

        broadcaster.client.displayText = function (name, message) {
            $('#messages').append('<li>' + name + ' said: ' + message + '</li>');
        };

        $.connection.hub.start().done(function () {
            $("#broadcast").click(function () {
                broadcaster.server.join($('#groupName').val());
                broadcaster.state.GroupName = $('#groupName').val();
                 broadcaster.server.broadcastMessage({ Name: $('#name').val(),Message: $('#message').val() });
                broadcaster.server.leave($('#groupName').val());
            });
        });
    });
</script>

<div>
    <input type="text" id="groupName" />
    <input type="text" id="name" />
    <input type="text" id="message" />
    <input type="button" id="broadcast" value="Broadcast" />

    <ul id="messages"></ul>
</div>
</code>```

Hub Implementation to Use the State Values

```<code>[HubName("firstHub")]
public class Chapter3Hub : Hub
{
    public void BroadcastMessage(Person person)
    {

    Context.ConnectionId).displayText(person.Name, person.Message);

        Clients.Group(Clients.Caller.GroupName).displayText(person.Name, person.Message);

    }

    public Task Join(string groupName)
    {
        return Groups.Add(Context.ConnectionId, groupName);
    }

    public Task Leave(string groupName)
    {
        return Groups.Remove(Context.ConnectionId, groupName);
    }
}
</code>```

When i run , VS bugs this. 'Microsoft.AspNet.SignalR.Hubs.IHubCallerConnectionContext' does not contain a definition for 'Group'

答:
hjk , I have modified this line .

```<code>  Clients.Group((string)Clients.Caller.GroupName).displayText(person.Name, person.Message);
</code>```

and run successfully.

Body:
I'am a newbie with signalR in ASP.NET C#.
the problem , I uses state management instead of Group property in Person class.

 public class Person
{
   public string Name { get; set; }
    public string Message { get; set; }

  //  public string Group { get; set; }
}

Client Code to Pass the State

    <input type="text" id="groupName" />
    <input type="text" id="name" />
    <input type="text" id="message" />
    <input type="button" id="broadcast" value="Broadcast" />

Hub Implementation to Use the State Values

[HubName("firstHub")]
public class Chapter3Hub : Hub
{
    public void BroadcastMessage(Person person)
    {

    Context.ConnectionId).displayText(person.Name, person.Message);

        Clients.Group(Clients.Caller.GroupName).displayText(person.Name, person.Message);

    }

    public Task Join(string groupName)
    {
        return Groups.Add(Context.ConnectionId, groupName);
    }

    public Task Leave(string groupName)
    {
        return Groups.Remove(Context.ConnectionId, groupName);
    }
}

When i run , VS bugs this. 'Microsoft.AspNet.SignalR.Hubs.IHubCallerConnectionContext' does not contain a definition for 'Group'

Body:
hjk , I have modified this line .

  Clients.Group((string)Clients.Caller.GroupName).displayText(person.Name, person.Message);

and run successfully.


答:
Ya you want to check out MessageKit It is the next version of the project but more focused on being all swift. Its still relatively new but version 0.11.0 just shipped and it has most of the features that JSQMessagesViewController had. Let me know if you need more help they have an active slack group you can join or just post more questions here on StackOverflow.

As for your question about not using pods It is possible to add any framework to a project but you miss out on what the "Dependency Manager" provides which is dependency management. IE any time a new feature is added to a framework the only way for you to get it in your project is to download the latest and add it manually to your project.

You also need to make sure you are adding the right thing. Essentially there is a .xproject but that may not be what you want to add to your project because that may be the "Project" that creates the Framework that actually gives you the capabilities you are looking for. So you may need to download the project open it in Xcode Build it and then find the "Product" which would be the framework the project produces and add that to your project.

CocoaPods or Carthage help you do that and update when new versions are available.

Title: Using JSQMessagesViewController without pod

Body:
I am trying to use JSQMessagesViewController in my swift project without using pod.

I downloaded the library from github and trying to run the Swift Example

in Swift Example project, I have added the JSQMessagesViewController folder.

I have a briding header with #import "JSQMessages.h" in it.

I have -ObjC other linker flag

My library search paths is empty

I am getting follwoing errors:

ld: warning: directory not found for option
  '-F/Users/Kashif/Library/Developer/Xcode/DerivedData/SwiftExample-ervbzkaxwylnjiabtkvejlktxmtv/Build/Products/Debug-iphonesimulator/JSQMessagesViewController'

ld: framework not found JSQMessagesViewController

clang: error: linker command failed with exit code 1 (use -v to see
  invocation)

What do you think I am missing?

Alternatively, if someone knows another library to achieve chat bubbles? as JSQMessagesViewController is now deprecated anyway.


问:
Linking Intel's MKL (BLAS & LAPACK) to GCC
I am trying to compile a giant software package, and this is the last hurdle I can't seem to figure out.

I'm getting errors like:

```<code>RNDiracDeterminantBase.cpp:(.text+0x22bf): undefined reference to `dgetrf_'
RNDiracDeterminantBase.cpp:(.text+0x2524): undefined reference to `dgetri_'
RNDiracDeterminantBase.cpp:(.text+0x3005): undefined reference to `dgetri_'
../../lib/libqmcwfs.a(RNDiracDeterminantBase.cpp.o): In function `qmcplusplus::RNDiracDeterminantBase::ratio(qmcplusplus::ParticleSet&, int, qmcplusplus::ParticleAttrib<qmcplusplus::TinyVector<double, 3u> >&, qmcplusplus::ParticleAttrib<double>&)':
RNDiracDeterminantBase.cpp:(.text+0x4156): undefined reference to `dgemv_'
RNDiracDeterminantBase.cpp:(.text+0x420f): undefined reference to `dger_'
</code>```

Google reveals that these references are to Intel's MKL library.  However, I don't know what file I need to link.  I've tried libmkl_core.a, libmkl_gnu_thread.a, libmkl_blacs_intelmpi_lp64.a, etc.  There's tons of files in:

/mkl/lib/intel64/

Can post more information if requested.

答:
I had a similar problem when setting up mingw on windows.

The following library linking order worked for me with gcc:

mkl_intel_thread

mkl_rt

mkl_core

mkl_intel_lp64

Hope this helps anyone stuck with this problem.

Body:
I am trying to compile a giant software package, and this is the last hurdle I can't seem to figure out.

I'm getting errors like:

RNDiracDeterminantBase.cpp:(.text+0x22bf): undefined reference to `dgetrf_'
RNDiracDeterminantBase.cpp:(.text+0x2524): undefined reference to `dgetri_'
RNDiracDeterminantBase.cpp:(.text+0x3005): undefined reference to `dgetri_'
../../lib/libqmcwfs.a(RNDiracDeterminantBase.cpp.o): In function `qmcplusplus::RNDiracDeterminantBase::ratio(qmcplusplus::ParticleSet&, int, qmcplusplus::ParticleAttrib<qmcplusplus::TinyVector<double, 3u> >&, qmcplusplus::ParticleAttrib<double>&)':
RNDiracDeterminantBase.cpp:(.text+0x4156): undefined reference to `dgemv_'
RNDiracDeterminantBase.cpp:(.text+0x420f): undefined reference to `dger_'

Google reveals that these references are to Intel's MKL library.  However, I don't know what file I need to link.  I've tried libmkl_core.a, libmkl_gnu_thread.a, libmkl_blacs_intelmpi_lp64.a, etc.  There's tons of files in:

/mkl/lib/intel64/

Can post more information if requested.


问:
Partially applied functions
While studying functional programming, the concept partially applied functions comes up a lot. In Haskell, something like the built-in function take is considered to be partially applied.

I am still unclear as to what it exactly means for a function to be partially applied or the use/implication of it.

答:
Strictly speaking, partial application refers to a situation where you supply fewer arguments than expected to a function, and get back a new function created on the fly that expects the remaining arguments.

Also strictly speaking, this does not apply in Haskell, because every function takes exactly one argument. There is no partial application, because you either apply the function to its argument or you don't.

However, Haskell provides syntactic sugar for defining functions that includes emulating multi-argument functions. In Haskell, then, "partial application" refers to supplying fewer than the full number of arguments needed to obtain a value that cannot be further applied to another argument. Using everyone's favorite add example,

```<code>add :: Int -> Int -> Int
add x y = x + y
</code>```

the type indicates that add takes one argument of type Int and returns a function of type Int -> Int. The -> type constructor is right-associative, so it helps to explicitly parenthesize it to emphasize the one-argument nature of a Haskell function: Int -> (Int -> Int).

When calling such a "multi-argument" function, we take advantage of the fact the function application is left-associative, so we can write add 3 5 instead of (add 3) 5. The call add 3 is thought of as partial application, because we could further apply the result to another argument.

I mentioned the syntactic sugar Haskell provides to ease defining complex higher-order functions. There is one fundamental way to define a function: using a lambda expression. For example, to define a function that adds 3 to its argument, we write

```<code>\x -> x + 3
</code>```

For ease of reference, we can assign a name to this function:

```<code>add = \x -> x + 3
</code>```

To further ease the defintion, Haskell lets us write in its place

```<code>add x = x + 3
</code>```

hiding the explicit lambda expression.

For higher-order, "multiargument" functions, we would write a function to add two values as

```<code>\x -> \y -> x + y
</code>```

To hide the currying, we can write instead

```<code>\x y -> x + y.
</code>```

Combined with the syntactic sugar of replacing a lambda expression with a paramterized name, all of the following are equivalent definitions for the explicitly typed function add :: Num a => a -> a -> a:

```<code>add = \x -> \y -> x + y -- or \x y -> x + y as noted above
add x = \y -> x + y
add x y = x + y
</code>```

Title: Partially applied functions

Body:
Strictly speaking, partial application refers to a situation where you supply fewer arguments than expected to a function, and get back a new function created on the fly that expects the remaining arguments.

Also strictly speaking, this does not apply in Haskell, because every function takes exactly one argument. There is no partial application, because you either apply the function to its argument or you don't.

However, Haskell provides syntactic sugar for defining functions that includes emulating multi-argument functions. In Haskell, then, "partial application" refers to supplying fewer than the full number of arguments needed to obtain a value that cannot be further applied to another argument. Using everyone's favorite add example,

add :: Int -> Int -> Int
add x y = x + y

the type indicates that add takes one argument of type Int and returns a function of type Int -> Int. The -> type constructor is right-associative, so it helps to explicitly parenthesize it to emphasize the one-argument nature of a Haskell function: Int -> (Int -> Int).

When calling such a "multi-argument" function, we take advantage of the fact the function application is left-associative, so we can write add 3 5 instead of (add 3) 5. The call add 3 is thought of as partial application, because we could further apply the result to another argument.

I mentioned the syntactic sugar Haskell provides to ease defining complex higher-order functions. There is one fundamental way to define a function: using a lambda expression. For example, to define a function that adds 3 to its argument, we write

\x -> x + 3

For ease of reference, we can assign a name to this function:

add = \x -> x + 3

To further ease the defintion, Haskell lets us write in its place

add x = x + 3

hiding the explicit lambda expression.

For higher-order, "multiargument" functions, we would write a function to add two values as

\x -> \y -> x + y

To hide the currying, we can write instead

\x y -> x + y.

Combined with the syntactic sugar of replacing a lambda expression with a paramterized name, all of the following are equivalent definitions for the explicitly typed function add :: Num a => a -> a -> a:

add = \x -> \y -> x + y -- or \x y -> x + y as noted above
add x = \y -> x + y
add x y = x + y


答:
Useless use of echo

This is what you could write:

```<code>cat > variables.env <<EOF
TOKEN=${TOKEN}
EOF
</code>```

Title: Bash preserve whitespaces and newlines from file content to variable

Body:
Useless use of echo

This is what you could write:

cat > variables.env <<EOF
TOKEN=${TOKEN}
EOF


问:
Querying varchars as decimals in SQL Server
I have a problem in SQL Server, I am trying to query

```<code>where x.numbers >= '9'
</code>```

where x.numbers was stored as varchar and some of the values I have in that field are

```<code>8.9
9.3
6.7
>10
8.3
>= 9
</code>```

If I try isnumeric(x.numbers), then it is excluding those values that start with > or >=. and I tried cast(x.numbers as decimal) but it is not working as well. Please advise

答:
I would use try_convert():

```<code> where try_convert(decimal(38, 6), field) > 9
</code>```

Now, this works for many circumstances and assumes that you want to ignore non-numeric values.

You can modify this to get rid of various "other" characters:

```<code> where try_convert(decimal(38, 6), replace(replace(replace(replace(field, ' ', ''), '=', ''), '>', ''), '<', '')) > 9
</code>```

This ignores the "operator" characters.

However, your problem is incompletely specified.  If the field were '< 12' or '> 7' what do you want it to return?

Body:
I have a problem in SQL Server, I am trying to query

where x.numbers >= '9'

where x.numbers was stored as varchar and some of the values I have in that field are

8.9
9.3
6.7
>10
8.3
>= 9

If I try isnumeric(x.numbers), then it is excluding those values that start with > or >=. and I tried cast(x.numbers as decimal) but it is not working as well. Please advise

Body:
I would use try_convert():

 where try_convert(decimal(38, 6), field) > 9

Now, this works for many circumstances and assumes that you want to ignore non-numeric values.

You can modify this to get rid of various "other" characters:

 where try_convert(decimal(38, 6), replace(replace(replace(replace(field, ' ', ''), '=', ''), '>', ''), '<', '')) > 9

This ignores the "operator" characters.

However, your problem is incompletely specified.  If the field were '< 12' or '> 7' what do you want it to return?


问:
pyinstaller QSqlDatabase: QSQLITE driver not loaded QSqlDatabase: available drivers:
I have witten a GUI app using pyqt5 and includes a QtSql database QSQLITE. The app works perfectly. However when I run pyinstaller to a package my app, the app runs until the time where it has to invoke QtSQL DATABASE QSQLITE. This is the error I get

QSqlDatabase: QSQLITE driver not loaded
QSqlDatabase: available drivers:

How do I load the driver so that it can be included when I run pyinstaller.

Thank you

答:
I experienced the same problem with QMYSQL driver using PySide and I found a solution.

You need to manually include the driver into the qt4_plugins/sqldrivers/ bundle directory.

For that, in your spec file add :

```<code>a = Analysis(...
    binaries=[('/usr/lib/x86_64-linux-gnu/qt4/plugins/sqldrivers/libqsqlmysql.so', 'qt4_plugins/sqldrivers')],
    ...
)
</code>```

This will works for QMYSQL driver but you just need to find the name of the SQLITE driver (probably libqsqlsqlite)

Body:
I experienced the same problem with QMYSQL driver using PySide and I found a solution.

You need to manually include the driver into the qt4_plugins/sqldrivers/ bundle directory.

For that, in your spec file add :

a = Analysis(...
    binaries=[('/usr/lib/x86_64-linux-gnu/qt4/plugins/sqldrivers/libqsqlmysql.so', 'qt4_plugins/sqldrivers')],
    ...
)

This will works for QMYSQL driver but you just need to find the name of the SQLITE driver (probably libqsqlsqlite)