问:
open a Pop Up view when saving data on Parse (SWIFT)
I'm making a register view on Swift for an app. I want to load a pop-up view when the user is successfully registered to add more data. I'm storing the data using Parse.

I'm using this code to save the data:

```<code>@IBAction func registerButtonPressed(_ sender: Any) {

    if emailTextField.text == "" || usuerTextField.text == "" || password1TextField.text == "" || password2TextField.text == "" {

        createAlert(title: "Error", message: "Fill all data")

    } else {

        if password1TextField.text != password2TextField.text {

            createAlert(title: "Error", message: "Passwords must be the same")
        } else {

            activityIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
            activityIndicator.center = self.view.center
            activityIndicator.hidesWhenStopped = true
            activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
            view.addSubview(activityIndicator)
            activityIndicator.startAnimating()
            UIApplication.shared.beginIgnoringInteractionEvents() // UIApplication.shared() is now UIApplication.shared

            let user = PFUser()

            user.username = usuerTextField.text
            user.email = emailTextField.text
            user.password = password1TextField.text

            let acl = PFACL()

            acl.getPublicWriteAccess = true

            user.acl = acl

            user.signUpInBackground(block: { (success, error) in

                self.activityIndicator.stopAnimating()
                UIApplication.shared.endIgnoringInteractionEvents() // UIApplication.shared() is now  UIApplication.shared

                if error != nil {

                    var displayErrorMessage = "Please try again later."

                    let error = error as NSError?

                    if let errorMessage = error?.userInfo["error"] as? String {

                        displayErrorMessage = errorMessage

                    }

                    self.createAlert(title: "Signup Error", message: displayErrorMessage)

                } else {

                }

            })
        }
    }
</code>```

In the else statement, I wanted to add this code:

```<code>    let vc = (
        storyboard?.instantiateViewController(
            withIdentifier: "sbPopUpID")
        )!
    vc.modalTransitionStyle = .crossDissolve
    present(vc, animated: true, completion: nil)
</code>```

But it only works if I load it in after viewDidLoad and didReceiveMemoryWarning, ¿how can I load this Pop Up if there aren't mistakes saving the user data?

Thanks

答:
Your code seems fine, you just forgot to add the implicit self declaration before some statements (the debugger should advise this to you in default). Try this:

```<code>let vc = self.storyboard!.instantiateViewController(withIdentifier: "sbPopUpID")
vc.modalTransitionStyle = .crossDissolve
self.present(vc, animated: true)
</code>```

Body:
I'm making a register view on Swift for an app. I want to load a pop-up view when the user is successfully registered to add more data. I'm storing the data using Parse.

I'm using this code to save the data:

