问:
Applying different colors to certain parts of SKLabelNode's text
I am pretty much sure that for this can't be used NSMutableAttributedString and NSAttributedString. What I've tried is:

```<code> NSMutableAttributedString * newString = [[NSMutableAttributedString alloc] initWithString:@"firstsecondthird"];
    [newString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)];
    [newString addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(5,6)];
    [newString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(11,5)];

labelNode.text = [newString string];
</code>```

This doesn't work and text still has it's original color. Is there any way to do this with SKLabelNode ? Using multiple SKLabelNodes is solution, but I can't say it's elegant (or performant).

答:
As of iOS 11, SKLabelNode supports NSAttributedStrings, so ASAttributedLabelNode should no longer be necessary. Your code would look like:</p>

```<code>NSMutableAttributedString * newString = [[NSMutableAttributedString alloc] initWithString:@"firstsecondthird"];
    [newString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)];
    [newString addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(5,6)];
    [newString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(11,5)];

labelNode.attributedText = newString;
</code>```

Body:
I am pretty much sure that for this can't be used NSMutableAttributedString and NSAttributedString. What I've tried is:

 NSMutableAttributedString * newString = [[NSMutableAttributedString alloc] initWithString:@"firstsecondthird"];
    [newString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)];
    [newString addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(5,6)];
    [newString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(11,5)];

labelNode.text = [newString string];

This doesn't work and text still has it's original color. Is there any way to do this with SKLabelNode ? Using multiple SKLabelNodes is solution, but I can't say it's elegant (or performant).

Body:
As of iOS 11, SKLabelNode supports NSAttributedStrings, so ASAttributedLabelNode should no longer be necessary. Your code would look like:

NSMutableAttributedString * newString = [[NSMutableAttributedString alloc] initWithString:@"firstsecondthird"];
    [newString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)];
    [newString addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(5,6)];
    [newString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(11,5)];

labelNode.attributedText = newString;


来源: stackexchange

问:
setScrollX function doesn't work well
I have some source code for scrolling.

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView tv = findViewById(R.id.txtv);
    HorizontalScrollView sv = findViewById(R.id.scroll);

    sv.setScrollX(100);
}
</code>```

I want to set x scroll position to 100px.
But setScrollX function doesn't work well.
What's the problem? How should I do?

答:
All You have to do is </p>

```<code>         sv.post(new Runnable() {
            @Override
            public void run() {
                 sv.smoothScrollBy(100, 0);// x,y
            }
        });
</code>```

ContentLicense: CC BY-SA 3.0

Title: setScrollX function doesn't work well

Body:
I have some source code for scrolling.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView tv = findViewById(R.id.txtv);
    HorizontalScrollView sv = findViewById(R.id.scroll);

    sv.setScrollX(100);
}

I want to set x scroll position to 100px.
But setScrollX function doesn't work well.
What's the problem? How should I do?

Body:
All You have to do is

         sv.post(new Runnable() {
            @Override
            public void run() {
                 sv.smoothScrollBy(100, 0);// x,y
            }
        });


问:
Grails form g:textField parameters to Controller
I'm quite new to Grails and I've modified some previously existing button functionality so that it now should send 2 parameters to the controller. By the help of this tutorial I've written:

gsp:

```<code><div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header"><button type="button" class="close" data-dismiss="modal">×</button><h4 class="modal-title">Some Title</h4></div>
            <div class="modal-body">
                <g:form>
                    <div class="input-group">
                        <span class="input-group-addon">Parameter 1</span>
                        <g:textField name="parameter1" size="24" class="form-control" />
                    </div>
                    <div class="input-group">
                        <span class="input-group-addon">Parameter 2</span>
                        <g:textField name="parameter2" size="24" class="form-control" />
                    </div>
                    <g:actionSubmit action="myAction" value="Go" class="btn btn-success"
                                    data-toggle="tooltip" data-placement="top"
                                    title="${grailsApplication.config.myTitle}" />
                </g:form>
            </div>
        </div>
    </div>
</div>
</code>```

MyController:

```<code>// Though it is not mentioned in the tutorial, I've added 2 class properties.
// Otherwise I'd get a groovy.lang.MissingPropertyException
def parameter1
def parameter2

def myAction = {
    doSomething(parameter1, parameter2)
}

// previously :
// def myAction = {
//     doSomething()
// }
</code>```

The two parameters are 'null' when the method is invoked. What can I do to make the parameters being handled to the controller method?

File names, imports and things alike should not be the problem here as the call of the function does well without parameters. The modal is new to the code as it is used to get the values of parameter1 and parameter2. The modal itself works well, as long as the parameters are not in the signature of the controller's method.

I've tried "grails clean" according to this answer. Grails version 2.5.4

答:
try with this</p>

```<code>// def parameter1 // you do not need this
// def parameter2 // you do not need this

def myAction = {
    doSomething(params.parameter1, params.parameter2)
}
</code>```

Body:
I'm quite new to Grails and I've modified some previously existing button functionality so that it now should send 2 parameters to the controller. By the help of this tutorial I've written:

gsp:

<button type="button" class="close" data-dismiss="modal">×</button>
Some Title

                <g:form>

                        Parameter 1
                        <g:textField name="parameter1" size="24" class="form-control" />

                        Parameter 2
                        <g:textField name="parameter2" size="24" class="form-control" />

                    <g:actionSubmit action="myAction" value="Go" class="btn btn-success"
                                    data-toggle="tooltip" data-placement="top"
                                    title="${grailsApplication.config.myTitle}" />
                </g:form>

MyController:

// Though it is not mentioned in the tutorial, I've added 2 class properties.
// Otherwise I'd get a groovy.lang.MissingPropertyException
def parameter1
def parameter2

def myAction = {
    doSomething(parameter1, parameter2)
}

// previously :
// def myAction = {
//     doSomething()
// }

The two parameters are 'null' when the method is invoked. What can I do to make the parameters being handled to the controller method?

File names, imports and things alike should not be the problem here as the call of the function does well without parameters. The modal is new to the code as it is used to get the values of parameter1 and parameter2. The modal itself works well, as long as the parameters are not in the signature of the controller's method.

I've tried "grails clean" according to this answer. Grails version 2.5.4

Body:
try with this

// def parameter1 // you do not need this
// def parameter2 // you do not need this

def myAction = {
    doSomething(params.parameter1, params.parameter2)
}


问:
Reading raw data file dlm
I have problem reading in a raw data file. The problem is that some of inputs gets cut of because of the delimiter. Since one of the title has "\" in front of the real title, the Book_Title output is only "\". I was wondering if there is a way of ignoring those symbols.

Input:

```<code>0195153448;"Classical Mythology";"Mark P. O. Morford";"2002";"Oxford University Press"
085409878X;"\"Pie-powder\"; being dust from the law courts;John Alderson Foote";"1973";"EP Publishing"
</code>```

The code:

```<code>data rating.books;
infile "&path\BX-Books.csv" dlm=';' missover dsd firstobs=2;
input   ISBN: $12.
            Book_Title: $quote150.
            Book_Author: $quote60.
            Year_Of_Publication: $quote8.
            Publisher: $quote60.;
run;
</code>```

Output:

```<code>ISBN | Book-Title | Book-Author | Publisher | Publication-Year
0195153448 | Classical Mythology | Mark P. O. Morford | Oxford University Press | 2002
085409878X | \ | being dust from the law courts,"|  1973 | Missing value
</code>```

Desired output:

```<code>     ISBN | Book-Title | Book-Author | Publisher | Publication-Year
    0195153448 | Classical Mythology | Mark P. O. Morford | Oxford University Press | 2002
    085409878X | Pie-powder being dust from the law courts |John Alderson Foote | EP Publishing | 1973
</code>```

答:
It does not look like your source data is following any known pattern.

If you read it without the DSD option then it will treat the second line as having 6 fields.

```<code>085409878X;"\"Pie-powder\"; being dust from the law courts;John Alderson Foote";"1973";"EP Publishing"

v1=085409878X
v2="\"Pie-powder\"
v3=being dust from the law courts
v4=John Alderson Foote"
v5="1973"
v6="EP Publishing"
</code>```

If you try to "fix" the escaped quotes

```<code>_infile_=tranwrd(_infile_,'\"','""');
</code>```

then you will end up with only 4 fields.

```<code>085409878X;"""Pie-powder""; being dust from the law courts;John Alderson Foote";"1973";"EP Publishing"

v1=085409878X
v2="Pie-powder"; being dust from the law courts;John Alderson Foote
v3=1973
v4=EP Publishing
v5=
v6=
</code>```

To get your desired output you could try removing the \"; and the "\" strings.

```<code>_infile_=tranwrd(_infile_,'\";',' ');
_infile_=tranwrd(_infile_,'"\"','');
</code>```

Which does make it read as you want.

```<code>085409878X; Pie-powder  being dust from the law courts;John Alderson Foote";"1973";"EP Publishing"

v1=085409878X
v2=Pie-powder  being dust from the law courts
v3=John Alderson Foote"
v4=1973
v5=EP Publishing
v6=
</code>```

Not sure if that will generalize to other lines with extra quotes or extra semi-colons.

Title: Reading raw data file dlm

Body:
I have problem reading in a raw data file. The problem is that some of inputs gets cut of because of the delimiter. Since one of the title has "\" in front of the real title, the Book_Title output is only "\". I was wondering if there is a way of ignoring those symbols.

Input:

0195153448;"Classical Mythology";"Mark P. O. Morford";"2002";"Oxford University Press"
085409878X;"\"Pie-powder\"; being dust from the law courts;John Alderson Foote";"1973";"EP Publishing"

The code:

data rating.books;
infile "&path\BX-Books.csv" dlm=';' missover dsd firstobs=2;
input   ISBN: $12.
            Book_Title: $quote150.
            Book_Author: $quote60.
            Year_Of_Publication: $quote8.
            Publisher: $quote60.;
run;

Output:

ISBN | Book-Title | Book-Author | Publisher | Publication-Year
0195153448 | Classical Mythology | Mark P. O. Morford | Oxford University Press | 2002
085409878X | \ | being dust from the law courts,"|  1973 | Missing value

Desired output:

     ISBN | Book-Title | Book-Author | Publisher | Publication-Year
    0195153448 | Classical Mythology | Mark P. O. Morford | Oxford University Press | 2002
    085409878X | Pie-powder being dust from the law courts |John Alderson Foote | EP Publishing | 1973

Body:
It does not look like your source data is following any known pattern.

If you read it without the DSD option then it will treat the second line as having 6 fields.

085409878X;"\"Pie-powder\"; being dust from the law courts;John Alderson Foote";"1973";"EP Publishing"

v1=085409878X
v2="\"Pie-powder\"
v3=being dust from the law courts
v4=John Alderson Foote"
v5="1973"
v6="EP Publishing"

If you try to "fix" the escaped quotes

_infile_=tranwrd(_infile_,'\"','""');

then you will end up with only 4 fields.

085409878X;"""Pie-powder""; being dust from the law courts;John Alderson Foote";"1973";"EP Publishing"

v1=085409878X
v2="Pie-powder"; being dust from the law courts;John Alderson Foote
v3=1973
v4=EP Publishing
v5=
v6=

To get your desired output you could try removing the \"; and the "\" strings.

_infile_=tranwrd(_infile_,'\";',' ');
_infile_=tranwrd(_infile_,'"\"','');

Which does make it read as you want.

085409878X; Pie-powder  being dust from the law courts;John Alderson Foote";"1973";"EP Publishing"

