问:
Using & Searching through jsonb data in mysql
We previously had PostgreSQL database setup and were using JSONB to hold some of our data in json since we need to keep one of our columns data dynamic in nature based on whatever JSON we could store in it. We could also perform textual search and comparison through the JSON keys and values and it all worked well.

Recently due to some technical reasons our team decided to move to MySQL. So my question is does JSON in MySQL support the search like PostgreSQL does and also how stable JSON in MySQL support is given it got introduced in versions >= MySQL 5.7.8, MySQL.

答:
Right from the MySQL Documentation:

JSON support

Beginning with MySQL 5.7.8, MySQL supports a native JSON type. JSON
  values are not stored as strings, instead using an internal binary
  format that permits quick read access to document elements. JSON
  documents stored in JSON columns are automatically validated whenever
  they are inserted or updated, with an invalid document producing an
  error. JSON documents are normalized on creation, and can be compared
  using most comparison operators such as =, <, <=, >, >=, <>, !=, and
  <=>; for information about supported operators as well as precedence
  and other rules that MySQL follows when comparing JSON values, see
  Comparison and Ordering of JSON Values.

MySQL 5.7.8 also introduces a number of functions for working with
  JSON values. These functions include those listed here:

Functions that create JSON values: JSON_ARRAY(), JSON_MERGE(), and
  JSON_OBJECT(). See Section 12.16.2, “Functions That Create JSON
  Values”. Functions that search JSON values: JSON_CONTAINS(),
  JSON_CONTAINS_PATH(), JSON_EXTRACT(), JSON_KEYS(), and JSON_SEARCH().
  See Section 12.16.3, “Functions That Search JSON Values”. Functions
  that modify JSON values: JSON_APPEND(), JSON_ARRAY_APPEND(),
  JSON_ARRAY_INSERT(), JSON_INSERT(), JSON_QUOTE(), JSON_REMOVE(),
  JSON_REPLACE(), JSON_SET(), and JSON_UNQUOTE(). See Section 12.16.4,
  “Functions That Modify JSON Values”. Functions that provide
  information about JSON values: JSON_DEPTH(), JSON_LENGTH(),
  JSON_TYPE(), and JSON_VALID(). See Section 12.16.5, “Functions That
  Return JSON Value Attributes”. In MySQL 5.7.9 and later, you can use
  column->path as shorthand for JSON_EXTRACT(column, path). This works
  as an alias for a column wherever a column identifier can occur in an
  SQL statement, including WHERE, ORDER BY, and GROUP BY clauses. This
  includes SELECT, UPDATE, DELETE, CREATE TABLE, and other SQL
  statements. The left hand side must be a JSON column identifier (and
  not an alias). The right hand side is a quoted JSON path expression
  which is evaluated against the JSON document returned as the column
  value.

See Section 12.16.3, “Functions That Search JSON Values”, for more
  information about -> and JSON_EXTRACT(). For information about JSON
  path support in MySQL 5.7, see Searching and Modifying JSON Values.
  See also Secondary Indexes and Virtual Generated Columns.

Also we have been using MySQL and storing data in JSON and it works pretty well as far as performance and scalability is concerned.

You can read more about it on: https://dev.mysql.com/doc/refman/5.7/en/json.html


来源: stackexchange

问:
enumeration toselectlist with correct value
USing ASPNET MVC 4, Say i have an enum

```<code>public enum IndicatorGroup
    {
        Include_ANY_MatchingIndicator = 1,
        Include_ALL_MatchingIndicator = 2,
        Exclude_ANY_MatchingIndicator = 3,
        Exclude_ALL_MatchingIndicator = 4
    };
</code>```

I use the following helper method to bind it to drop down list as described here: How do you create a dropdownlist from an enum in ASP.NET MVC?

```<code>public static class MyExtensions{
    public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
        where TEnum : struct, IComparable, IFormattable, IConvertible
    {
        var values = from TEnum e in Enum.GetValues(typeof(TEnum))
            select new { Id = e, Name = e.ToString() };
        return new SelectList(values, "Id", "Name", enumObj);
    }
}
</code>```

Now i want that the selected value is a number (this is probably specified in the above code as)

```<code>Id = e ,
</code>```

but when i get the selected value it returns me the text Exclude_ALL_MatchingIndicator instead of the number 4. How do i set it properly?

VIEW

```<code> @Html.DropDownListFor(m => m.IndicatorGroups, Model.IndicatorGroups.ToSelectList(), new { @id = "ddlIndicatorGroup" })
</code>```

答:
You can use Convert.ToInt32(e), so that the code becomes

```<code>var values = from TEnum e in Enum.GetValues(typeof(TEnum))
             select new { Id = Convert.ToInt32(e), Name = e.ToString() };
return new SelectList(values, "Id", "Name", Convert.ToInt32(enumObj));
</code>```

However, you do not really want to do that. If the value of property IndicatorGroups is say IndicatorGroup.Exclude_ANY_MatchingIndicator, then your DropDownListFor() method will initially display the first option because the value of the property does not match any of the option values. Internally, the method builds a new IEnumerable<SelectListItem> based on the 2nd parameter, and sets the Selected property if the .ToString() value of the property matches the Value property of any SelectListItem - in your case "Exclude_ANY_MatchingIndicator" will not match 1, 2, 3, or 4 so the first option will be selected (because something has to be).

You have indicated in the comments that you want to save the selected value as anINT in the database, in which case, in your POST method, convert the bound value to an int. Assuming you select the 2nd option in the view, then the IndicatorGroups property of your model will be IndicatorGroup.Include_ALL_MatchingIndicator. To save the value as an int, use

```<code>int valueToSave = (int)model.IndicatorGroups; // returns 2
</code>```

ContentLicense: CC BY-SA 3.0

Body:
USing ASPNET MVC 4, Say i have an enum

public enum IndicatorGroup
    {
        Include_ANY_MatchingIndicator = 1,
        Include_ALL_MatchingIndicator = 2,
        Exclude_ANY_MatchingIndicator = 3,
        Exclude_ALL_MatchingIndicator = 4
    };

I use the following helper method to bind it to drop down list as described here: How do you create a dropdownlist from an enum in ASP.NET MVC?

public static class MyExtensions{
    public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
        where TEnum : struct, IComparable, IFormattable, IConvertible
    {
        var values = from TEnum e in Enum.GetValues(typeof(TEnum))
            select new { Id = e, Name = e.ToString() };
        return new SelectList(values, "Id", "Name", enumObj);
    }
}

Now i want that the selected value is a number (this is probably specified in the above code as)

Id = e ,

but when i get the selected value it returns me the text Exclude_ALL_MatchingIndicator instead of the number 4. How do i set it properly?

VIEW

 @Html.DropDownListFor(m => m.IndicatorGroups, Model.IndicatorGroups.ToSelectList(), new { @id = "ddlIndicatorGroup" })

Body:
You can use Convert.ToInt32(e), so that the code becomes

var values = from TEnum e in Enum.GetValues(typeof(TEnum))
             select new { Id = Convert.ToInt32(e), Name = e.ToString() };
return new SelectList(values, "Id", "Name", Convert.ToInt32(enumObj));

However, you do not really want to do that. If the value of property IndicatorGroups is say IndicatorGroup.Exclude_ANY_MatchingIndicator, then your DropDownListFor() method will initially display the first option because the value of the property does not match any of the option values. Internally, the method builds a new IEnumerable<SelectListItem> based on the 2nd parameter, and sets the Selected property if the .ToString() value of the property matches the Value property of any SelectListItem - in your case "Exclude_ANY_MatchingIndicator" will not match 1, 2, 3, or 4 so the first option will be selected (because something has to be).

You have indicated in the comments that you want to save the selected value as anINT in the database, in which case, in your POST method, convert the bound value to an int. Assuming you select the 2nd option in the view, then the IndicatorGroups property of your model will be IndicatorGroup.Include_ALL_MatchingIndicator. To save the value as an int, use

int valueToSave = (int)model.IndicatorGroups; // returns 2


问:
updating counter increment when click on link in laravel
I have an audio file on public folder like this-

```<code> @foreach ($songs as $song)
     <a href="{{asset('/audio/' . $song->song)}}" download="" >
        <button type="button" class="btn btn-xs btn-info download" style="margin-bottom: 15px;">
           <i class="glyphicon glyphicon-download">Download</i>
        </button>
     </a>
 @endforeach
</code>```

So, when i click that button it downloads the song. i have a song database where i put the song and a column download_count set to default(0). I want to increase the download_count every time the button is clicked. so how can i pass this logic to controller for updating the database?

答:
You can simply update your download count dynamically via Ajax.

A simple example:

```<code>@foreach ($songs as $song)
   <a href="{{asset('/audio/' . $song->song)}}">
     <button type="button" class="download" data-id="{{ $song->id}}">Download</button>
   </a>
@endforeach

<script>
$('.download').click(function(){
 $.ajax({
   url: "/update_download_count",
   type:"POST",
   data: {
     song_id:   $(this).attr('data-id')
   },
   success: function (data) {
     console.log(data);
   },
   error: function (request, status, error) {
     console.log('code: '+request.status+"\n"+'message: '+request.responseText+"\n"+'error: '+error);
   }
 });
});
</script>
</code>```

Your route:

```<code>Route::post('/update_download_count', 'SongController@updateDownloadCount');
</code>```

Your controller:

```<code>public function updateDownloadCount(){
 $song_id = $_POST['song_id'];
 // your database update logic
}
</code>```

Body:
I have an audio file on public folder like this-

 @foreach ($songs as $song)
     song)}}" download="" >
        <button type="button" class="btn btn-xs btn-info download" style="margin-bottom: 15px;">
           Download
        </button>

 @endforeach

So, when i click that button it downloads the song. i have a song database where i put the song and a column download_count set to default(0). I want to increase the download_count every time the button is clicked. so how can i pass this logic to controller for updating the database?

Body:
You can simply update your download count dynamically via Ajax.

A simple example:

@foreach ($songs as $song)
   <a href="{{asset('/audio/' . $song->song)}}">
     <button type="button" class="download" data-id="{{ $song->id}}">Download</button>
   </a>
@endforeach