@IBAction func registerButtonPressed(_ sender: Any) {

    if emailTextField.text == "" || usuerTextField.text == "" || password1TextField.text == "" || password2TextField.text == "" {

        createAlert(title: "Error", message: "Fill all data")

    } else {

        if password1TextField.text != password2TextField.text {

            createAlert(title: "Error", message: "Passwords must be the same")
        } else {

            activityIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
            activityIndicator.center = self.view.center
            activityIndicator.hidesWhenStopped = true
            activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
            view.addSubview(activityIndicator)
            activityIndicator.startAnimating()
            UIApplication.shared.beginIgnoringInteractionEvents() // UIApplication.shared() is now UIApplication.shared

            let user = PFUser()

            user.username = usuerTextField.text
            user.email = emailTextField.text
            user.password = password1TextField.text

            let acl = PFACL()

            acl.getPublicWriteAccess = true

            user.acl = acl

            user.signUpInBackground(block: { (success, error) in

                self.activityIndicator.stopAnimating()
                UIApplication.shared.endIgnoringInteractionEvents() // UIApplication.shared() is now  UIApplication.shared

                if error != nil {

                    var displayErrorMessage = "Please try again later."

                    let error = error as NSError?

                    if let errorMessage = error?.userInfo["error"] as? String {

                        displayErrorMessage = errorMessage

                    }

                    self.createAlert(title: "Signup Error", message: displayErrorMessage)

                } else {

                }

            })
        }
    }

In the else statement, I wanted to add this code:

    let vc = (
        storyboard?.instantiateViewController(
            withIdentifier: "sbPopUpID")
        )!
    vc.modalTransitionStyle = .crossDissolve
    present(vc, animated: true, completion: nil)

But it only works if I load it in after viewDidLoad and didReceiveMemoryWarning, ¿how can I load this Pop Up if there aren't mistakes saving the user data?

Thanks

Body:
Your code seems fine, you just forgot to add the implicit self declaration before some statements (the debugger should advise this to you in default). Try this:

let vc = self.storyboard!.instantiateViewController(withIdentifier: "sbPopUpID")
vc.modalTransitionStyle = .crossDissolve
self.present(vc, animated: true)


来源: stackexchange

问:
Adding a Dropdown Select menu to select csv files in highcharts
Hi I am very new in programming and trying my hand. I am working on a project where i am using highchart. I am using csv file as data source. please take a look at the code

```<code><script type='text/javascript'>
$(document).ready(function() {
    $.get('dhaka.csv', function(csv) {
        // Create the chart
        window.chart = new Highcharts.StockChart({
            chart: {
                renderTo: 'container',
                type:'spline'
            },
            data: {
                csv: csv
            },
        }, function(chart) {

        });
    });
});
</script>

</head>
<body>
<select id="selectOpt">
    <option value="dhaka.csv">Dhaka</option>
    <option value="khulna.csv">Khulna</option>
    <option value="maymansingh.csv">Maymanshingh</option>
</select>
<div id="container" style="height: 600px; min-width: 600px; margin-top:10px;"></div>
</body>
</code>```

I will be having multiple csv file and need to have an option to select from a dropdown menu. Hope i have explained properly. Thanks in advance. Your help is appriciated.

I have used parsecsv.lib to read a csv file and my select menu will get the options from that csv. which i have done already. but i need to pass few other values ass well which i can not. please help me on this.. the updated code is here

```<code>    <?php
        require_once('parsecsv.lib.php');
        $csv = new parseCSV();
        $csv->auto('latlang.csv');
        $num = count($csv->data);
        $numRow = $num-1;
    ?>
    <select id="selectOpt" style="width:200px;">
    <?php
        for ($x = 0; $x <= $numRow; $x++) {
            $ston= $csv->data[$x]['Station'];
            //$arr = explode(' ',trim($ston));
            echo "<option value=".$ston.">".$ston."</option>";
        }
    ?>
    </select>
    <div id="container" style="height: 400px; width: 600px; margin-top:10px;"></div>
    <p id="demo"></p>

</body>
<script type='text/javascript'>
$(document).ready(function() {
     getChart('Amalshid');
});
var getChart = function(strFileName){
    $.get( strFileName + '.csv', function(csv) {
    // I AM STUCK HERE //
    //  data form latlang.csv
    var locations = <?php print json_encode($csv->data); ?>;
    for (i = 0; i < locations.length; i++) {
        var dataz = locations[i];
        document.getElementById('demo').innerHTML = strFileName + '<br>' + dataz.Station + '<br>' + dataz.DL + '<br>' + dataz.HRWL;
    }
        // Create the chart
        window.chart = new Highcharts.StockChart({
            chart: {
                renderTo: 'container',
                type:'spline'
            },
            data: {
                csv: csv,
                startRow: 34,
                startColumn:3
            },
        }, function(chart) {

        });
    });
};

$("#selectOpt").on("change",function(e){
    getChart($(this).val());
});
</code>```

The csv file looks like this

```<code>Station,RiverName,Longtitude,Latitude,DL,HRWL,CL
Amalshid,Kushiyara,92.4716,24.8845,15.85,18.28,100
Bahadurabad,B'putra,89.6743,25.0934,19.5,20.62,1
Hardinge.Bridge,Ganges,89.0279,24.072,14.25,15.19,1
</code>```

All I need, when I select from the drop-down menu it will take River name and DL and pass the value. thanks in advance

答:
So set an event listener on your select element so that on change it gets the selected csv and then uses high charts series.setdata command

You are using highcharts so assuming you have jquery installed

Things you will need:
event binding: https://api.jquery.com/change/

highcharts event reference: http://api.highcharts.com/highcharts/Series.setData

ContentLicense: CC BY-SA 3.0

Body:
Hi I am very new in programming and trying my hand. I am working on a project where i am using highchart. I am using csv file as data source. please take a look at the code

<select id="selectOpt">
    <option value="dhaka.csv">Dhaka</option>
    <option value="khulna.csv">Khulna</option>
    <option value="maymansingh.csv">Maymanshingh</option>
</select>

I will be having multiple csv file and need to have an option to select from a dropdown menu. Hope i have explained properly. Thanks in advance. Your help is appriciated.

I have used parsecsv.lib to read a csv file and my select menu will get the options from that csv. which i have done already. but i need to pass few other values ass well which i can not. please help me on this.. the updated code is here

    <?php
        require_once('parsecsv.lib.php');
        $csv = new parseCSV();
        $csv->auto('latlang.csv');
        $num = count($csv->data);
        $numRow = $num-1;
    ?>
    <select id="selectOpt" style="width:200px;">
    <?php
        for ($x = 0; $x <= $numRow; $x++) {
            $ston= $csv->data[$x]['Station'];
            //$arr = explode(' ',trim($ston));
            echo "<option value=".$ston.">".$ston."</option>";
        }
    ?>
    </select>


问:
Error on add to source control - Unable to transfer a file: error detected by clearcase subsystem
We are setting up new servers at CC 8.1.1.11 and going through basic tests.

From a CC Explorer client we try and add a simple .txt file to source control and get the error

```<code>Error adding "path to filename.txt" to source control Unable to transfer file :
error detected by Clearcase Subsystem.
</code>```

Selecting Ok on the error pop-up we can then see the "Green Tick" against the file showing it checked out but when we try to check in we get the same error.

In the mvfs log on the client machine we see the following

```<code>Fetch cleartext view=viewname vob=\vobname dbid=0x43 - I/O error
See view log on  view server for more info.
</code>```

View Log on view Server -

```<code>Error: view_server.exe error unable to construct cleartext for object "0x43" in vob "path to vob"
Error detected by clearcase subsystem
Error unable to transfer a file.
</code>```

Client machine and view server are windows. Vob server aix

No significant errors when running ClearCase doctor.

How can I avoid this error?

答:
As mentioned in this thread

The usual reason is access rights in the cleartext pool (down from the 'c' directory in the vob storage).

But I recently got this in conjunction with a clearer report in the vobrpc log (I think), for 'group not declared in the vob' (or similar).

  The user was actually work as root, and his group was 'other'.
  Although he was allowed to write to the (local) cleartext pool, the type_manager would refuse with this (misleading?) error...

So double-check your vobrpc logs, and check your CLEARCASE_PRIMARY_GROUP (whose group needs to be part of the primary or secondary groups of the Vob involved with those files)

Check also the protections associated with your view:

```<code>cd /path/to/my/view
cleartool lsview -l -full -pro -cview
</code>```

Body:
We are setting up new servers at CC 8.1.1.11 and going through basic tests.

From a CC Explorer client we try and add a simple .txt file to source control and get the error

Error adding "path to filename.txt" to source control Unable to transfer file :
error detected by Clearcase Subsystem.

Selecting Ok on the error pop-up we can then see the "Green Tick" against the file showing it checked out but when we try to check in we get the same error.

In the mvfs log on the client machine we see the following

Fetch cleartext view=viewname vob=\vobname dbid=0x43 - I/O error
See view log on  view server for more info.

View Log on view Server -

Error: view_server.exe error unable to construct cleartext for object "0x43" in vob "path to vob"
Error detected by clearcase subsystem
Error unable to transfer a file.

Client machine and view server are windows. Vob server aix

No significant errors when running ClearCase doctor.

How can I avoid this error?

Body:
As mentioned in this thread

The usual reason is access rights in the cleartext pool (down from the 'c' directory in the vob storage).

But I recently got this in conjunction with a clearer report in the vobrpc log (I think), for 'group not declared in the vob' (or similar).

  The user was actually work as root, and his group was 'other'.
  Although he was allowed to write to the (local) cleartext pool, the type_manager would refuse with this (misleading?) error...

So double-check your vobrpc logs, and check your CLEARCASE_PRIMARY_GROUP (whose group needs to be part of the primary or secondary groups of the Vob involved with those files)

Check also the protections associated with your view:

cd /path/to/my/view
cleartool lsview -l -full -pro -cview


问:
How to run gulp tasks in terminal
I am a beginner in gulp. I have created a task named task1 in gulp.js and when i tried to execute that task using "gulp task1" in command line,  Its opening the gulp.js file  on brackets editor rather than  executing in command line. Can somebody help me in solving this problem

The code in my gulp file is

```<code>var gulp = require('gulp');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');

gulp.task('task1', function () {
    return gulp
        .src(['./src/**/x.js', './*.js'])
        .pipe(jscs())
        .pipe(jshint())
        .pipe(jshint.reporter('jshint-stylish', {
            verbose: true
        }));

})
</code>```

答:
Have you install Gulp on NPM?.
If not, do the following.

```<code>$ npm install gulp
$ npm install jshint gulp-jshint --save-dev
$ npm install --save-dev gulp-jscs
</code>```

In case it's not installed, try to:

```<code>$ sudo npm install -g gulp
$ sudo npm install -g jshint gulp-jshint --save-dev
$ sudo npm install -g --save-dev gulp-jscs
</code>```

After completing the installation, try gulp on terminal (Remember that you must be in the same directory of the file).

Title: How to run gulp tasks in terminal

Body:
I am a beginner in gulp. I have created a task named task1 in gulp.js and when i tried to execute that task using "gulp task1" in command line,  Its opening the gulp.js file  on brackets editor rather than  executing in command line. Can somebody help me in solving this problem

The code in my gulp file is

var gulp = require('gulp');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');

gulp.task('task1', function () {
    return gulp
        .src(['./src/**/x.js', './*.js'])
        .pipe(jscs())
        .pipe(jshint())
        .pipe(jshint.reporter('jshint-stylish', {
            verbose: true
        }));

})

Body:
Have you install Gulp on NPM?.
If not, do the following.

$ npm install gulp
$ npm install jshint gulp-jshint --save-dev
$ npm install --save-dev gulp-jscs

In case it's not installed, try to:

$ sudo npm install -g gulp
$ sudo npm install -g jshint gulp-jshint --save-dev
$ sudo npm install -g --save-dev gulp-jscs

After completing the installation, try gulp on terminal (Remember that you must be in the same directory of the file).


问:
php - How do I weed out similar items from an associative array?
UPDATE: someone edited my question incorrectly, but it's fixed now

Let's say I have the following associative array:

```<code>Array (
[Postponement no issue for Man Utd (BBC) ] => 8
[Postponement no issue for Man Utd ] => 7
[Postponement no issue for Man Utd: Manchester United say they have no issue over Sunday's game at Chelsea being ... ] => 3
)
</code>```

You'll notice that the term "Postponement no issue for Man Utd" appears in all three keys. I want to turn this array into a new array like this:

```<code>Array ( [Postponement no issue for Man Utd] => 18 )
</code>```

Where 18 is the sum of all values where the key contains "Postponement no issue for Man Utd".

In other words: if one key appears inside another key, the latter is dropped fom the new array and it's value is added on to the former key's value.

Is this possible and how? Thanks in advance.

答:
Depending on the size of your data this may not be feasible. There is almost certainly a more optimal solution, but this works:

```<code><?php
$array = array(
    'Postponement no issue for Man Utd (BBC)' => 8,
    'Postponement no issue for Man Utd' => 7,
    'Postponement no issue for Man Utd: Manchester United say they have no issue over Sunday\'s game at Chelsea being ...' => 3
);

$keys = array_keys($array);
usort($keys, 'lengthCmp');
$flippedKeys = array_flip($keys);

$data = array();

foreach ($keys as $k => $v)
{
 $sum = 0;

 foreach ($array as $key => $val)
 {
  if (stripos($key, $v) !== FALSE)
  {
   $sum += $val;
   unset($array[$key]);
   unset($keys[$flippedKeys[$v]]);
  }
 }

 $data[$v] = $sum;
}

foreach ($data as $key => $val)
{
 if ($val == 0)
  unset($data[$key]);
}

var_dump($data);

function lengthCmp($a, $b)
{
 return strlen($a) - strlen($b);
}
?>
</code>```

Output:

```<code>array(1) {["Postponement no issue for Man Utd"] => int(18)}
</code>```

And with this data set:

```<code>$array = array(
    'test test' => 1,
    'Postponement no issue for Man Utd (BBC)' => 8,
    'Postponement no issue for Man Utd' => 7,
    'Postponement no issue for Man Utd: Manchester United say they have no issue over Sunday\'s game at Chelsea being ...' => 3,
    'test' => 1,
    'not here' => 1,
    'another test' => 1
);
</code>```

Output:

```<code>array(3) {
    ["test"] => int(3)
    ["not here"] => int(1)
    ["Postponement no issue for Man Utd"] => int(18)
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
UPDATE: someone edited my question incorrectly, but it's fixed now

Let's say I have the following associative array:

Array (
[Postponement no issue for Man Utd (BBC) ] => 8
[Postponement no issue for Man Utd ] => 7
[Postponement no issue for Man Utd: Manchester United say they have no issue over Sunday's game at Chelsea being ... ] => 3
)

You'll notice that the term "Postponement no issue for Man Utd" appears in all three keys. I want to turn this array into a new array like this:

Array ( [Postponement no issue for Man Utd] => 18 )

Where 18 is the sum of all values where the key contains "Postponement no issue for Man Utd".

In other words: if one key appears inside another key, the latter is dropped fom the new array and it's value is added on to the former key's value.

Is this possible and how? Thanks in advance.

Body:
Depending on the size of your data this may not be feasible. There is almost certainly a more optimal solution, but this works:

<?php
$array = array(
    'Postponement no issue for Man Utd (BBC)' => 8,
    'Postponement no issue for Man Utd' => 7,
    'Postponement no issue for Man Utd: Manchester United say they have no issue over Sunday\'s game at Chelsea being ...' => 3
);

$keys = array_keys($array);
usort($keys, 'lengthCmp');
$flippedKeys = array_flip($keys);

$data = array();

foreach ($keys as $k => $v)
{
 $sum = 0;

 foreach ($array as $key => $val)
 {
  if (stripos($key, $v) !== FALSE)
  {
   $sum += $val;
   unset($array[$key]);
   unset($keys[$flippedKeys[$v]]);
  }
 }

 $data[$v] = $sum;
}

foreach ($data as $key => $val)
{
 if ($val == 0)
  unset($data[$key]);
}

var_dump($data);

function lengthCmp($a, $b)
{
 return strlen($a) - strlen($b);
}
?>

Output:

array(1) {["Postponement no issue for Man Utd"] => int(18)}

And with this data set:

$array = array(
    'test test' => 1,
    'Postponement no issue for Man Utd (BBC)' => 8,
    'Postponement no issue for Man Utd' => 7,
    'Postponement no issue for Man Utd: Manchester United say they have no issue over Sunday\'s game at Chelsea being ...' => 3,
    'test' => 1,
    'not here' => 1,
    'another test' => 1
);

Output:

array(3) {
    ["test"] => int(3)
    ["not here"] => int(1)
    ["Postponement no issue for Man Utd"] => int(18)
}


问:
Is it possible to take input from a file in NotesSQL
For example I have to run a query to fetch data for a list of part numbers.

The list is very big say 1000. So I do not want to give all the part numbers in the query instead want to take it from a file say .txt or .xls

Is It possible with Notes SQL?

答: Why use Notes SQL to import data from a text file into Notes? Just write a Lotusscript agent that does the import.</p>


问:
How did NPM create the border for their update message?
I'm assuming they used unicode characters to render the yellow box around the update message.

What characters were used and does it look the same on all platforms?

答:
How did NPM create the border for their update message?

NPM uses npmlog to print to the console, and npmlog utilizes console-control-strings & gauge.

console-control-strings mostly offers convenience functions for moving the cursor around the line and coloring the text.

gauge provides the progress bar and spinner and a way to style them.

What characters were used and does it look the same on all platforms?

Unicode box-drawing characters are used for the border characters. I didn't research the exact unicode characters that NPM uses. Assuming that the terminal/platform is implemented to support unicode and, doesn't override the standard charset with its own characters (ie. emojis), I don't see why it wouldn't look the same across platform.

The below snippet unicode characters don't match exactly. Instead, it demonstrates how to use control-control-strings to print something close to what NPM outputs. I'm sure with enough tinkering you could get it to be exact.

```<code>const control = require('console-control-strings')

let title = `${control.color('cyan')}Update available 5.0.3 \u2192 5.0.4${control.color('reset')}`
let subtitle = `Run ${control.color('cyan')} npm i -g npm ${control.color('reset')}`
let borderWidth = (title.length > subtitle.length ? title.length : subtitle.length)

let topLeftCorner = '\u256D'
let topRightCorner = '\u256E'
let btmRightCorner = '\u256F'
let btmLeftCorner = '\u2570'

let border = [...Array(borderWidth)].map(() => { return '\u2500' }).join('')
let topBorder = `${control.nextLine()}${control.color('yellow')}${topLeftCorner}${border}${topRightCorner}${control.color('reset')}`
let btmBorder = `${control.nextLine()}${control.color('yellow')}${btmLeftCorner}${border}${btmRightCorner}${control.color('reset')}`
let lineWrapper = `${control.color('yellow')}\u2502${control.color('reset')}`

console.log(topBorder)
console.log(`${lineWrapper}${control.forward(borderWidth)}${lineWrapper}`)
console.log(`${control.nextLine()}${lineWrapper}${control.forward(4)}${title}${control.forward(5)}${lineWrapper}`)
console.log(`${lineWrapper}${control.forward(11)}${subtitle}${control.forward(10)}${lineWrapper}`)
console.log(`${lineWrapper}${control.forward(borderWidth)}${lineWrapper}`)
console.log(`${btmBorder}${control.color('reset')}`)
</code>```

Body:
How did NPM create the border for their update message?

NPM uses npmlog to print to the console, and npmlog utilizes console-control-strings & gauge.

console-control-strings mostly offers convenience functions for moving the cursor around the line and coloring the text.

gauge provides the progress bar and spinner and a way to style them.

What characters were used and does it look the same on all platforms?

Unicode box-drawing characters are used for the border characters. I didn't research the exact unicode characters that NPM uses. Assuming that the terminal/platform is implemented to support unicode and, doesn't override the standard charset with its own characters (ie. emojis), I don't see why it wouldn't look the same across platform.

The below snippet unicode characters don't match exactly. Instead, it demonstrates how to use control-control-strings to print something close to what NPM outputs. I'm sure with enough tinkering you could get it to be exact.

const control = require('console-control-strings')

let title = `${control.color('cyan')}Update available 5.0.3 \u2192 5.0.4${control.color('reset')}`
let subtitle = `Run ${control.color('cyan')} npm i -g npm ${control.color('reset')}`
let borderWidth = (title.length > subtitle.length ? title.length : subtitle.length)

let topLeftCorner = '\u256D'
let topRightCorner = '\u256E'
let btmRightCorner = '\u256F'
let btmLeftCorner = '\u2570'

let border = [...Array(borderWidth)].map(() => { return '\u2500' }).join('')
let topBorder = `${control.nextLine()}${control.color('yellow')}${topLeftCorner}${border}${topRightCorner}${control.color('reset')}`
let btmBorder = `${control.nextLine()}${control.color('yellow')}${btmLeftCorner}${border}${btmRightCorner}${control.color('reset')}`
let lineWrapper = `${control.color('yellow')}\u2502${control.color('reset')}`

console.log(topBorder)
console.log(`${lineWrapper}${control.forward(borderWidth)}${lineWrapper}`)
console.log(`${control.nextLine()}${lineWrapper}${control.forward(4)}${title}${control.forward(5)}${lineWrapper}`)
console.log(`${lineWrapper}${control.forward(11)}${subtitle}${control.forward(10)}${lineWrapper}`)
console.log(`${lineWrapper}${control.forward(borderWidth)}${lineWrapper}`)
console.log(`${btmBorder}${control.color('reset')}`)


问:
HttpClientFactory.Create vs new HttpClient
I am curious what is the purpose of the HttpClientFactory class. There is no description of why it exists on MSDN (see link).

There are Create methods with more specialized arguments, but mostly I wonder what is the difference between the call with no parameters and the normal constructor.

var httpClient = HttpClientFactory.Create();
```
<p>VS</p>
<pre class="lang-cs prettyprint-override"><code>var httpClient = new HttpClient();
</code>```

In most examples I see the use of new HttpClient(), without any using statements, even though the HttpClient class derives from IDisposable.

Since the HttpClient class derives from IDisposable, is there some pooling or caching done by the factory? Are there performance benefits, or does it not matter?

Update – IHttpClientFactory in .NET Core 2.1

Please note that since this question was asked, newer versions of .NET have been released, and .NET Core 2.1 introduced a new and much improved approach for getting a HTTP client.

Refer to Ali Bayat's answer below for using IHttpClientFactory instead with .NET Core.

However, I'm keeping Darrel Miller's answer as the accepted answer since this is the correct answer for usage in .NET Framework up to v4.8, for which this question was asked.

With .NET 5 the discrepancy between .NET Framework and .NET Core will be aligned, and you should use IHttpClientFactory instead.

Update – Official guidance

Microsoft has added documentation regarding the disposal behavior and recommended use:
https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/httpclient-guidelines

答:
Let me add to @DarrelMiller's answer:

You should pay attention to the lifetime of your HttpClient instances if scaling is of any importance to you.  Please refer to What is the overhead of creating a new HttpClient per call in a WebAPI client?

ContentLicense: CC BY-SA 4.0

Body:
I am curious what is the purpose of the HttpClientFactory class. There is no description of why it exists on MSDN (see link).

There are Create methods with more specialized arguments, but mostly I wonder what is the difference between the call with no parameters and the normal constructor.

var httpClient = HttpClientFactory.Create();

VS

var httpClient = new HttpClient();

In most examples I see the use of new HttpClient(), without any using statements, even though the HttpClient class derives from IDisposable.

Since the HttpClient class derives from IDisposable, is there some pooling or caching done by the factory? Are there performance benefits, or does it not matter?

Update – IHttpClientFactory in .NET Core 2.1

Please note that since this question was asked, newer versions of .NET have been released, and .NET Core 2.1 introduced a new and much improved approach for getting a HTTP client.

Refer to Ali Bayat's answer below for using IHttpClientFactory instead with .NET Core.

However, I'm keeping Darrel Miller's answer as the accepted answer since this is the correct answer for usage in .NET Framework up to v4.8, for which this question was asked.

With .NET 5 the discrepancy between .NET Framework and .NET Core will be aligned, and you should use IHttpClientFactory instead.

Update – Official guidance

Microsoft has added documentation regarding the disposal behavior and recommended use:
https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/httpclient-guidelines


问:
Extracting multiple xml trees from a mixed content document
I'm trying to use Python to extract multiple XML elements from a mixed-content document. The use case is an email that contains email text but also contains multiple XML trees.

Here's the example document:

```<code>Email text email text email text email text.

email signature email signature.

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications
      with XML.</description>
   </book>
</catalog>

Email text email text email text email text.

email signature email signature.

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications
      with XML.</description>
   </book>
</catalog>

Email text email text email text email text.

email signature email signature.

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications
      with XML.</description>
   </book>
</catalog>

Email text email text email text email text.

email signature email signature.
</code>```

I want to extract the XML trees so they can be parsed by an XML parser in a for loop. I've perfected parsing the XML, and if I take one of the XML trees and parse it directly, it works llike a charm.

Any advise on how to extract the XML trees? This example is over-simplified as well, the email text and signatures are different in each example that I have, so the only reliable text to key on is the beginning and ending of the XML tree.

答:
Question: I want to extract the XML trees so they can be parsed by an XML parser

Do you realy want to get multiple XML Trees?

I want to suggest to make one XML Tree with multiple <book subelements.

Nevertheless, here is what you want:

```<code>xml_tag = "<?xml"
catalog_end_tag = "</catalog>"

xml_tree = []
_xml = False
with open('test/Mixed_email_xml') as fh:
    while True:
        line = fh.readline()
        if not line: break

        if line.find(xml_tag) >=0:
            _xml = True

        if _xml:
            xml_tree.append(line)

        if line.find(catalog_end_tag) >=0:
            _xml = False

for line in xml_tree:
    print('{}'.format(line[:-1]))
</code>```

Tested with Python: 3.4.2

Body:
I'm trying to use Python to extract multiple XML elements from a mixed-content document. The use case is an email that contains email text but also contains multiple XML trees.

Here's the example document:

Email text email text email text email text.

email signature email signature.

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications
      with XML.</description>
   </book>
</catalog>

Email text email text email text email text.

email signature email signature.

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications
      with XML.</description>
   </book>
</catalog>

Email text email text email text email text.

email signature email signature.

<?xml version="1.0"?>
<catalog>
   <book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications
      with XML.</description>
   </book>
</catalog>

Email text email text email text email text.

email signature email signature.

I want to extract the XML trees so they can be parsed by an XML parser in a for loop. I've perfected parsing the XML, and if I take one of the XML trees and parse it directly, it works llike a charm.

Any advise on how to extract the XML trees? This example is over-simplified as well, the email text and signatures are different in each example that I have, so the only reliable text to key on is the beginning and ending of the XML tree.

Body:
Question: I want to extract the XML trees so they can be parsed by an XML parser

Do you realy want to get multiple XML Trees?

I want to suggest to make one XML Tree with multiple <book subelements.

Nevertheless, here is what you want:

xml_tag = "<?xml"
catalog_end_tag = "</catalog>"

xml_tree = []
_xml = False
with open('test/Mixed_email_xml') as fh:
    while True:
        line = fh.readline()
        if not line: break

        if line.find(xml_tag) >=0:
            _xml = True

        if _xml:
            xml_tree.append(line)

        if line.find(catalog_end_tag) >=0:
            _xml = False

for line in xml_tree:
    print('{}'.format(line[:-1]))

Tested with Python: 3.4.2


问:
How to match a newline \n in a perl regex?
I want to match this line,

```<code><center>'''<font color="blue"><font size="18.0pt">No Change Alarms Help & Information</font></font>'''</center>
</code>```

and replace it with,

```<code>=<center>'''<font color="blue">No Change Alarms Help & Information</font>'''</center>=
</code>```

Now it would be simple if the tags were always font colour or center, but they can be absolutely anything and there can be multiple of them.

My current code is this:

```<code>$html =~ s/<font size=".+">(.+)<\/font>/$1/g;
</code>```

but this obviously does not do the = on each end.

What I would like to do is this:

```<code>$html =~ s/\n(.+)<font size=".+">(.+)<\/font>(.+)\n/=$1$2$3=/g;
</code>```

However it fails to match the newline characters and I cannot figure out how to make it match them, any clues?

(I'm converting html to wiki markup, however the converter stuffs up the font sizes so I'm manually converting them to wiki style headings.)

答: All I needed was /gm on the end of my query, turns out it ignores new lines by default.

Body:
I want to match this line,

'''No Change Alarms Help & Information'''

and replace it with,

='''No Change Alarms Help & Information'''=

Now it would be simple if the tags were always font colour or center, but they can be absolutely anything and there can be multiple of them.

My current code is this:

$html =~ s/(.+)<\/font>/$1/g;

but this obviously does not do the = on each end.

What I would like to do is this:

$html =~ s/\n(.+)(.+)<\/font>(.+)\n/=$1$2$3=/g;

However it fails to match the newline characters and I cannot figure out how to make it match them, any clues?

(I'm converting html to wiki markup, however the converter stuffs up the font sizes so I'm manually converting them to wiki style headings.)


问:
Failed to install Python Cryptography package with PIP and setup.py
When I try to install the Cryptography package for Python through either pip install cryptography or by downloading the package from their site and running python setup.py, I get the following error:

```<code>D:\Anaconda\Scripts\pip-script.py run on 02/27/14 16:13:17
Downloading/unpacking cryptography
  Getting page https://pypi.python.org/simple/cryptography/
  URLs to search for versions for cryptography:
  * https://pypi.python.org/simple/cryptography/
  Analyzing links from page https://pypi.python.org/simple/cryptography/
    Skipping https://pypi.python.org/packages/cp26/c/cryptography/cryptography-0.2-cp26-none-win32.whl#md5=13e5c4b19520e7dc6f07c6502b3f74e2 (from https://pypi.python.org/simple/cryptography/) because it is not compatible with this Python
    Skipping https://pypi.python.org/packages/cp26/c/cryptography/cryptography-0.2.1-cp26-none-win32.whl#md5=00e733648ee5cdb9e58876238b1328f8 (from https://pypi.python.org/simple/cryptography/) because it is not compatible with this Python
    Skipping https://pypi.python.org/packages/cp27/c/cryptography/cryptography-0.2-cp27-none-win32.whl#md5=013ccafa6a5a3ea92c73f2c1c4879406 (from https://pypi.python.org/simple/cryptography/) because it is not compatible with this Python
    Skipping https://pypi.python.org/packages/cp27/c/cryptography/cryptography-0.2.1-cp27-none-win32.whl#md5=127d6a5dc687250721f892d55720a06c (from https://pypi.python.org/simple/cryptography/) because it is not compatible with this Python
    Skipping https://pypi.python.org/packages/cp32/c/cryptography/cryptography-0.2-cp32-none-win32.whl#md5=051424a36e91039807b72f112333ded3 (from https://pypi.python.org/simple/cryptography/) because it is not compatible with this Python
    Skipping https://pypi.python.org/packages/cp32/c/cryptography/cryptography-0.2.1-cp32-none-win32.whl#md5=53f6f57db8e952d64283baaa14cbde3d (from https://pypi.python.org/simple/cryptography/) because it is not compatible with this Python
    Skipping https://pypi.python.org/packages/cp33/c/cryptography/cryptography-0.2-cp33-none-win32.whl#md5=302812c1c1a035cf9ba3292f8dbf3f9e (from https://pypi.python.org/simple/cryptography/) because it is not compatible with this Python
    Skipping https://pypi.python.org/packages/cp33/c/cryptography/cryptography-0.2.1-cp33-none-win32.whl#md5=81acca90caf8a45f2ca73f3f9859fae4 (from https://pypi.python.org/simple/cryptography/) because it is not compatible with this Python
    Found link https://pypi.python.org/packages/source/c/cryptography/cryptography-0.1.tar.gz#md5=bdc1c5fe069deca7467b71a0cc538f17 (from https://pypi.python.org/simple/cryptography/), version: 0.1
    Found link https://pypi.python.org/packages/source/c/cryptography/cryptography-0.2.1.tar.gz#md5=872fc04268dadc66a0305ae5ab1c123b (from https://pypi.python.org/simple/cryptography/), version: 0.2.1
    Found link https://pypi.python.org/packages/source/c/cryptography/cryptography-0.2.tar.gz#md5=8a3d21e837a21e1b7634ee1f22b06bb6 (from https://pypi.python.org/simple/cryptography/), version: 0.2
  Using version 0.2.1 (newest of versions: 0.2.1, 0.2, 0.1)
  Downloading from URL https://pypi.python.org/packages/source/c/cryptography/cryptography-0.2.1.tar.gz#md5=872fc04268dadc66a0305ae5ab1c123b (from https://pypi.python.org/simple/cryptography/)
  Running setup.py (path:c:\users\paco\appdata\local\temp\pip_build_Paco\cryptography\setup.py) egg_info for package cryptography
    In file included from c/_cffi_backend.c:7:0:
    c/misc_win32.h:225:23: error: two or more data types in declaration specifiers
    c/misc_win32.h:225:1: warning: useless type name in empty declaration [enabled by default]
    c/_cffi_backend.c: In function 'convert_array_from_object':
    c/_cffi_backend.c:1105:26: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1105:26: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c:1130:30: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1130:30: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c:1150:30: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1150:30: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c: In function 'convert_struct_from_object':
    c/_cffi_backend.c:1183:26: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1183:26: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c:1196:30: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1196:30: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c: In function 'cdata_repr':
    c/_cffi_backend.c:1583:13: warning: unknown conversion type character 'L' in format [-Wformat]
    c/_cffi_backend.c:1583:13: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c:1595:9: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1595:9: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c: In function 'cdataowning_repr':
    c/_cffi_backend.c:1647:30: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1647:30: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c: In function '_cdata_get_indexed_ptr':
    c/_cffi_backend.c:1820:26: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1820:26: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1820:26: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c: In function '_cdata_getslicearg':
    c/_cffi_backend.c:1872:26: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1872:26: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1872:26: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c: In function 'cdata_ass_slice':
    c/_cffi_backend.c:1951:26: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1951:26: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1951:26: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c:1969:30: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1969:30: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1969:30: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c:1983:22: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1983:22: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c: In function 'cdata_call':
    c/_cffi_backend.c:2367:30: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:2367:30: warning: format '%s' expects argument of type 'char *', but argument 3 has type 'Py_ssize_t' [-Wformat]
    c/_cffi_backend.c:2367:30: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c: In function 'cast_to_integer_or_char':
    c/_cffi_backend.c:2916:26: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:2916:26: warning: format '%s' expects argument of type 'char *', but argument 3 has type 'Py_ssize_t' [-Wformat]
    c/_cffi_backend.c:2916:26: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c:2928:26: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:2928:26: warning: format '%s' expects argument of type 'char *', but argument 3 has type 'Py_ssize_t' [-Wformat]
    c/_cffi_backend.c:2928:26: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c: In function 'new_array_type':
    c/_cffi_backend.c:3480:9: warning: unknown conversion type character 'l' in format [-Wformat]
    c/_cffi_backend.c:3480:9: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c: In function 'b_complete_struct_or_union':
    c/_cffi_backend.c:3878:22: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:3878:22: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:3878:22: warning: too many arguments for format [-Wformat-extra-args]
    Traceback (most recent call last):
      File "<string>", line 17, in <module>
      File "c:\users\paco\appdata\local\temp\pip_build_Paco\cryptography\setup.py", line 113, in <module>
        "build": cffi_build,
      File "D:\Anaconda\lib\distutils\core.py", line 112, in setup
        _setup_distribution = dist = klass(attrs)
      File "build\bdist.win-amd64\egg\setuptools\dist.py", line 239, in __init__
      File "build\bdist.win-amd64\egg\setuptools\dist.py", line 264, in fetch_build_eggs
      File "build\bdist.win-amd64\egg\pkg_resources.py", line 580, in resolve
        dist = best[req.key] = env.best_match(req, ws, installer)
      File "build\bdist.win-amd64\egg\pkg_resources.py", line 818, in best_match
        return self.obtain(req, installer) # try and download/install
      File "build\bdist.win-amd64\egg\pkg_resources.py", line 830, in obtain
        return installer(requirement)
      File "build\bdist.win-amd64\egg\setuptools\dist.py", line 314, in fetch_build_egg
      File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line 593, in easy_install

      File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line 623, in install_item

      File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line 809, in install_eggs

      File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line 1015, in build_and_install

      File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line 1003, in run_setup

    distutils.errors.DistutilsError: Setup script exited with error: command 'gcc' failed with exit status 1
    Complete output from command python setup.py egg_info:
    In file included from c/_cffi_backend.c:7:0:

c/misc_win32.h:225:23: error: two or more data types in declaration specifiers

c/misc_win32.h:225:1: warning: useless type name in empty declaration [enabled by default]

c/_cffi_backend.c: In function 'convert_array_from_object':

c/_cffi_backend.c:1105:26: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1105:26: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c:1130:30: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1130:30: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c:1150:30: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1150:30: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c: In function 'convert_struct_from_object':

c/_cffi_backend.c:1183:26: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1183:26: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c:1196:30: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1196:30: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c: In function 'cdata_repr':

c/_cffi_backend.c:1583:13: warning: unknown conversion type character 'L' in format [-Wformat]

c/_cffi_backend.c:1583:13: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c:1595:9: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1595:9: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c: In function 'cdataowning_repr':

c/_cffi_backend.c:1647:30: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1647:30: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c: In function '_cdata_get_indexed_ptr':

c/_cffi_backend.c:1820:26: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1820:26: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1820:26: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c: In function '_cdata_getslicearg':

c/_cffi_backend.c:1872:26: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1872:26: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1872:26: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c: In function 'cdata_ass_slice':

c/_cffi_backend.c:1951:26: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1951:26: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1951:26: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c:1969:30: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1969:30: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1969:30: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c:1983:22: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1983:22: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c: In function 'cdata_call':

c/_cffi_backend.c:2367:30: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:2367:30: warning: format '%s' expects argument of type 'char *', but argument 3 has type 'Py_ssize_t' [-Wformat]

c/_cffi_backend.c:2367:30: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c: In function 'cast_to_integer_or_char':

c/_cffi_backend.c:2916:26: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:2916:26: warning: format '%s' expects argument of type 'char *', but argument 3 has type 'Py_ssize_t' [-Wformat]

c/_cffi_backend.c:2916:26: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c:2928:26: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:2928:26: warning: format '%s' expects argument of type 'char *', but argument 3 has type 'Py_ssize_t' [-Wformat]

c/_cffi_backend.c:2928:26: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c: In function 'new_array_type':

c/_cffi_backend.c:3480:9: warning: unknown conversion type character 'l' in format [-Wformat]

c/_cffi_backend.c:3480:9: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c: In function 'b_complete_struct_or_union':

c/_cffi_backend.c:3878:22: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:3878:22: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:3878:22: warning: too many arguments for format [-Wformat-extra-args]

Traceback (most recent call last):

  File "<string>", line 17, in <module>

  File "c:\users\paco\appdata\local\temp\pip_build_Paco\cryptography\setup.py", line 113, in <module>

    "build": cffi_build,

  File "D:\Anaconda\lib\distutils\core.py", line 112, in setup

    _setup_distribution = dist = klass(attrs)

  File "build\bdist.win-amd64\egg\setuptools\dist.py", line 239, in __init__

  File "build\bdist.win-amd64\egg\setuptools\dist.py", line 264, in fetch_build_eggs

  File "build\bdist.win-amd64\egg\pkg_resources.py", line 580, in resolve

    dist = best[req.key] = env.best_match(req, ws, installer)

  File "build\bdist.win-amd64\egg\pkg_resources.py", line 818, in best_match

    return self.obtain(req, installer) # try and download/install

  File "build\bdist.win-amd64\egg\pkg_resources.py", line 830, in obtain

    return installer(requirement)

  File "build\bdist.win-amd64\egg\setuptools\dist.py", line 314, in fetch_build_egg

  File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line 593, in easy_install

  File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line 623, in install_item

  File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line 809, in install_eggs

  File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line 1015, in build_and_install

  File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line 1003, in run_setup

distutils.errors.DistutilsError: Setup script exited with error: command 'gcc' failed with exit status 1

----------------------------------------
Cleaning up...
  Removing temporary dir c:\users\paco\appdata\local\temp\pip_build_Paco...
Command python setup.py egg_info failed with error code 1 in c:\users\paco\appdata\local\temp\pip_build_Paco\cryptography
Exception information:
Traceback (most recent call last):
  File "D:\Anaconda\lib\site-packages\pip-1.5.4-py2.7.egg\pip\basecommand.py", line 122, in main
    status = self.run(options, args)
  File "D:\Anaconda\lib\site-packages\pip-1.5.4-py2.7.egg\pip\commands\install.py", line 278, in run
    requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)
  File "D:\Anaconda\lib\site-packages\pip-1.5.4-py2.7.egg\pip\req.py", line 1229, in prepare_files
    req_to_install.run_egg_info()
  File "D:\Anaconda\lib\site-packages\pip-1.5.4-py2.7.egg\pip\req.py", line 325, in run_egg_info
    command_desc='python setup.py egg_info')
  File "D:\Anaconda\lib\site-packages\pip-1.5.4-py2.7.egg\pip\util.py", line 697, in call_subprocess
    % (command_desc, proc.returncode, cwd))