v1=085409878X
v2=Pie-powder  being dust from the law courts
v3=John Alderson Foote"
v4=1973
v5=EP Publishing
v6=

Not sure if that will generalize to other lines with extra quotes or extra semi-colons.


问:
Adding a dictionary to a list python - ValueError: dictionary update sequence element #0 has length 1; 2 is required
I keep getting a "ValueError: dictionary update sequence element #0 has length 1; 2 is required" when i try to post a new comment into the comments list </p>

```<code># import the Flask class from the flask module
from flask import Flask, render_template, request

# create the application object
app = Flask(__name__)

posts=[]

@app.route('/index')
def index():
user = {'nickname': 'Miguel'}
posts = [
    {'author': {'nickname': 'John'}, 'body': 'Beautiful day in Portland!'},
    {'author': {'nickname': 'Susan'}, 'body': 'The Avengers movie was so
cool!'}
]
return render_template("index.html", title='Home', user=user, posts=posts)

@app.route('/postAnonComment', methods=['POST'])
def SaveDetails():
userName = request.form['user_name']
userMail = request.form['user_mail']
userMessage = request.form['user_message']

newDictionaryItem = newDictionaryItem = "{'author': {'nickname': '{}'},
'body': '{}'}".format(userName, userMessage)
posts.append(dict(newDictionaryItem))

return render_template('index.html', user=userName, posts=posts)

# start the server with the 'run()' method
if __name__ == '__main__':
app.run(debug=True)
</code>```

答:
You are trying to create a dict from a str:

```<code>newDictionaryItem = """{'author': {'nickname': '%s'}, 'body': '%s'}""" % (userName, userMessage)
posts.append(dict(newDictionaryItem))
             ^^^^^
</code>```

Python will not do this parsing for you. To fix this, create the dictionary manually:

```<code>newDictionaryItem = {'author': {'nickname': userName }, 'body': userMessage }
posts.append(newDictionaryItem)
</code>```

Body:
I keep getting a "ValueError: dictionary update sequence element #0 has length 1; 2 is required" when i try to post a new comment into the comments list

# import the Flask class from the flask module
from flask import Flask, render_template, request

# create the application object
app = Flask(__name__)

posts=[]

@app.route('/index')
def index():
user = {'nickname': 'Miguel'}
posts = [
    {'author': {'nickname': 'John'}, 'body': 'Beautiful day in Portland!'},
    {'author': {'nickname': 'Susan'}, 'body': 'The Avengers movie was so
cool!'}
]
return render_template("index.html", title='Home', user=user, posts=posts)

@app.route('/postAnonComment', methods=['POST'])
def SaveDetails():
userName = request.form['user_name']
userMail = request.form['user_mail']
userMessage = request.form['user_message']

newDictionaryItem = newDictionaryItem = "{'author': {'nickname': '{}'},
'body': '{}'}".format(userName, userMessage)
posts.append(dict(newDictionaryItem))

return render_template('index.html', user=userName, posts=posts)

# start the server with the 'run()' method
if __name__ == '__main__':
app.run(debug=True)

Body:
You are trying to create a dict from a str:

newDictionaryItem = """{'author': {'nickname': '%s'}, 'body': '%s'}""" % (userName, userMessage)
posts.append(dict(newDictionaryItem))
             ^^^^^

Python will not do this parsing for you. To fix this, create the dictionary manually:

newDictionaryItem = {'author': {'nickname': userName }, 'body': userMessage }
posts.append(newDictionaryItem)


问:
or_like not working in codeIgniter
I am trying to run a query with multiple like combined using or in mysql query from code Igniter.
I have following code for that purpose.

```<code>$this->db->group_start();
                    foreach ($active['result'] as $outcode) {
                        $this->db->or_like('postcode',$outcode['outcode']);

                    }
                    $this->db->group_end();
</code>```

It does create the query as expected apart from the problem that it contains ESCAPE '!' between each part.
here is query printed.

```<code>SELECT * FROM `tbl_service_providers` WHERE `is_active` >= 1 AND ( `postcode` LIKE '%SS13%' ESCAPE '!' OR `postcode` LIKE '%SS14%' ESCAPE '!')
</code>```

答:
You can try to use $this->db->escape_like_str()

```<code>$this->db->or_like('postcode', $this->db->escape_like_str($outcode['outcode']));
</code>```

Title: or_like not working in codeIgniter

Body:
I am trying to run a query with multiple like combined using or in mysql query from code Igniter.
I have following code for that purpose.

$this->db->group_start();
                    foreach ($active['result'] as $outcode) {
                        $this->db->or_like('postcode',$outcode['outcode']);

                    }
                    $this->db->group_end();

It does create the query as expected apart from the problem that it contains ESCAPE '!' between each part.
here is query printed.

SELECT * FROM `tbl_service_providers` WHERE `is_active` >= 1 AND ( `postcode` LIKE '%SS13%' ESCAPE '!' OR `postcode` LIKE '%SS14%' ESCAPE '!')

Body:
You can try to use $this->db->escape_like_str()

$this->db->or_like('postcode', $this->db->escape_like_str($outcode['outcode']));


答:
It is not recommended to do it they way you used dict via a string but you could:

```<code>posts.append(dict(eval(newDictionaryItem)))
</code>```

Better would be to just use a normal dict assignment:

```<code>newDictionaryItem = {'author': {'nickname': userName}, 'body': userMessage}
posts.append(newDictionaryItem)
</code>```

Title: Adding a dictionary to a list python - ValueError: dictionary update sequence element #0 has length 1; 2 is required

Body:
It is not recommended to do it they way you used dict via a string but you could:

posts.append(dict(eval(newDictionaryItem)))

Better would be to just use a normal dict assignment:

newDictionaryItem = {'author': {'nickname': userName}, 'body': userMessage}
posts.append(newDictionaryItem)


问:
Easy way to convert web forms to MVC3?
I haven't worked with MVC3 that much - as it was just released, but I was wondering if there was some kind of conversion tool - to convert exisiting Views / Forms into the newer up-to-date "Razor" view engine.

I'm not sure if it is possible but I just thought this would be the place to ask...

Thanks!

答:
Given that Asp.net webforms works well for simple pages and there is no point in moving to MVC for the sake of it.   I don't think a converter will do a good job, as:

your pages are complex

and/or you wish to do unit testing - so need to redesign

or you are moving for the sake of it (way?)

OwnerDisplayName: Online Prodigy

ContentLicense: CC BY-SA 2.5

Title: Easy way to convert web forms to MVC3?


答:
The problem is, that at that point the actual view is not laid out yet. You have to delay the scrolling until HorizontalScrollView is laid out:

```
<code>
    protected void onCreate(Bundle savedInstanceState) {
        ...
        HorizontalScrollView sv = findViewById(R.id.scroll);
        sv.post(new Runnable() {
            @Override
            public void run() {
                sv.smoothScrollBy(100, 0);
            }
        })
    }
</code>
```

Title: setScrollX function doesn't work well

Body:
The problem is, that at that point the actual view is not laid out yet. You have to delay the scrolling until HorizontalScrollView is laid out:

    protected void onCreate(Bundle savedInstanceState) {
        ...
        HorizontalScrollView sv = findViewById(R.id.scroll);
        sv.post(new Runnable() {
            @Override
            public void run() {
                sv.smoothScrollBy(100, 0);
            }
        })
    }


问:
How to loop over JSON objects in a ruby function
I want to loop over JSON objects and check for a condition in a ruby function.
I have 2 classes:

Class A

Class B

Class A has a function that reads the JSON file.
This function returns an array of hash objects representing the data:

```<code>def self.data
  path = 'data/songs.json'
  file = File.read(path)
  JSON.parse(file)
end
</code>```

I want to use this method in class B to access the songs.json objects and check if a certain condition is true.

Here is the code for class B:

```<code>def mention_count
  count = 0
  array= []
  array.push(Song.data)
  array.each do |i|
    if(@name === i[:name])
      count +=1;
    end
  end
end
</code>```

Th JSON file has a key called name, and I am checking if it is identical to the class B variable name. If true the count variable is increased and returned.

The JSON file is an array of JSON object and it looks like this

```<code>[
{
"Name": "Bad",
"Artist": "Michael Jackson",
"Record": 825,
},
{
"Name": "Thriller",
"Artist": "Michael Jackson",
"Record": 846,
}]
</code>```

I am not getting the expected result. The array.push(Song.data) is only adding the first object of the JSON file and not the whole JSON file.

How do I call the method Song.data in class B and loop over the JSON objects?

答:
It seems at first glance that you're wrapping an array of data (returned in class A) in another array in class B. Therefore, when you're calling each on the array, the first result is the original array. You get me?

Therefore, you could use:

```<code>Song.data.each do ....
  ...
end
</code>```

Does that help?

Assuming that solves it, there's a purpose built method for this, where you can pass a count while you loop through your objects using reduce(0).

I'd refactor the code in class B a little, as follows:

```<code>def mention_count
  Song.data.reduce(0) do |count, i|
    count += 1 if @name == i[:name]
    count
  end
end
</code>```

To briefly break this down:

reduce(0) passes the arg (0) along with the objects you're looking to loop through (to count and i respectively)

if @name == i[:name], count is incremented

count is returned, so it's available for the next item we loop through

reduce then returns the value of count when all looping is complete

Hope that helps!

Body:
I want to loop over JSON objects and check for a condition in a ruby function.
I have 2 classes:

Class A

Class B

Class A has a function that reads the JSON file.
This function returns an array of hash objects representing the data:

def self.data
  path = 'data/songs.json'
  file = File.read(path)
  JSON.parse(file)
end

I want to use this method in class B to access the songs.json objects and check if a certain condition is true.

Here is the code for class B:

def mention_count
  count = 0
  array= []
  array.push(Song.data)
  array.each do |i|
    if(@name === i[:name])
      count +=1;
    end
  end
end

Th JSON file has a key called name, and I am checking if it is identical to the class B variable name. If true the count variable is increased and returned.

The JSON file is an array of JSON object and it looks like this

[
{
"Name": "Bad",
"Artist": "Michael Jackson",
"Record": 825,
},
{
"Name": "Thriller",
"Artist": "Michael Jackson",
"Record": 846,
}]

I am not getting the expected result. The array.push(Song.data) is only adding the first object of the JSON file and not the whole JSON file.

How do I call the method Song.data in class B and loop over the JSON objects?

Body:
It seems at first glance that you're wrapping an array of data (returned in class A) in another array in class B. Therefore, when you're calling each on the array, the first result is the original array. You get me?

Therefore, you could use:

Song.data.each do ....
  ...
end

Does that help?

Assuming that solves it, there's a purpose built method for this, where you can pass a count while you loop through your objects using reduce(0).

I'd refactor the code in class B a little, as follows:

def mention_count
  Song.data.reduce(0) do |count, i|
    count += 1 if @name == i[:name]
    count
  end
end

To briefly break this down:

reduce(0) passes the arg (0) along with the objects you're looking to loop through (to count and i respectively)

if @name == i[:name], count is incremented

count is returned, so it's available for the next item we loop through

reduce then returns the value of count when all looping is complete

Hope that helps!


问:
How is "void()" useful?
You cannot declare a void variable:

```<code>void fn() {
    void a; // ill-formed
}
</code>```

Yet this compiles:

```<code>void fn() {
    void(); // a void object?
}
</code>```

What does void() mean? How is it useful? Why is void a; ill-formed, while void() OK?