<script>
$('.download').click(function(){
 $.ajax({
   url: "/update_download_count",
   type:"POST",
   data: {
     song_id:   $(this).attr('data-id')
   },
   success: function (data) {
     console.log(data);
   },
   error: function (request, status, error) {
     console.log('code: '+request.status+"\n"+'message: '+request.responseText+"\n"+'error: '+error);
   }
 });
});
</script>

Your route:

Route::post('/update_download_count', 'SongController@updateDownloadCount');

Your controller:

public function updateDownloadCount(){
 $song_id = $_POST['song_id'];
 // your database update logic
}


问:
Redirect 301 not working in Chrome
I am using .htaccess to redirect a link to an external page (outside root).
however, redirect 301 is not working in Google Chrome.
but on other browsers e.g. Safari, Firefox, and IE are working.

Below is my .htaccess file:

```<code><FilesMatch "\.(jpg|png)$">
Header set Cache-Control "public, max-age=2592000"
</FilesMatch>

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html

Redirect 301 /explore http://flights.skiffly.com/map/?marker=84376.map
</code>```

please help.

答:
Can you clear the Chrome browser's cache, and then do again?
Sometimes I got same issues, then I always clear the browser cache, and then try it again. </p>

Title: Redirect 301 not working in Chrome

Body:
I am using .htaccess to redirect a link to an external page (outside root).
however, redirect 301 is not working in Google Chrome.
but on other browsers e.g. Safari, Firefox, and IE are working.

Below is my .htaccess file:

<FilesMatch "\.(jpg|png)$">
Header set Cache-Control "public, max-age=2592000"
</FilesMatch>

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html

Redirect 301 /explore http://flights.skiffly.com/map/?marker=84376.map

please help.


问:
Database schema which can support specialized properties
I need to store a set of entities, of which there are several specialized versions. They have some common properties, but the specialized ones contain properties specific for that entity.

Solutions

The data store is a relational DBMS, and this is not for discussion :-) Specifically, it is the Microsoft SQL Server 2005.

I could easily create a table for the common properties and then a table for each of the specialized versions. However, it is likely that new entities will have to be added to the solution later and I don't want to maintain both an object model and a database schema.

Another idea is to create a table

```<code>reading(<common properties>, extended_properties)
</code>```

and have the extended_propertiesfield be some kind of serialization of the extended properties. I was thinking either JSON or XML. I will most likely be using an ORM framework, but I haven't decided yet.  Either way, the object representation of a specialized entity from the reading could expose a dictionary {extended_property_name, value} containing the parsed key/value pairs from the extended_properties field.

From this http://msdn.microsoft.com/en-us/library/ms345117(SQL.90).aspx I gather that XML fields, combined with schemas for these, give the notion of typed XML inside the DBMS. Also, queries involving the XML contents in the extended_propertiesfield can take these into account, too.

What I want

Feedback on my solution suggestions, primarily the one with the reading table and serialization of the extended properties.

Also, I realize this is one of the limitations of relational DBMS' compared to key/value based stores. However, there surely must be some modelling techniques to accommodate this.

Any feedback is greatly appreciated!

答:
This is a classic example of the gen-spec design pattern.  Gen-spec is covered in every tutorial on object modeling, because it is handled by inheritance.  It's frequently skipped over in tutorials on relational data modeling.  But it's well understood.

Do a web sreach on "generalization specialization relational modeling".  You'll see several articles on how to set up a single table for the general class and a table for each specialized class.  The articles will help you with foreign key design.  In particular, the primary key of each specialized table does double duty.  It's also a foreign key to the generalized table.

This won't look very familiar to you if you are used to object modeling.  But you'll find it works well.  And the solution offered by most of the articles is not dynamic, so you'll have to do some DDL every time a new specialized subclass is discovered.

ContentLicense: CC BY-SA 2.5

Body:
I need to store a set of entities, of which there are several specialized versions. They have some common properties, but the specialized ones contain properties specific for that entity.

Solutions

The data store is a relational DBMS, and this is not for discussion :-) Specifically, it is the Microsoft SQL Server 2005.

I could easily create a table for the common properties and then a table for each of the specialized versions. However, it is likely that new entities will have to be added to the solution later and I don't want to maintain both an object model and a database schema.

Another idea is to create a table

reading(<common properties>, extended_properties)

and have the extended_propertiesfield be some kind of serialization of the extended properties. I was thinking either JSON or XML. I will most likely be using an ORM framework, but I haven't decided yet.  Either way, the object representation of a specialized entity from the reading could expose a dictionary {extended_property_name, value} containing the parsed key/value pairs from the extended_properties field.

From this http://msdn.microsoft.com/en-us/library/ms345117(SQL.90).aspx I gather that XML fields, combined with schemas for these, give the notion of typed XML inside the DBMS. Also, queries involving the XML contents in the extended_propertiesfield can take these into account, too.

What I want

Feedback on my solution suggestions, primarily the one with the reading table and serialization of the extended properties.

Also, I realize this is one of the limitations of relational DBMS' compared to key/value based stores. However, there surely must be some modelling techniques to accommodate this.

Any feedback is greatly appreciated!


问:
How To Create a Pulse Effect On an SKSpriteNode?
Hi would like to learn how to create a visual pulse effect as in the video below.

https://www.youtube.com/watch?v=uiHj-KZWjpU

I followed the link posted in the video; however, I have not been able to achieve the same effect. I am having trouble doing it with an SKSpriteNode.

Preferably I would like to be able to loop this effect to repeat every second or so.

Any help would be very much appreciated! Thanks!

答:
A real easy way of doing this would be to have your button image, and an outline image right below you button. then just run the pulse func on the button outline image and voila! It works with any shape and you can just adjust the actions as you see fit. These are added via the scene editor but it makes no difference how they are added as long as the outline images have a lower zPosition than the button.

```<code>class LevelMenu: SKScene {

    private var button1 = SKSpriteNode()
    private var button1Outline = SKSpriteNode()
    private var button2 = SKSpriteNode()
    private var button2Outline = SKSpriteNode()
    private var button3 = SKSpriteNode()
    private var button3Outline = SKSpriteNode()

    override func didMove(to view: SKView) {

        if let button1 = self.childNode(withName: "button1") as? SKSpriteNode {
            self.button1 = button1
        }

        if let button2 = self.childNode(withName: "button2") as? SKSpriteNode {
            self.button2 = button2
        }

        if let button3 = self.childNode(withName: "button3") as? SKSpriteNode {
            self.button3 = button3
        }

        if let button1Outline = self.childNode(withName: "button1Outline") as? SKSpriteNode {
            self.button1Outline = button1Outline
        }

        if let button2Outline = self.childNode(withName: "button2Outline") as? SKSpriteNode {
            self.button2Outline = button2Outline
        }

        if let button3Outline = self.childNode(withName: "button3Outline") as? SKSpriteNode {
            self.button3Outline = button3Outline
        }
    }

    func pulseAction(node: SKSpriteNode) {

        let copyNode = node.copy() as! SKSpriteNode
        copyNode.position = node.position
        addChild(copyNode)

        let scale = SKAction.scale(by: 1.75, duration: 0.4)
        scale.timingMode = .easeInEaseOut
        let wait = SKAction.wait(forDuration: 0.25)
        let fadeOut = SKAction.fadeOut(withDuration: 0.15)
        let fadeSeq = SKAction.sequence([wait, fadeOut])
        let pulseGroup = SKAction.group([scale, fadeSeq])

        copyNode.run(pulseGroup, completion: { copyNode.removeFromParent() })
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        pulseAction(node: button1Outline)
        pulseAction(node: button2Outline)
        pulseAction(node: button3Outline)
    }
}
</code>```

Body:
A real easy way of doing this would be to have your button image, and an outline image right below you button. then just run the pulse func on the button outline image and voila! It works with any shape and you can just adjust the actions as you see fit. These are added via the scene editor but it makes no difference how they are added as long as the outline images have a lower zPosition than the button.

class LevelMenu: SKScene {

    private var button1 = SKSpriteNode()
    private var button1Outline = SKSpriteNode()
    private var button2 = SKSpriteNode()
    private var button2Outline = SKSpriteNode()
    private var button3 = SKSpriteNode()
    private var button3Outline = SKSpriteNode()

    override func didMove(to view: SKView) {

        if let button1 = self.childNode(withName: "button1") as? SKSpriteNode {
            self.button1 = button1
        }

        if let button2 = self.childNode(withName: "button2") as? SKSpriteNode {
            self.button2 = button2
        }

        if let button3 = self.childNode(withName: "button3") as? SKSpriteNode {
            self.button3 = button3
        }

        if let button1Outline = self.childNode(withName: "button1Outline") as? SKSpriteNode {
            self.button1Outline = button1Outline
        }

        if let button2Outline = self.childNode(withName: "button2Outline") as? SKSpriteNode {
            self.button2Outline = button2Outline
        }

        if let button3Outline = self.childNode(withName: "button3Outline") as? SKSpriteNode {
            self.button3Outline = button3Outline
        }
    }

    func pulseAction(node: SKSpriteNode) {

        let copyNode = node.copy() as! SKSpriteNode
        copyNode.position = node.position
        addChild(copyNode)

        let scale = SKAction.scale(by: 1.75, duration: 0.4)
        scale.timingMode = .easeInEaseOut
        let wait = SKAction.wait(forDuration: 0.25)
        let fadeOut = SKAction.fadeOut(withDuration: 0.15)
        let fadeSeq = SKAction.sequence([wait, fadeOut])
        let pulseGroup = SKAction.group([scale, fadeSeq])

        copyNode.run(pulseGroup, completion: { copyNode.removeFromParent() })
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        pulseAction(node: button1Outline)
        pulseAction(node: button2Outline)
        pulseAction(node: button3Outline)
    }
}


问:
Loading image to opengl texture qt c++
I'm using opengl calls on Qt with c++, in order to display images to the screen. In order to get the image to the texture, I first read it as a QImage, and then use the following code to load to texture:

```<code>void imageDisplay::loadImage(const QImage &img){
    glEnable(GL_TEXTURE_2D); // Enable texturing
    glBindTexture(GL_TEXTURE_2D, texture); // Set as the current texture
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
    glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, img.width(),
                  img.height(),
                  0, GL_BGRA,      GL_UNSIGNED_BYTE, img.bits() );
    glFinish();
    glDisable(GL_TEXTURE_2D);
}
</code>```