InstallationError: Command python setup.py egg_info failed with error code 1 in c:\users\paco\appdata\local\temp\pip_build_Paco\cryptography
</code>```

I found other egg_info error posts (here and here) but the solutions there provided wouldn't solve my problem. Also, I am able to install other packages through PIP.

PIP version 1.5.4 setuptools version 2.2

答: I encountered a similar issue recently. In my case the versions of cffi and cryptography written in requirements.txt weren't compatible (cffi==1.8.9 and cryptography==1.9). I solved updating cffi with the last available version.

Body:
When I try to install the Cryptography package for Python through either pip install cryptography or by downloading the package from their site and running python setup.py, I get the following error:

D:\Anaconda\Scripts\pip-script.py run on 02/27/14 16:13:17
Downloading/unpacking cryptography
  Getting page https://pypi.python.org/simple/cryptography/
  URLs to search for versions for cryptography:
  * https://pypi.python.org/simple/cryptography/
  Analyzing links from page https://pypi.python.org/simple/cryptography/
    Skipping https://pypi.python.org/packages/cp26/c/cryptography/cryptography-0.2-cp26-none-win32.whl#md5=13e5c4b19520e7dc6f07c6502b3f74e2 (from https://pypi.python.org/simple/cryptography/) because it is not compatible with this Python
    Skipping https://pypi.python.org/packages/cp26/c/cryptography/cryptography-0.2.1-cp26-none-win32.whl#md5=00e733648ee5cdb9e58876238b1328f8 (from https://pypi.python.org/simple/cryptography/) because it is not compatible with this Python
    Skipping https://pypi.python.org/packages/cp27/c/cryptography/cryptography-0.2-cp27-none-win32.whl#md5=013ccafa6a5a3ea92c73f2c1c4879406 (from https://pypi.python.org/simple/cryptography/) because it is not compatible with this Python
    Skipping https://pypi.python.org/packages/cp27/c/cryptography/cryptography-0.2.1-cp27-none-win32.whl#md5=127d6a5dc687250721f892d55720a06c (from https://pypi.python.org/simple/cryptography/) because it is not compatible with this Python
    Skipping https://pypi.python.org/packages/cp32/c/cryptography/cryptography-0.2-cp32-none-win32.whl#md5=051424a36e91039807b72f112333ded3 (from https://pypi.python.org/simple/cryptography/) because it is not compatible with this Python
    Skipping https://pypi.python.org/packages/cp32/c/cryptography/cryptography-0.2.1-cp32-none-win32.whl#md5=53f6f57db8e952d64283baaa14cbde3d (from https://pypi.python.org/simple/cryptography/) because it is not compatible with this Python
    Skipping https://pypi.python.org/packages/cp33/c/cryptography/cryptography-0.2-cp33-none-win32.whl#md5=302812c1c1a035cf9ba3292f8dbf3f9e (from https://pypi.python.org/simple/cryptography/) because it is not compatible with this Python
    Skipping https://pypi.python.org/packages/cp33/c/cryptography/cryptography-0.2.1-cp33-none-win32.whl#md5=81acca90caf8a45f2ca73f3f9859fae4 (from https://pypi.python.org/simple/cryptography/) because it is not compatible with this Python
    Found link https://pypi.python.org/packages/source/c/cryptography/cryptography-0.1.tar.gz#md5=bdc1c5fe069deca7467b71a0cc538f17 (from https://pypi.python.org/simple/cryptography/), version: 0.1
    Found link https://pypi.python.org/packages/source/c/cryptography/cryptography-0.2.1.tar.gz#md5=872fc04268dadc66a0305ae5ab1c123b (from https://pypi.python.org/simple/cryptography/), version: 0.2.1
    Found link https://pypi.python.org/packages/source/c/cryptography/cryptography-0.2.tar.gz#md5=8a3d21e837a21e1b7634ee1f22b06bb6 (from https://pypi.python.org/simple/cryptography/), version: 0.2
  Using version 0.2.1 (newest of versions: 0.2.1, 0.2, 0.1)
  Downloading from URL https://pypi.python.org/packages/source/c/cryptography/cryptography-0.2.1.tar.gz#md5=872fc04268dadc66a0305ae5ab1c123b (from https://pypi.python.org/simple/cryptography/)
  Running setup.py (path:c:\users\paco\appdata\local\temp\pip_build_Paco\cryptography\setup.py) egg_info for package cryptography
    In file included from c/_cffi_backend.c:7:0:
    c/misc_win32.h:225:23: error: two or more data types in declaration specifiers
    c/misc_win32.h:225:1: warning: useless type name in empty declaration [enabled by default]
    c/_cffi_backend.c: In function 'convert_array_from_object':
    c/_cffi_backend.c:1105:26: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1105:26: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c:1130:30: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1130:30: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c:1150:30: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1150:30: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c: In function 'convert_struct_from_object':
    c/_cffi_backend.c:1183:26: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1183:26: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c:1196:30: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1196:30: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c: In function 'cdata_repr':
    c/_cffi_backend.c:1583:13: warning: unknown conversion type character 'L' in format [-Wformat]
    c/_cffi_backend.c:1583:13: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c:1595:9: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1595:9: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c: In function 'cdataowning_repr':
    c/_cffi_backend.c:1647:30: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1647:30: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c: In function '_cdata_get_indexed_ptr':
    c/_cffi_backend.c:1820:26: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1820:26: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1820:26: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c: In function '_cdata_getslicearg':
    c/_cffi_backend.c:1872:26: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1872:26: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1872:26: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c: In function 'cdata_ass_slice':
    c/_cffi_backend.c:1951:26: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1951:26: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1951:26: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c:1969:30: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1969:30: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1969:30: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c:1983:22: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:1983:22: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c: In function 'cdata_call':
    c/_cffi_backend.c:2367:30: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:2367:30: warning: format '%s' expects argument of type 'char *', but argument 3 has type 'Py_ssize_t' [-Wformat]
    c/_cffi_backend.c:2367:30: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c: In function 'cast_to_integer_or_char':
    c/_cffi_backend.c:2916:26: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:2916:26: warning: format '%s' expects argument of type 'char *', but argument 3 has type 'Py_ssize_t' [-Wformat]
    c/_cffi_backend.c:2916:26: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c:2928:26: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:2928:26: warning: format '%s' expects argument of type 'char *', but argument 3 has type 'Py_ssize_t' [-Wformat]
    c/_cffi_backend.c:2928:26: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c: In function 'new_array_type':
    c/_cffi_backend.c:3480:9: warning: unknown conversion type character 'l' in format [-Wformat]
    c/_cffi_backend.c:3480:9: warning: too many arguments for format [-Wformat-extra-args]
    c/_cffi_backend.c: In function 'b_complete_struct_or_union':
    c/_cffi_backend.c:3878:22: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:3878:22: warning: unknown conversion type character 'z' in format [-Wformat]
    c/_cffi_backend.c:3878:22: warning: too many arguments for format [-Wformat-extra-args]
    Traceback (most recent call last):
      File "<string>", line 17, in <module>
      File "c:\users\paco\appdata\local\temp\pip_build_Paco\cryptography\setup.py", line 113, in <module>
        "build": cffi_build,
      File "D:\Anaconda\lib\distutils\core.py", line 112, in setup
        _setup_distribution = dist = klass(attrs)
      File "build\bdist.win-amd64\egg\setuptools\dist.py", line 239, in __init__
      File "build\bdist.win-amd64\egg\setuptools\dist.py", line 264, in fetch_build_eggs
      File "build\bdist.win-amd64\egg\pkg_resources.py", line 580, in resolve
        dist = best[req.key] = env.best_match(req, ws, installer)
      File "build\bdist.win-amd64\egg\pkg_resources.py", line 818, in best_match
        return self.obtain(req, installer) # try and download/install
      File "build\bdist.win-amd64\egg\pkg_resources.py", line 830, in obtain
        return installer(requirement)
      File "build\bdist.win-amd64\egg\setuptools\dist.py", line 314, in fetch_build_egg
      File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line 593, in easy_install

      File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line 623, in install_item

      File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line 809, in install_eggs

      File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line 1015, in build_and_install

      File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line 1003, in run_setup

    distutils.errors.DistutilsError: Setup script exited with error: command 'gcc' failed with exit status 1
    Complete output from command python setup.py egg_info:
    In file included from c/_cffi_backend.c:7:0:

c/misc_win32.h:225:23: error: two or more data types in declaration specifiers

c/misc_win32.h:225:1: warning: useless type name in empty declaration [enabled by default]

c/_cffi_backend.c: In function 'convert_array_from_object':

c/_cffi_backend.c:1105:26: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1105:26: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c:1130:30: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1130:30: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c:1150:30: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1150:30: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c: In function 'convert_struct_from_object':

c/_cffi_backend.c:1183:26: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1183:26: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c:1196:30: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1196:30: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c: In function 'cdata_repr':

c/_cffi_backend.c:1583:13: warning: unknown conversion type character 'L' in format [-Wformat]

c/_cffi_backend.c:1583:13: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c:1595:9: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1595:9: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c: In function 'cdataowning_repr':

c/_cffi_backend.c:1647:30: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1647:30: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c: In function '_cdata_get_indexed_ptr':

c/_cffi_backend.c:1820:26: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1820:26: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1820:26: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c: In function '_cdata_getslicearg':

c/_cffi_backend.c:1872:26: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1872:26: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1872:26: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c: In function 'cdata_ass_slice':

c/_cffi_backend.c:1951:26: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1951:26: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1951:26: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c:1969:30: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1969:30: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1969:30: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c:1983:22: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:1983:22: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c: In function 'cdata_call':

c/_cffi_backend.c:2367:30: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:2367:30: warning: format '%s' expects argument of type 'char *', but argument 3 has type 'Py_ssize_t' [-Wformat]

c/_cffi_backend.c:2367:30: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c: In function 'cast_to_integer_or_char':

c/_cffi_backend.c:2916:26: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:2916:26: warning: format '%s' expects argument of type 'char *', but argument 3 has type 'Py_ssize_t' [-Wformat]

c/_cffi_backend.c:2916:26: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c:2928:26: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:2928:26: warning: format '%s' expects argument of type 'char *', but argument 3 has type 'Py_ssize_t' [-Wformat]

c/_cffi_backend.c:2928:26: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c: In function 'new_array_type':

c/_cffi_backend.c:3480:9: warning: unknown conversion type character 'l' in format [-Wformat]

c/_cffi_backend.c:3480:9: warning: too many arguments for format [-Wformat-extra-args]

c/_cffi_backend.c: In function 'b_complete_struct_or_union':

c/_cffi_backend.c:3878:22: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:3878:22: warning: unknown conversion type character 'z' in format [-Wformat]

c/_cffi_backend.c:3878:22: warning: too many arguments for format [-Wformat-extra-args]

Traceback (most recent call last):

  File "<string>", line 17, in <module>

  File "c:\users\paco\appdata\local\temp\pip_build_Paco\cryptography\setup.py", line 113, in <module>

    "build": cffi_build,

  File "D:\Anaconda\lib\distutils\core.py", line 112, in setup

    _setup_distribution = dist = klass(attrs)

  File "build\bdist.win-amd64\egg\setuptools\dist.py", line 239, in __init__

  File "build\bdist.win-amd64\egg\setuptools\dist.py", line 264, in fetch_build_eggs

  File "build\bdist.win-amd64\egg\pkg_resources.py", line 580, in resolve

    dist = best[req.key] = env.best_match(req, ws, installer)

  File "build\bdist.win-amd64\egg\pkg_resources.py", line 818, in best_match

    return self.obtain(req, installer) # try and download/install

  File "build\bdist.win-amd64\egg\pkg_resources.py", line 830, in obtain

    return installer(requirement)

  File "build\bdist.win-amd64\egg\setuptools\dist.py", line 314, in fetch_build_egg

  File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line 593, in easy_install

  File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line 623, in install_item

  File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line 809, in install_eggs

  File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line 1015, in build_and_install

  File "build\bdist.win-amd64\egg\setuptools\command\easy_install.py", line 1003, in run_setup

distutils.errors.DistutilsError: Setup script exited with error: command 'gcc' failed with exit status 1

----------------------------------------
Cleaning up...
  Removing temporary dir c:\users\paco\appdata\local\temp\pip_build_Paco...
Command python setup.py egg_info failed with error code 1 in c:\users\paco\appdata\local\temp\pip_build_Paco\cryptography
Exception information:
Traceback (most recent call last):
  File "D:\Anaconda\lib\site-packages\pip-1.5.4-py2.7.egg\pip\basecommand.py", line 122, in main
    status = self.run(options, args)
  File "D:\Anaconda\lib\site-packages\pip-1.5.4-py2.7.egg\pip\commands\install.py", line 278, in run
    requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)
  File "D:\Anaconda\lib\site-packages\pip-1.5.4-py2.7.egg\pip\req.py", line 1229, in prepare_files
    req_to_install.run_egg_info()
  File "D:\Anaconda\lib\site-packages\pip-1.5.4-py2.7.egg\pip\req.py", line 325, in run_egg_info
    command_desc='python setup.py egg_info')
  File "D:\Anaconda\lib\site-packages\pip-1.5.4-py2.7.egg\pip\util.py", line 697, in call_subprocess
    % (command_desc, proc.returncode, cwd))
InstallationError: Command python setup.py egg_info failed with error code 1 in c:\users\paco\appdata\local\temp\pip_build_Paco\cryptography

I found other egg_info error posts (here and here) but the solutions there provided wouldn't solve my problem. Also, I am able to install other packages through PIP.

PIP version 1.5.4 setuptools version 2.2


问:
How can I select random words from an external file in java processing?
I have this assignment that I have to make a word cloud of the most common words used in an external text file which all words will start from the center and expand/animate to a word cloud... I already made a word counter to determine which words are most often used in the text file, now that I know which words are most often used, how can I select at least 15 random words from the top 50 most used words in the text file?

if that question can be easily answered how can I overlap all the selected words on the canvas?

note: I am very noob at java and processing so a code would help...

here is my code:

```<code>    String[] words;
    IntDict concordance;
    int index = 0;

    void setup() {
      size(500, 500);
      background(0);
      String[] lines = loadStrings("alice_just_text.txt");
      String entireplay = join(lines, " ");
      words = splitTokens(entireplay, ",.?!:-;:()03 ");
      concordance = new IntDict();
      frameRate(5);

      for (int i = 0; i < words.length; i++) {
        concordance.increment(words[i].toLowerCase());
      }
      concordance.sortValuesReverse();

      String[] keys = concordance.keyArray();
      for (int i = 0; i < keys.length; i++) {
        int count = concordance.get(keys[i]); //word counts
        println(keys[i], count);

      }

    }

    void draw() {

      background(0);
      textSize(64);
      textAlign(CENTER);
      text(words[index], width / 2, height / 2);
      index++;

    }