```<code>void fn() {
    void a = void(); // ill-formed
}
</code>```

答:
The statement

```<code>void();
</code>```

creates a void value and then discards it.  (You can't actually do much with a void value other than discard it or return it.)

The standard† says in 5.2.3 [expr.type.conv

The expression T(), where T is a simple-type-specifier or typename-specifier for a non-array complete object
  type or the (possibly cv-qualified) void type, creates a prvalue of the specified type, whose value is that
  produced by value-initializing (8.5) an object of type T; no initialization is done for the void() case

Note that it explictaly calls out that void() is legal.

† My link is to N4296 which was the last public committee draft before C++14, however the various versions of the standard do not vary here.

Edit

Is it useful?  Explicitly like this? No.  I can't see a use for it.  It is however, useful in template functions which sometimes do something like:

```<code>template <typename T>
T foo() {
    if (prepare_for_for()) {
        return do_foo();
    } else {
        return T();
    }
}
</code>```

And this will work, even for T == void.

Title: How is "void()" useful?

Body:
You cannot declare a void variable:

void fn() {
    void a; // ill-formed
}

Yet this compiles:

void fn() {
    void(); // a void object?
}

What does void() mean? How is it useful? Why is void a; ill-formed, while void() OK?

void fn() {
    void a = void(); // ill-formed
}

Body:
The statement

void();

creates a void value and then discards it.  (You can't actually do much with a void value other than discard it or return it.)

The standard† says in 5.2.3 [expr.type.conv

The expression T(), where T is a simple-type-specifier or typename-specifier for a non-array complete object
  type or the (possibly cv-qualified) void type, creates a prvalue of the specified type, whose value is that
  produced by value-initializing (8.5) an object of type T; no initialization is done for the void() case

Note that it explictaly calls out that void() is legal.

† My link is to N4296 which was the last public committee draft before C++14, however the various versions of the standard do not vary here.

Edit

Is it useful?  Explicitly like this? No.  I can't see a use for it.  It is however, useful in template functions which sometimes do something like:

template <typename T>
T foo() {
    if (prepare_for_for()) {
        return do_foo();
    } else {
        return T();
    }
}

And this will work, even for T == void.


问:
Is there any good way to "encode" binary data as plausible madeup words and back again?
To give you a very simple and bad example. The data is split in 4 bits. The 16 possible numbers correspond to the first 16 consonants. You add a random vowel to make it pronounceable. So "08F734F7" can become "ba lo ta ku fo go ta ka". You can join some syllables and add punctuation and capitalization and it can become "Balo ta kufogo, Taka?" which looks like a plausible language.

Just to make it clear, I'm not trying to protect the binary data.

I want to use this after I compress and encrypt my (UTF-8) plain text diary. The resulting binary data should look pretty random. I need to convert this data into a plausible looking language and be able to revert it back. I'm going to print the "language" on paper and make a custom book.

So what I'm looking for is the best method of converting random data to readable plausible words. By good I mean the biggest bits to letters ratio (while making it look like a real language). In my example it's exactly 2 bits per letter. Or 4 letters for a byte.

答:
Summary

This solution will let you use any of a large number of languages including pronounceable nonsense with a customizable efficiency.  You can even create something that looks like grammatically correct but meaningless English or French (or worse, something that shifts between the two like a drunken polyglot).  The basic idea is to use your data to continually select paths from a context free grammar until you run out of data.

Details

Add a string to the end of your input that doesn't occur anywhere inside of it ("This is the end of my input, thank you very much" would be very unlikely to occur in a string of encrypted text, for example.)  You can do this without the string but it makes it easier.

Treat your input as one very long integer encoded low-bit first. Obviously your machine won't be able to process such a big integer, every time you have a zero high byte, just strip off the next byte worth of values from your file and multiply them in.

Create your language as a context free grammar.  To avoid forgetting what the encoding is, you can print it at the end of your book.  Avoid ambiguity.  If your grammar is ambiguous, you won't be able to decode.  This is not hard, essentially don't use the same terminal in two places, ensure that the concatenation of two terminals cannot make another terminal, and ensure that reading the output you can tell where you put the formatting symbols.

Now, to take an integer and turn it into language, use the following pseudo-code that uses n to choose which production to take.

```<code>cur=grammar.root (cur is a list of tokens)
n=my input as one big integer
while(n > 0 || cur != grammar root){
    if (cur.first.isTerminalSymbol) {
        output cur.first
        cur.pop_first
        if(cur.isEmpty){
            cur = grammar root
        }
    }else{
        p = grammar[cur.first].number of productions
        t = n mod p // t = low order digit base p
        n = n div p // Shift left in base p
        cur.pop_first
        cur.push_first( grammar[cur.first].productionNumber[t] )
    }
}
</code>```

To decode you use a standard parser generator like GNU bison which should also help you avoid creating an ambiguous grammar.

Run the parser on the input.  Now, start n at 0.  You can get the production number at each time by referencing the syntax tree generated by the parser.  Then multiply n by the number of productions and add the production number to get n after that particular input.  As you fill up the lower byte of your machine word, shift it off into your decoded file.  When you read your unique phrase, stop decoding.

Example 1

This will be clearer with an example or three.

My example simple language is as follows (non-terminals are capitalized).  Note because of the large size of the terminals compared with their depth of the tree, it is not very efficient but I think that having more terminals or making them shorter can give you any efficiency you want (up to the number of bits wasted per character by using n bits per character).

S -> __capital Noun I-Verb Punct | __capital Noun T-Verb Noun Punct

Noun -> joe | sally | spot | the car | the cookie | the hose

I-Verb -> runs | lives | jumps | flies

T-Verb -> jumps over | eats | grows | spins

Punct -> . | ! | ?

You could just as easily do this with syllables as an expansion of verbs and nouns.  You could also include noun-phrases and verb phrases to have adjectives etc. in your language.  You will probably also want paragraph and chapter symbols that break down into appropriate subunits with formatting.  The number of alternate choices at a certain level of the tree determines the average number of bits encoded by each symbol.  __capital is an example of a formatting symbol that, on output, capitalizes the next word.

So, imagine that my input becomes the number 77.  Then I would encode it as follows:

S goes to two things.  77 % 2 = 1.  Remainder 77 / 2 = 38.

Now our number is 38 and we are expanding __capital, Noun, T-Verb, Noun, Punct

First word is __capital which is a terminal symbol.  Output __capital (setting the print routine to capitalize the next word).

Now expanding Noun.  Noun has 6 options.  38 % 6 = 2.  38 / 6 = 6.  We choose spot

Now expanding spot,T-verb,Noun,Punct.  Spot is terminal.  Output spot.  The printer being in capital mode writes "Spot" to the output file.

Now expanding T-Verb.  Our number is 6.  T-verb has 4 options.  6 % 4 = 2.  6 / 4 = 1.  So we choose "grows".  In the next step we output grows to our file since it is a terminal.

Now expanding Noun, Punct.  Noun has 6 options.  Our number is 1.  1 % 6 = 1  1/6 = 0.  So we choose "sally",  which is output on the next step.

Finally we are expanding Punct which has 3 options.  Our number is 0 (and will stay that way forever - this is why you append an end-of-text string to the end of your input, otherwise your decoding would end with an infinite string of zeroes.)  We choose ".", which is output.

Now the current string to expand is empty so we set it back to the root "S".  But since n is 0, the algorithm terminates.

Thus 77 has become "Spot grows sally."

Example 2

Things get more efficient if I replace my terminals with:

I-Verb IVS _space | IVS I-Verb

IVS IVSS vowel

IVSS w | r

Vowel a | e | i | o | u | y

T-Verb TVS _space | TVS T-Verb

TVS TVSS vowel

TVSS p | s

Noun NS _space | NS

NS NSS Vowel

NSS j | v

77 yields "Jo papa ja." under this encoding  (and is really encoded by just the "Jo " and the fact that papa has 2 syllables.  The extra would be a very small fraction in any book-length file.)

Example 3

Your example "08F734F7" would be "1000111101110011010011110111" in binary, which is "1110111100101100111011110001" when reversed and that is, 250793713 in decimal.

If I run that through the more compact grammar, I get:

```<code>25079713 % 2 = 1  n=125396856, S-> __capital Noun T-Verb Noun Punct
125396856 % 2 = 0 n=62698428,  Noun->NS _space-> NSS Vowel _space
62698428 % 2 = 0  n=31349214,  NSS->j
31349214 % 6 = 0  n=5224869,   Vowel->a
5224869 % 2 = 1   n=2612434,   T-Verb->TVS T-Verb->TVSS Vowel T-Verb
2612434 % 2 = 0   n=1306217,   TVSS->p
1306217 % 6 = 5   n=217702,    Vowel->y
217702 % 2 = 0    n=108851,    T-Verb->TVSS Vowel _space
108851 % 2 = 1    n=54425,     TVSS->s
54425 % 6 = 5     n=9070,      Vowel->y
9070 % 2 = 0      n=4535,      Noun->NSS Vowel _space
4535 % 2 = 1      n=2267       NSS->v
2267 % 6 = 5      n=377        Vowel->y
377 % 3 = 2       n=125        Punct->?
125 % 2 = 1       n=62         S->__capital Noun T-Verb Noun Punct
62 % 2 = 0        n=31         Noun->NSS Vowel _space
31 % 2 = 1        n=15         NSS->v
15 % 6 = 3        n=2          Vowel->o
2 % 2 = 0         n=1          T-Verb->TVSS Vowel _space
1 % 2 = 1         n=0          TVSS->p
                  n=0          Vowel _space Noun Punct -> "a ja."
</code>```

This yields:
"Ja pysy vy? Vo pa ja." from 08F734F7
(note that my print routine removes spaces before punctuation)

Body:
Summary

This solution will let you use any of a large number of languages including pronounceable nonsense with a customizable efficiency.  You can even create something that looks like grammatically correct but meaningless English or French (or worse, something that shifts between the two like a drunken polyglot).  The basic idea is to use your data to continually select paths from a context free grammar until you run out of data.

Details

Add a string to the end of your input that doesn't occur anywhere inside of it ("This is the end of my input, thank you very much" would be very unlikely to occur in a string of encrypted text, for example.)  You can do this without the string but it makes it easier.

Treat your input as one very long integer encoded low-bit first. Obviously your machine won't be able to process such a big integer, every time you have a zero high byte, just strip off the next byte worth of values from your file and multiply them in.

Create your language as a context free grammar.  To avoid forgetting what the encoding is, you can print it at the end of your book.  Avoid ambiguity.  If your grammar is ambiguous, you won't be able to decode.  This is not hard, essentially don't use the same terminal in two places, ensure that the concatenation of two terminals cannot make another terminal, and ensure that reading the output you can tell where you put the formatting symbols.

Now, to take an integer and turn it into language, use the following pseudo-code that uses n to choose which production to take.

cur=grammar.root (cur is a list of tokens)
n=my input as one big integer
while(n > 0 || cur != grammar root){
    if (cur.first.isTerminalSymbol) {
        output cur.first
        cur.pop_first
        if(cur.isEmpty){
            cur = grammar root
        }
    }else{
        p = grammar[cur.first].number of productions
        t = n mod p // t = low order digit base p
        n = n div p // Shift left in base p
        cur.pop_first
        cur.push_first( grammar[cur.first].productionNumber[t] )
    }
}

To decode you use a standard parser generator like GNU bison which should also help you avoid creating an ambiguous grammar.

Run the parser on the input.  Now, start n at 0.  You can get the production number at each time by referencing the syntax tree generated by the parser.  Then multiply n by the number of productions and add the production number to get n after that particular input.  As you fill up the lower byte of your machine word, shift it off into your decoded file.  When you read your unique phrase, stop decoding.

Example 1

This will be clearer with an example or three.

My example simple language is as follows (non-terminals are capitalized).  Note because of the large size of the terminals compared with their depth of the tree, it is not very efficient but I think that having more terminals or making them shorter can give you any efficiency you want (up to the number of bits wasted per character by using n bits per character).

S -> __capital Noun I-Verb Punct | __capital Noun T-Verb Noun Punct

Noun -> joe | sally | spot | the car | the cookie | the hose

I-Verb -> runs | lives | jumps | flies

T-Verb -> jumps over | eats | grows | spins

Punct -> . | ! | ?

You could just as easily do this with syllables as an expansion of verbs and nouns.  You could also include noun-phrases and verb phrases to have adjectives etc. in your language.  You will probably also want paragraph and chapter symbols that break down into appropriate subunits with formatting.  The number of alternate choices at a certain level of the tree determines the average number of bits encoded by each symbol.  __capital is an example of a formatting symbol that, on output, capitalizes the next word.

So, imagine that my input becomes the number 77.  Then I would encode it as follows:

S goes to two things.  77 % 2 = 1.  Remainder 77 / 2 = 38.

Now our number is 38 and we are expanding __capital, Noun, T-Verb, Noun, Punct

First word is __capital which is a terminal symbol.  Output __capital (setting the print routine to capitalize the next word).

Now expanding Noun.  Noun has 6 options.  38 % 6 = 2.  38 / 6 = 6.  We choose spot

Now expanding spot,T-verb,Noun,Punct.  Spot is terminal.  Output spot.  The printer being in capital mode writes "Spot" to the output file.

Now expanding T-Verb.  Our number is 6.  T-verb has 4 options.  6 % 4 = 2.  6 / 4 = 1.  So we choose "grows".  In the next step we output grows to our file since it is a terminal.

Now expanding Noun, Punct.  Noun has 6 options.  Our number is 1.  1 % 6 = 1  1/6 = 0.  So we choose "sally",  which is output on the next step.

Finally we are expanding Punct which has 3 options.  Our number is 0 (and will stay that way forever - this is why you append an end-of-text string to the end of your input, otherwise your decoding would end with an infinite string of zeroes.)  We choose ".", which is output.

Now the current string to expand is empty so we set it back to the root "S".  But since n is 0, the algorithm terminates.

Thus 77 has become "Spot grows sally."

Example 2

Things get more efficient if I replace my terminals with:

I-Verb IVS _space | IVS I-Verb

IVS IVSS vowel

IVSS w | r

Vowel a | e | i | o | u | y

T-Verb TVS _space | TVS T-Verb

TVS TVSS vowel

TVSS p | s

Noun NS _space | NS

NS NSS Vowel

NSS j | v

77 yields "Jo papa ja." under this encoding  (and is really encoded by just the "Jo " and the fact that papa has 2 syllables.  The extra would be a very small fraction in any book-length file.)

Example 3

Your example "08F734F7" would be "1000111101110011010011110111" in binary, which is "1110111100101100111011110001" when reversed and that is, 250793713 in decimal.

If I run that through the more compact grammar, I get:

25079713 % 2 = 1  n=125396856, S-> __capital Noun T-Verb Noun Punct
125396856 % 2 = 0 n=62698428,  Noun->NS _space-> NSS Vowel _space
62698428 % 2 = 0  n=31349214,  NSS->j
31349214 % 6 = 0  n=5224869,   Vowel->a
5224869 % 2 = 1   n=2612434,   T-Verb->TVS T-Verb->TVSS Vowel T-Verb
2612434 % 2 = 0   n=1306217,   TVSS->p
1306217 % 6 = 5   n=217702,    Vowel->y
217702 % 2 = 0    n=108851,    T-Verb->TVSS Vowel _space
108851 % 2 = 1    n=54425,     TVSS->s
54425 % 6 = 5     n=9070,      Vowel->y
9070 % 2 = 0      n=4535,      Noun->NSS Vowel _space
4535 % 2 = 1      n=2267       NSS->v
2267 % 6 = 5      n=377        Vowel->y
377 % 3 = 2       n=125        Punct->?
125 % 2 = 1       n=62         S->__capital Noun T-Verb Noun Punct
62 % 2 = 0        n=31         Noun->NSS Vowel _space
31 % 2 = 1        n=15         NSS->v
15 % 6 = 3        n=2          Vowel->o
2 % 2 = 0         n=1          T-Verb->TVSS Vowel _space
1 % 2 = 1         n=0          TVSS->p
                  n=0          Vowel _space Noun Punct -> "a ja."

This yields:
"Ja pysy vy? Vo pa ja." from 08F734F7
(note that my print routine removes spaces before punctuation)


问:
QXcbIntegration: Cannot create platform OpenGL context
I've been trying to add Qt5 support to a core-image-sato image using Yocto's Poky Pyro on Raspberry Pi 3.

In my bblayer.conf I added these lines:

```<code>BBLAYERS ?= " \
        /poky-pyro/meta \
        /poky-pyro/meta-poky \
        /poky-pyro/meta-yocto-bsp \
        /poky-pyro/meta-openembedded/meta-oe \
        /poky-pyro/meta-openembedded/meta-multimedia \
        /poky-pyro/meta-openembedded/meta-networking \
        /poky-pyro/meta-openembedded/meta-perl \
        /poky-pyro/meta-openembedded/meta-python \
        /poky-pyro/meta-raspberrypi \
        /poky-pyro/meta-qt5 \
  "
</code>```

In my local.conf I added these lines:

```<code>DISTRO_FEATURES_append = " opengl "
IMAGE_INSTALL_append = " qtbase qtdeclarative qtquickcontrols2 qtmultimedia qttools cinematicexperience "
</code>```

Bitbake finished building the image successfully, but when I run Qt5_cenimaticExperience on the target I get this error message:

```<code>QXcbIntegration: Cannot create platform OpenGL context, neither GLX nor EGL are enabled.
</code>```

答:
This is the default configuration of Qtbase and based on what you have:

```<code>PACKAGECONFIG_GL ?= "${@bb.utils.contains('DISTRO_FEATURES', 'opengl', 'gl', '', d)}"
PACKAGECONFIG_DEFAULT ?= "dbus udev evdev widgets tools libs freetype tests"
PACKAGECONFIG_SYSTEM ?= "jpeg libpng zlib"
</code>```

As you can see, we only enabled -opengl desktop;  What we need is opengl es2 for embedded system.

To correct this, add this line to your local.conf:

```<code>PACKAGECONFIG_append_pn-qtbase = " gles2 "
</code>```

By the way, this is my qtbase configuration:

```<code>PACKAGECONFIG_append_pn-qtbase = " gles2 fontconfig \
                gstreamer \
                accessibility \
                tslib examples \
                "
</code>```

Body:
I've been trying to add Qt5 support to a core-image-sato image using Yocto's Poky Pyro on Raspberry Pi 3.

In my bblayer.conf I added these lines:

BBLAYERS ?= " \
        /poky-pyro/meta \
        /poky-pyro/meta-poky \
        /poky-pyro/meta-yocto-bsp \
        /poky-pyro/meta-openembedded/meta-oe \
        /poky-pyro/meta-openembedded/meta-multimedia \
        /poky-pyro/meta-openembedded/meta-networking \
        /poky-pyro/meta-openembedded/meta-perl \
        /poky-pyro/meta-openembedded/meta-python \
        /poky-pyro/meta-raspberrypi \
        /poky-pyro/meta-qt5 \
  "

In my local.conf I added these lines:

DISTRO_FEATURES_append = " opengl "
IMAGE_INSTALL_append = " qtbase qtdeclarative qtquickcontrols2 qtmultimedia qttools cinematicexperience "

Bitbake finished building the image successfully, but when I run Qt5_cenimaticExperience on the target I get this error message:

QXcbIntegration: Cannot create platform OpenGL context, neither GLX nor EGL are enabled.

Body:
This is the default configuration of Qtbase and based on what you have:

PACKAGECONFIG_GL ?= "${@bb.utils.contains('DISTRO_FEATURES', 'opengl', 'gl', '', d)}"
PACKAGECONFIG_DEFAULT ?= "dbus udev evdev widgets tools libs freetype tests"
PACKAGECONFIG_SYSTEM ?= "jpeg libpng zlib"

As you can see, we only enabled -opengl desktop;  What we need is opengl es2 for embedded system.

To correct this, add this line to your local.conf:

PACKAGECONFIG_append_pn-qtbase = " gles2 "

By the way, this is my qtbase configuration:

PACKAGECONFIG_append_pn-qtbase = " gles2 fontconfig \
                gstreamer \
                accessibility \
                tslib examples \
                "


问:
How do I properly use boost::optional with types with public member variables?
Here is a motivating example demonstrating what my problem is:

struct Foo
{
  int x;
  int y;
};

boost::optional<Foo> opt_foo;

opt_foo->x = 1; // legal
opt_foo->y = 2; // legal

auto foo = opt_foo.get(); // legal (returns valid instance of Foo with x = 1 and y = 2)

if (opt_foo) // false
{
  ...
}
```

I understand that in order for the optional object to be initialized, I would have to use boost::optional<Foo> opt_foo = Foo();. However, I was surprised to see that if it is forgotten, I can still do all the things I marked as legal (especially get()). Was this intended behavior? Is there any way I can make opt_foo consider itself initialized without boost::optional<Foo> opt_foo = Foo();?

答:
Under the hood, boost::optional is implemented as a simple

```<code>struct {
  bool _present;
  T _t;
}
</code>```

So whether you explicitly initialize or not the optional with a value, the storage for this value already exists, and in C++ we don't usually like to pay for what we don't need (eg. checking if an optional is present on each call of operator->).

It is duty of the developer to only try to access the optional value if it is present, as explained in the documentation:

An attempt to extract the contained value of an uninitialized optional object is an undefined behaviour (UB). This implementation guards the call with BOOST_ASSERT. Therefore you should be sure that the contained value is there before extracting.

Actually your code should SIGABRT on the assertion, are you running it in debug mode?

You can use value() if you want to avoid any risk of UB (but you need to place that in a try block).

Body:
Here is a motivating example demonstrating what my problem is:

struct Foo
{
  int x;
  int y;
};

boost::optional<Foo> opt_foo;

opt_foo->x = 1; // legal
opt_foo->y = 2; // legal

auto foo = opt_foo.get(); // legal (returns valid instance of Foo with x = 1 and y = 2)

if (opt_foo) // false
{
  ...
}

I understand that in order for the optional object to be initialized, I would have to use boost::optional<Foo> opt_foo = Foo();. However, I was surprised to see that if it is forgotten, I can still do all the things I marked as legal (especially get()). Was this intended behavior? Is there any way I can make opt_foo consider itself initialized without boost::optional<Foo> opt_foo = Foo();?

Body:
Under the hood, boost::optional is implemented as a simple

struct {
  bool _present;
  T _t;
}

So whether you explicitly initialize or not the optional with a value, the storage for this value already exists, and in C++ we don't usually like to pay for what we don't need (eg. checking if an optional is present on each call of operator->).

It is duty of the developer to only try to access the optional value if it is present, as explained in the documentation:

An attempt to extract the contained value of an uninitialized optional object is an undefined behaviour (UB). This implementation guards the call with BOOST_ASSERT. Therefore you should be sure that the contained value is there before extracting.

Actually your code should SIGABRT on the assertion, are you running it in debug mode?

You can use value() if you want to avoid any risk of UB (but you need to place that in a try block).


问:
Is there a basic Java Set implementation that does not permit nulls?
The API for the Java Set interface states:

For example, some implementations prohibit null elements and some have restrictions on the types of their elements

I am looking for a basic Set implementation that does not require ordering (as ArrayList provides for the List interface) and that does not permit null. TreeSet, HashSet, and LinkedHashSet all allow null elements. Additionally, TreeSet has the requirement that elements implement Comparable.

It seems that no such basic Set exists currently. Does anyone know why? Or if one does exist where I can find it?

[Edit]: I do not want to allow nulls, because later in the code my class will iterate over all elements in the collection and call a specific method. (I'm actually using HashSet<MyRandomObject>). I would rather fail fast than fail later or accidentally incur some bizarre behavior due to a null being in the set.

答:
for me, I didn't find one,
so I overrode the add function

```<code>Collection<String> errors = new HashSet<String>() {
    @Override
    public boolean add(String s) {
        return StringUtil.hasContent(s) && super.add(s);//we don't want add null and we allow HashSet.add(null)
    }
};
</code>```

OwnerDisplayName: Aaron K

LastEditorDisplayName: Aaron K

Body:
for me, I didn't find one,
so I overrode the add function

Collection<String> errors = new HashSet<String>() {
    @Override
    public boolean add(String s) {
        return StringUtil.hasContent(s) && super.add(s);//we don't want add null and we allow HashSet.add(null)
    }
};


问:
[LAContext biometryType]: unrecognized selector on iOS 11.0.0
I see dozens of crashes in fabric

```<code>Fatal Exception: NSInvalidArgumentException
-[LAContext biometryType]: unrecognized selector sent to instance 0x1c066aa00
</code>```

And it's strange because I do call biometryType on LAContext only for iOS 11+.

The code:

```<code>    private static var biometryType: BiometryType? {
        let context = LAContext()

        guard context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil),
            context.evaluatedPolicyDomainState == BiometryManager.savedPolicyDomainState else { return nil }

        if #available(iOS 11.0, *) {
            switch context.biometryType {
            case .typeFaceID: return .typeFaceID
            case .typeTouchID: return .typeTouchID
            case .none: return nil
            }
        }
        return .typeTouchID
    }
</code>```

Any suggestions?

The only clue I have is that all crashes related to 11.0.0. So maybe Apple added biometryType not in 11.0.0 but a bit later.

Links:

https://developer.apple.com/documentation/localauthentication/lacontext/2867583-biometrytype

http://www.codeprocedures.com/question/nsinvalidargumentexception-unrecognized-selector-sent-to-instance-on-specific-phone-with-ios-11/

答:
It's not much of a solution, but this appears to be a bug in iOS 11.0.

I've seen multiple reports of this crash and all have been resolved when the user upgraded to a more recent version of iOS.

Body:
I see dozens of crashes in fabric

Fatal Exception: NSInvalidArgumentException
-[LAContext biometryType]: unrecognized selector sent to instance 0x1c066aa00

And it's strange because I do call biometryType on LAContext only for iOS 11+.

The code:

    private static var biometryType: BiometryType? {
        let context = LAContext()

        guard context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil),
            context.evaluatedPolicyDomainState == BiometryManager.savedPolicyDomainState else { return nil }

        if #available(iOS 11.0, *) {
            switch context.biometryType {
            case .typeFaceID: return .typeFaceID
            case .typeTouchID: return .typeTouchID
            case .none: return nil
            }
        }
        return .typeTouchID
    }

Any suggestions?

The only clue I have is that all crashes related to 11.0.0. So maybe Apple added biometryType not in 11.0.0 but a bit later.

Links:

https://developer.apple.com/documentation/localauthentication/lacontext/2867583-biometrytype

http://www.codeprocedures.com/question/nsinvalidargumentexception-unrecognized-selector-sent-to-instance-on-specific-phone-with-ios-11/


问:
Digest auth using http-auth
Trying to implement Digest auth in nodejs. Below is the code

```<code>var http = require('http');
var auth = require('http-auth');
var express = require('express');
var app = express();
var user;

var basic = auth.basic({
    realm: 'Sample',
    file: __dirname + "/users.htpasswd",
    algorithm:'md5'
});

basic.on('success', (result, req) => {
    console.log(`User authenticated: ${result.user}`);
    user = result.user;
});

basic.on('fail', (result, req) => {
    console.log(`User authentication failed: ${result.user}`);
    console.log(req.headers.authorization);
});

basic.on('error', (error, req) => {
    console.log(`Authentication error: ${error.code + " - " + error.message}`);
});

http.createServer(app).listen(8000);

app.use(auth.connect(basic));

app.get('/', function(req, res) {
    console.log(req.headers);
    console.log(basic);
    res.json('Hello from '+ user);
    res.end();
});

app.post('/', function(req, res) {
    console.log(req.headers);
    console.log(basic);
    res.json('Hello from '+ user);
    res.end();
});
</code>```

This is the content of users.htpasswd file:-
ankit:Sample:e4b2d19b03346a1c45ce86ad41b85c5e

Using postman to call the end point with username ankit, pwd ankit & realm Sample, everytime I am getting 401.

Please let me know where I am doing wrong.

Thanks

答: You're mixing basic auth and digest auth. Replace auth.basic with auth.digest and your code should work as-is.

Title: Digest auth using http-auth

Body:
Trying to implement Digest auth in nodejs. Below is the code

var http = require('http');
var auth = require('http-auth');
var express = require('express');
var app = express();
var user;

var basic = auth.basic({
    realm: 'Sample',
    file: __dirname + "/users.htpasswd",
    algorithm:'md5'
});

basic.on('success', (result, req) => {
    console.log(`User authenticated: ${result.user}`);
    user = result.user;
});

basic.on('fail', (result, req) => {
    console.log(`User authentication failed: ${result.user}`);
    console.log(req.headers.authorization);
});

basic.on('error', (error, req) => {
    console.log(`Authentication error: ${error.code + " - " + error.message}`);
});

http.createServer(app).listen(8000);

app.use(auth.connect(basic));

app.get('/', function(req, res) {
    console.log(req.headers);
    console.log(basic);
    res.json('Hello from '+ user);
    res.end();
});

app.post('/', function(req, res) {
    console.log(req.headers);
    console.log(basic);
    res.json('Hello from '+ user);
    res.end();
});

This is the content of users.htpasswd file:-
ankit:Sample:e4b2d19b03346a1c45ce86ad41b85c5e

Using postman to call the end point with username ankit, pwd ankit & realm Sample, everytime I am getting 401.

Please let me know where I am doing wrong.

Thanks


问:
Multiple Permission at once not working in android
I am trying to get 2 permissions at once but Iam unable to do so.

```<code>if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

    if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(context, Array<String>(2) {
            Manifest.permission.READ_CONTACTS;
            Manifest.permission.WRITE_EXTERNAL_STORAGE},
        1);
    }
}
</code>```

It only asks for WRITE_EXTERNAL_STORAGE permission and not READ_CONTACTS. Actually, If I write WRITE_EXTERNAL_STORAGE one first and READ_CONTACTS after that then it will only ask for contact and not WRITE_EXTERNAL_STORAGE.

答:
Use this code for multiple permission in kotlin</p>

```<code> ActivityCompat.requestPermissions(context as Activity,
                                arrayOf(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE),
                                PERMISSION_CAMER)