However, when profiling performance, I suspect this is not the most efficient way of doing this. Performance is critical for the application that I am developing, and I would really appreciate any suggestions on how to improve this part.
(BTW - reading the image is done on a separate module than the one that is displaying it - is it possible to read and load to a texture, and then move the texture the displaying object?)

Thank you

答:
It's hard to say without looking at your profiling results, but a few things to try:

You are sending your data via glTexImage2D() in GL_BGRA format and having the driver reformat. Does it work any faster when you pre-format the bits?: (would be surprising, but you never know what drivers do under the hood.)

QImage imageUpload = imageOriginal.convertToFormat( QImage::Format_ARGB32 ).rgbSwapped();
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, image.width(), image.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, image.bits() );

Are you populating that QImage from a file on disk? How big is it? If the sheer volume of image data is the problem, and it's a static texture, you can try compressing the image to a DXT/St3 format offline and saving that for later. Then read and upload those bits at runtime instead. This will reduce the number of bytes being transferred to the GPU (and stored on GPU memory) to 1/6 or 1/4 the original. If you need to generate the QImage at runtime and can't precompress, then this will probably slow things down, so keep that in mind.

Is the alpha combine important? i.e. if you remove glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); does it help? I wonder if that's causing some unwanted churn. I.e. it to be downloaded to host, modified, then sent back or something...

I agree that you should remove the glFinish(); unless you have a VERY specific reason for it.

How often are you needing to do this? every frame?

Title: Loading image to opengl texture qt c++

Body:
I'm using opengl calls on Qt with c++, in order to display images to the screen. In order to get the image to the texture, I first read it as a QImage, and then use the following code to load to texture:

void imageDisplay::loadImage(const QImage &img){
    glEnable(GL_TEXTURE_2D); // Enable texturing
    glBindTexture(GL_TEXTURE_2D, texture); // Set as the current texture
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
    glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, img.width(),
                  img.height(),
                  0, GL_BGRA,      GL_UNSIGNED_BYTE, img.bits() );
    glFinish();
    glDisable(GL_TEXTURE_2D);
}

However, when profiling performance, I suspect this is not the most efficient way of doing this. Performance is critical for the application that I am developing, and I would really appreciate any suggestions on how to improve this part.
(BTW - reading the image is done on a separate module than the one that is displaying it - is it possible to read and load to a texture, and then move the texture the displaying object?)

Thank you


问:
Contains search using lodash.js
```<code>var codes = [
{id: 1, code: '123'},
{id: 2, code: '14123'},
{id: 3, code: '556'},
{id: 4, code: '71239'},
{id: 5, code: '289'},
];

var filterCodes = _.filter(codes, function (o) {
  return o.code ? _.includes(o.code, '123') : false
});
</code>```

Output will be : '123','14123','71239'

答:
If I understand right, you are loking for all the codes and not entire object, which has "123" in them.

array.forEach

var codes = [{id: 1, code: '123'},{id: 2, code: '14123'},{id: 3, code: '556'},{id: 4, code: '71239'},{id: 5, code: '289'}];

var result = [];
codes.forEach(function(o){
  o.code && o.code.indexOf('123') >= 0 && result.push(o.code)
});
console.log(result)```

Title: Contains search using lodash.js

Body:
var codes = [
{id: 1, code: '123'},
{id: 2, code: '14123'},
{id: 3, code: '556'},
{id: 4, code: '71239'},
{id: 5, code: '289'},
];

var filterCodes = _.filter(codes, function (o) {
  return o.code ? _.includes(o.code, '123') : false
});

Output will be : '123','14123','71239'


问:
Javascript "set __proto__" in console
I am wondering that, what is the set __proto__ in Javascript Console. I searched on Google, but there is only __proto__ in results.

答:
```<code>var Circle = function () {};
var shape = {};
var circle = new Circle();
shape.__proto__ = circle;
console.log(shape.__proto__ === circle); // true
</code>```

Like the above code, maybe it was not set__proto__and more like set.__proto__

var set= {};

Title: Javascript "set __proto__" in console

Body:
var Circle = function () {};
var shape = {};
var circle = new Circle();
shape.__proto__ = circle;
console.log(shape.__proto__ === circle); // true

Like the above code, maybe it was not set__proto__and more like set.__proto__

var set= {};


问:
Auto-Update for (private) Android apps
I'm developing a non-public Android app, i.e. the app won't be available in the global Android Market. The app will be installed on a limited number of clients, e.g. by using an apk file.
How can I enable an auto-update functionality in this app?

I see different potential options (I do not know if those are technically hard or even impossible to implement or if there are any existing functionalities that can be reused):

On each launch the app tests if a new version exists (by requesting a server), if so downloads the new apk and replaces itself with the new version.

Use (or develop?) a separated app or service that undertakes the update-check and replacement-process.

Use (or develop?) a private market app which has an auto-update option. This option is similar to the second one, but more generic: The market app would be connected to a repository, i.e. it would handle an arbitrary number of (private) apps.

I would prefer option one since the auto-update functionality is included in the app which needs less development efforts.

答:
I think option one is the least amount of work for you, and actually the cleanest one too since it will go through the proper channel of using Android's built-in package installer which includes user notification and the option for the user to abort the installation if desired.

You already have it all outlined - check for a new version on a server (would be nice to give the user the option to turn that off), and if there is a new version, you could either just link to the URL with the APK (which will, IIRC, use the browser's download manager to download it), or you could download it with your app and then point the intent to your local file. Using the HTTP link is technically less work and cleaner - the more you let the operating system do, the better - unless there's a reason not to.

Title: Auto-Update for (private) Android apps


问:
How to format the date in HTML in dd-MM-YYYY format using ng-model
I would like to format the date in HTML as dd-mm-yyyy format in ng-model but the result which I am getting is in the form of mm-dd-yyyy.I have tried using interpolator where it worked fine and I would like to know to get the output in a dd-mm-yyyy format in HTML itself using ng-model.</p>

```<code><label class="item item-input">
  <input placeholder="Date" type="date" date="dd-MM-yyyy" ng-model="vm.advance.date"></input>
</label>
</code>```

答:
Please check the below example.

```<code>angular.module('app', [])

.controller('Ctrl', function($scope){
  $scope.firstDate = new Date();
    $scope.secondDate = "2014-02-20";
})