</code>```

答:
Once you've read all the words from your file, I would use a Map<String, Integer> instance to store each word with its corresponding frequency.

After words = splitTokens (entireplay, ",.?!:-;:()03 "); put the following:

```<code>    Map<String, Integer> wordsMap = new HashMap<>();
    for (int i = 0; i < words.length; i++)
    {
        if (wordsMap.containsKey(words[i]))
        {
            wordsMap.put(words[i], wordsMap.get(words[i]));
        }
        else
        {
            wordsMap.put(words[i], 1);
        }
    }
</code>```

Now all words are stored in the map with the corresponding frequency.

There's a great post on how to sort a map by value. Check here

Once you have it sorted, do the following to clear all but the top 50 from the list, shuffle the list, then print the first 15:

```<code>    for (int i = 50; i < listOfWords.size(); i++)
    {
        listOfWords.remove(i);
    }

    Collections.shuffle(listOfWords);
    for (int i = 0; i < 15; i++)
    {
        // Print the first 15 elements of the shuffled list.
    }
</code>```

Body:
I have this assignment that I have to make a word cloud of the most common words used in an external text file which all words will start from the center and expand/animate to a word cloud... I already made a word counter to determine which words are most often used in the text file, now that I know which words are most often used, how can I select at least 15 random words from the top 50 most used words in the text file?

if that question can be easily answered how can I overlap all the selected words on the canvas?

note: I am very noob at java and processing so a code would help...

here is my code:

    String[] words;
    IntDict concordance;
    int index = 0;

    void setup() {
      size(500, 500);
      background(0);
      String[] lines = loadStrings("alice_just_text.txt");
      String entireplay = join(lines, " ");
      words = splitTokens(entireplay, ",.?!:-;:()03 ");
      concordance = new IntDict();
      frameRate(5);

      for (int i = 0; i < words.length; i++) {
        concordance.increment(words[i].toLowerCase());
      }
      concordance.sortValuesReverse();

      String[] keys = concordance.keyArray();
      for (int i = 0; i < keys.length; i++) {
        int count = concordance.get(keys[i]); //word counts
        println(keys[i], count);

      }

    }

    void draw() {

      background(0);
      textSize(64);
      textAlign(CENTER);
      text(words[index], width / 2, height / 2);
      index++;

    }

Body:
Once you've read all the words from your file, I would use a Map<String, Integer> instance to store each word with its corresponding frequency.

After words = splitTokens (entireplay, ",.?!:-;:()03 "); put the following:

    Map<String, Integer> wordsMap = new HashMap<>();
    for (int i = 0; i < words.length; i++)
    {
        if (wordsMap.containsKey(words[i]))
        {
            wordsMap.put(words[i], wordsMap.get(words[i]));
        }
        else
        {
            wordsMap.put(words[i], 1);
        }
    }

Now all words are stored in the map with the corresponding frequency.

There's a great post on how to sort a map by value. Check here

Once you have it sorted, do the following to clear all but the top 50 from the list, shuffle the list, then print the first 15:

    for (int i = 50; i < listOfWords.size(); i++)
    {
        listOfWords.remove(i);
    }

    Collections.shuffle(listOfWords);
    for (int i = 0; i < 15; i++)
    {
        // Print the first 15 elements of the shuffled list.
    }


问:
keeping search and filter dropdown on same line
Im working on a section on a webpage, using bootstrap but cant keep filter on same line. Ive tried a few ways, currently trying columns, tried divs inline, still not lining up correctly.

div class="col-lg-12">

        <input type="text" style="width: 80%;" id="rev-search" placeholder="Search" autofocus="" />

       <button class="btn btn-default dropdown-toggle" style="float: right;" type="button" id="group_filter" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"><?php echo $text_filter_group;?></button>

       <?php
        foreach ($customer_groups as $group){
         echo '
'.$group['name'].'
';
        }
        ?>

```