</code>```

Body:
I am trying to get 2 permissions at once but Iam unable to do so.

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

    if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(context, Array<String>(2) {
            Manifest.permission.READ_CONTACTS;
            Manifest.permission.WRITE_EXTERNAL_STORAGE},
        1);
    }
}

It only asks for WRITE_EXTERNAL_STORAGE permission and not READ_CONTACTS. Actually, If I write WRITE_EXTERNAL_STORAGE one first and READ_CONTACTS after that then it will only ask for contact and not WRITE_EXTERNAL_STORAGE.

Body:
Use this code for multiple permission in kotlin

 ActivityCompat.requestPermissions(context as Activity,
                                arrayOf(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE),
                                PERMISSION_CAMER)


问:
Testing ES2015 class with Intern v4
How do I import my class and write unit tests using Intern v4. I keep running into an error SyntaxError: Unexpected token import

Unit test file demo.js:

```<code>import Demo from '../../app/demo.js';

const { suite, test } = intern.getInterface('tdd');
const { assert } = intern.getPlugin('chai');
const { expect } = intern.getPlugin('chai');
</code>```

Demo.js class:

```<code>class Demo{
  constructor(){

  }

  print(){
    console.log(`hello world`);
  }

}

export default {Demo};
</code>```

答:
JS's module system (import/export) isn't natively supported by many environments yet. To use that syntax you'll need to use a module loader like SystemJS, or babel-register (see this page in the docs).

Most of the examples for Intern 4 assume tests are written in TypeScript and then built to CommonJS or AMD/UMD modules.

Title: Testing ES2015 class with Intern v4

Body:
How do I import my class and write unit tests using Intern v4. I keep running into an error SyntaxError: Unexpected token import

Unit test file demo.js:

import Demo from '../../app/demo.js';

const { suite, test } = intern.getInterface('tdd');
const { assert } = intern.getPlugin('chai');
const { expect } = intern.getPlugin('chai');

Demo.js class:

class Demo{
  constructor(){

  }

  print(){
    console.log(`hello world`);
  }

}

export default {Demo};


答:
Your algorithm seems to check only four most distant points on X and Y axis. I guess that if you provide points that represent square shape it will also pass is_circle test.

I propose that you do two-stage test with some extra roundness margin called e. Walk over whole set of points and remember x_min, y_min, x_max and y_max. Then make check if difference between delta of X and delta of Y is in the error margin i.e. abs((x_max-x_min) - (y_max-y_min)) <= e. That checks squarness of shape so that it can be circle, not oval. If that test passes then calculate center point c at (x_c, y_c) = (x_min+(x_max-x_min)/2, y_min+(y_max-y_min)/2) and for each point calculate if radius (distance from any point to center c) is within error margin e. To save on expensive calculations check if squared radius of each point is within error margin i.e. if abs((x-x_c)^2 + (y-y_c)^2 - r^2) <= e, where r^2 is computed for center c and first point on the list.

Title: javascript algorithm: Check x/y-points to get if component is a circle or not

Body:
I have an matrix like this, so I hope you can get the circle outline:

EDIT 1: What about the outline? The outline doesn't includes spaces (so every y-value gets minimum 2 x-values)

EDIT 2: What is a circle? Searching for an more ore less "exact circles" like the example below! (nearly same radius at every point)

    00000000000000000000000000000000
    00000000000001111111100000000000
    00000000000100000000010000000000
    00000000010000000000000100000000
    00000000100000000000000010000000
    00000000100000000000000010000000
    00000001000000000000000001000000
    00000010000000000000000000100000
    00000010000000000000000000100000
    00000010000000000000000000100000
    00000100000000000000000000100000
    00000100000000000000000000100000
    00000100000000000000000000100000
    00000100000000000000000000100000
    00000100000000000000000000100000
    00000010000000000000000000100000
    00000010000000000000000000100000
    00000010000000000000000001000000
    00000001000000000000000010000000
    00000000100000000000000010000000
    00000000100000000000000100000000
    00000000010000000000001000000000
    00000000000111111111100000000000
    00000000000000000000000000000000
    00000000000000000000000000000000

and I also have an array like this including all positions of the outline:

var coordinates = [
  [13,1],[14,1],[15,1],[16,1],[17,1],[18,1],[19,1],[20,1],
  [11,2],[21,2],
  [9,3],[23,3],
  [8,4],[24,4],
  [8,5],[24,5],
  [7,6],[25,6],
  [6,7],[26,7],
  [6,8],[26,8],
  [6,9],[26,9],
  [5,10],[26,10],
  [5,11],[26,11],
  [5,12],[26,12],
  [5,13],[26,13],
  [5,14],[26,14],
  [6,15],[26,15],
  [6,16],[26,16],
  [6,17],[25,17],
  [7,18],[24,18],
  [8,19],[24,19],
  [8,20],[23,20],
  [9,21],[22,21],
  [11,22],[12,22],[13,22],[14,22],[15,22],[16,22],[17,22],[18,22],[19,22],[20,22]]

What is a good way to check if the coordinates are matching to be a circle?

My first idea was using some code like this but tbh I'm sure there is a way more efficient & working way:

var circle = [[13,1],[14,1],[15,1],[16,1],[17,1],[18,1],[19,1],[20,1],[11,2],[21,2],[9,3],[23,3],[8,4],[24,4],[8,5],[24,5],[7,6],[25,6],[6,7],[26,7],[6,8],[26,8],[6,9],[26,9],[5,10],[26,10],[5,11],[26,11],[5,12],[26,12],[5,13],[26,13],[5,14],[26,14],[6,15],[26,15],[6,16],[26,16],[6,17],[25,17],[7,18],[24,18],[8,19],[24,19],[8,20],[23,20],[9,21],[22,21],[11,22],[12,22],[13,22],[14,22],[15,22],[16,22],[17,22],[18,22],[19,22],[20,22]]

var no_circle= [[13,1],[14,1],[25,4]]

Array.prototype.is_circle = function() {
var min = {
 'x': Infinity,
 'y': Infinity
};
var max = {
 'x': 0,
 'y': 0
};
var center = {
 'x': 0,
 'y': 0
};
var radius;
this.forEach(function(a) {
  a[0] = a[0]
  a[1] = a[1]
 if (a[0] > max.x) max.x = a[0];
 if (a[0] < min.x) min.x = a[0];
 if (a[1] > max.y) max.y = a[1];
 if (a[1] < min.y) min.y = a[1];
});
center.x = (max.x + min.x) / 2;
center.y = (max.y + min.y) / 2;
radius = []
radius[0] = max.x - center.x
radius[1] = center.x - min.x
radius[2] = center.y - min.y
radius[3] = max.y - center.y

r = (radius[0] + radius[1] + radius[2] + radius[3]) / 4;

if ((radius[0] > r-1 && radius[0] < r+1) && (radius[1] > r-1 && radius[1] < r+1) && (radius[2] > r-1 && radius[2] < r+1) && (radius[3] > r-1 && radius[3] < r+1)) return true;

   return false

}

var result1 = circle.is_circle();
console.log(result1)

var result2 = no_circle.is_circle();
console.log(result2)


问:
Apache Web Server : ProxyPass and ProxyPassReverse
I have scanned through the internet and also stackoverflow and I'm still not sure of the purpose of proxypass and proxypassreverse.

Why do we need proxypass (instead of using mod_jk) for apache server to connect to tomcat?

答:
The ProxyPassReverse is used to change the headers sent to Apache from a proxied app server, before Apache sends it to the browser.

For example, if the app sits on localhost:8080, it will respond with a redirect and location header of http://localhost:8080/new_path/, and Apache will take this and send it off to the browser. The browser will try to send a request to Page on localhost:8080 and receive an error.

ProxyPassReverse will intercept those headers, and rewrite them to match the Apache proxy server.

ProxyPass will create a reverse proxy. A reverse proxy (or gateway), appears to the client just like an ordinary web server. The client makes ordinary requests for content in the namespace of the reverse proxy. The reverse proxy then decides where to send those requests and returns the content as if it were itself the origin.

https://www.quora.com/Whats-the-difference-between-proxypassreverse-and-proxypass

https://httpd.apache.org/docs/2.4/mod/mod_proxy.html

ContentLicense: CC BY-SA 4.0


问:
Hide a div if sibling has an specific class
I have a div with the grafico class, and it has two children. One of them, the one with "terminal-alert" class, should not appear if it's sibling, the grafico-arc has the specific "green" class.
I tried the jquery below, and managed to hide the "terminal-alert" div, but it does not appear on the ones where the sibling doesn't have the "green" class.

$(".grafico-arc").each(function() {
  if ($(this).hasClass("green")) {
    $(".terminal-alert").siblings().css("display", "none");
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sliderCard">
  <div class="grafico">

    <div class="grafico-arc green">
      <div class="topo"></div>

      <div class="consumoTerminal">
        <h3>1 <span>GB</span></h3>
        <p>(21) 98899-0805</p>
        <button class="detail"></button>
      </div>

    </div>

    <div class="terminal-alert">
      <p>Saldo esgotando Mais internet</p>
    </div>

  </div>
</div>

<div class="sliderCard">
  <div class="grafico">

    <div class="grafico-arc yellow">
      <div class="topo"></div>

      <div class="consumoTerminal">
        <h3>2 <span>GB</span></h3>
        <p>(21) 98899-0805</p>
        <button class="detail"></button>
      </div>

    </div>

    <div class="terminal-alert">
      <p>Saldo esgotando Mais internet</p>
    </div>

  </div>
</div>

<div class="sliderCard">
  <div class="grafico">

    <div class="grafico-arc red">
      <div class="topo"></div>

      <div class="consumoTerminal">
        <h3>3 <span>GB</span></h3>
        <p>(21) 98899-0805</p>
        <button class="detail"></button>
      </div>

    </div>

    <div class="terminal-alert">
      <p>Saldo esgotando Mais internet</p>
    </div>

  </div>
</div></code>```