// Here is where the magic works
.directive('date', function (dateFilter) {
    return {
        require:'ngModel',
        link:function (scope, elm, attrs, ctrl) {

            var dateFormat = attrs['date'] || 'yyyy-MM-dd';

            ctrl.$formatters.unshift(function (modelValue) {
                return dateFilter(modelValue, dateFormat);
            });
        }
    };
})
</code>```

Demo

Body:
I would like to format the date in HTML as dd-mm-yyyy format in ng-model but the result which I am getting is in the form of mm-dd-yyyy.I have tried using interpolator where it worked fine and I would like to know to get the output in a dd-mm-yyyy format in HTML itself using ng-model.

  <input placeholder="Date" type="date" date="dd-MM-yyyy" ng-model="vm.advance.date"></input>

Body:
Please check the below example.

angular.module('app', [])

.controller('Ctrl', function($scope){
  $scope.firstDate = new Date();
    $scope.secondDate = "2014-02-20";
})

// Here is where the magic works
.directive('date', function (dateFilter) {
    return {
        require:'ngModel',
        link:function (scope, elm, attrs, ctrl) {

            var dateFormat = attrs['date'] || 'yyyy-MM-dd';

            ctrl.$formatters.unshift(function (modelValue) {
                return dateFilter(modelValue, dateFormat);
            });
        }
    };
})

Demo


问:
How to parse a csv file encoded in GB18030 with Apache Commons CSV
I have a csv file encoded with GB18030, and I want to use apache commons CSV to parse the file and get the chinese characters inside the file.

How to do this? as I got some wired character using default configuration.

Thanks

答:
It turns out not a Apache Commons CSV package problem. It's java IO reader problem.

```<code>InputStreamReader isr = new InputStreamReader(new FileInputStream(file), Charset.forName("GB18030"));
</code>```

Using specified charset when read file using java would help.

Body:
It turns out not a Apache Commons CSV package problem. It's java IO reader problem.

InputStreamReader isr = new InputStreamReader(new FileInputStream(file), Charset.forName("GB18030"));

Using specified charset when read file using java would help.


问:
Rest Web Service deployment descriptor query java
am working on implementing Rest web service and need clarification on the deployment descriptor file. Below is the web.xml code and what I have understood is that whenever the url contains /webapi/ the ServletContainer class gets invoked. Please correct me if am wrong till this point. Further can you tell me what's the significance of the attributes param-name and param-value. Is it that the package mentioned in the param-value is passed as argument to the ServletContainer class?

```<code><?xml version="1.0" encoding="UTF-8"?>
<!-- This web.xml file is not required when using Servlet 3.0 container,
     see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html -->
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>org.xyz.ws.transporter</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/webapi/*</url-pattern>
    </servlet-mapping>
</web-app>
</code>```

Thanks in advance for your help.

答:
I have understood is that whenever the url contains /webapi/ the ServletContainer class gets invoked.

True.

Further can you tell me what's the significance of the attributes param-name and param-value

init-params are basically just configuration properties that the servlet/filter can use to configure itself.

Here you are configuring a specific property named jersey.config.server.provider.packages, with the value of org.xyz.ws.transporter.  Jersey will use the value of the this specific configuration property to set up package scanning. Jersey will scan the package you specify (recursively) for classes annotated with @Provider and @Path. This allows Jersey to register all resources and provider classes.

Body:
am working on implementing Rest web service and need clarification on the deployment descriptor file. Below is the web.xml code and what I have understood is that whenever the url contains /webapi/ the ServletContainer class gets invoked. Please correct me if am wrong till this point. Further can you tell me what's the significance of the attributes param-name and param-value. Is it that the package mentioned in the param-value is passed as argument to the ServletContainer class?

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>org.xyz.ws.transporter</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/webapi/*</url-pattern>
    </servlet-mapping>
</web-app>

Thanks in advance for your help.


问:
angular2 - infinite loop when i call method from a Angular 2 class inside template
I have a problem when i call a method from component in the template by interpolation: {{get_method()}}. The method runs, but in infinite loop I don't know why. Any help please ??

the code of method is like this :

```<code>get_name() {
  console.log("bonjour");
}
</code>```

and I call it in my template like this :

```<code>{{get_name()}}
</code>```

and this is the result :

答:
You should not use methods in your template, because each time Angular runs change detection, the method will be called, which can happen often. So actually this is not an infinite loop, the method just gets called on each change detection.

To avoid this, you need to change your code to handle the logic of methods in your component, and use variables in your template instead.

Body:
I have a problem when i call a method from component in the template by interpolation: {{get_method()}}. The method runs, but in infinite loop I don't know why. Any help please ??

the code of method is like this :

get_name() {
  console.log("bonjour");
}

and I call it in my template like this :

{{get_name()}}

and this is the result :


问:
How do I get session data in Django?
Basically, what I'm looking for is the Django/Python equivalent to the PHP

```<code>session_start();
print_R($_SESSION);
</code>```

That is, I'd like to dump all the information I currently have stored in the session so I can see what's in there.

答:
Since Django middleware stores all session data in request, we can access the session data in any view.As session is just a python dictionary(key,value pair),all the data can be accessed just like a normal python dictionary.

To store the data in session just do:

```<code>request.session['USER_NAME'] = 'John'
</code>```

Similarly, You can access it anywhere you have request object:

```<code>request.session.get('USER_NAME')
</code>```

So,To see the actual dictionary you can either print or log:

```<code>request.session
</code>```

Title: How do I get session data in Django?

Body:
Basically, what I'm looking for is the Django/Python equivalent to the PHP

session_start();
print_R($_SESSION);

That is, I'd like to dump all the information I currently have stored in the session so I can see what's in there.

Body:
Since Django middleware stores all session data in request, we can access the session data in any view.As session is just a python dictionary(key,value pair),all the data can be accessed just like a normal python dictionary.

To store the data in session just do:

request.session['USER_NAME'] = 'John'

Similarly, You can access it anywhere you have request object:

request.session.get('USER_NAME')

So,To see the actual dictionary you can either print or log:

request.session


问:
Creating a simple menu using while loop in c++
I'm trying to create a simple program in c++ to calculate the mean, sum, max and min value out of 10 numbers. I want to allow the user to click 4 to stop the program. This is the part of my code I need help with:</p>

```<code>void printOut(int max, int min, int avr)
{
    int run = true;
    short choice;

    while(run == true)
        {
    cout<<endl<<"1 = mean "<<endl;
    cout<<"2 = max/min "<<endl;
    cout<<"3 = sum "<<endl;
    cout<<"4 = quit "<<endl;
    cin >> choice;

    if (choice == 1)
    {
        cout<<endl<<"Mean = "<<avr<<endl;

    }
    else if (choice == 2)
    {
        cout<<endl<<"Max = "<<max<<endl<<"Min = "<<min<<endl;
    }
     else if (choice == 3)
    {
        cout<<endl<<"Sum = "<<sum<<endl;
    }
    else if (choice == 4)
    {
        run == false;
    }
    else
    {
        cout << "Error";
    }
        }
}
</code>```

答:
You're using run == instead of run =. 1 = declare, 2 == test.
Also, instead of doing if(run==true) just use if(run), as then if run is true it will show up as true and vice versa, so long as it is a bool.

Body:
I'm trying to create a simple program in c++ to calculate the mean, sum, max and min value out of 10 numbers. I want to allow the user to click 4 to stop the program. This is the part of my code I need help with:

void printOut(int max, int min, int avr)
{
    int run = true;
    short choice;

    while(run == true)
        {
    cout<<endl<<"1 = mean "<<endl;
    cout<<"2 = max/min "<<endl;
    cout<<"3 = sum "<<endl;
    cout<<"4 = quit "<<endl;
    cin >> choice;

    if (choice == 1)
    {
        cout<<endl<<"Mean = "<<avr<<endl;

    }
    else if (choice == 2)
    {
        cout<<endl<<"Max = "<<max<<endl<<"Min = "<<min<<endl;
    }
     else if (choice == 3)
    {
        cout<<endl<<"Sum = "<<sum<<endl;
    }
    else if (choice == 4)
    {
        run == false;
    }
    else
    {
        cout << "Error";
    }
        }
}


问:
Xamarin Amazon S3 Uploads
Has anyone had any experience using Amazon S3 file uploads on Xamarin? It should be simple, but I am having trouble getting it to work. I'm trying to use https://github.com/xamarin/amazon to do my upload of a file like so:

```<code>try
{
    var client = new AmazonS3Client ("REDACTED", "REDACTED");
    var transferUtility = new TransferUtility (client);
    TransferUtilityUploadRequest request = new TransferUtilityUploadRequest()
        .WithBucketName("bucketname")
        .WithFilePath(image.LocalPath)
        .WithKey("rodsTest")
        .WithTimeout(5 * 60 * 1000);
    transferUtility.Upload(request);

} catch (Exception ex){
    Console.WriteLine (ex.ToString ());
}
</code>```

But I'm getting this exception:

System.ObjectDisposedException: The object was used after being disposed. at System.Net.WebConnection.BeginWrite (System.Net.HttpWebRequest request, System.Byte[] buffer, Int32 offset, Int32 size, System.AsyncCallback cb, System.Object state) [0x0001f] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/WebConnection.cs:1033 at System.Net.WebConnectionStream.BeginWrite (System.Byte[] buffer, Int32 offset, Int32 size, System.AsyncCallback cb, System.Object state) [0x0026c] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/WebConnectionStream.cs:541

The github repo hasn't been updated in a year so maybe it's just broken? All I want to do is PUT and DELETE files so my next step is to just hit the REST API with RestSharp rather than use a wrapper but surely this is something others have done, can anyone shed some light?

答:
Check out: amazon s3 file upload using xamarin  c#</p>
```<code>AmazonS3Config config = new AmazonS3Config();
config.ServiceURL = serviceUrl; // amazon s3 URL
config.UseHttp = true;
config.RegionEndpoint =Amazon.RegionEndpoint.APNortheast1; // your region

AmazonS3Client client = new AmazonS3Client(accessKey,
    secretAccessKey, config);

TransferUtility transferUtility = new TransferUtility(client);

TransferUtilityUploadRequest request = new TransferUtilityUploadRequest();
request.BucketName = s3Bucket;
request.FilePath = filePath; // local file path

// Test that the path is correct
UIImage image = UIImage.FromFile(filePath);

System.Threading.CancellationToken cancellationToken = new System.Threading.CancellationToken();
await transferUtility.UploadAsync(request, cancellationToken);
</code>```

Title: Xamarin Amazon S3 Uploads

Body:
Has anyone had any experience using Amazon S3 file uploads on Xamarin? It should be simple, but I am having trouble getting it to work. I'm trying to use https://github.com/xamarin/amazon to do my upload of a file like so:

try
{
    var client = new AmazonS3Client ("REDACTED", "REDACTED");
    var transferUtility = new TransferUtility (client);
    TransferUtilityUploadRequest request = new TransferUtilityUploadRequest()
        .WithBucketName("bucketname")
        .WithFilePath(image.LocalPath)
        .WithKey("rodsTest")
        .WithTimeout(5 * 60 * 1000);
    transferUtility.Upload(request);

} catch (Exception ex){
    Console.WriteLine (ex.ToString ());
}

But I'm getting this exception:

System.ObjectDisposedException: The object was used after being disposed. at System.Net.WebConnection.BeginWrite (System.Net.HttpWebRequest request, System.Byte[] buffer, Int32 offset, Int32 size, System.AsyncCallback cb, System.Object state) [0x0001f] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/WebConnection.cs:1033 at System.Net.WebConnectionStream.BeginWrite (System.Byte[] buffer, Int32 offset, Int32 size, System.AsyncCallback cb, System.Object state) [0x0026c] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/WebConnectionStream.cs:541

The github repo hasn't been updated in a year so maybe it's just broken? All I want to do is PUT and DELETE files so my next step is to just hit the REST API with RestSharp rather than use a wrapper but surely this is something others have done, can anyone shed some light?

Body:
Check out: amazon s3 file upload using xamarin  c#

AmazonS3Config config = new AmazonS3Config();
config.ServiceURL = serviceUrl; // amazon s3 URL
config.UseHttp = true;
config.RegionEndpoint =Amazon.RegionEndpoint.APNortheast1; // your region

AmazonS3Client client = new AmazonS3Client(accessKey,
    secretAccessKey, config);

TransferUtility transferUtility = new TransferUtility(client);

TransferUtilityUploadRequest request = new TransferUtilityUploadRequest();
request.BucketName = s3Bucket;
request.FilePath = filePath; // local file path

// Test that the path is correct
UIImage image = UIImage.FromFile(filePath);

System.Threading.CancellationToken cancellationToken = new System.Threading.CancellationToken();
await transferUtility.UploadAsync(request, cancellationToken);

ContentLicense: CC BY-SA 4.0


问:
Use Sql Server Compact Edition Database File in ReportViewer .Net 4.0
I have finished a Windows Forms application using Sql Server Compact Edition 4, and .Net Framework 4.0. I want to use the database file to create a report in ReportViewer, but I don't know how to do that, when I try to create a new Datasource in the ReportViewer wizard I have a successful connection, but when I press next, the database file isn't recognized, it says Error getting database information and This selector doesn't accept the specified type. I have been searching a lot but I just find code fragments that are marked as solution.

答: You can create a DataSet in code, and use that with the Report Viewer. For a full discussion and link to solution, see https://github.com/ErikEJ/SqlCeToolbox/issues/39 </p>


问:
Correct use of subprocess in python 2.7
I have 2 pdf files to convert into text everyday via terminal, pdftotext module, and from there sort the data with a python script. To save time typing in,for file in *.pdf; do pdftotext -layout "$file"; done into the terminal, I thought I could add it to the top of the following .py script.

I believe subprocess is the answer, but for the life of me I am unable to get it to save a .txt file beside the .pdf the same as pdftotext does via the terminal.

I have tried "Quotes", [Lists] and "Quotes" in [Lists], even tried "usr/lib/pdftotext".

Why does this not work for a pdf in home folder,

```<code>import subprocess

process = subprocess.Popen(['pdftotext', '-layout', 'ALL.pdf', 'ALL.txt'])
</code>```

Thanks

答:
this is what you should do, for more info check subprocess documentation

https://docs.python.org/2/library/subprocess.html

```<code>import os, subprocess

process = subprocess.call('pdftotext -layout ALL.pdf ALL.txt', shell=True, cwd=os.path.expanduser('~'))
</code>```

Title: Correct use of subprocess in python 2.7

Body:
I have 2 pdf files to convert into text everyday via terminal, pdftotext module, and from there sort the data with a python script. To save time typing in,for file in *.pdf; do pdftotext -layout "$file"; done into the terminal, I thought I could add it to the top of the following .py script.

I believe subprocess is the answer, but for the life of me I am unable to get it to save a .txt file beside the .pdf the same as pdftotext does via the terminal.

I have tried "Quotes", [Lists] and "Quotes" in [Lists], even tried "usr/lib/pdftotext".

Why does this not work for a pdf in home folder,

import subprocess

process = subprocess.Popen(['pdftotext', '-layout', 'ALL.pdf', 'ALL.txt'])

Thanks

Body:
this is what you should do, for more info check subprocess documentation

https://docs.python.org/2/library/subprocess.html

import os, subprocess

process = subprocess.call('pdftotext -layout ALL.pdf ALL.txt', shell=True, cwd=os.path.expanduser('~'))


问:
CoreData Basics Help
EDIT:
I have altered the NSPredicate as recommended so that my fetch code look like so. Having printed to the UITextView like this, when I press load it spits out the following:

```<code><NSManagedObject: 0x1c7cf0>(entity: DatedText; id: 0x1420c0 <x - coredata://B52D4F88-0210-4AE2-9DA6-C05ED64FE389/DatedText/p12> ; data: <fault>)
</code>```

So either its not getting any data data because it hasn't been saved/loaded correctly or I am trying to get the loaded result into a UITextView the incorrect way. Any ideas?

```<code>NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
    NSEntityDescription *testEntity = [NSEntityDescription entityForName:@"DatedText" inManagedObjectContext:self.managedObjectContext];
    [fetch setEntity:testEntity];
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"dateSaved == %@", datePicker.date];
    [fetch setPredicate:pred];

    NSError *fetchError = nil;
    NSArray *fetchedObjs = [self.managedObjectContext executeFetchRequest:fetch error:&fetchError];
    if (fetchError != nil) {
        NSLog(@" fetchError=%@,details=%@",fetchError,fetchError.userInfo);
        return nil;
    }
    NSString *object = [NSString stringWithFormat:@"%@",[fetchedObjs objectAtIndex:0]];
    noteTextView.text = object;
</code>```

I have been having all sorts of problems working out how to use Core Data, so I have gone back to basics, new window based ipad project using core data.

I have added a view and some code which doesn't work, hehe. Im basically trying to save some text to a date, then when going back to that date, the text which was previously saved will be shown again.

答:
I checked your project and aside from having to synthesize the CoreData properties, I also just noticed you were trying to assign an NSArray to your fetch predicate, but it actually expects an NSPredicate object. You should use this instead:

```<code>NSPredicate *pred = [NSPredicate predicateWithFormat:@"(dateSaved == %@)", datePicker.date];
[fetch setPredicate:pred];
</code>```

If you want to set more than 1 predicate you should do that on your predicate string i.e.

```<code>NSPredicate *pred = [NSPredicate predicateWithFormat:@"(dateSaved == %@) AND (dateSaved <= %@", datePicker.date, [NSDate date]];
</code>```

Cheers,
Rog

Title: CoreData Basics Help

Body:
EDIT:
I have altered the NSPredicate as recommended so that my fetch code look like so. Having printed to the UITextView like this, when I press load it spits out the following:

<NSManagedObject: 0x1c7cf0>(entity: DatedText; id: 0x1420c0 <x - coredata://B52D4F88-0210-4AE2-9DA6-C05ED64FE389/DatedText/p12> ; data: <fault>)

So either its not getting any data data because it hasn't been saved/loaded correctly or I am trying to get the loaded result into a UITextView the incorrect way. Any ideas?

NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
    NSEntityDescription *testEntity = [NSEntityDescription entityForName:@"DatedText" inManagedObjectContext:self.managedObjectContext];
    [fetch setEntity:testEntity];
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"dateSaved == %@", datePicker.date];
    [fetch setPredicate:pred];

    NSError *fetchError = nil;
    NSArray *fetchedObjs = [self.managedObjectContext executeFetchRequest:fetch error:&fetchError];
    if (fetchError != nil) {
        NSLog(@" fetchError=%@,details=%@",fetchError,fetchError.userInfo);
        return nil;
    }
    NSString *object = [NSString stringWithFormat:@"%@",[fetchedObjs objectAtIndex:0]];
    noteTextView.text = object;

I have been having all sorts of problems working out how to use Core Data, so I have gone back to basics, new window based ipad project using core data.

I have added a view and some code which doesn't work, hehe. Im basically trying to save some text to a date, then when going back to that date, the text which was previously saved will be shown again.

Body:
I checked your project and aside from having to synthesize the CoreData properties, I also just noticed you were trying to assign an NSArray to your fetch predicate, but it actually expects an NSPredicate object. You should use this instead:

NSPredicate *pred = [NSPredicate predicateWithFormat:@"(dateSaved == %@)", datePicker.date];
[fetch setPredicate:pred];

If you want to set more than 1 predicate you should do that on your predicate string i.e.

NSPredicate *pred = [NSPredicate predicateWithFormat:@"(dateSaved == %@) AND (dateSaved <= %@", datePicker.date, [NSDate date]];

Cheers,
Rog


问:
get_field() returns wrong data
I am using ACF repeater fields and I am trying to write a function which counts the number of rows of the repeater. The function returns 1 even if the number of rows in a repeater are 0 or more than 0.
Can someone help me to fix this ?

```<code>$rows = get_field('sub_seminars');
$row_count = count($rows);
echo count($row_count);
</code>```

A var_dump also returns int(1) even if the number of rows in a repeater are 0 or more than 0.

答:
Let's have a look at your code:

```<code>$rows = get_field('sub_seminars');
$row_count = count($rows);  //returning some digit
echo count($row_count);  //counting the returned digit
</code>```

You are double counting the returned count and that is why it is returning 1. Try this:

```<code>$rows = get_field('sub_seminars');
$row_count = count($rows);     //will return a digit
echo $row_count;  //echo the count
</code>```

Title: get_field() returns wrong data

Body:
I am using ACF repeater fields and I am trying to write a function which counts the number of rows of the repeater. The function returns 1 even if the number of rows in a repeater are 0 or more than 0.
Can someone help me to fix this ?

$rows = get_field('sub_seminars');
$row_count = count($rows);
echo count($row_count);

A var_dump also returns int(1) even if the number of rows in a repeater are 0 or more than 0.

Body:
Let's have a look at your code:

$rows = get_field('sub_seminars');
$row_count = count($rows);  //returning some digit
echo count($row_count);  //counting the returned digit

You are double counting the returned count and that is why it is returning 1. Try this:

$rows = get_field('sub_seminars');
$row_count = count($rows);     //will return a digit
echo $row_count;  //echo the count


问:
Change existing row of database by query in java
I want to update a row in mysql...for that I used update query when update button pressed, but it not works...even not getting any error...So difficult to find out why it not works?</p>

```<code>public void actionPerformed(ActionEvent arg0)
{
    try
    {
        String b="";
        String query1="update salesbill set `TaxAmount`='"+b+"' where SONumber = ?";
        PreparedStatement   pst=conn.prepareStatement(query1);
        pst.setString(1,sonum.getText()); //sonum is textfield where values passed for SONumber

        pst.setString(1, amt.getText());    //amt istextfield variable
        b=amt.getText();

        System.out.println(query1);

        pst.execute();
    }
    catch(Exception g)
    {
        g.printStackTrace();
    }
}
</code>```

答:
You need to comment-out

```<code> pst.setString(1, amt.getText());
</code>```

As it is overwriting

```<code>pst.setString(1,sonum.getText());
</code>```

And, your query expects SONumber

==Updated==

As OP mentioned in his/her comment that, he/she was trying to update TaxAmount which is amt.getText(). So, updated my post.

```<code>String query1="update salesbill set `TaxAmount`=? where SONumber = ?";
PreparedStatement   pst=conn.prepareStatement(query1);
pst.setString(1, amt.getText());
pst.setString(2,sonum.getText()); //sonum is textfield where values passed for SONumber
pst.execute();
</code>```

Please refer PreparedStatement, to use appropriate method to set your value.

Body:
I want to update a row in mysql...for that I used update query when update button pressed, but it not works...even not getting any error...So difficult to find out why it not works?

public void actionPerformed(ActionEvent arg0)
{
    try
    {
        String b="";
        String query1="update salesbill set `TaxAmount`='"+b+"' where SONumber = ?";
        PreparedStatement   pst=conn.prepareStatement(query1);
        pst.setString(1,sonum.getText()); //sonum is textfield where values passed for SONumber

        pst.setString(1, amt.getText());    //amt istextfield variable
        b=amt.getText();

        System.out.println(query1);

        pst.execute();
    }
    catch(Exception g)
    {
        g.printStackTrace();
    }
}

Body:
You need to comment-out

 pst.setString(1, amt.getText());

As it is overwriting

pst.setString(1,sonum.getText());

And, your query expects SONumber

==Updated==

As OP mentioned in his/her comment that, he/she was trying to update TaxAmount which is amt.getText(). So, updated my post.

String query1="update salesbill set `TaxAmount`=? where SONumber = ?";
PreparedStatement   pst=conn.prepareStatement(query1);
pst.setString(1, amt.getText());
pst.setString(2,sonum.getText()); //sonum is textfield where values passed for SONumber
pst.execute();

Please refer PreparedStatement, to use appropriate method to set your value.


问:
Testing that a print function works (C)
I am trying to make a main function which will test a whole bunch of other functions to make sure that they work. That is, if they contain bugs, return 1, if no bugs, return 0

Suppose one of the functions I am trying to test is the following:

```<code>void list_print(list_t*list);
</code>```

this should print a list in "human-readable form" from first to last elements, between curly braces.

Now, naturally I could simply print an array and see for myself that it looks good, but I need to do this so that it is automatic, i.e. if the print function prints accurately, return 0, otherwise, return 1.

How do I go about doing this (in a general sort of way)? I keep googling and can't really find the answer.

答:
I recommend that you redirect stdout to a buffer in memory using freopen and setbuf, as they describe in this question. Then, run the list_print method.

Then you can compare the contents of your buffer with what you would expect to see. You can be strict on this step or you can use heuristics to try to identify a generally accepted pattern of output that is acceptable.

I don't think there is a better way to "see" what is output to the terminal, except for un-portable OS-specific libraries.

If you post your working attempt then I can help you out more with a concrete code example.

Title: Testing that a print function works (C)

Body:
I am trying to make a main function which will test a whole bunch of other functions to make sure that they work. That is, if they contain bugs, return 1, if no bugs, return 0

Suppose one of the functions I am trying to test is the following:

void list_print(list_t*list);

this should print a list in "human-readable form" from first to last elements, between curly braces.

Now, naturally I could simply print an array and see for myself that it looks good, but I need to do this so that it is automatic, i.e. if the print function prints accurately, return 0, otherwise, return 1.

How do I go about doing this (in a general sort of way)? I keep googling and can't really find the answer.


问:
Counting repeated characters in a string in Python
I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z
and incrementing a counter?

Update (in reference to Anthony's answer): Whatever you have suggested till now I have to write 26 times. Is there an easier way?

答:
Grand Performance Comparison

Scroll to the end for a TL;DR graph

Since I had "nothing better to do" (understand: I had just a lot of work), I decided to do
a little performance contest. I assembled the most sensible or interesting answers and did
some simple timeit in CPython 3.5.1 on them. I tested them with only one string, which
is a typical input in my case:

```<code>>>> s = 'ZDXMZKMXFDKXZFKZ'
>>> len(s)
16
</code>```

Be aware that results might vary for different inputs, be it different length of the string or
different number of distinct characters, or different average number of occurrences per character.

Don't reinvent the wheel

Python has made it simple for us. The collections.Counter class does exactly what we want
and a lot more. Its usage is by far the simplest of all the methods mentioned here.

taken from @oefe, nice find

```<code>>>> timeit('Counter(s)', globals=locals())
8.208566107001388
</code>```

Counter goes the extra mile, which is why it takes so long.

¿Dictionary, comprende?

Let's try using a simple dict instead. First, let's do it declaratively, using dict
comprehension.

I came up with this myself...

```<code>>>> timeit('{c: s.count(c) for c in s}', globals=locals())
4.551155784000002
</code>```

This will go through s from beginning to end, and for each character it will count the number
of its occurrences in s. Since s contains duplicate characters, the above method searches
s several times for the same character. The result is naturally always the same. So let's count
the number of occurrences just once for each character.

I came up with this myself, and so did @IrshadBhat

```<code>>>> timeit('{c: s.count(c) for c in set(s)}', globals=locals())
3.1484066140001232
</code>```

Better. But we still have to search through the string to count the occurrences. One search for
each distinct character. That means we're going to read the string more than once. We can do
better than that! But for that, we have to get off our declarativist high horse and descend into
an imperative mindset.

Exceptional code

AKA Gotta catch 'em all!

inspired by @anthony

```<code>>>> timeit('''
... d = {}
... for c in s:
...   try:
...     d[c] += 1
...   except KeyError:
...     d[c] = 1
... ''', globals=locals())
3.7060273620008957
</code>```

Well, it was worth a try. If you dig into the Python source (I can't say with certainty because
I have never really done that), you will probably find that when you do except ExceptionType,
Python has to check whether the exception raised is actually of ExceptionType or some other
type. Just for the heck of it, let's see how long will it take if we omit that check and catch
all exceptions.

made by @anthony

```<code>>>> timeit('''
... d = {}
... for c in s:
...   try:
...     d[c] += 1
...   except:
...     d[c] = 1
... ''', globals=locals())
3.3506563019982423
</code>```

It does save some time, so one might be tempted to use this as some sort of optimization.

Don't do that! Or actually do. Do it now:

INTERLUDE 1

```<code>import time
while True:
  try:
    time.sleep(1)
  except:
    print("You're trapped in your own trap!")
</code>```

You see? It catches KeyboardInterrupt, besides other things. In fact, it catches all the
exceptions there are. Including ones you might not have even heard about, like SystemExit.

INTERLUDE 2

```<code>import sys
try:
  print("Goodbye. I'm going to die soon.")
  sys.exit()
except:
  print('BACK FROM THE DEAD!!!')
</code>```

Now back to counting letters and numbers and other characters.

Playing catch-up

Exceptions aren't the way to go. You have to try hard to catch up with them, and when you finally
do, they just throw up on you and then raise their eyebrows like it's your fault. Luckily brave
fellows have paved our way so we can do away with exceptions, at least in this little exercise.

The dict class has a nice method – get – which allows us to retrieve an item from a
dictionary, just like d[k]. Except when the key k is not in the dictionary, it can return
a default value. Let's use that method instead of fiddling with exceptions.

credit goes to @Usman

```<code>>>> timeit('''
... d = {}
... for c in s:
...   d[c] = d.get(c, 0) + 1
... ''', globals=locals())
3.2133633289995487
</code>```

Almost as fast as the set-based dict comprehension. On larger inputs, this one would probably be
even faster.

Use the right tool for the job

For at least mildly knowledgeable Python programmer, the first thing that comes to mind is
probably defaultdict. It does pretty much the same thing as the version above, except instead
of a value, you give it a value factory. That might cause some overhead, because the value has
to be "constructed" for each missing key individually. Let's see how it performs.

hope @AlexMartelli won't crucify me for from collections import defaultdict

```<code>>>> timeit('''
... dd = defaultdict(int)
... for c in s:
...   dd[c] += 1
... ''', globals=locals())
3.3430528169992613
</code>```

Not that bad. I'd say the increase in execution time is a small tax to pay for the improved
readability. However, we also favor performance, and we will not stop here. Let's take it further
and prepopulate the dictionary with zeros. Then we won't have to check every time if the item
is already there.

hats off to @sqram

```<code>>>> timeit('Counter(s)', globals=locals())
8.208566107001388
</code>```0

That's good. Over three times as fast as Counter, yet still simple enough. Personally, this is
my favorite in case you don't want to add new characters later. And even if you do, you can
still do it. It's just less convenient than it would be in other versions:

```<code>>>> timeit('Counter(s)', globals=locals())
8.208566107001388
</code>```1

Practicality beats purity (except when it's not really practical)

Now a bit different kind of counter. @IdanK has come up with something interesting. Instead
of using a hash table (a.k.a. dictionary a.k.a. dict), we can avoid the risk of hash collisions
and consequent overhead of their resolution. We can also avoid the overhead of hashing the key,
and the extra unoccupied table space. We can use a list. The ASCII values of characters will be
indices and their counts will be values. As @IdanK has pointed out, this list gives us constant
time access to a character's count. All we have to do is convert each character from str to
int using the built-in function ord. That will give us an index into the list, which we will
then use to increment the count of the character. So what we do is this: we initialize the list
with zeros, do the job, and then convert the list into a dict. This dict will only contain
those characters which have non-zero counts, in order to make it compliant with other versions.

As a side note, this technique is used in a linear-time sorting algorithm known as
count sort or counting sort. It's very efficient, but the range of values being sorted
is limited, since each value has to have its own counter. To sort a sequence of 32-bit integers,
4.3 billion counters would be needed.

```<code>>>> timeit('Counter(s)', globals=locals())
8.208566107001388
</code>```2

Ouch! Not cool! Let's try and see how long it takes when we omit building the dictionary.

```<code>>>> timeit('Counter(s)', globals=locals())
8.208566107001388
</code>```3

Still bad. But wait, what's [0 for _ in range(256)]? Can't we write it more simply? How about
[0] * 256? That's cleaner. But will it perform better?

```<code>>>> timeit('Counter(s)', globals=locals())
8.208566107001388
</code>```4

Considerably. Now let's put the dictionary back in.

```<code>>>> timeit('Counter(s)', globals=locals())
8.208566107001388
</code>```5

Almost six times slower. Why does it take so long? Because when we enumerate(counts), we have
to check every one of the 256 counts and see if it's zero. But we already know which counts are
zero and which are not.

```<code>>>> timeit('Counter(s)', globals=locals())
8.208566107001388
</code>```6

It probably won't get much better than that, at least not for such a small input. Plus it's only
usable for 8-bit EASCII characters. О блять!

And the winner is...

```<code>>>> timeit('Counter(s)', globals=locals())
8.208566107001388
</code>```7

Yep. Even if you have to check every time whether c is in d, for this input it's the fastest
way. No pre-population of d will make it faster (again, for this input). It's a lot more
verbose than Counter or defaultdict, but also more efficient.

That's all folks

This little exercise teaches us a lesson: when optimizing, always measure performance, ideally
with your expected inputs. Optimize for the common case. Don't presume something is actually
more efficient just because its asymptotic complexity is lower. And last but not least, keep
readability in mind. Try to find a compromise between "computer-friendly" and "human-friendly".

UPDATE

I have been informed by @MartijnPieters of the function collections._count_elements
available in Python 3.

```<code>>>> timeit('Counter(s)', globals=locals())
8.208566107001388
</code>```8

This function is implemented in C, so it should be faster, but this extra performance comes
at a price. The price is incompatibility with Python 2 and possibly even future versions, since
we're using a private function.

From the documentation:

[...] a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part
  of the API (whether it is a function, a method or a data member).
  It should be considered an implementation detail and subject to change without notice.

That said, if you still want to save those 620 nanoseconds per iteration:

```<code>>>> timeit('Counter(s)', globals=locals())
8.208566107001388
</code>```9

UPDATE 2: Large strings

I thought it might be a good idea to re-run the tests on some larger input, since a 16 character
string is such a small input that all the possible solutions were quite comparably fast
(1,000 iterations in under 30 milliseconds).

I decided to use the complete works of Shakespeare as a testing corpus,
which turned out to be quite a challenge (since it's over 5MiB in size ). I just used the first
100,000 characters of it, and  I had to limit the number of iterations from 1,000,000 to 1,000.

```<code>>>> timeit('{c: s.count(c) for c in s}', globals=locals())
4.551155784000002
</code>```0

collections.Counter was really slow on a small input, but the tables have turned

```<code>>>> timeit('{c: s.count(c) for c in s}', globals=locals())
4.551155784000002
</code>```1

Naïve Θ(n2) time dictionary comprehension simply doesn't work

```<code>>>> timeit('{c: s.count(c) for c in s}', globals=locals())
4.551155784000002
</code>```2

Smart Θ(n) time dictionary comprehension works fine

```<code>{c: s.count(c) for c in set(s)}

=> 8.882608592999986
</code>```

Exceptions are clumsy and slow

```<code>d = {}
for c in s:
  try:
    d[c] += 1
  except KeyError:
    d[c] = 1

=> 21.26615508399982
</code>```

Omitting the exception type check doesn't save time (since the exception is only thrown
a few times)

```<code>d = {}
for c in s:
  try:
    d[c] += 1
  except:
    d[c] = 1

=> 21.943328911999743
</code>```

dict.get looks nice but runs slow

```<code>d = {}
for c in s:
  d[c] = d.get(c, 0) + 1

=> 28.530086210000007
</code>```

collections.defaultdict isn't very fast either

```<code>dd = defaultdict(int)
for c in s:
  dd[c] += 1

=> 19.43012963199999
</code>```

dict.fromkeys requires reading the (very long) string twice

```<code>d = dict.fromkeys(s, 0)
for c in s:
  d[c] += 1

=> 22.70960557699999
</code>```

Using list instead of dict is neither nice nor fast

```<code>counts = [0 for _ in range(256)]
for c in s:
  counts[ord(c)] += 1

d = {chr(i): count for i,count in enumerate(counts) if count != 0}

=> 26.535474792000002
</code>```

Leaving out the final conversion to dict doesn't help

```<code>>>> timeit('{c: s.count(c) for c in set(s)}', globals=locals())
3.1484066140001232
</code>```0

It doesn't matter how you construct the list, since it's not the bottleneck

```<code>>>> timeit('{c: s.count(c) for c in set(s)}', globals=locals())
3.1484066140001232
</code>```1

```<code>>>> timeit('{c: s.count(c) for c in set(s)}', globals=locals())
3.1484066140001232
</code>```2

If you convert list to dict the "smart" way, it's even slower (since you iterate over
the string twice)

```<code>>>> timeit('{c: s.count(c) for c in set(s)}', globals=locals())
3.1484066140001232
</code>```3

The dict.__contains__ variant may be fast for small strings, but not so much for big ones

```<code>>>> timeit('{c: s.count(c) for c in set(s)}', globals=locals())
3.1484066140001232
</code>```4

collections._count_elements is about as fast as collections.Counter (which uses
_count_elements internally)

```<code>>>> timeit('{c: s.count(c) for c in set(s)}', globals=locals())
3.1484066140001232
</code>```5

Final verdict: Use collections.Counter unless you cannot or don't want to :)

Appendix: NumPy

The numpy package provides a method numpy.unique which accomplishes (almost)
precisely what we want.

The way this method works is very different from all the above methods:

It first sorts a copy of the input using Quicksort, which is an O(n2) time
operation in the worst case, albeit O(n log n) on average and O(n) in the best case.

Then it creates a "mask" array containing True at indices where a run of the same values
begins, viz. at indices where the value differs from the previous value. Repeated values produce
False in the mask. Example: [5,5,5,8,9,9] produces a mask
[True, False, False, True, True, False].

This mask is then used to extract the unique values from the sorted input ‒ unique_chars in
the code below. In our example, they would be [5, 8, 9].

Positions of the True values in the mask are taken into an array, and the length of the input
is appended at the end of this array. For the above example, this array would be [0, 3, 4, 6].

For this array, differences between its elements are calculated, eg. [3, 1, 2]. These are the
respective counts of the elements in the sorted array ‒ char_counts in the code below.

Finally, we create a dictionary by zipping unique_chars and char_counts:
{5: 3, 8: 1, 9: 2}.

```<code>>>> timeit('{c: s.count(c) for c in set(s)}', globals=locals())
3.1484066140001232
</code>```6

For the test input (first 100,000 characters of the complete works of Shakespeare), this method performs better than any other tested here. But note that on
a different input, this approach might yield worse performance than the other methods.
Pre-sortedness of the input and number of repetitions per element are important factors affecting
the performance.

```<code>>>> timeit('{c: s.count(c) for c in set(s)}', globals=locals())
3.1484066140001232
</code>```7

If you are thinking about using this method because it's over twice as fast as
collections.Counter, consider this:

collections.Counter has linear time complexity. numpy.unique is linear at best, quadratic
at worst.

The speedup is not really that significant ‒ you save ~3.5 milliseconds per iteration
on an input of length 100,000.

Using numpy.unique obviously requires numpy.

That considered, it seems reasonable to use Counter unless you need to be really fast. And in
that case, you better know what you're doing or else you'll end up being slower with numpy than
without it.

Appendix 2: A somewhat useful plot

I ran the 13 different methods above on prefixes of the complete works of Shakespeare and made an interactive plot. Note that in the plot, both prefixes and durations are displayed in logarithmic scale (the used prefixes are of exponentially increasing length). Click on the items in the legend to show/hide them in the plot.

Click to open!

Body:
Grand Performance Comparison

Scroll to the end for a TL;DR graph

Since I had "nothing better to do" (understand: I had just a lot of work), I decided to do
a little performance contest. I assembled the most sensible or interesting answers and did
some simple timeit in CPython 3.5.1 on them. I tested them with only one string, which
is a typical input in my case:

>>> s = 'ZDXMZKMXFDKXZFKZ'
>>> len(s)
16

Be aware that results might vary for different inputs, be it different length of the string or
different number of distinct characters, or different average number of occurrences per character.

Don't reinvent the wheel

Python has made it simple for us. The collections.Counter class does exactly what we want
and a lot more. Its usage is by far the simplest of all the methods mentioned here.

taken from @oefe, nice find

>>> timeit('Counter(s)', globals=locals())
8.208566107001388

Counter goes the extra mile, which is why it takes so long.

¿Dictionary, comprende?

Let's try using a simple dict instead. First, let's do it declaratively, using dict
comprehension.

I came up with this myself...

>>> timeit('{c: s.count(c) for c in s}', globals=locals())
4.551155784000002

This will go through s from beginning to end, and for each character it will count the number
of its occurrences in s. Since s contains duplicate characters, the above method searches
s several times for the same character. The result is naturally always the same. So let's count
the number of occurrences just once for each character.

I came up with this myself, and so did @IrshadBhat

>>> timeit('{c: s.count(c) for c in set(s)}', globals=locals())
3.1484066140001232

Better. But we still have to search through the string to count the occurrences. One search for
each distinct character. That means we're going to read the string more than once. We can do
better than that! But for that, we have to get off our declarativist high horse and descend into
an imperative mindset.

Exceptional code

AKA Gotta catch 'em all!

inspired by @anthony

>>> timeit('''
... d = {}
... for c in s:
...   try:
...     d[c] += 1
...   except KeyError:
...     d[c] = 1
... ''', globals=locals())
3.7060273620008957

Well, it was worth a try. If you dig into the Python source (I can't say with certainty because
I have never really done that), you will probably find that when you do except ExceptionType,
Python has to check whether the exception raised is actually of ExceptionType or some other
type. Just for the heck of it, let's see how long will it take if we omit that check and catch
all exceptions.

made by @anthony

>>> timeit('''
... d = {}
... for c in s:
...   try:
...     d[c] += 1
...   except:
...     d[c] = 1
... ''', globals=locals())
3.3506563019982423

It does save some time, so one might be tempted to use this as some sort of optimization.

Don't do that! Or actually do. Do it now:

INTERLUDE 1

import time
while True:
  try:
    time.sleep(1)
  except:
    print("You're trapped in your own trap!")

You see? It catches KeyboardInterrupt, besides other things. In fact, it catches all the
exceptions there are. Including ones you might not have even heard about, like SystemExit.

INTERLUDE 2

import sys
try:
  print("Goodbye. I'm going to die soon.")
  sys.exit()
except:
  print('BACK FROM THE DEAD!!!')

Now back to counting letters and numbers and other characters.

Playing catch-up

Exceptions aren't the way to go. You have to try hard to catch up with them, and when you finally
do, they just throw up on you and then raise their eyebrows like it's your fault. Luckily brave
fellows have paved our way so we can do away with exceptions, at least in this little exercise.

The dict class has a nice method – get – which allows us to retrieve an item from a
dictionary, just like d[k]. Except when the key k is not in the dictionary, it can return
a default value. Let's use that method instead of fiddling with exceptions.

credit goes to @Usman

>>> timeit('''
... d = {}
... for c in s:
...   d[c] = d.get(c, 0) + 1
... ''', globals=locals())
3.2133633289995487

Almost as fast as the set-based dict comprehension. On larger inputs, this one would probably be
even faster.

Use the right tool for the job

For at least mildly knowledgeable Python programmer, the first thing that comes to mind is
probably defaultdict. It does pretty much the same thing as the version above, except instead
of a value, you give it a value factory. That might cause some overhead, because the value has
to be "constructed" for each missing key individually. Let's see how it performs.

hope @AlexMartelli won't crucify me for from collections import defaultdict

>>> timeit('''
... dd = defaultdict(int)
... for c in s:
...   dd[c] += 1
... ''', globals=locals())
3.3430528169992613

Not that bad. I'd say the increase in execution time is a small tax to pay for the improved
readability. However, we also favor performance, and we will not stop here. Let's take it further
and prepopulate the dictionary with zeros. Then we won't have to check every time if the item
is already there.

hats off to @sqram

>>> timeit('''
... d = dict.fromkeys(s, 0)
... for c in s:
...   d[c] += 1
... ''', globals=locals())
2.6081761489986093

That's good. Over three times as fast as Counter, yet still simple enough. Personally, this is
my favorite in case you don't want to add new characters later. And even if you do, you can
still do it. It's just less convenient than it would be in other versions:

d.update({ c: 0 for c in set(other_string) - d.keys() })

Practicality beats purity (except when it's not really practical)

Now a bit different kind of counter. @IdanK has come up with something interesting. Instead
of using a hash table (a.k.a. dictionary a.k.a. dict), we can avoid the risk of hash collisions
and consequent overhead of their resolution. We can also avoid the overhead of hashing the key,
and the extra unoccupied table space. We can use a list. The ASCII values of characters will be
indices and their counts will be values. As @IdanK has pointed out, this list gives us constant
time access to a character's count. All we have to do is convert each character from str to
int using the built-in function ord. That will give us an index into the list, which we will
then use to increment the count of the character. So what we do is this: we initialize the list
with zeros, do the job, and then convert the list into a dict. This dict will only contain
those characters which have non-zero counts, in order to make it compliant with other versions.

As a side note, this technique is used in a linear-time sorting algorithm known as
count sort or counting sort. It's very efficient, but the range of values being sorted
is limited, since each value has to have its own counter. To sort a sequence of 32-bit integers,
4.3 billion counters would be needed.

>>> timeit('''
... counts = [0 for _ in range(256)]
... for c in s:
...   counts[ord(c)] += 1
... d = {chr(i): count for i,count in enumerate(counts) if count != 0}
... ''', globals=locals())
25.438595562001865

Ouch! Not cool! Let's try and see how long it takes when we omit building the dictionary.

>>> timeit('''
... counts = [0 for _ in range(256)]
... for c in s:
...   counts[ord(c)] += 1
... ''', globals=locals())
10.564866792999965

Still bad. But wait, what's [0 for _ in range(256)]? Can't we write it more simply? How about
[0] * 256? That's cleaner. But will it perform better?

>>> timeit('''
... counts = [0] * 256
... for c in s:
...   counts[ord(c)] += 1
... ''', globals=locals())
3.290163638001104

Considerably. Now let's put the dictionary back in.

>>> timeit('''
... counts = [0] * 256
... for c in s:
...   counts[ord(c)] += 1
... d = {chr(i): count for i,count in enumerate(counts) if count != 0}
... ''', globals=locals())
18.000623562998953

Almost six times slower. Why does it take so long? Because when we enumerate(counts), we have
to check every one of the 256 counts and see if it's zero. But we already know which counts are
zero and which are not.

>>> timeit('''
... counts = [0] * 256
... for c in s:
...   counts[ord(c)] += 1
... d = {c: counts[ord(c)] for c in set(s)}
... ''', globals=locals())
5.826531438000529

It probably won't get much better than that, at least not for such a small input. Plus it's only
usable for 8-bit EASCII characters. О блять!

And the winner is...

>>> timeit('''
... d = {}
... for c in s:
...   if c in d:
...     d[c] += 1
...   else:
...     d[c] = 1
... ''', globals=locals())
1.8509794599995075

Yep. Even if you have to check every time whether c is in d, for this input it's the fastest
way. No pre-population of d will make it faster (again, for this input). It's a lot more
verbose than Counter or defaultdict, but also more efficient.

That's all folks

This little exercise teaches us a lesson: when optimizing, always measure performance, ideally
with your expected inputs. Optimize for the common case. Don't presume something is actually
more efficient just because its asymptotic complexity is lower. And last but not least, keep
readability in mind. Try to find a compromise between "computer-friendly" and "human-friendly".

UPDATE

I have been informed by @MartijnPieters of the function collections._count_elements
available in Python 3.

Help on built-in function _count_elements in module _collections:

_count_elements(...)
    _count_elements(mapping, iterable) -> None

    Count elements in the iterable, updating the mappping

This function is implemented in C, so it should be faster, but this extra performance comes
at a price. The price is incompatibility with Python 2 and possibly even future versions, since
we're using a private function.

From the documentation:

[...] a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part
  of the API (whether it is a function, a method or a data member).
  It should be considered an implementation detail and subject to change without notice.

That said, if you still want to save those 620 nanoseconds per iteration:

>>> timeit('''
... d = {}
... _count_elements(d, s)
... ''', globals=locals())
1.229239897998923

UPDATE 2: Large strings

I thought it might be a good idea to re-run the tests on some larger input, since a 16 character
string is such a small input that all the possible solutions were quite comparably fast
(1,000 iterations in under 30 milliseconds).

I decided to use the complete works of Shakespeare as a testing corpus,
which turned out to be quite a challenge (since it's over 5MiB in size ). I just used the first
100,000 characters of it, and  I had to limit the number of iterations from 1,000,000 to 1,000.

import urllib.request
url = 'https://ocw.mit.edu/ans7870/6/6.006/s08/lecturenotes/files/t8.shakespeare.txt'
s = urllib.request.urlopen(url).read(100_000)

collections.Counter was really slow on a small input, but the tables have turned

Counter(s)

=> 7.63926783799991

Naïve Θ(n2) time dictionary comprehension simply doesn't work

{c: s.count(c) for c in s}

=> 15347.603935000052s (tested on 10 iterations; adjusted for 1000)

Smart Θ(n) time dictionary comprehension works fine

{c: s.count(c) for c in set(s)}

=> 8.882608592999986

Exceptions are clumsy and slow

d = {}
for c in s:
  try:
    d[c] += 1
  except KeyError:
    d[c] = 1

=> 21.26615508399982

Omitting the exception type check doesn't save time (since the exception is only thrown
a few times)

d = {}
for c in s:
  try:
    d[c] += 1
  except:
    d[c] = 1

=> 21.943328911999743

dict.get looks nice but runs slow

d = {}
for c in s:
  d[c] = d.get(c, 0) + 1

=> 28.530086210000007

collections.defaultdict isn't very fast either

dd = defaultdict(int)
for c in s:
  dd[c] += 1

=> 19.43012963199999

dict.fromkeys requires reading the (very long) string twice

d = dict.fromkeys(s, 0)
for c in s:
  d[c] += 1

=> 22.70960557699999

Using list instead of dict is neither nice nor fast

counts = [0 for _ in range(256)]
for c in s:
  counts[ord(c)] += 1

d = {chr(i): count for i,count in enumerate(counts) if count != 0}

=> 26.535474792000002

Leaving out the final conversion to dict doesn't help

counts = [0 for _ in range(256)]
for c in s:
  counts[ord(c)] += 1

=> 26.27811567400005

It doesn't matter how you construct the list, since it's not the bottleneck

counts = [0] * 256
for c in s:
  counts[ord(c)] += 1

=> 25.863524940000048

counts = [0] * 256
for c in s:
  counts[ord(c)] += 1

d = {chr(i): count for i,count in enumerate(counts) if count != 0}

=> 26.416733378000004

If you convert list to dict the "smart" way, it's even slower (since you iterate over
the string twice)

counts = [0] * 256
for c in s:
  counts[ord(c)] += 1

d = {c: counts[ord(c)] for c in set(s)}

=> 29.492915620000076

The dict.__contains__ variant may be fast for small strings, but not so much for big ones

d = {}
for c in s:
  if c in d:
    d[c] += 1
  else:
    d[c] = 1

=> 23.773295123000025

collections._count_elements is about as fast as collections.Counter (which uses
_count_elements internally)

d = {}
_count_elements(d, s)

=> 7.5814381919999505

Final verdict: Use collections.Counter unless you cannot or don't want to :)

Appendix: NumPy

The numpy package provides a method numpy.unique which accomplishes (almost)
precisely what we want.

The way this method works is very different from all the above methods:

It first sorts a copy of the input using Quicksort, which is an O(n2) time
operation in the worst case, albeit O(n log n) on average and O(n) in the best case.

Then it creates a "mask" array containing True at indices where a run of the same values
begins, viz. at indices where the value differs from the previous value. Repeated values produce
False in the mask. Example: [5,5,5,8,9,9] produces a mask
[True, False, False, True, True, False].

This mask is then used to extract the unique values from the sorted input ‒ unique_chars in
the code below. In our example, they would be [5, 8, 9].

Positions of the True values in the mask are taken into an array, and the length of the input
is appended at the end of this array. For the above example, this array would be [0, 3, 4, 6].

For this array, differences between its elements are calculated, eg. [3, 1, 2]. These are the
respective counts of the elements in the sorted array ‒ char_counts in the code below.

Finally, we create a dictionary by zipping unique_chars and char_counts:
{5: 3, 8: 1, 9: 2}.

import numpy as np

def count_chars(s):
  # The following statement needs to be changed for different input types.
  # Our input `s` is actually of type `bytes`, so we use `np.frombuffer`.
  # For inputs of type `str`, change `np.frombuffer` to `np.fromstring`
  #  or transform the input into a `bytes` instance.
  arr = np.frombuffer(s, dtype=np.uint8)

  unique_chars, char_counts = np.unique(arr, return_counts=True)

  return dict(zip(unique_chars, char_counts))

For the test input (first 100,000 characters of the complete works of Shakespeare), this method performs better than any other tested here. But note that on
a different input, this approach might yield worse performance than the other methods.
Pre-sortedness of the input and number of repetitions per element are important factors affecting
the performance.

count_chars(s)

=> 2.960809530000006

If you are thinking about using this method because it's over twice as fast as
collections.Counter, consider this:

collections.Counter has linear time complexity. numpy.unique is linear at best, quadratic
at worst.

The speedup is not really that significant ‒ you save ~3.5 milliseconds per iteration
on an input of length 100,000.

Using numpy.unique obviously requires numpy.

That considered, it seems reasonable to use Counter unless you need to be really fast. And in
that case, you better know what you're doing or else you'll end up being slower with numpy than
without it.

Appendix 2: A somewhat useful plot

I ran the 13 different methods above on prefixes of the complete works of Shakespeare and made an interactive plot. Note that in the plot, both prefixes and durations are displayed in logarithmic scale (the used prefixes are of exponentially increasing length). Click on the items in the legend to show/hide them in the plot.

Click to open!


问:
How to change width of underline in css
I have a cell in a table like this:

```<code><td><b>Grand Total</b></td>
</code>```

I need to give it a line under the text "Grand Total". I used text-decoration: underline;. It worked well, but I need to change the color and thickness of the underline. I used text-decoration-color: red; to add color but it doesn't work. How can I solve this problem?

答:
use border-bottom  define color cording  like this

b {
    border-bottom: 1px solid red;
    padding: 0 0 4px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><td><b>Grand Total</b></td></code>```

Title: How to change width of underline in css

Body:
I have a cell in a table like this:

Grand Total

I need to give it a line under the text "Grand Total". I used text-decoration: underline;. It worked well, but I need to change the color and thickness of the underline. I used text-decoration-color: red; to add color but it doesn't work. How can I solve this problem?

Body:
use border-bottom  define color cording  like this

b {
    border-bottom: 1px solid red;
    padding: 0 0 4px;
}

<td><b>Grand Total</b></td>