答:
I believe it's because there is padding on the col-lg-10 and col-lg-2. Add this to your css to remove the padding which is pushing your drop down to the next row.</p>

```<code>.col-lg-10, .col-lg-2 {
  padding: 0;
}
</code>```

Body:
I believe it's because there is padding on the col-lg-10 and col-lg-2. Add this to your css to remove the padding which is pushing your drop down to the next row.

.col-lg-10, .col-lg-2 {
  padding: 0;
}


问:
Difference between int a[5],int a[], int a[]={2,3} in Java
How could we statically declare array? Can't it be by int a[5];?

```<code>package oops;

public class exception {
    int arr1[] = new int[10];

    public static void main(String args[]){
        int a[] ={1,9};
        int[] a ;
        int a[9];
        a[0]=10;
    }
}
</code>```

答:
Consider the following scenarios</p>

```<code>// Create new array with the following two values
int a[] = {1,9};
Assert.assertTrue( 2 == a.length );
Assert.assertTrue( 1 == a[0] );
Assert.assertTrue( 9 == a[1] );

// Create a new, uninitialized array
int[] a;
Assert.assertTrue( null == a );
Assert.assertTrue( 0 == a.length ); // NullPointerException

int a[9]; // this will not compile, should be
int a[] = new int[9];
Assert.assertTrue( 9 == a.length );
Assert.assertTrue( null == a[0] );

// Provided 'a' has not been previously defined
int a[];
a[0] = 10; // NullPointerExcpetion

// Provided 'a' has been defined as having 0 indicies
int a[] = new int[0];
a[0] = 10; // IndexOutOfBoundsException

// Provided 'a' has been defined as an empty array
int a[] = new int[1];
a[0] = 10; // Reassign index 0, to value 10.
</code>```