答:
Use $(this) instead of $(".terminal-alert")

$(".grafico-arc").each(function() {
  if ($(this).hasClass("green")) {
    $(this).siblings().css("display", "none");
    //---------------------^ // also you can use hide();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sliderCard">
  <div class="grafico">

    <div class="grafico-arc green">
      <div class="topo"></div>

      <div class="consumoTerminal">
        <h3>1 <span>GB</span></h3>
        <p>(21) 98899-0805</p>
        <button class="detail"></button>
      </div>

    </div>

    <div class="terminal-alert">
      <p>Saldo esgotando Mais internet</p>
    </div>

  </div>
</div>

<div class="sliderCard">
  <div class="grafico">

    <div class="grafico-arc yellow">
      <div class="topo"></div>

      <div class="consumoTerminal">
        <h3>2 <span>GB</span></h3>
        <p>(21) 98899-0805</p>
        <button class="detail"></button>
      </div>

    </div>

    <div class="terminal-alert">
      <p>Saldo esgotando Mais internet</p>
    </div>

  </div>
</div>

<div class="sliderCard">
  <div class="grafico">

    <div class="grafico-arc red">
      <div class="topo"></div>

      <div class="consumoTerminal">
        <h3>3 <span>GB</span></h3>
        <p>(21) 98899-0805</p>
        <button class="detail"></button>
      </div>

    </div>

    <div class="terminal-alert">
      <p>Saldo esgotando Mais internet</p>
    </div>

  </div>
</div></code>```

Body:
I have a div with the grafico class, and it has two children. One of them, the one with "terminal-alert" class, should not appear if it's sibling, the grafico-arc has the specific "green" class.
I tried the jquery below, and managed to hide the "terminal-alert" div, but it does not appear on the ones where the sibling doesn't have the "green" class.

$(".grafico-arc").each(function() {
  if ($(this).hasClass("green")) {
    $(".terminal-alert").siblings().css("display", "none");
  }
});

1 GB

(21) 98899-0805

        <button class="detail"></button>

Saldo esgotando Mais internet

2 GB

(21) 98899-0805

        <button class="detail"></button>

Saldo esgotando Mais internet

3 GB

(21) 98899-0805

        <button class="detail"></button>

Saldo esgotando Mais internet

Body:
Use $(this) instead of $(".terminal-alert")

$(".grafico-arc").each(function() {
  if ($(this).hasClass("green")) {
    $(this).siblings().css("display", "none");
    //---------------------^ // also you can use hide();
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sliderCard">
  <div class="grafico">

    <div class="grafico-arc green">
      <div class="topo"></div>

      <div class="consumoTerminal">
        <h3>1 <span>GB</span></h3>
        <p>(21) 98899-0805</p>
        <button class="detail"></button>
      </div>

    </div>

    <div class="terminal-alert">
      <p>Saldo esgotando <a href="#">Mais internet</a></p>
    </div>

  </div>
</div>

<div class="sliderCard">
  <div class="grafico">

    <div class="grafico-arc yellow">
      <div class="topo"></div>

      <div class="consumoTerminal">
        <h3>2 <span>GB</span></h3>
        <p>(21) 98899-0805</p>
        <button class="detail"></button>
      </div>

    </div>

    <div class="terminal-alert">
      <p>Saldo esgotando <a href="#">Mais internet</a></p>
    </div>

  </div>
</div>

<div class="sliderCard">
  <div class="grafico">

    <div class="grafico-arc red">
      <div class="topo"></div>

      <div class="consumoTerminal">
        <h3>3 <span>GB</span></h3>
        <p>(21) 98899-0805</p>
        <button class="detail"></button>
      </div>

    </div>

    <div class="terminal-alert">
      <p>Saldo esgotando <a href="#">Mais internet</a></p>
    </div>

  </div>
</div>


问:
Invalid Token. Not accepting integers that start with 0
So I'm trying to make a check digit function, and embarrassingly, I've already run into a snag early on that I've been trying to search the problem for, but most of the explanations I've run into are unfortunately beyond my comprehension. I'm hoping someone could give me a specific run-down as to what my problem is right now

```<code>mam = []

def check_digit():
    a = int(input("Please enter your 10 digit book number"))
    b = str(a)
    for c in b:
        mam.append(c)
        print(c)

check_digit()
</code>```

Sorry about no set names for variables, I prefer coding this way even if it eventually gets awkward for others to read. Well anyway, every time I write in an integer which starts with 0, the Syntax error "Invalid token" appears and I don't know how to solve it. Could anyone help me? I would be grateful

Fixed. I really need to update Python, I'm running 2.7 at the moment.

raw_input solved the issue

答:
This fixed the problem of str versus int with me:

```<code>mam = []

def check_digit():
    a = str(input("Please enter your 10 digit book number: "))
    [mam.append(int(inputted)) for inputted in a]
    print(mam)

check_digit()
print(mam[0] + mam[1])
print(type(mam[0]))
</code>```

input:

```<code>Please enter your 10 digit book number: 0123456789
</code>```

output:

```<code>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1
<class 'int'>
</code>```

Body:
So I'm trying to make a check digit function, and embarrassingly, I've already run into a snag early on that I've been trying to search the problem for, but most of the explanations I've run into are unfortunately beyond my comprehension. I'm hoping someone could give me a specific run-down as to what my problem is right now

mam = []

def check_digit():
    a = int(input("Please enter your 10 digit book number"))
    b = str(a)
    for c in b:
        mam.append(c)
        print(c)

check_digit()

Sorry about no set names for variables, I prefer coding this way even if it eventually gets awkward for others to read. Well anyway, every time I write in an integer which starts with 0, the Syntax error "Invalid token" appears and I don't know how to solve it. Could anyone help me? I would be grateful

Fixed. I really need to update Python, I'm running 2.7 at the moment.

raw_input solved the issue

Body:
This fixed the problem of str versus int with me:

mam = []

def check_digit():
    a = str(input("Please enter your 10 digit book number: "))
    [mam.append(int(inputted)) for inputted in a]
    print(mam)

check_digit()
print(mam[0] + mam[1])
print(type(mam[0]))

input:

Please enter your 10 digit book number: 0123456789

output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1
<class 'int'>


问:
How to grep and execute command for every multiline match
Is there the possibility to process a multiline grep-output by one command each?

I've got something like

```<code><fulldata>
<value>1</value>
<value>2</value>
</fulldata>
<fulldata>
<value>2</value>
<value>3</value>
</fulldata>
</code>```

and want to get means, standard deviation and do some other things with data-element on its own.

In this case, I want to execute

```<code>function printStatistics {
        mean1=$(awk -F ';' '{print $1}' $1 | awk '{sum += $1; square += $1^2} END {print sum / NR}')
        deviation1=$(awk -F ';' '{print $1}' $1 | awk '{sum += $1; square += $1^2} END {print sqrt(square / NR - (sum/NR)^2)}')
        size=$(cat $1 | wc -l)
        echo $mean1 $deviation1 $size
}
</code>```

with the expected result (for the sample data), idealy separated by newline:

```<code>1,5 0,7 2
2,5 0,7 2
</code>```

Running

```<code>cat add.xml | grep "<fulldata" -A 2001 | while read line ; do echo "Line: $line" ; done
</code>```

like suggested in How to grep and execute a command (for every match) does result in one entry for each line; but I want one entry for each entry (in order to execute awk stuff on it later).

Is this possible with grep, or is this a use case where another language would be more appropriate?

答:
Complex xmlstarlet + awk solution:

```<code>xmlstarlet ed -u "//fulldata/value" -x "concat(.,',')" add.xml \
| xmlstarlet sel -B -t -v "//fulldata" -n \
| awk -F, '{ n=NF-1; sum=sq=0; for(i=1;i<=n;i++) { sum+=$i; sq+=$i^2 }
  printf "%.1f\n%.1f\n%d\n", sum/n, sqrt((sq-sum^2/n)/(n-1)), n }'
</code>```

The output:

```<code>1.5
0.7
2
2.5
0.7
2
</code>```

Body:
Is there the possibility to process a multiline grep-output by one command each?

I've got something like

<fulldata>
<value>1</value>
<value>2</value>
</fulldata>
<fulldata>
<value>2</value>
<value>3</value>
</fulldata>

and want to get means, standard deviation and do some other things with data-element on its own.

In this case, I want to execute

function printStatistics {
        mean1=$(awk -F ';' '{print $1}' $1 | awk '{sum += $1; square += $1^2} END {print sum / NR}')
        deviation1=$(awk -F ';' '{print $1}' $1 | awk '{sum += $1; square += $1^2} END {print sqrt(square / NR - (sum/NR)^2)}')
        size=$(cat $1 | wc -l)
        echo $mean1 $deviation1 $size
}

with the expected result (for the sample data), idealy separated by newline:

1,5 0,7 2
2,5 0,7 2

Running

cat add.xml | grep "<fulldata" -A 2001 | while read line ; do echo "Line: $line" ; done

like suggested in How to grep and execute a command (for every match) does result in one entry for each line; but I want one entry for each entry (in order to execute awk stuff on it later).

Is this possible with grep, or is this a use case where another language would be more appropriate?

Body:
Complex xmlstarlet + awk solution:

xmlstarlet ed -u "//fulldata/value" -x "concat(.,',')" add.xml \
| xmlstarlet sel -B -t -v "//fulldata" -n \
| awk -F, '{ n=NF-1; sum=sq=0; for(i=1;i<=n;i++) { sum+=$i; sq+=$i^2 }
  printf "%.1f\n%.1f\n%d\n", sum/n, sqrt((sq-sum^2/n)/(n-1)), n }'

The output:

1.5
0.7
2
2.5
0.7
2


问:
python dictionaries - combine values
I have these dictionaries

```<code>{
    'id': 5,
    'quantity: 10
}

{
    'id': 5,
    'quantity: 15
}
</code>```

I want something like this

```<code>{
    'id': 5,
    'quantity': 25
}
</code>```

EDIT: Basically, I want to combine the quantity of similar ids
Sorry if I simplified my question way too much. Yes I have a list of these dicts

```<code>products = [{...}, {...}, {...}, ...]
</code>```

答:
You can use a dict comprehension.

```<code>d = {key: dict1[key] + dict2[key] for key in dict1}
</code>```

This will work if and only if your dictionaries have exactly the same keys. In more complex situations, you'll either have unrepresented keys or throw a KeyError. If this is a problem, you might try using collections.Counter objects (avoids KeyError by having default values of 0 for integers) or just refactoring your code and breaking this out into a loop to get exactly what you need.

This will work if there is a chance that the dicts will have different IDs:

```<code>from collections import Counter
c1 = Counter(dict1)

for key in dict2:
   c1[key] += dict2[key]
</code>```

c1 is your added-together dict. If dict1 has keys that aren't in dict2, they will appear in c1 from the initialization step. If dict2 has keys that aren't in dict1, they will be added to c1 without modification.

Title: python dictionaries - combine values

Body:
I have these dictionaries

{
    'id': 5,
    'quantity: 10
}

{
    'id': 5,
    'quantity: 15
}

I want something like this

{
    'id': 5,
    'quantity': 25
}

EDIT: Basically, I want to combine the quantity of similar ids
Sorry if I simplified my question way too much. Yes I have a list of these dicts

products = [{...}, {...}, {...}, ...]

Body:
You can use a dict comprehension.

d = {key: dict1[key] + dict2[key] for key in dict1}

This will work if and only if your dictionaries have exactly the same keys. In more complex situations, you'll either have unrepresented keys or throw a KeyError. If this is a problem, you might try using collections.Counter objects (avoids KeyError by having default values of 0 for integers) or just refactoring your code and breaking this out into a loop to get exactly what you need.

This will work if there is a chance that the dicts will have different IDs:

from collections import Counter
c1 = Counter(dict1)

for key in dict2:
   c1[key] += dict2[key]

c1 is your added-together dict. If dict1 has keys that aren't in dict2, they will appear in c1 from the initialization step. If dict2 has keys that aren't in dict1, they will be added to c1 without modification.


问:
PHP — Convert milliseconds to Hours : Minutes : Seconds.fractional
I've got a script that takes in a value in seconds (to 2 decimal points of fractional seconds):

```<code>$seconds_input = 23.75
</code>```

I then convert it to milliseconds:

```<code>$milliseconds = $seconds_input * 1000; // --> 23750
</code>```

And then I want to format it like so:

```<code>H:M:S.x // --> 0:0:23.75
</code>```

Where 'x' is the fraction of the second (however many places after the decimal there are).

Any help? I can't seem to wrap my mind around this. I tried using gmdate() but it kept lopping off the fractional seconds.

Thanks.

答:
Mine is much less readable, so it must be better. :p

Basically the same idea as @ircmaxell's version. It does trim the trailing '0's and even will skip the last '.' separator if milliseconds are 0.

```<code><?

function format_period($seconds_input)
{
  $hours = (int)($minutes = (int)($seconds = (int)($milliseconds = (int)($seconds_input * 1000)) / 1000) / 60) / 60;
  return $hours.':'.($minutes%60).':'.($seconds%60).(($milliseconds===0)?'':'.'.rtrim($milliseconds%1000, '0'));
}

echo format_period(23.75);
</code>```

Body:
I've got a script that takes in a value in seconds (to 2 decimal points of fractional seconds):

$seconds_input = 23.75

I then convert it to milliseconds:

$milliseconds = $seconds_input * 1000; // --> 23750

And then I want to format it like so:

H:M:S.x // --> 0:0:23.75

Where 'x' is the fraction of the second (however many places after the decimal there are).

Any help? I can't seem to wrap my mind around this. I tried using gmdate() but it kept lopping off the fractional seconds.

Thanks.

Body:
Mine is much less readable, so it must be better. :p

Basically the same idea as @ircmaxell's version. It does trim the trailing '0's and even will skip the last '.' separator if milliseconds are 0.

<?

function format_period($seconds_input)
{
  $hours = (int)($minutes = (int)($seconds = (int)($milliseconds = (int)($seconds_input * 1000)) / 1000) / 60) / 60;
  return $hours.':'.($minutes%60).':'.($seconds%60).(($milliseconds===0)?'':'.'.rtrim($milliseconds%1000, '0'));
}

echo format_period(23.75);


问:
The difference between console.log and return in javaScript
So I created two different functions to build triangles out of asterisks: buildTriangle and buildTriangle2. The makeLine function is just used to make the lines in the triangles. This is what my code looks like:

function makeLine(length) {
  var line = "";
  for (var j = 1; j <= length; j++) {
    line += "* "
  }
  return line + "\n";
}

// This is the build triangle function with the return key
function buildTriangle(triWidth) {
    var y = ""
    for(var i = 0; i <= triWidth; i++) {
        y += makeLine(i)
    }
    return y;
}

console.log(buildTriangle(10))

// This is the build triangle function with console.log
function buildTriangle2(triWidth) {
    for(var i = 0; i <= triWidth; i++) {
        console.log(makeLine(i));
    }
}

buildTriangle2(10)```

The output looks like this: https://i.stack.imgur.com/QrHxO.png.
First, I just had a quick question as to why there are spaces between each line in the second output and not in the first. Also, I just wanted to know why the the function with the return key needs to store the information in the variable first and then return it? Why is this not the case in the second function that uses the console.log? I am asking this question because I think these two functions illustrate the differences between console.log and return. Also, since I don't understand the difference between console.log and return I was hoping someone could explain it by using these functions. I also believe this will help other beginners besides for myself.

答:
return doesn't do anything to the value, so you build what you want and you get exactly that.

console.log() is meant for outputting stuff (mainly for development purposes originally, but now with things like Node.js, also for general output).

In most environments, console.log() will always include a newline on it's own (similar to other languages println() functions).

That's why you need to have the \n for the return, and not for console.log(), since it is basically adding one to each line for you. If you add an extra \n yourself, you'll end up with a blank line.

Body:
So I created two different functions to build triangles out of asterisks: buildTriangle and buildTriangle2. The makeLine function is just used to make the lines in the triangles. This is what my code looks like:

function makeLine(length) {
  var line = "";
  for (var j = 1; j <= length; j++) {
    line += "* "
  }
  return line + "\n";
}

// This is the build triangle function with the return key
function buildTriangle(triWidth) {
    var y = ""
    for(var i = 0; i <= triWidth; i++) {
        y += makeLine(i)
    }
    return y;
}

console.log(buildTriangle(10))

// This is the build triangle function with console.log
function buildTriangle2(triWidth) {
    for(var i = 0; i <= triWidth; i++) {
        console.log(makeLine(i));
    }
}

buildTriangle2(10)

The output looks like this: https://i.stack.imgur.com/QrHxO.png.
First, I just had a quick question as to why there are spaces between each line in the second output and not in the first. Also, I just wanted to know why the the function with the return key needs to store the information in the variable first and then return it? Why is this not the case in the second function that uses the console.log? I am asking this question because I think these two functions illustrate the differences between console.log and return. Also, since I don't understand the difference between console.log and return I was hoping someone could explain it by using these functions. I also believe this will help other beginners besides for myself.


答:
It appears as if you can do this with just some CSS, no JavaScript or jQuery needed:

```<code>.grafico-arc.green+.terminal-alert {
  display: none;
}
</code>```

.grafico-arc.green+.terminal-alert {
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="sliderCard">
  <div class="grafico">

    <div class="grafico-arc green">
      <div class="topo"></div>

      <div class="consumoTerminal">
        <h3>1 <span>GB</span></h3>
        <p>(21) 98899-0805</p>
        <button class="detail"></button>
      </div>

    </div>

    <div class="terminal-alert">
      <p>Saldo esgotando Mais internet</p>
    </div>

  </div>
</div>

<div class="sliderCard">
  <div class="grafico">

    <div class="grafico-arc yellow">
      <div class="topo"></div>

      <div class="consumoTerminal">
        <h3>2 <span>GB</span></h3>
        <p>(21) 98899-0805</p>
        <button class="detail"></button>
      </div>

    </div>

    <div class="terminal-alert">
      <p>Saldo esgotando Mais internet</p>
    </div>

  </div>
</div>

<div class="sliderCard">
  <div class="grafico">

    <div class="grafico-arc red">
      <div class="topo"></div>

      <div class="consumoTerminal">
        <h3>3 <span>GB</span></h3>
        <p>(21) 98899-0805</p>
        <button class="detail"></button>
      </div>

    </div>

    <div class="terminal-alert">
      <p>Saldo esgotando Mais internet</p>
    </div>

  </div>
</div></code>```

Title: Hide a div if sibling has an specific class

Body:
It appears as if you can do this with just some CSS, no JavaScript or jQuery needed:

.grafico-arc.green+.terminal-alert {
  display: none;
}

.grafico-arc.green+.terminal-alert {
  display: none;
}

<div class="sliderCard">
  <div class="grafico">

    <div class="grafico-arc green">
      <div class="topo"></div>

      <div class="consumoTerminal">
        <h3>1 <span>GB</span></h3>
        <p>(21) 98899-0805</p>
        <button class="detail"></button>
      </div>

    </div>

    <div class="terminal-alert">
      <p>Saldo esgotando <a href="#">Mais internet</a></p>
    </div>

  </div>
</div>

<div class="sliderCard">
  <div class="grafico">

    <div class="grafico-arc yellow">
      <div class="topo"></div>

      <div class="consumoTerminal">
        <h3>2 <span>GB</span></h3>
        <p>(21) 98899-0805</p>
        <button class="detail"></button>
      </div>

    </div>

    <div class="terminal-alert">
      <p>Saldo esgotando <a href="#">Mais internet</a></p>
    </div>

  </div>
</div>

<div class="sliderCard">
  <div class="grafico">

    <div class="grafico-arc red">
      <div class="topo"></div>

      <div class="consumoTerminal">
        <h3>3 <span>GB</span></h3>
        <p>(21) 98899-0805</p>
        <button class="detail"></button>
      </div>

    </div>

    <div class="terminal-alert">
      <p>Saldo esgotando <a href="#">Mais internet</a></p>
    </div>

  </div>
</div>


问:
Git Pull is Not Possible, Unmerged Files
I've read all of the similar questions on this; it seems that none of the following have worked:

```<code>Delete offending files
git reset --hard HEAD
git stash
git pull
</code>```

Nearly every combination, stashing changes and pulling from repository, results in unmergable files. I'd like to discard all local changes and just use the remote, but I cannot clone again (bandwidth and internet usage limitations with the developer trying to do this). How do I do this?

Just tried:

```<code>git stash
git pull
</code>```

Also did not work.

More Info

There is one local commit, and the upstream has a commit as well. I've thus tried git pull --rebase but it's still not working properly... That gives me errors - "exiting because of an unresolved conflict". If I do git stash, git reset --hard HEAD, git pull --rebase, I get the error "pull is not possible, unmerged changes..."

答:
Ryan Stewart's answer was almost there. In the case where you actually don't want to delete your local changes, there's a workflow you can use to merge:

Run git status. It will give you a list of unmerged files.

Merge them (by hand, etc.)

Run git commit

Git will commit just the merges into a new commit. (In my case, I had additional added files on disk, which weren't lumped into that commit.)

Git then considers the merge successful and allows you to move forward.

Body:
I've read all of the similar questions on this; it seems that none of the following have worked:

Delete offending files
git reset --hard HEAD
git stash
git pull

Nearly every combination, stashing changes and pulling from repository, results in unmergable files. I'd like to discard all local changes and just use the remote, but I cannot clone again (bandwidth and internet usage limitations with the developer trying to do this). How do I do this?

Just tried:

git stash
git pull

Also did not work.

More Info

There is one local commit, and the upstream has a commit as well. I've thus tried git pull --rebase but it's still not working properly... That gives me errors - "exiting because of an unresolved conflict". If I do git stash, git reset --hard HEAD, git pull --rebase, I get the error "pull is not possible, unmerged changes..."


答:
This might not be the way you wish to do this since you specified jQuery, but I want to leave this here anyway. (a jQuery version is further down)

CSS Version:

You can accomplish the same principal using only CSS with the Adjacent Sibling Combinator.

"The adjacent sibling combinator (+) separates two selectors and matches the second element only if it immediately follows the first element, and both are children of the same parent element."

.grafico-arc.green + .terminal-alert {
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="sliderCard">
    <div class="grafico">
        <div class="grafico-arc green">
            <div class="topo"></div>

            <div class="consumoTerminal">
                <h3>1 <span>GB</span></h3>
                <p>(21) 98899-0805</p>
                <button class="detail"></button>
            </div>
        </div>
        <div class="terminal-alert">
            <p>Saldo esgotando Mais internet</p>
        </div>
    </div>
</div>

<div class="sliderCard">
    <div class="grafico">
        <div class="grafico-arc yellow">
            <div class="topo"></div>
            <div class="consumoTerminal">
                <h3>2 <span>GB</span></h3>
                <p>(21) 98899-0805</p>
                <button class="detail"></button>
            </div>
        </div>
        <div class="terminal-alert">
            <p>Saldo esgotando Mais internet</p>
        </div>
    </div>
</div>
<div class="sliderCard">
    <div class="grafico">
        <div class="grafico-arc red">
            <div class="topo"></div>
            <div class="consumoTerminal">
                <h3>3 <span>GB</span></h3>
                <p>(21) 98899-0805</p>
                <button class="detail"></button>
            </div>
        </div>
        <div class="terminal-alert">
            <p>Saldo esgotando Mais internet</p>
        </div>
    </div>
</div></code>```

jQuery Version

You just need to run your function using a selector that matches both classes (green and grafico-arc).  Using this method there's no need for the extra conditional statement using hasClass:

$(".grafico-arc.green").each(function() {
   $(this).siblings(".terminal-alert").css("display", "none");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sliderCard">
  <div class="grafico">
    <div class="grafico-arc green">
      <div class="topo"></div>
      <div class="consumoTerminal">
        <h3>1 <span>GB</span></h3>
        <p>(21) 98899-0805</p>
        <button class="detail"></button>
      </div>
    </div>
    <div class="terminal-alert">
      <p>Saldo esgotando Mais internet</p>
    </div>
  </div>
</div>
<div class="sliderCard">
  <div class="grafico">
    <div class="grafico-arc yellow">
      <div class="topo"></div>

      <div class="consumoTerminal">
        <h3>2 <span>GB</span></h3>
        <p>(21) 98899-0805</p>
        <button class="detail"></button>
      </div>
    </div>
    <div class="terminal-alert">
      <p>Saldo esgotando Mais internet</p>
    </div>
  </div>
</div>
<div class="sliderCard">
  <div class="grafico">
    <div class="grafico-arc red">
      <div class="topo"></div>
      <div class="consumoTerminal">
        <h3>3 <span>GB</span></h3>
        <p>(21) 98899-0805</p>
        <button class="detail"></button>
      </div>
    </div>
    <div class="terminal-alert">
      <p>Saldo esgotando Mais internet</p>
    </div>
  </div>
</div></code>```

Body:
This might not be the way you wish to do this since you specified jQuery, but I want to leave this here anyway. (a jQuery version is further down)

CSS Version:

You can accomplish the same principal using only CSS with the Adjacent Sibling Combinator.

"The adjacent sibling combinator (+) separates two selectors and matches the second element only if it immediately follows the first element, and both are children of the same parent element."

.grafico-arc.green + .terminal-alert {
  display: none;
}

<div class="sliderCard">
    <div class="grafico">
        <div class="grafico-arc green">
            <div class="topo"></div>

            <div class="consumoTerminal">
                <h3>1 <span>GB</span></h3>
                <p>(21) 98899-0805</p>
                <button class="detail"></button>
            </div>
        </div>
        <div class="terminal-alert">
            <p>Saldo esgotando <a href="#">Mais internet</a></p>
        </div>
    </div>
</div>

<div class="sliderCard">
    <div class="grafico">
        <div class="grafico-arc yellow">
            <div class="topo"></div>
            <div class="consumoTerminal">
                <h3>2 <span>GB</span></h3>
                <p>(21) 98899-0805</p>
                <button class="detail"></button>
            </div>
        </div>
        <div class="terminal-alert">
            <p>Saldo esgotando <a href="#">Mais internet</a></p>
        </div>
    </div>
</div>
<div class="sliderCard">
    <div class="grafico">
        <div class="grafico-arc red">
            <div class="topo"></div>
            <div class="consumoTerminal">
                <h3>3 <span>GB</span></h3>
                <p>(21) 98899-0805</p>
                <button class="detail"></button>
            </div>
        </div>
        <div class="terminal-alert">
            <p>Saldo esgotando <a href="#">Mais internet</a></p>
        </div>
    </div>
</div>

jQuery Version

You just need to run your function using a selector that matches both classes (green and grafico-arc).  Using this method there's no need for the extra conditional statement using hasClass:

$(".grafico-arc.green").each(function() {
   $(this).siblings(".terminal-alert").css("display", "none");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sliderCard">
  <div class="grafico">
    <div class="grafico-arc green">
      <div class="topo"></div>
      <div class="consumoTerminal">
        <h3>1 <span>GB</span></h3>
        <p>(21) 98899-0805</p>
        <button class="detail"></button>
      </div>
    </div>
    <div class="terminal-alert">
      <p>Saldo esgotando <a href="#">Mais internet</a></p>
    </div>
  </div>
</div>
<div class="sliderCard">
  <div class="grafico">
    <div class="grafico-arc yellow">
      <div class="topo"></div>

      <div class="consumoTerminal">
        <h3>2 <span>GB</span></h3>
        <p>(21) 98899-0805</p>
        <button class="detail"></button>
      </div>
    </div>
    <div class="terminal-alert">
      <p>Saldo esgotando <a href="#">Mais internet</a></p>
    </div>
  </div>
</div>
<div class="sliderCard">
  <div class="grafico">
    <div class="grafico-arc red">
      <div class="topo"></div>
      <div class="consumoTerminal">
        <h3>3 <span>GB</span></h3>
        <p>(21) 98899-0805</p>
        <button class="detail"></button>
      </div>
    </div>
    <div class="terminal-alert">
      <p>Saldo esgotando <a href="#">Mais internet</a></p>
    </div>
  </div>
</div>