Body:
How could we statically declare array? Can't it be by int a[5];?

package oops;

public class exception {
    int arr1[] = new int[10];

    public static void main(String args[]){
        int a[] ={1,9};
        int[] a ;
        int a[9];
        a[0]=10;
    }
}

Body:
Consider the following scenarios

// Create new array with the following two values
int a[] = {1,9};
Assert.assertTrue( 2 == a.length );
Assert.assertTrue( 1 == a[0] );
Assert.assertTrue( 9 == a[1] );

// Create a new, uninitialized array
int[] a;
Assert.assertTrue( null == a );
Assert.assertTrue( 0 == a.length ); // NullPointerException

int a[9]; // this will not compile, should be
int a[] = new int[9];
Assert.assertTrue( 9 == a.length );
Assert.assertTrue( null == a[0] );

// Provided 'a' has not been previously defined
int a[];
a[0] = 10; // NullPointerExcpetion

// Provided 'a' has been defined as having 0 indicies
int a[] = new int[0];
a[0] = 10; // IndexOutOfBoundsException

// Provided 'a' has been defined as an empty array
int a[] = new int[1];
a[0] = 10; // Reassign index 0, to value 10.


问:
How do I prevent a JavasScript function from launching when the browser loads?
So I created a function (onSuccess) that launches when an AJAX request is successful. The problem is that my function launches when my browser loads and I would only like for the function only to be called when a button with id myButton is clicked. I am locating my button using document.getElementById("myButton"); but when I run console.log(document.getElementById("myButton")); in my browser console I get a Null result.

I've looked around and gotten a few suggestions stating that my element wasn't in the DOM when my script ran. I can understand that but when I moved the location of my script and moved the document.getElementById... my script still doesn't work. I viewed a few suggestions on Stackoverflow but they were mostly JQuery solutions. I'm looking for a pure JavaScript solution. My  code is below

JSFiddle Example

```<code>            var el = document.getElementById("myButton");
            el.onclick = addUser("username", "email", onSuccess);

            function onSuccess(result){
               alert ('successful');
            }

            // Do not modify this function. Add user service wrapper.
            function addUser(username, email, callback) {
                var xhr = new XMLHttpRequest();
                var response;
                var success = (!!Math.round(Math.random()));

                if (!success){
                    response = JSON.stringify({
                        success: success,
                        error: "Oups, something went wrong!"
                    });
                } else {
                    response = JSON.stringify({
                        success: success,
                        user: {
                            username: username,
                            email: email
                        }
                    });
                }

                xhr.open("POST", "/echo/json/");
                xhr.onload = function () {
                        if (xhr.status === 200) {
                            callback(JSON.parse(xhr.responseText));
                    }
                }
                xhr.send("json=" + response);
            };
</code>```

答:
You've gone a little wrong here, but I think I know what you need to do.

You want to pass a function reference to the onclick attribute, but instead you're executing the function and setting onclick to be whatever that function returns.

This is why your function is running when the browser loads. You need to pass the reference; not execute it and pass the output of the function.

So how do you solve it?

There is a cool practice in functional programming called Currying Functions. It's very useful in situations like this, when you need to pass in some parameters but you want to delay execution. In this case, you could do something like this:

```<code>function buildAddUser(username, email, callback) {
    return function() {
        addUser(username, email, callback)
    }
}
</code>```

Then, you set your button to be equal to the output of buildAddUser..

```<code>el.onclick = buildAddUser("username", "email", onSuccess);
</code>```

This will set the onclick attribute to be equal to a function that invokes the addUser function.

Why not just use an anonymous function?

I prefer to wrap these things in named functions, to make your code easier to read. Anonymous functions flying all over the place can make things confusing.

Extra Reading

Functional Programming in Javascript is one of the most exciting new developments and offers a wide array of tools to help solve problems just like this. You should have a read through some of the material available

Body:
So I created a function (onSuccess) that launches when an AJAX request is successful. The problem is that my function launches when my browser loads and I would only like for the function only to be called when a button with id myButton is clicked. I am locating my button using document.getElementById("myButton"); but when I run console.log(document.getElementById("myButton")); in my browser console I get a Null result.

I've looked around and gotten a few suggestions stating that my element wasn't in the DOM when my script ran. I can understand that but when I moved the location of my script and moved the document.getElementById... my script still doesn't work. I viewed a few suggestions on Stackoverflow but they were mostly JQuery solutions. I'm looking for a pure JavaScript solution. My  code is below

JSFiddle Example

            var el = document.getElementById("myButton");
            el.onclick = addUser("username", "email", onSuccess);

            function onSuccess(result){
               alert ('successful');
            }

            // Do not modify this function. Add user service wrapper.
            function addUser(username, email, callback) {
                var xhr = new XMLHttpRequest();
                var response;
                var success = (!!Math.round(Math.random()));

                if (!success){
                    response = JSON.stringify({
                        success: success,
                        error: "Oups, something went wrong!"
                    });
                } else {
                    response = JSON.stringify({
                        success: success,
                        user: {
                            username: username,
                            email: email
                        }
                    });
                }

                xhr.open("POST", "/echo/json/");
                xhr.onload = function () {
                        if (xhr.status === 200) {
                            callback(JSON.parse(xhr.responseText));
                    }
                }
                xhr.send("json=" + response);
            };

Body:
You've gone a little wrong here, but I think I know what you need to do.

You want to pass a function reference to the onclick attribute, but instead you're executing the function and setting onclick to be whatever that function returns.

This is why your function is running when the browser loads. You need to pass the reference; not execute it and pass the output of the function.

So how do you solve it?

There is a cool practice in functional programming called Currying Functions. It's very useful in situations like this, when you need to pass in some parameters but you want to delay execution. In this case, you could do something like this:

function buildAddUser(username, email, callback) {
    return function() {
        addUser(username, email, callback)
    }
}

Then, you set your button to be equal to the output of buildAddUser..

el.onclick = buildAddUser("username", "email", onSuccess);

This will set the onclick attribute to be equal to a function that invokes the addUser function.

Why not just use an anonymous function?

I prefer to wrap these things in named functions, to make your code easier to read. Anonymous functions flying all over the place can make things confusing.

Extra Reading

Functional Programming in Javascript is one of the most exciting new developments and offers a wide array of tools to help solve problems just like this. You should have a read through some of the material available


问:
viewmodel problem, "does not contain definition"
I get this error 'object' does not contain a definition for 'Images' and no extension method 'Images' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

inside my index.aspx

```<code><div class="wrapCarousel">
<div class="Carousel">
   <% foreach (var image in Model.Images){ %>
   <div class="placeImages">
    <img width="150px" height="150px" src="../Img/<%=image.TnImg%>" alt="<%=image.Name%>" />
    <div class="imageText">
     <%=image.Name%>
    </div>
   </div>
   <% } %>
</code>```

this is my homecontroller.cs:

```<code>        public ActionResult Index()
    {
        ViewData["noOfPlaces"] = noOfPlaces();

        ImageViewModel imageViewModel = new ImageViewModel();
        imageViewModel.Images = getImages();

        return View("Index", imageViewModel);
    }
</code>```

and this is my Imageviewmodel.cs:

```<code>    namespace laMVC.Models
{
    public class ImageViewModel
    {
        public IList<Image> GetImages { get; set; }
        public IList<Image> Images { get; set; }
        public Image Image { get; set; }
    }
}
</code>```

How come index.aspx can't find Model.Images?

答: Change your view to inherit ViewPage<PubbaMVC.Models.ImageViewModel>.

Body:
I get this error 'object' does not contain a definition for 'Images' and no extension method 'Images' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

inside my index.aspx

   <% foreach (var image in Model.Images){ %>

    <img width="150px" height="150px" src="../Img/<%=image.TnImg%>" alt="<%=image.Name%>" />

     <%=image.Name%>

   <% } %>

this is my homecontroller.cs:

        public ActionResult Index()
    {
        ViewData["noOfPlaces"] = noOfPlaces();

        ImageViewModel imageViewModel = new ImageViewModel();
        imageViewModel.Images = getImages();

        return View("Index", imageViewModel);
    }

and this is my Imageviewmodel.cs:

    namespace laMVC.Models
{
    public class ImageViewModel
    {
        public IList<Image> GetImages { get; set; }
        public IList<Image> Images { get; set; }
        public Image Image { get; set; }
    }
}

How come index.aspx can't find Model.Images?