问:
tempusdominus : datetimepicker is not a function
I'm trying to use tempusdominus to show a date picker with the locales in fr but I have an error : "datetimepicker is not a function" and the icons dosen't show up and also the language in french
does somebody know why please ?

here's a screenshot https://ibb.co/fGsjyDC

my code :

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://momentjs.com/downloads/moment.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha14/js/tempusdominus-bootstrap-4.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha14/css/tempusdominus-bootstrap-4.min.css" />

<div class="container">
        <div class="row">
            <div class="col-sm-6">
                <div class="form-group">

                    <div class="input-group date" id="datetimepicker2" data-target-input="nearest">
                        <input type="text" class="form-control datetimepicker-input" data-target="#datetimepicker2"/>
                        <div class="input-group-append" data-target="#datetimepicker2" data-toggle="datetimepicker">
                            <div class="input-group-text"><i class="fa fa-calendar"></i></div>
                        </div>
                    </div>

                </div>
            </div>

            <script type="text/javascript">

                $(function () {
                    $('#datetimepicker2').datetimepicker({
                        locale: 'fr'
                    });
                });

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

答:
Include files in HEAD in the following order will remove this error

```<code><!--Bootstrap CSS CDN-->
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<!--Bootstrap JS CDN-->
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>

<!--Moment JS CDN-->
<script src="https://momentjs.com/downloads/moment.js"></script>

<!--Tempusdominus JS CDN-->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha14/js/tempusdominus-bootstrap-4.min.js"></script>

<!--Tempusdominus CSS CDN-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha14/css/tempusdominus-bootstrap-4.min.css" />
</code>```

Body:
I'm trying to use tempusdominus to show a date picker with the locales in fr but I have an error : "datetimepicker is not a function" and the icons dosen't show up and also the language in french
does somebody know why please ?

here's a screenshot https://ibb.co/fGsjyDC

my code :

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha14/css/tempusdominus-bootstrap-4.min.css" />

                        <input type="text" class="form-control datetimepicker-input" data-target="#datetimepicker2"/>

Body:
Include files in HEAD in the following order will remove this error

<!--Bootstrap CSS CDN-->
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<!--Bootstrap JS CDN-->
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>

<!--Moment JS CDN-->
<script src="https://momentjs.com/downloads/moment.js"></script>

<!--Tempusdominus JS CDN-->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha14/js/tempusdominus-bootstrap-4.min.js"></script>

<!--Tempusdominus CSS CDN-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha14/css/tempusdominus-bootstrap-4.min.css" />


来源: stackexchange

问:
Sum the number equivalent of alphabets in a word until it's single digit?
I am trying to solve a problem where a user gives a text input then I have to convert the text into given numeric values, add them together unless the answer is a single digit number.

So far, I have been able to get input, transform them into given numbers and store them in an array. But I cannot figure out what I will do next. How I will add the values together until it is left a single digit number.

var values = {a:1,b:2,c:3,d:4,e:5,f:6,g:7,h:8,i:9,j:10,k:11,l:12,m:13,n:14,o:15,p:16,q:17,r:18,s:19,t:20,u:21,v:22,w:23,x:24,y:25,z:26};
var someText = prompt('');

someText = someText.trim();
someText = someText.match(/\S/g);

var result = "";
for (i = 0; i < someText.length; i++) {
  result += values[someText[i]];
}

alert(result);```

For Example if input is "action" then numeric values will be
 =>1.3.20.9.15.14.
-Add these values together.
   1+3+20+9+15+14 answer will be 62.
-As the Answer is a 2 digit number, we add the numbers again
   e.g 62 = 6+2= 8.

Note:
If answer is more then 1 digits: e.g 199 => 1+9+9 => 19 => 1+9 => 10 = 1+0 = 1.
Answer must always be a single digit number.

答:
You should use a function to sum the values and return the value when it's one digit or call itself otherwise:</p>

```<code>var values = {a:1,b:2,c:3,d:4,e:5,f:6,g:7,h:8,i:9,j:10,k:11,l:12,m:13,n:14,o:15,p:16,q:17,r:18,s:19,t:20,u:21,v:22,w:23,x:24,y:25,z:26};
var someText = prompt('');

someText = someText.match(/\S/g);

var result = 0;

function getSum(string) {
    for (i = 0; i < string.length; i++) {
        if (isNaN(string[i])) {
            result += values[string[i]];
        } else {
            result += parseInt(string[i]);
        }
    }
    if (result.toString().length > 1) {
        var aux = result.toString();
        result = 0;
        return getSum(aux);
    } else {
        return result;
    }
}

alert(getSum(someText));
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to solve a problem where a user gives a text input then I have to convert the text into given numeric values, add them together unless the answer is a single digit number.

So far, I have been able to get input, transform them into given numbers and store them in an array. But I cannot figure out what I will do next. How I will add the values together until it is left a single digit number.

var values = {a:1,b:2,c:3,d:4,e:5,f:6,g:7,h:8,i:9,j:10,k:11,l:12,m:13,n:14,o:15,p:16,q:17,r:18,s:19,t:20,u:21,v:22,w:23,x:24,y:25,z:26};
var someText = prompt('');

someText = someText.trim();
someText = someText.match(/\S/g);

var result = "";
for (i = 0; i < someText.length; i++) {
  result += values[someText[i]];
}

alert(result);

For Example if input is "action" then numeric values will be
 =>1.3.20.9.15.14.
-Add these values together.
   1+3+20+9+15+14 answer will be 62.
-As the Answer is a 2 digit number, we add the numbers again
   e.g 62 = 6+2= 8.

Note:
If answer is more then 1 digits: e.g 199 => 1+9+9 => 19 => 1+9 => 10 = 1+0 = 1.
Answer must always be a single digit number.

Body:
You should use a function to sum the values and return the value when it's one digit or call itself otherwise:

var values = {a:1,b:2,c:3,d:4,e:5,f:6,g:7,h:8,i:9,j:10,k:11,l:12,m:13,n:14,o:15,p:16,q:17,r:18,s:19,t:20,u:21,v:22,w:23,x:24,y:25,z:26};
var someText = prompt('');

someText = someText.match(/\S/g);

var result = 0;

function getSum(string) {
    for (i = 0; i < string.length; i++) {
        if (isNaN(string[i])) {
            result += values[string[i]];
        } else {
            result += parseInt(string[i]);
        }
    }
    if (result.toString().length > 1) {
        var aux = result.toString();
        result = 0;
        return getSum(aux);
    } else {
        return result;
    }
}

alert(getSum(someText));


问:
Create a list of Key-Value pair
I have these facts:

```<code>name(john),
name(mary),
name(jack),
</code>```

When I "iterate" all facts I find for every name something like a rating(a number). I want that rating to be paired with the name something like 2-john or john-2, store them in a list and sort the list based on the number. How can I do that in ProLog?

```<code>name(PersonsName), findRating(PersonsName, Rating), fail.
</code>```

答:
@false gave the correct answer in the comment:

```<code>setof(V-K, ( name(K), rating(K, V) ), VKs)
</code>```

Personal side joke for @false, that was more than :-.  :)

I will just expand on it here for those needing the missing parts.

First the facts need to be facts, i.e.

name(john),  is not a fact because it ends with a ,. A fact needs to end with a period (.).

Next facts are needed to associate a rating with the person.

```<code>rating(john,2).
rating(mary,3).
rating(jack,4).
</code>```

Now for setof/3

The signature of setof/3 is setof(+Template, +Goal, -Set)

Goal is the query that will return the needed data, in this case goal is name(K), rating(K,V), but since that is more than one statement it is wrapped in () becoming ( name(K), rating(K, V) )

Example run:

```<code>?- name(Name),rating(Name,Rating).
Name = john,
Rating = 2 ;
Name = mary,
Rating = 3 ;
Name = jack,
Rating = 4.
</code>```

While that gives us the data needed it is not in a format that is useful and returns the results one by one.

Template is the format of the data in the result, in this case V-K, where V for Value is the rating and K for Key is the key. The result will be like 2-john.

Here is an example of what we have so far demonstrated with a query and example run:

```<code>rating(V-K) :-
    name(K),
    rating(K,V).

?- rating(Ratings).
Ratings = 2-john ;
Ratings = 3-mary ;
Ratings = 4-jack.
</code>```

Notice that the results are cumming back in the correct format but still not in a list.

Set is what is collected into the result.

Since you asked for a sorted result, setof/3 is used instead of bagof/3. As noted in setof/3: sorts the result using sort/2 to get a sorted list of alternatives without duplicates.

To make it easier to run the query instead of typing the entire setof/3 each time, just put it into a predicate.

```<code>ratings(VKs) :-
    setof(V-K,(name(K),rating(K,V)),VKs).
</code>```

Complete code.

```<code>name(john).
name(mary).
name(jack).

rating(john,2).
rating(mary,3).
rating(jack,4).

ratings(VKs) :-
    setof(V-K,(name(K),rating(K,V)),VKs).
</code>```

Example run:

```<code>?- ratings(VKs).
VKs = [2-john, 3-mary, 4-jack].
</code>```

Note: This could also be done using library(assoc): Association lists but for this problem using setof/3 is so much more concise.

Title: Create a list of Key-Value pair

Body:
I have these facts:

name(john),
name(mary),
name(jack),

When I "iterate" all facts I find for every name something like a rating(a number). I want that rating to be paired with the name something like 2-john or john-2, store them in a list and sort the list based on the number. How can I do that in ProLog?

name(PersonsName), findRating(PersonsName, Rating), fail.

Body:
@false gave the correct answer in the comment:

setof(V-K, ( name(K), rating(K, V) ), VKs)

Personal side joke for @false, that was more than :-.  :)

I will just expand on it here for those needing the missing parts.

First the facts need to be facts, i.e.

name(john),  is not a fact because it ends with a ,. A fact needs to end with a period (.).

Next facts are needed to associate a rating with the person.

rating(john,2).
rating(mary,3).
rating(jack,4).

Now for setof/3

The signature of setof/3 is setof(+Template, +Goal, -Set)

Goal is the query that will return the needed data, in this case goal is name(K), rating(K,V), but since that is more than one statement it is wrapped in () becoming ( name(K), rating(K, V) )

Example run:

?- name(Name),rating(Name,Rating).
Name = john,
Rating = 2 ;
Name = mary,
Rating = 3 ;
Name = jack,
Rating = 4.

While that gives us the data needed it is not in a format that is useful and returns the results one by one.

Template is the format of the data in the result, in this case V-K, where V for Value is the rating and K for Key is the key. The result will be like 2-john.

Here is an example of what we have so far demonstrated with a query and example run:

rating(V-K) :-
    name(K),
    rating(K,V).

?- rating(Ratings).
Ratings = 2-john ;
Ratings = 3-mary ;
Ratings = 4-jack.

Notice that the results are cumming back in the correct format but still not in a list.

Set is what is collected into the result.

Since you asked for a sorted result, setof/3 is used instead of bagof/3. As noted in setof/3: sorts the result using sort/2 to get a sorted list of alternatives without duplicates.

To make it easier to run the query instead of typing the entire setof/3 each time, just put it into a predicate.

ratings(VKs) :-
    setof(V-K,(name(K),rating(K,V)),VKs).

Complete code.

name(john).
name(mary).
name(jack).

rating(john,2).
rating(mary,3).
rating(jack,4).

ratings(VKs) :-
    setof(V-K,(name(K),rating(K,V)),VKs).

Example run:

?- ratings(VKs).
VKs = [2-john, 3-mary, 4-jack].

Note: This could also be done using library(assoc): Association lists but for this problem using setof/3 is so much more concise.


问:
Why does Backdrop filter blur my entire app
I am trying to achieve a very similar effect to what was shown in the widget of the week video on flutter's channel: https://www.youtube.com/watch?v=dYRs7Q1vfYI#t=1m20s

On the right you see the desired result, on the left you see what's currently going on in my app.

The code I've been using is pretty similar to the one from the example video, using a Stack to position the Backdrop filter over my image. The rounded image and the blur over it are inside one widget, which will is placed inside another stack (along with the text at the bottom). Since I applied the filter only a small section of the image, I don't understand why entire app is blurred. Here's the code for the Image Widget:

```<code>Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size.width - 75;
    return Container(
      height: size,
      width: size,
      child: Stack(
        alignment: Alignment.center,
        children: <Widget>[
          Image(imageUri: "...", size: size - 30), // this is just a container with the image
          Positioned(
            top: 100,
            left: 100,
            bottom: 100,
            right: 100,
            child: BackdropFilter(
              filter: ImageFilter.blur(
                sigmaX: 5,
                sigmaY: 5,
              ),
              child: Container(
                color: Color(0x66FF0000),
              ),
            ),
          )
        ],
      ),
    );
  }
}
</code>```

答:
It turns out the video is missing an important part from the documentation:

If there's no clip, the filter will be applied to the full screen.

So the solution is to wrap the filter into a ClipRect, as taken from the example:

```<code>ClipRect(  // <-- clips to the 200x200 [Container] below
        child: BackdropFilter(
          filter: ui.ImageFilter.blur(
            sigmaX: 5.0,
            sigmaY: 5.0,
          ),
          child: Container(
            alignment: Alignment.center,
            width: 200.0,
            height: 200.0,
            child: Text('Hello World'),
          ),
        ),
      ),
</code>```

Body:
I am trying to achieve a very similar effect to what was shown in the widget of the week video on flutter's channel: https://www.youtube.com/watch?v=dYRs7Q1vfYI#t=1m20s

On the right you see the desired result, on the left you see what's currently going on in my app.

The code I've been using is pretty similar to the one from the example video, using a Stack to position the Backdrop filter over my image. The rounded image and the blur over it are inside one widget, which will is placed inside another stack (along with the text at the bottom). Since I applied the filter only a small section of the image, I don't understand why entire app is blurred. Here's the code for the Image Widget:

Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size.width - 75;
    return Container(
      height: size,
      width: size,
      child: Stack(
        alignment: Alignment.center,
        children: <Widget>[
          Image(imageUri: "...", size: size - 30), // this is just a container with the image
          Positioned(
            top: 100,
            left: 100,
            bottom: 100,
            right: 100,
            child: BackdropFilter(
              filter: ImageFilter.blur(
                sigmaX: 5,
                sigmaY: 5,
              ),
              child: Container(
                color: Color(0x66FF0000),
              ),
            ),
          )
        ],
      ),
    );
  }
}

Body:
It turns out the video is missing an important part from the documentation:

If there's no clip, the filter will be applied to the full screen.

So the solution is to wrap the filter into a ClipRect, as taken from the example:

ClipRect(  // <-- clips to the 200x200 [Container] below
        child: BackdropFilter(
          filter: ui.ImageFilter.blur(
            sigmaX: 5.0,
            sigmaY: 5.0,
          ),
          child: Container(
            alignment: Alignment.center,
            width: 200.0,
            height: 200.0,
            child: Text('Hello World'),
          ),
        ),
      ),


问:
How to do Flask WTForms form validation when form is partially generated client-side
I'm building a simple user interface with two dropdowns. Based on what is selected in the first dropdown, the second dropdown is populated with some new values via jquery/AJAX. The problem is that when the form is submitted, form validation rightly fails because the option in the second dropdown that comes back was not in the list that generated the dropdown in the first place.

I've gotten it to work by injecting whatever data was sent from dropdown 2 into the form object before validating the form. This code is shown below, but it feels like a hacky solution.

form = SearchForm(request.form)

# dropdown 1
form.node_type.choices = [('default', 'Please select a node type')]
form.node_type.choices.extend([(t, t) for t in node_types()])

# dropdown 2
form.node_name.choices = [('default', 'Select a node type first')]

if request.method == 'POST':
    # the below 2 lines are the hack that make it work.
    node_name = request.form.get('node_name')
    form.node_name.choices.append((node_name, node_name))

    if form.validate():
        print('hooray')
```

Is there a standard/recommended way to dynamically add options on the client-side and still have WTForms perform form validation properly?

答:
This is a pure wtforms solution, but should work with flask-wtf (flask-wtf calls form.validate() within form.validate_on_submit()).

The code extends Form.validate to call a custom validation function if the node_name field has failed validation with the 'Not a valid choice' error.  If the validation function returns True it removes the 'Not a valid choice' error from Form.errors and returns True if Form.errors is now empty.

```<code>import werkzeug
import wtforms

class Form(wtforms.Form):

    node_type = wtforms.SelectField(choices=[(x, x) for x in 'ABCDEF'])
    node_name = wtforms.SelectField(choices=[('', '')])

    def validate(self):
        if super().validate():
            return True
        invalid_choice = 'Not a valid choice'
        if 'node_name' in self.errors and invalid_choice in self.errors['node_name']:
            is_valid_node_name = self.cross_validate_node_name()
            if is_valid_node_name:
                self.errors['node_name'].remove(invalid_choice)
                if not self.errors['node_name']:
                    del self.errors['node_name']
                return not self.errors
        return False

    def cross_validate_node_name(self):
        # Implement your validation logic here.
        return self.node_type.data == 'B' and self.node_name.data == 'spam'

if __name__ == '__main__':
    datas = [werkzeug.MultiDict([('node_type', 'A'), ('node_name', 'spam')]),
             werkzeug.MultiDict([('node_type', 'B'), ('node_name', 'spam')])]
    for data in datas:
        form = Form(formdata=data)
        if form.validate():
            print('OK')
        else:
            print(form.errors)
</code>```

Body:
I'm building a simple user interface with two dropdowns. Based on what is selected in the first dropdown, the second dropdown is populated with some new values via jquery/AJAX. The problem is that when the form is submitted, form validation rightly fails because the option in the second dropdown that comes back was not in the list that generated the dropdown in the first place.

I've gotten it to work by injecting whatever data was sent from dropdown 2 into the form object before validating the form. This code is shown below, but it feels like a hacky solution.

form = SearchForm(request.form)

# dropdown 1
form.node_type.choices = [('default', 'Please select a node type')]
form.node_type.choices.extend([(t, t) for t in node_types()])

# dropdown 2
form.node_name.choices = [('default', 'Select a node type first')]

if request.method == 'POST':
    # the below 2 lines are the hack that make it work.
    node_name = request.form.get('node_name')
    form.node_name.choices.append((node_name, node_name))

    if form.validate():
        print('hooray')

Is there a standard/recommended way to dynamically add options on the client-side and still have WTForms perform form validation properly?

Body:
This is a pure wtforms solution, but should work with flask-wtf (flask-wtf calls form.validate() within form.validate_on_submit()).

The code extends Form.validate to call a custom validation function if the node_name field has failed validation with the 'Not a valid choice' error.  If the validation function returns True it removes the 'Not a valid choice' error from Form.errors and returns True if Form.errors is now empty.

import werkzeug
import wtforms

class Form(wtforms.Form):

    node_type = wtforms.SelectField(choices=[(x, x) for x in 'ABCDEF'])
    node_name = wtforms.SelectField(choices=[('', '')])

    def validate(self):
        if super().validate():
            return True
        invalid_choice = 'Not a valid choice'
        if 'node_name' in self.errors and invalid_choice in self.errors['node_name']:
            is_valid_node_name = self.cross_validate_node_name()
            if is_valid_node_name:
                self.errors['node_name'].remove(invalid_choice)
                if not self.errors['node_name']:
                    del self.errors['node_name']
                return not self.errors
        return False

    def cross_validate_node_name(self):
        # Implement your validation logic here.
        return self.node_type.data == 'B' and self.node_name.data == 'spam'

if __name__ == '__main__':
    datas = [werkzeug.MultiDict([('node_type', 'A'), ('node_name', 'spam')]),
             werkzeug.MultiDict([('node_type', 'B'), ('node_name', 'spam')])]
    for data in datas:
        form = Form(formdata=data)
        if form.validate():
            print('OK')
        else:
            print(form.errors)


问:
Using enums with SpringBoot and Angular
I would like to have field like task important and later make query using JPA to sort it according to task value. I do not know how to set enums with mysql, springboot and angular correctly so I came up with something like this: just add new column in database it would be String. Secondly, in Angular make

```<code>export enum Task_Weight {
    IMPORTANT = 'IMPORTANT',
    NOT_IMPORTANT = 'NOT_IMPORTANT'
}
</code>```

Just make options that user can select. It should work, but now I have a problem. How can I write JPA query to sort all tasks according to Task_Weight? Maybe, I should do this in Angular?

Cheers

答:
You can always sort the data (JSON) fetched from back-end. All you need to do it to convert your data in an array and use lodash (very rich JS utils framework library) to sort it in angular itself.

Example - let's assume you have an array like below:

const arr = [ { id: 1, task_weight: 44 }, {id: 2, task_weight: 22}, { id: 3, task_weight: 55}]

To sort this using lodash in angular component-

import * as _ from 'lodash';
_.sort(arr, ['task_weight']);

Title: Using enums with SpringBoot and Angular

Body:
I would like to have field like task important and later make query using JPA to sort it according to task value. I do not know how to set enums with mysql, springboot and angular correctly so I came up with something like this: just add new column in database it would be String. Secondly, in Angular make

export enum Task_Weight {
    IMPORTANT = 'IMPORTANT',
    NOT_IMPORTANT = 'NOT_IMPORTANT'
}

Just make options that user can select. It should work, but now I have a problem. How can I write JPA query to sort all tasks according to Task_Weight? Maybe, I should do this in Angular?

Cheers


问:
How can I conditionally insert a character into a string?
Brand new to programming, what I've learned so far I've just copied from similar examples online.

This is a random sentence generator for a foreign language. But, I want to insert a character in between two specific characters in a string if they happen to occur next to each other. In this case, I want the characters in the evowel and avowel variables to be separated by 'y'.

I thought I could try a conditional split + rejoin, but I'm not sure how to search for (in this case) evowel_avowel, split it at that boundary, insert y, then join it back. So a randomly generated string 'eametetuk' would change to 'eyametetuk', 'eseapah' > 'eseyapah' etc.

Edit: I need to be able to handle anything in the evowel with anything in the avowel. For simplicity's sake I've only included two varations of each, but the language has more vowels and more variations (so roughly 60 permutations where this change needs to happen).

Would I need to create my own function for this? I'm guessing I would need regex somewhere.

import random

c1 = ("e","é")
c2 = ("a","se")
root = ("apa","mete")
tense = ("h","tuk")

avowel = ("a","á")
evowel = ("e","é")

#syntax
x = [c1,c2,root,tense]

#randomly selects morphemes
s = "".join([random.choice(i) for i in x])

print(s)
```

答:
You can achieve that by iterating through all pairs of characters in your string, checking if the first is in evowels and the second in avowels, returning the first with following y if yes, otherwise the first only.

If this is done in a list comprehension it can be directly joined to the resulting string:

```<code>txt1 = "eametetuk"
txt2 = "eseapah"
evowel = 'eé' #("e","é")    you're free to put all vowels in one string, too'
avowel = 'aá' #("a","á")    because strings are also iterables

def vowel_pair_sep(txt, sep='y', ev='eé', av='aá'):
    return (''.join(
    e + sep
    if (e in ev) and (a in av)
    else e
    for e, a in zip(txt[:-1], txt[1:]))
    + txt[-1])

vowel_pair_sep(txt1)
# eyametetuk
vowel_pair_sep(txt2)
# eseyapah
</code>```

Because the separator and the vowels are parameters of the function, it can easily be adapted to different needs:

```<code>vowel_pair_sep('tkdgtkdg', '_', 'dt', 'gk')
# t_kd_gt_kd_g
</code>```

Body:
You can achieve that by iterating through all pairs of characters in your string, checking if the first is in evowels and the second in avowels, returning the first with following y if yes, otherwise the first only.

If this is done in a list comprehension it can be directly joined to the resulting string:

txt1 = "eametetuk"
txt2 = "eseapah"
evowel = 'eé' #("e","é")    you're free to put all vowels in one string, too'
avowel = 'aá' #("a","á")    because strings are also iterables

def vowel_pair_sep(txt, sep='y', ev='eé', av='aá'):
    return (''.join(
    e + sep
    if (e in ev) and (a in av)
    else e
    for e, a in zip(txt[:-1], txt[1:]))
    + txt[-1])

vowel_pair_sep(txt1)
# eyametetuk
vowel_pair_sep(txt2)
# eseyapah

Because the separator and the vowels are parameters of the function, it can easily be adapted to different needs:

vowel_pair_sep('tkdgtkdg', '_', 'dt', 'gk')
# t_kd_gt_kd_g


问:
Trying to understand a recursive function to reverse a string
I can't understand why this code works. Do characters in the string get removed because they are being passed by reference? I see no decrement or such, so I find that really confusing. Also, is the string getting reversed because of the lifo nature of the function call stack?</p>

```<code> void reverse(const char * const sPtr){
   if('\0' == sPtr[0])
     return;
     else{
       reverse(&sPtr[1]);
       putchar(sPtr[0]);
    }
 }
</code>```

答:
After the last reverse(&sPtr[1]) there will be stacked 3 calls of putchar.

Each call of reverse grows the pointer with 1, so the stacked calls will be --supposing the input string is made of 3 characters--

```<code>CURRENT FRAME -- *(ptr+3) is NULL
putchar(*(ptr+2))
putchar(*(ptr+1))
putchar(*(ptr+0))
</code>```

Body:
I can't understand why this code works. Do characters in the string get removed because they are being passed by reference? I see no decrement or such, so I find that really confusing. Also, is the string getting reversed because of the lifo nature of the function call stack?

 void reverse(const char * const sPtr){
   if('\0' == sPtr[0])
     return;
     else{
       reverse(&sPtr[1]);
       putchar(sPtr[0]);
    }
 }

Body:
After the last reverse(&sPtr[1]) there will be stacked 3 calls of putchar.

Each call of reverse grows the pointer with 1, so the stacked calls will be --supposing the input string is made of 3 characters--

CURRENT FRAME -- *(ptr+3) is NULL
putchar(*(ptr+2))
putchar(*(ptr+1))
putchar(*(ptr+0))


问:
Classloader specific properties
We developed an application container that creates a new classloader for each independent application running in the container.  When a specific application is invoked, the Thread's context classloader is set appropriately with the application's classloader.

Avoiding the use of ThreadLocal, is it possible to store properties within a classloader, such that you would be able to retrieve, in this case, application-specific properties directly from the classloader.

For example, I want to be able to somehow save and then later retrieve properties when accessing the context classloader:

```<code>Thread.currentThread().getContextClassLoader()
</code>```

Is this possible?  Or is ThreadLocal the only viable option?

答: How about subclassing the context classloader, extending it with the property support you need, then just casting the Thread.currentThread().getContextClassLoader()?</p>

ContentLicense: CC BY-SA 3.0

Title: Classloader specific properties

Body:
We developed an application container that creates a new classloader for each independent application running in the container.  When a specific application is invoked, the Thread's context classloader is set appropriately with the application's classloader.

Avoiding the use of ThreadLocal, is it possible to store properties within a classloader, such that you would be able to retrieve, in this case, application-specific properties directly from the classloader.

For example, I want to be able to somehow save and then later retrieve properties when accessing the context classloader:

Thread.currentThread().getContextClassLoader()

Is this possible?  Or is ThreadLocal the only viable option?


问:
how to solve DeprecationWarning while use of Imputer of sklearn
scikit-learn provide handy class to take care of missing value of attribute
Imputer of sklearn.preprocessing

```<code>from sklearn.preprocessing import Imputer
im=Imputer(strategy="median")

</code>```

i expect a result but some kind of warning shows

```<code>/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:66: DeprecationWarning: Class Imputer is deprecated; Imputer was deprecated in version 0.20 and will be removed in 0.22. Import impute.SimpleImputer from sklearn instead.
  warnings.warn(msg, category=DeprecationWarning)
</code>```

答: The warning shows that you should be using SimpleImputer class instead of the Imputer class. The Imputer class is going to be removed in the upcoming versions of scikit-learn. For examples see this. If you still want to use it. You should use the .fit method or the .fit_transform method of the Imputer class.

Body:
scikit-learn provide handy class to take care of missing value of attribute
Imputer of sklearn.preprocessing

from sklearn.preprocessing import Imputer
im=Imputer(strategy="median")

i expect a result but some kind of warning shows

/usr/local/lib/python3.6/dist-packages/sklearn/utils/deprecation.py:66: DeprecationWarning: Class Imputer is deprecated; Imputer was deprecated in version 0.20 and will be removed in 0.22. Import impute.SimpleImputer from sklearn instead.
  warnings.warn(msg, category=DeprecationWarning)


问:
How to retrieve float_val from a PredictResponse object?
I am running a prediction on a tensorflow-serving model, and I get back this PredictResponse object as output:

Result:

```<code>outputs {
  key: "outputs"
  value {
    dtype: DT_FLOAT
    tensor_shape {
      dim {
        size: 1
      }
      dim {
        size: 20
      }
    }
    float_val: 0.000343723397236
    float_val: 0.999655127525
    float_val: 3.96821117632e-11
    float_val: 1.20521548297e-09
    float_val: 2.09611101809e-08
    float_val: 1.46216549979e-09
    float_val: 3.87274603497e-08
    float_val: 1.83520256769e-08
    float_val: 1.47733780764e-08
    float_val: 8.00914179422e-08
    float_val: 2.29388191997e-07
    float_val: 6.27798826258e-08
    float_val: 1.08802950649e-07
    float_val: 4.39628813353e-08
    float_val: 7.87182985462e-10
    float_val: 1.31638898893e-07
    float_val: 1.42612295306e-08
    float_val: 3.0768305237e-07
    float_val: 1.12661648899e-08
    float_val: 1.68554503688e-08
  }
}
</code>```

I would like to get the out the float vals as a list. Or, alternatively, return the value/index of the argmax float_val!

This is generated by:

stub = prediction_service_pb2.beta_create_PredictionService_stub(channel)
  result = stub.Predict(request, 200.0)

Thanks for your help in advance.

答:
You generally want to recover a tensor, with a shape (not just a long list of floats). Here's how:

outputs_tensor_proto = result.outputs["outputs"]
shape = tf.TensorShape(outputs_tensor_proto.tensor_shape)
outputs = tf.constant(outputs_tensor_proto.float_val, shape=shape)
```

<p>If you prefer to get a NumPy array, then just replace the last line:</p>

<pre class="lang-py prettyprint-override"><code>outputs = np.array(outputs_tensor_proto.float_val).reshape(shape.as_list())
</code>```

If you don't want to depend on the TensorFlow library at all, for some reason:

outputs_tensor_proto = result.outputs["outputs"]
shape = [dim.size for dim in outputs_tensor_proto.tensor_shape.dim]
outputs = np.array(outputs_tensor_proto.float_val).reshape(shape)
```

Body:
I am running a prediction on a tensorflow-serving model, and I get back this PredictResponse object as output:

Result:

outputs {
  key: "outputs"
  value {
    dtype: DT_FLOAT
    tensor_shape {
      dim {
        size: 1
      }
      dim {
        size: 20
      }
    }
    float_val: 0.000343723397236
    float_val: 0.999655127525
    float_val: 3.96821117632e-11
    float_val: 1.20521548297e-09
    float_val: 2.09611101809e-08
    float_val: 1.46216549979e-09
    float_val: 3.87274603497e-08
    float_val: 1.83520256769e-08
    float_val: 1.47733780764e-08
    float_val: 8.00914179422e-08
    float_val: 2.29388191997e-07
    float_val: 6.27798826258e-08
    float_val: 1.08802950649e-07
    float_val: 4.39628813353e-08
    float_val: 7.87182985462e-10
    float_val: 1.31638898893e-07
    float_val: 1.42612295306e-08
    float_val: 3.0768305237e-07
    float_val: 1.12661648899e-08
    float_val: 1.68554503688e-08
  }
}

I would like to get the out the float vals as a list. Or, alternatively, return the value/index of the argmax float_val!

This is generated by:

stub = prediction_service_pb2.beta_create_PredictionService_stub(channel)
  result = stub.Predict(request, 200.0)

Thanks for your help in advance.

Body:
You generally want to recover a tensor, with a shape (not just a long list of floats). Here's how:

outputs_tensor_proto = result.outputs["outputs"]
shape = tf.TensorShape(outputs_tensor_proto.tensor_shape)
outputs = tf.constant(outputs_tensor_proto.float_val, shape=shape)

If you prefer to get a NumPy array, then just replace the last line:

outputs = np.array(outputs_tensor_proto.float_val).reshape(shape.as_list())

If you don't want to depend on the TensorFlow library at all, for some reason:

outputs_tensor_proto = result.outputs["outputs"]
shape = [dim.size for dim in outputs_tensor_proto.tensor_shape.dim]
outputs = np.array(outputs_tensor_proto.float_val).reshape(shape)


问:
multi matchs in espresso test android
I need to check view is display and is enabled.

```<code>  btn.check(matches(isDisplayed()))
            .check(matches(isEnabled()))
</code>```

can I use an array for this?

for example:

```<code> btn.check(matches(isDisplayed(),isEnabled()))
</code>```

答:
You can use allOf method which matches all of the specified matchers:

```<code> btn.check(matches(allOf(isDisplayed(),isEnabled())))
</code>```

Title: multi matchs in espresso test android

Body:
I need to check view is display and is enabled.

  btn.check(matches(isDisplayed()))
            .check(matches(isEnabled()))

can I use an array for this?

for example:

 btn.check(matches(isDisplayed(),isEnabled()))

Body:
You can use allOf method which matches all of the specified matchers:

 btn.check(matches(allOf(isDisplayed(),isEnabled())))


问:
Update Product Features via PHP in Prestashop
I would like to change the value from custom features (Product Features) (Artikeleigenschaften) in my own class.

To change product values is very simple:

```<code>$productObj = new Product($produktId);
$productObj->setFieldsToUpdate(array('ean13'));
$productObj->ean13 = "johndoo";
$productObj->save();
</code>```

But is there a similar way to change the Product Features?

答:
I created this function based upon ImportControlloer. Add this function to Product.php override and use it

```<code> /**
 * Adds a feature value to a Product. If You want to have feature selected from dropdown leave $custom to false.
 * @param int|$id_product
 * @param int|$id_feature_group
 * @param string|$feature_value
 * @param bool|true $custom
 * @param int|$id_lang
 * @return bool
 */
public static function setFeatureValueToProduct($id_product, $id_feature_group, $feature_value, $custom = false, $id_lang)
{
    $group_feature_obj = Feature::getFeature($id_lang, $id_feature_group);

    if ($group_feature_obj){
        $feature_name = $group_feature_obj['name'];
        $feature_value = $feature_value ? trim($feature_value) : '';
        $position = false;

        if (!empty($feature_name) && !empty($feature_value)) {
            $id_feature = (int)FeatureCore::addFeatureImport($feature_name, $position);

            $id_feature_value = (int)FeatureValue::addFeatureValueImport($id_feature, $feature_value, $id_product, $id_lang, $custom);
            if (Product::addFeatureProductImport($id_product, $id_feature, $id_feature_value)){
                Feature::cleanPositions();
                return true;
            } else {
                return;
            }
        }
    } else {
        return;
    }
}
</code>```

Example of use:

```<code>Product::setFeatureValue(1597, 15,  'Dracarys', false, 1);
</code>```

It will upload Dropdown value "Dracarys" into product with ID 1597 and group feature with ID 15. If You want to make it custom value (not-predefined) just set 4th parametr to true.

Body:
I would like to change the value from custom features (Product Features) (Artikeleigenschaften) in my own class.

To change product values is very simple:

$productObj = new Product($produktId);
$productObj->setFieldsToUpdate(array('ean13'));
$productObj->ean13 = "johndoo";
$productObj->save();

But is there a similar way to change the Product Features?

Body:
I created this function based upon ImportControlloer. Add this function to Product.php override and use it

 /**
 * Adds a feature value to a Product. If You want to have feature selected from dropdown leave $custom to false.
 * @param int|$id_product
 * @param int|$id_feature_group
 * @param string|$feature_value
 * @param bool|true $custom
 * @param int|$id_lang
 * @return bool
 */
public static function setFeatureValueToProduct($id_product, $id_feature_group, $feature_value, $custom = false, $id_lang)
{
    $group_feature_obj = Feature::getFeature($id_lang, $id_feature_group);

    if ($group_feature_obj){
        $feature_name = $group_feature_obj['name'];
        $feature_value = $feature_value ? trim($feature_value) : '';
        $position = false;

        if (!empty($feature_name) && !empty($feature_value)) {
            $id_feature = (int)FeatureCore::addFeatureImport($feature_name, $position);

            $id_feature_value = (int)FeatureValue::addFeatureValueImport($id_feature, $feature_value, $id_product, $id_lang, $custom);
            if (Product::addFeatureProductImport($id_product, $id_feature, $id_feature_value)){
                Feature::cleanPositions();
                return true;
            } else {
                return;
            }
        }
    } else {
        return;
    }
}

Example of use:

Product::setFeatureValue(1597, 15,  'Dracarys', false, 1);

It will upload Dropdown value "Dracarys" into product with ID 1597 and group feature with ID 15. If You want to make it custom value (not-predefined) just set 4th parametr to true.


问:
How to git ls-remote tags in a specific branch
Before cloning a repository, I want to list all the tags in the master branch to filter and finally retrieve a subset of required commits without transferring any additional data.

Is it possible to use git ls-remote to list all tags in a particular branch?

答:
```<code>git tag --list --merged <branchName>
</code>```

would do the job on a repo you already have locally. Could it help your case?

I guess not unless you somehow have access to the remote machine itself.

Body:
git tag --list --merged <branchName>

would do the job on a repo you already have locally. Could it help your case?

I guess not unless you somehow have access to the remote machine itself.


问:
Reshaping database using reshape package-part 2
Following the interaction in the previous post Reshaping database using reshape package I create this one to ask other question.
Briefly: I have a database with some rows that it replicate for Id column, I would like to transpose it. The following cose show a little example of my database.

```<code>test<-data.frame(Id=c(1,1,2,3),
                 St=c(20,80,80,20),
                 gap=seq(0.02,0.08,by=0.02),
                 gip=c(0.23,0.60,0.86,2.09),
                 gat=c(0.0107,0.989,0.337,0.663))
</code>```

I would like a final database like this figure that I attached:

With one row for each Id value and the different columns attached.

Can you give me any suggestions?

答:
You can use dcast from data.table. This function allows to spread multiple value variables.

```<code>library(data.table)
setDT(test) # convert test to a data.table
test1 <- dcast(test, Id ~ rowid(Id),
               value.var = c('St', 'gap', 'gip', 'gat'), fill = 0)
test1
#   Id St_1 St_2 gap_1 gap_2 gip_1 gip_2  gat_1 gat_2
#1:  1   20   80  0.02  0.04  0.23   0.6 0.0107 0.989
#2:  2   80    0  0.06  0.00  0.86   0.0 0.3370 0.000
#3:  3   20    0  0.08  0.00  2.09   0.0 0.6630 0.000
</code>```

If you want to continue with a data.frame call setDF(test1) at the end.

Body:
Following the interaction in the previous post Reshaping database using reshape package I create this one to ask other question.
Briefly: I have a database with some rows that it replicate for Id column, I would like to transpose it. The following cose show a little example of my database.

test<-data.frame(Id=c(1,1,2,3),
                 St=c(20,80,80,20),
                 gap=seq(0.02,0.08,by=0.02),
                 gip=c(0.23,0.60,0.86,2.09),
                 gat=c(0.0107,0.989,0.337,0.663))

I would like a final database like this figure that I attached:

With one row for each Id value and the different columns attached.

Can you give me any suggestions?

Body:
You can use dcast from data.table. This function allows to spread multiple value variables.

library(data.table)
setDT(test) # convert test to a data.table
test1 <- dcast(test, Id ~ rowid(Id),
               value.var = c('St', 'gap', 'gip', 'gat'), fill = 0)
test1
#   Id St_1 St_2 gap_1 gap_2 gip_1 gip_2  gat_1 gat_2
#1:  1   20   80  0.02  0.04  0.23   0.6 0.0107 0.989
#2:  2   80    0  0.06  0.00  0.86   0.0 0.3370 0.000
#3:  3   20    0  0.08  0.00  2.09   0.0 0.6630 0.000

If you want to continue with a data.frame call setDF(test1) at the end.


问:
Change the behaviour of cooked mode
On a terminal, the cooked (canonical) mode allows the user to input in text, and the text is sent to the program when the user hits enter. While in cooked mode, the arrow keys don't work, and they just appear as ^[[A and similar, but backspace does.

So is it possible to allow arrow keys in the terminal? Ideally, I would be able to even specify my own default 'cooker' to use.

And if it is not possible, then why are all terminals like this?

If it helps, I use suckless terminal, but I would prefer a solution that works on all terminals.

答: As a workaround, you can run your commands with rlwrap, which provides readline's line editing, including arrow key movement.</p>

Title: Change the behaviour of cooked mode


问:
Best practices for multithreaded processing of database records
I have a single process that queries a table for records where PROCESS_IND = 'N', does some processing, and then updates the PROCESS_IND to 'Y'.

I'd like to allow for multiple instances of this process to run, but don't know what the best practices are for avoiding concurrency problems.

Where should I start?

答:
The most obvious way is locking, if your database doesn't have locks, you could implement it yourself by adding a "Locked" field.

Some of the ways to simplify the concurrency is to randomize the access to unprocessed items, so instead of competition on the first item, they distribute the access randomly.

OwnerDisplayName: Mike S

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Drew Noakes

OwnerDisplayName: Osama ALASSIRY


问:
Iphone get coords in background
Can I make iphone app that get coords from gps in 2 seconds and save them in file. In the end of the day I should send via mail?</p>

答:
You never know how long the device would take to detect the user's location.

You can of course make an app which should check the user's accurate location and then write it to plist and later whenever you planned to share it via email or any other source, you should able to share it easily.

To get the user's most accurate location look up for the accuracy property in CoreLocation framework. If you considering time limit just for the sake that the user need not to wait until the app gets the accurate location, then you should use background location service introduced in iOS 4.0.

Title: Iphone get coords in background


问:
How can I know if a process is running background or foreground in commans "ps" or "ps -ef"?
How can I know if a process is running background or foreground in commans "ps" or "ps -ef" ?

I first thought that when I type in ps -ef , there is a section named TTY.

when I look into the list of TTY, most of them are '?' (question marks)

I wonder if that question mark means process running background

I want to check if I am right!

If not, I want to know how I can know if the process is running background or foreground

ps. commnand "jobs" is not used here

答:
I like this question and have a twisted solution for listing ps information about the background jobs/processes.

By definition of a job/background process. They are lists with jobs -l command.

Store the background jobs pid in a list

```<code>echo "$(jobs -l)" | awk '{print $2}' > jobs.lst
</code>```

Intersect the jobs list with current process

```<code>ps -eo pid,args | grep -f jobs.lst
</code>```

The output is ps -eo pid,args result for background jobs.

Providing the id and the command line arguments for the background jobs.

P.S

I used ps output option -o to list only pid and args. Change it to your liking, but make sure pid is there.

Body:
I like this question and have a twisted solution for listing ps information about the background jobs/processes.

By definition of a job/background process. They are lists with jobs -l command.

Store the background jobs pid in a list

echo "$(jobs -l)" | awk '{print $2}' > jobs.lst

Intersect the jobs list with current process

ps -eo pid,args | grep -f jobs.lst

The output is ps -eo pid,args result for background jobs.

Providing the id and the command line arguments for the background jobs.

P.S

I used ps output option -o to list only pid and args. Change it to your liking, but make sure pid is there.


问:
how to get specific numbers out of string value that is changing ; php
I'm trying to get latitude and longitude number values out of location info string.

if I search 'hawaii' on the map, the map api returns the string value like below.

$location = {map: geo="20.471884,-157.505,6" p="Hawaii"}

and I'd like to get latitude and longitude value into $lat, $lng.

How can I make it in php???

答:
If you don't want to match that pattern without the ,6 afterwards, you might use:

```<code>^{map:\h+geo="(?P<lat>-?\d+(?:\.\d+)?)(?:,\d+)?,(?P<lon>-?\d+(?:\.\d+)?)(?:,\d+)?"[^}]+}
</code>```

Explanation

^{map:\h+geo= Start of string, match {map: and 1+ horizonal whitespaces and geo="

(?P<lat> Named capturing group lat

-?\d+ Match optional -, 1+ digits

(?:\.\d+)? Optional part for . and 1+ digits

) Close group

(?:,\d+)? Optional part for , and 1+ digits

, The comma between the values

(?P<lon> Named capturing group lon

-?\d+ Match optional -, 1+ digits

(?:\.\d+)? Optional part for . and 1+ digits

) Close group

(?:,\d+)? Optional part for , and 1+ digits

"[^}]+} Match " and then until the closing }

Regex demo | Php demo

For example

```<code>$re = '/^{map:\h+geo="(?P<lat>-?\d+(?:\.\d+)?)(?:,\d+)?,(?P<lon>-?\d+(?:\.\d+)?)(?:,\d+)?"[^}]+}/';
$str = '{map: geo="20.471884,-157.505,6" p="Hawaii"}';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

$lat = $matches[0]["lat"];
$lon = $matches[0]["lon"];

echo $lat; // 20.471884
echo PHP_EOL;
echo $lon; // -157.505
</code>```

You might shorten the pattern a bit by recursing the first subpattern using (?1)

```<code>^{map:\h+geo="(?P<lat>-?\d+(?:\.\d+)?)(?:,\d+)?,(?P<lon>(?1))(?:,\d+)?"[^}]+}
</code>```

Body:
If you don't want to match that pattern without the ,6 afterwards, you might use:

^{map:\h+geo="(?P<lat>-?\d+(?:\.\d+)?)(?:,\d+)?,(?P<lon>-?\d+(?:\.\d+)?)(?:,\d+)?"[^}]+}

Explanation

^{map:\h+geo= Start of string, match {map: and 1+ horizonal whitespaces and geo="

(?P<lat> Named capturing group lat

-?\d+ Match optional -, 1+ digits

(?:\.\d+)? Optional part for . and 1+ digits

) Close group

(?:,\d+)? Optional part for , and 1+ digits

, The comma between the values

(?P<lon> Named capturing group lon

-?\d+ Match optional -, 1+ digits

(?:\.\d+)? Optional part for . and 1+ digits

) Close group

(?:,\d+)? Optional part for , and 1+ digits

"[^}]+} Match " and then until the closing }

Regex demo | Php demo

For example

$re = '/^{map:\h+geo="(?P<lat>-?\d+(?:\.\d+)?)(?:,\d+)?,(?P<lon>-?\d+(?:\.\d+)?)(?:,\d+)?"[^}]+}/';
$str = '{map: geo="20.471884,-157.505,6" p="Hawaii"}';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

$lat = $matches[0]["lat"];
$lon = $matches[0]["lon"];

echo $lat; // 20.471884
echo PHP_EOL;
echo $lon; // -157.505

You might shorten the pattern a bit by recursing the first subpattern using (?1)

^{map:\h+geo="(?P<lat>-?\d+(?:\.\d+)?)(?:,\d+)?,(?P<lon>(?1))(?:,\d+)?"[^}]+}


问:
Iterating keys in NSMapTable retains the weak values forever
I'm trying to use NSMapTable to weakly store some object instances, indexed by a string.

(My use case is to store some cached metadata about remote servers, and have every active client share that metadata. When there are no clients connecting to that specific server anymore, the metadata should be removed from memory.)

This is all working fine, as long as I never iterate over the keys. It seems like, that if I have iterated over a specific key, the value for that key will never be released.

I've managed to reduce it down to a small code snippet that shows the problem:

```<code>import Foundation

class Foobar {
    let id: String
    init(_ id: String) { print("init \(id)"); self.id = id }
    deinit { print("deinit \(id)") }
}

let map = NSMapTable<NSString, Foobar>(keyOptions: .strongMemory, valueOptions: .weakMemory)

func addSome() {
    let a = Foobar("a")
    let b = Foobar("b")
    let c = Foobar("c")

    map.setObject(a, forKey: "a")
    map.setObject(b, forKey: "b")
    map.setObject(c, forKey: "c")

    let e = map.keyEnumerator()
    print("nextObject: \(e.nextObject() ?? "nil")")
    print("nextObject: \(e.nextObject() ?? "nil")")
    print("nextObject: \(e.nextObject() ?? "nil")")
    print("nextObject: \(e.nextObject() ?? "nil")")
}

addSome()

print(map.object(forKey: "a") ?? "nil")
print(map.object(forKey: "b") ?? "nil")
print(map.object(forKey: "c") ?? "nil")
</code>```

If I comment out one or more of the e.nextObject() calls, the values for the corresponding keys will be properly released, and map.object(forKey:) will properly return nil.

Do I have to manually clean up the enumerator after I'm done with it in some way?

答:
Apparently the map enumerator returns “autoreleased” objects – these are released when the scope of the current autorelease pool is left.

In iOS or macOS applications that would happen automatically when program control returns to the main event loop. In any case, you can use a local autorelease pool

```<code>autoreleasepool {
    let e = map.keyEnumerator()
    print("nextObject: \(e.nextObject() ?? "nil")")
    print("nextObject: \(e.nextObject() ?? "nil")")
    print("nextObject: \(e.nextObject() ?? "nil")")
    print("nextObject: \(e.nextObject() ?? "nil")")
}
</code>```

to have the objects released immediately after the enumeration.

Remark: NSEnumerator is a Sequence, so that you can enumerate it with a for-loop:

```<code>autoreleasepool {
    let e = map.keyEnumerator()
    for case let key as String in e {
        print(key)
    }
}
</code>```

Body:
I'm trying to use NSMapTable to weakly store some object instances, indexed by a string.

(My use case is to store some cached metadata about remote servers, and have every active client share that metadata. When there are no clients connecting to that specific server anymore, the metadata should be removed from memory.)

This is all working fine, as long as I never iterate over the keys. It seems like, that if I have iterated over a specific key, the value for that key will never be released.

I've managed to reduce it down to a small code snippet that shows the problem:

import Foundation

class Foobar {
    let id: String
    init(_ id: String) { print("init \(id)"); self.id = id }
    deinit { print("deinit \(id)") }
}

let map = NSMapTable<NSString, Foobar>(keyOptions: .strongMemory, valueOptions: .weakMemory)

func addSome() {
    let a = Foobar("a")
    let b = Foobar("b")
    let c = Foobar("c")

    map.setObject(a, forKey: "a")
    map.setObject(b, forKey: "b")
    map.setObject(c, forKey: "c")

    let e = map.keyEnumerator()
    print("nextObject: \(e.nextObject() ?? "nil")")
    print("nextObject: \(e.nextObject() ?? "nil")")
    print("nextObject: \(e.nextObject() ?? "nil")")
    print("nextObject: \(e.nextObject() ?? "nil")")
}

addSome()

print(map.object(forKey: "a") ?? "nil")
print(map.object(forKey: "b") ?? "nil")
print(map.object(forKey: "c") ?? "nil")

If I comment out one or more of the e.nextObject() calls, the values for the corresponding keys will be properly released, and map.object(forKey:) will properly return nil.

Do I have to manually clean up the enumerator after I'm done with it in some way?

Body:
Apparently the map enumerator returns “autoreleased” objects – these are released when the scope of the current autorelease pool is left.

In iOS or macOS applications that would happen automatically when program control returns to the main event loop. In any case, you can use a local autorelease pool

autoreleasepool {
    let e = map.keyEnumerator()
    print("nextObject: \(e.nextObject() ?? "nil")")
    print("nextObject: \(e.nextObject() ?? "nil")")
    print("nextObject: \(e.nextObject() ?? "nil")")
    print("nextObject: \(e.nextObject() ?? "nil")")
}

to have the objects released immediately after the enumeration.

Remark: NSEnumerator is a Sequence, so that you can enumerate it with a for-loop:

autoreleasepool {
    let e = map.keyEnumerator()
    for case let key as String in e {
        print(key)
    }
}


问:
Elasticsearch Filtered Query Results Confusing
I'm trying to use a filtered query on an Elasticsearch index that has about 3M documents and I can't seem to get it to work as I would expect.

To elaborate, my query looks like this (my index is for college course information):

```<code>{
  "query":{
    "filtered":{
      "query":{
        "match_phrase_prefix":{
          "course_abbreviation":"CS 3"
        }
      },
      "filter":{
        "term":{
          "department_id":49599
        }
      }
    }
  }
}
</code>```

This produces no results.  However, if I give an entire "course_abbreviation" (ex: CS 301), I get one result.

To further add to my confusion, if I do the following query:

```<code>{
  "query":{
    "match_phrase_prefix":{
      "course_abbreviation": "CS 3"
    }
  }
}
</code>```

I get multiple documents that have my desired department_id (as well as documents with other department_ids) and that also match course_abbreviations such as "CS 301", "CS 322", "CS 365", etc.

Am I wrong to expect that my filtered query would produce the same documents as the non-filtered query sans the documents with other department_ids?

答:
I think your problem is due to the fact that elasticsearch will not consider all the suffixes of "CS 3". By default only the first 50 suffixes will be considered. If the documents containing the 50 suffixes selected by elasticsearch does not match on your department_id term query, then no results will be returned. In your case, if you have 3M documents, this does not seems unlikely.

You can increase the number of selected suffixes using the match_expansions parameter.

```<code>{
  "query":{
    "filtered":{
      "query":{
        "match_phrase_prefix":{
          "course_abbreviation":"CS 3",
          "match_expansions": 100
        }
      },
      "filter":{
        "term":{
          "department_id":49599
        }
      }
    }
  }
}
</code>```

Increasing parameter match_expansions will also make you request slower. See the documentation on match_phrase_prefix.

Body:
I'm trying to use a filtered query on an Elasticsearch index that has about 3M documents and I can't seem to get it to work as I would expect.

To elaborate, my query looks like this (my index is for college course information):

{
  "query":{
    "filtered":{
      "query":{
        "match_phrase_prefix":{
          "course_abbreviation":"CS 3"
        }
      },
      "filter":{
        "term":{
          "department_id":49599
        }
      }
    }
  }
}

This produces no results.  However, if I give an entire "course_abbreviation" (ex: CS 301), I get one result.

To further add to my confusion, if I do the following query:

{
  "query":{
    "match_phrase_prefix":{
      "course_abbreviation": "CS 3"
    }
  }
}

I get multiple documents that have my desired department_id (as well as documents with other department_ids) and that also match course_abbreviations such as "CS 301", "CS 322", "CS 365", etc.

Am I wrong to expect that my filtered query would produce the same documents as the non-filtered query sans the documents with other department_ids?

Body:
I think your problem is due to the fact that elasticsearch will not consider all the suffixes of "CS 3". By default only the first 50 suffixes will be considered. If the documents containing the 50 suffixes selected by elasticsearch does not match on your department_id term query, then no results will be returned. In your case, if you have 3M documents, this does not seems unlikely.

You can increase the number of selected suffixes using the match_expansions parameter.

{
  "query":{
    "filtered":{
      "query":{
        "match_phrase_prefix":{
          "course_abbreviation":"CS 3",
          "match_expansions": 100
        }
      },
      "filter":{
        "term":{
          "department_id":49599
        }
      }
    }
  }
}

Increasing parameter match_expansions will also make you request slower. See the documentation on match_phrase_prefix.


问:
ActiveRecord: doing a join with unscoped doesn't skip the default_scope
I am having some issues when trying to skip a default_scope when doing an ActiveRecord join.

Even though the codebase is quite large, I am just showing the basics as I think it shows pretty well what the problem is:

class Client
  belongs_to :company
end

class Company
  default_scope { where(version_id: nil) }
end
```

<p>I am building a complex report, so I need to join multiple tables and filter on them. However, I can't successfully skip the default scope when fetching <code>Client</code>s.</p>

<pre class="lang-rb prettyprint-override"><code>Client.joins(:company).to_sql
# SELECT clients.* FROM clients INNER JOIN companies
# ON companies.id = clients.company_id AND companies.version_id IS NULL
</code>```

As you can see that is automatically including the Company default_scope. So I tried this:

Company.unscoped { Client.joins(:company) }.to_sql
# SELECT clients.* FROM clients INNER JOIN companies
# ON companies.id = clients.company_id AND companies.version_id IS NULL
```

<p>Again, I got the same result, even when using <code>unscoped</code> with the block.</p>

<p>Then I decided to add a new association to the model, with the <code>unscoped</code> scope:</p>

<pre class="lang-rb prettyprint-override"><code>class Client
  belongs_to :company
  belongs_to :unscoped_company, -> { unscoped }, foreign_key: :company_id, class_name: "Company"
end
</code>```

Having added that, I gave another try:

Client.joins(:unscoped_company).to_sql
# SELECT clients.* FROM clients INNER JOIN companies
# ON companies.id = clients.company_id AND companies.version_id IS NULL
```

And still the scoped is being applied.

Do you know how can I successfully join both tables without applying that default_scope?
Removing that default_scope is not an option as It is a big application and changing that will require too much time.

Rails v4.2.7

Ruby v2.2.3

答:
Apply directly as a class method</p>

```<code>Client.unscoped.joins(:company).to_sql
</code>```

Body:
I am having some issues when trying to skip a default_scope when doing an ActiveRecord join.

Even though the codebase is quite large, I am just showing the basics as I think it shows pretty well what the problem is:

class Client
  belongs_to :company
end

class Company
  default_scope { where(version_id: nil) }
end

I am building a complex report, so I need to join multiple tables and filter on them. However, I can't successfully skip the default scope when fetching Clients.

Client.joins(:company).to_sql
# SELECT clients.* FROM clients INNER JOIN companies
# ON companies.id = clients.company_id AND companies.version_id IS NULL

As you can see that is automatically including the Company default_scope. So I tried this:

Company.unscoped { Client.joins(:company) }.to_sql
# SELECT clients.* FROM clients INNER JOIN companies
# ON companies.id = clients.company_id AND companies.version_id IS NULL

Again, I got the same result, even when using unscoped with the block.

Then I decided to add a new association to the model, with the unscoped scope:

class Client
  belongs_to :company
  belongs_to :unscoped_company, -> { unscoped }, foreign_key: :company_id, class_name: "Company"
end

Having added that, I gave another try:

Client.joins(:unscoped_company).to_sql
# SELECT clients.* FROM clients INNER JOIN companies
# ON companies.id = clients.company_id AND companies.version_id IS NULL

And still the scoped is being applied.

Do you know how can I successfully join both tables without applying that default_scope?
Removing that default_scope is not an option as It is a big application and changing that will require too much time.

Rails v4.2.7

Ruby v2.2.3

Body:
Apply directly as a class method

Client.unscoped.joins(:company).to_sql


问:
dd a compressed *.xz image into a partition
I'm trying to copy a compressed image into a partition inside a Beaglebone.
Usually, it is a 2 step process:

```<code>xz -d console.img.xz # console.img is created
dd if=console.img of=/dev/mmcblk0p3
</code>```

Is there a way, I can do it in a single step without uncompressing the file *.img.xz? This is because after uncompressed the image, it is too big for the current partition.

答:
xzcat console.img.xz | dd of=/dev/mmcblk0p3 status=progress

xz -dc console.img.xz | dd of=/dev/mmcblk0p3 status=progress

Body:
I'm trying to copy a compressed image into a partition inside a Beaglebone.
Usually, it is a 2 step process:

xz -d console.img.xz # console.img is created
dd if=console.img of=/dev/mmcblk0p3

Is there a way, I can do it in a single step without uncompressing the file *.img.xz? This is because after uncompressed the image, it is too big for the current partition.


问:
How to write a switch statement that continues to prompt a user by pressing a number
First off, I'm a newbie when it comes to scripting. So far I have the first few lines of script running. My log files output to a text file, but I'm having trouble creating switch” statement that continues to prompt a user by pressing a random number. Any help would be appreciated.</p>

```<code>Clear-Host

$Dir = Get-ChildItem C:\Users\rtres\Downloads\ -Recurse
$List = $Dir | where {$_.Extension -eq ".log"} | Out-File 'C:\Users\rtres\Downloads\Log.txt'

Clear-Host

$Dir = Get-ChildItem C:\Users\rtres\Downloads\ -Recurse
$List = $Dir | where {$_.Extension -eq ".log"} | Out-File 'C:\Users\rtres\Downloads\Log.txt'
</code>```

答:
As you are new to PowerShell, I suggest you read something about the Get-ChildItem cmdlet to understand what kind of objects it returns.

Reading your code, it makes me think you are expecting a list of file names as strings, but in fact it is a list of FileInfo and/or DirectoryInfo objects.

Having said that, creating a loop to prompt a user for entering a certain value is not that hard to do. Try this:

```<code># create variables for the folder to search through and the complete path and filename for the output
$folder = 'C:\Users\rtres\Downloads'
$file   = Join-Path -Path $folder -ChildPath 'Log.txt'

# enter an endless loop
while ($true) {
    Clear-Host
    $answer = Read-Host "Press any number to continue. Type Q to quit."
    if ($answer -eq 'Q') { break }  # exit the loop when user wants to quit
    if ($answer -match '^\d+$') {   # a number has been entered
        # do your code here.

        # from the question, I have no idea what you are trying to write to the log..
        # perhaps just add the file names in there??

        # use the '-Filter' parameter instead of 'where {$_.Extension -eq ".log"}'
        # Filters are more efficient than other parameters, because the provider applies them when
        # the cmdlet gets the objects rather than having PowerShell filter the objects after they are retrieved.
        Get-ChildItem $folder -Recurse -File -Filter '*.log' | ForEach-Object {
            Add-Content -Path $file -Value $_.FullName
        }
    }
    else {
        Write-Warning "You did not enter a number.. Please try again."
    }
    # wait a little before clearing the console and repeat the prompt
    Start-Sleep -Seconds 4
}
</code>```

Hope that helps

Body:
First off, I'm a newbie when it comes to scripting. So far I have the first few lines of script running. My log files output to a text file, but I'm having trouble creating switch” statement that continues to prompt a user by pressing a random number. Any help would be appreciated.

Clear-Host

$Dir = Get-ChildItem C:\Users\rtres\Downloads\ -Recurse
$List = $Dir | where {$_.Extension -eq ".log"} | Out-File 'C:\Users\rtres\Downloads\Log.txt'

Clear-Host

$Dir = Get-ChildItem C:\Users\rtres\Downloads\ -Recurse
$List = $Dir | where {$_.Extension -eq ".log"} | Out-File 'C:\Users\rtres\Downloads\Log.txt'

Body:
As you are new to PowerShell, I suggest you read something about the Get-ChildItem cmdlet to understand what kind of objects it returns.

Reading your code, it makes me think you are expecting a list of file names as strings, but in fact it is a list of FileInfo and/or DirectoryInfo objects.

Having said that, creating a loop to prompt a user for entering a certain value is not that hard to do. Try this:

# create variables for the folder to search through and the complete path and filename for the output
$folder = 'C:\Users\rtres\Downloads'
$file   = Join-Path -Path $folder -ChildPath 'Log.txt'

# enter an endless loop
while ($true) {
    Clear-Host
    $answer = Read-Host "Press any number to continue. Type Q to quit."
    if ($answer -eq 'Q') { break }  # exit the loop when user wants to quit
    if ($answer -match '^\d+$') {   # a number has been entered
        # do your code here.

        # from the question, I have no idea what you are trying to write to the log..
        # perhaps just add the file names in there??

        # use the '-Filter' parameter instead of 'where {$_.Extension -eq ".log"}'
        # Filters are more efficient than other parameters, because the provider applies them when
        # the cmdlet gets the objects rather than having PowerShell filter the objects after they are retrieved.
        Get-ChildItem $folder -Recurse -File -Filter '*.log' | ForEach-Object {
            Add-Content -Path $file -Value $_.FullName
        }
    }
    else {
        Write-Warning "You did not enter a number.. Please try again."
    }
    # wait a little before clearing the console and repeat the prompt
    Start-Sleep -Seconds 4
}

Hope that helps


问:
Why do i get in the Date arrivalMuseum +7 Hours?
When i bring time from ZonedDateTime to Date I get the time increased exactly 7 hours in arrivalMuseum. What is the reason?</p>

```<code>public static String determine(final String departureTime, final String city)
            throws ParseException {

        final ZoneId leavingZone = ZoneId.of("Europe/Minsk");
        final ZonedDateTime departure = ZonedDateTime.of(LocalDateTime.parse(departureTime),
                leavingZone);

        final ZoneId arrivingZone = ZoneId.of("Europe/London");
        final ZonedDateTime arrival = departure.withZoneSameInstant(arrivingZone).plusMinutes(270);

        final Instant instant = arrival.toInstant();
        final Date arrivalMuseum = Date.from(instant);
}
</code>```

答:
There is a reason why Date is only compatible with the Instant class of the java.time package. This is because it only deals with the date in your personal timezone.

So when you print the arrivalMuseum object it gets automatically converted to whatever timezone you are currently in. Given the time difference of 7 hours this is probably UTC+8.

If you really need to use the old API you will need to use the Calendar api to get a date formatted for a specific timezone, but there are reasons a new date/time API was created and dealing with other timezones is one of them.

Body:
When i bring time from ZonedDateTime to Date I get the time increased exactly 7 hours in arrivalMuseum. What is the reason?

public static String determine(final String departureTime, final String city)
            throws ParseException {

        final ZoneId leavingZone = ZoneId.of("Europe/Minsk");
        final ZonedDateTime departure = ZonedDateTime.of(LocalDateTime.parse(departureTime),
                leavingZone);

        final ZoneId arrivingZone = ZoneId.of("Europe/London");
        final ZonedDateTime arrival = departure.withZoneSameInstant(arrivingZone).plusMinutes(270);

        final Instant instant = arrival.toInstant();
        final Date arrivalMuseum = Date.from(instant);
}


问:
how to just print the statement without any loop condition in java?
I just want to print the "hello" 5 times without using for loop,while loop ?</p>

答: You can do this with recursion. Is this homework? Sounds like it, so I'll not give a full answer unless you say otherwise.</p>


问:
Python Binomial Coefficient

```<code>import math
x = int(input("Enter a value for x: "))
y = int(input("Enter a value for y: "))

if y == 1 or y == x:
    print(1)

if y > x:
    print(0)
else:
    a = math.factorial(x)
    b = math.factorial(y)
    div = a // (b*(x-y))
    print(div)
</code>```

This binomial coefficient program works but when I input two of the same number which is supposed to equal to 1 or when y is greater than x it is supposed to equal to 0.

答:
Note that starting Python 3.8, the standard library provides the math.comb function to compute the binomial coefficient:

math.comb(n, k)

which is the number of ways to choose k items from n items without repetition
n! / (k! (n - k)!):

```<code>import math
math.comb(10, 5)  # 252
math.comb(10, 10) # 1
</code>```

Title: Python Binomial Coefficient

Body:
import math
x = int(input("Enter a value for x: "))
y = int(input("Enter a value for y: "))

if y == 1 or y == x:
    print(1)

if y > x:
    print(0)
else:
    a = math.factorial(x)
    b = math.factorial(y)
    div = a // (b*(x-y))
    print(div)

This binomial coefficient program works but when I input two of the same number which is supposed to equal to 1 or when y is greater than x it is supposed to equal to 0.

Body:
Note that starting Python 3.8, the standard library provides the math.comb function to compute the binomial coefficient:

math.comb(n, k)

which is the number of ways to choose k items from n items without repetition
n! / (k! (n - k)!):

import math
math.comb(10, 5)  # 252
math.comb(10, 10) # 1


问:
Pyinstaller Error when converting .py to .exe
Whenever I try to put any .py file into pyinstaller I always get an error TypeError: expected str, bytes or os.PathLike object, not NoneType I havent been able to find any fixes that make sense.

Ive tried reinstalling pyinstaller and different files.

I dont think there is any code problems since this occurs no matter what file I use

Expected: a compiled exe file.

Actual Result:
TypeError: expected str, bytes or os.PathLike object, not NoneType
error and nothing is compiled

答:
First, uninstall pyinstaller completely with pip uninstall pyinstaller then delete C:/Users/<Username>/AppData/Roaming/Pyinstaller directory.

Next Install pyinstaller with pip install -U pyinstaller.

If still shows the same error try to replace bindepend.py from here in <Python path>\Lib\site-packages\PyInstaller\depend directory.


问:
Can someone please explain the meaning of two lines below in the program to implement pipe?
Need explanation about what the writer is trying to do here.
Why cannot I use Single dimension array instead od 2d array?

```<code>char writemessages[2][20]={"Hi", "Hello"};
char readmessage[20];
</code>```

Program snippet:

```<code>   int main() {
   int pipefds[2];
   int returnstatus;
   char writemessages[2][20]={"Hi", "Hello"}; //why can't i use singlr char array
   char readmessage[20];
   returnstatus = pipe(pipefds);

   if (returnstatus == -1) {
      printf("Unable to create pipe\n");
      return 1;
   }

   printf("Writing to pipe - Message 1 is %s\n", writemessages[0]);
   write(pipefds[1], writemessages[0], sizeof(writemessages[0]));
   read(pipefds[0], readmessage, sizeof(readmessage));
   printf("Reading from pipe – Message 1 is %s\n", readmessage);
   printf("Writing to pipe - Message 2 is %s\n", writemessages[0]);
   write(pipefds[1], writemessages[1], sizeof(writemessages[0]));
   read(pipefds[0], readmessage, sizeof(readmessage));
   printf("Reading from pipe – Message 2 is %s\n", readmessage);
   return 0;
}
</code>```

答:
explain the meaning of two lines below

The line

```<code>char writemessages[2][20]={"Hi", "Hello"};
</code>```

defines an array of characters having 2 rows of 20 columns and initializes it, because of the null character to end the strings the array can contains 2 strings having up to 19 characters excluding the null character.

The initialization makes the first string to be 'H' 'i' then the null char, and the second 'H' 'e' 'l' 'l' 'o' then the null char

This is a short way equivalent to :

```<code>char writemessages[2][20]={ { 'H', 'i', 0 }, { 'H', 'e', 'l', 'l', 'o', 0 }};
</code>```

or

```<code>char writemessages[2][20]= {
   { 'H', 'i', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
   { 'H', 'e', 'l', 'l', 'o', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
</code>```

The line

```<code>char readmessage[20];
</code>```

defines an array of size 20 so allowing up to 19 characters more the null character.

Why cannot I use Single dimension array instead od 2d array?

this is just a choice to group them in a 2 dimensional array, you can also use single dimension arrays :

```<code> char writemessage1[20] = "Hi";
 char writemessage1[20] = "Hello";

 printf("Writing to pipe - Message 1 is %s\n", writemessage1);
 write(pipefds[1], writemessage1, sizeof(writemessage1));
 ...
 printf("Writing to pipe - Message 2 is %s\n", writemessage2);
 write(pipefds[1], writemessage2, sizeof(writemessage2));
</code>```

Note the code send always 20 characters, changing the definitions to have

```<code> char writemessage1[] = "Hi";
 char writemessage1[] = "Hello";
</code>```

write(pipefds[1], writemessage1, sizeof(writemessage1)); sends 3 characters and write(pipefds[1], writemessage2, sizeof(writemessage2)); sends 6 characters because of the size of the arrays (they are automatically sized and initialized to contain the ending null character)

probably

```<code>printf("Writing to pipe - Message 2 is %s\n", writemessages[0]);
write(pipefds[1], writemessages[1], sizeof(writemessages[0]));
</code>```

must be

```<code>printf("Writing to pipe - Message 2 is %s\n", writemessages[1]);
write(pipefds[1], writemessages[1], sizeof(writemessages[1]));
</code>```

to send "Hello" rather than again "Hi"

Body:
Need explanation about what the writer is trying to do here.
Why cannot I use Single dimension array instead od 2d array?

char writemessages[2][20]={"Hi", "Hello"};
char readmessage[20];

Program snippet:

   int main() {
   int pipefds[2];
   int returnstatus;
   char writemessages[2][20]={"Hi", "Hello"}; //why can't i use singlr char array
   char readmessage[20];
   returnstatus = pipe(pipefds);

   if (returnstatus == -1) {
      printf("Unable to create pipe\n");
      return 1;
   }

   printf("Writing to pipe - Message 1 is %s\n", writemessages[0]);
   write(pipefds[1], writemessages[0], sizeof(writemessages[0]));
   read(pipefds[0], readmessage, sizeof(readmessage));
   printf("Reading from pipe – Message 1 is %s\n", readmessage);
   printf("Writing to pipe - Message 2 is %s\n", writemessages[0]);
   write(pipefds[1], writemessages[1], sizeof(writemessages[0]));
   read(pipefds[0], readmessage, sizeof(readmessage));
   printf("Reading from pipe – Message 2 is %s\n", readmessage);
   return 0;
}

Body:
explain the meaning of two lines below

The line

char writemessages[2][20]={"Hi", "Hello"};

defines an array of characters having 2 rows of 20 columns and initializes it, because of the null character to end the strings the array can contains 2 strings having up to 19 characters excluding the null character.

The initialization makes the first string to be 'H' 'i' then the null char, and the second 'H' 'e' 'l' 'l' 'o' then the null char

This is a short way equivalent to :

char writemessages[2][20]={ { 'H', 'i', 0 }, { 'H', 'e', 'l', 'l', 'o', 0 }};

or

char writemessages[2][20]= {
   { 'H', 'i', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
   { 'H', 'e', 'l', 'l', 'o', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};

The line

char readmessage[20];

defines an array of size 20 so allowing up to 19 characters more the null character.

Why cannot I use Single dimension array instead od 2d array?

this is just a choice to group them in a 2 dimensional array, you can also use single dimension arrays :

 char writemessage1[20] = "Hi";
 char writemessage1[20] = "Hello";

 printf("Writing to pipe - Message 1 is %s\n", writemessage1);
 write(pipefds[1], writemessage1, sizeof(writemessage1));
 ...
 printf("Writing to pipe - Message 2 is %s\n", writemessage2);
 write(pipefds[1], writemessage2, sizeof(writemessage2));

Note the code send always 20 characters, changing the definitions to have

 char writemessage1[] = "Hi";
 char writemessage1[] = "Hello";

write(pipefds[1], writemessage1, sizeof(writemessage1)); sends 3 characters and write(pipefds[1], writemessage2, sizeof(writemessage2)); sends 6 characters because of the size of the arrays (they are automatically sized and initialized to contain the ending null character)

probably

printf("Writing to pipe - Message 2 is %s\n", writemessages[0]);
write(pipefds[1], writemessages[1], sizeof(writemessages[0]));

must be

printf("Writing to pipe - Message 2 is %s\n", writemessages[1]);
write(pipefds[1], writemessages[1], sizeof(writemessages[1]));

to send "Hello" rather than again "Hi"


问:
How to test (unit test) a BehaviorSubject in Flutter?
I would like to test the controllers stream that manages my form. Here I am trying to test my email controller which is connected to a validator.

I managed to get the controller value add via the sink method and recover via the stream method.

Declaration

```<code>  final emailController = BehaviorSubject<String>();

  Stream<String> get email => emailController.stream.transform(validateEmail);

  Function(String) get changeEmail => emailController.sink.add;

</code>```

Validator to test

```<code>final validateEmail =
      StreamTransformer<String, String>.fromHandlers(handleData: (email, sink) {
    final emailRegExp = new RegExp(
      r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,253}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,253}[a-zA-Z0-9])?)*$",
      caseSensitive: false,
      multiLine: false,
    );

    emailRegExp.hasMatch(email).toString();
    if (email.contains('@')) {
      sink.add(email);
    } else {
      sink.addError('Enter a valid email');
    }
  });
</code>```

Unit test

```<code>void main() {
  UserProfilEditBloc userProfilEditBloc = new UserProfilEditBloc();

  test('Email check BehaviorSubject', () {
    userProfilEditBloc.changeEmail('testtest'); //Expected @

    expect(userProfilEditBloc.email, emits('Enter a valid email'));
  });
}
</code>```

Error message

```<code>00:02 +0 -1: Email check BehaviorSubject [E]
  Enter a valid email
  dart:async                                              _StreamController.addError
  package:async/src/result/error.dart 30:10               ErrorResult.addTo
  package:async/src/stream_queue.dart 959:29              _TransactionRequest.update
  package:async/src/stream_queue.dart 426:31              StreamQueue._updateRequests
  package:async/src/stream_queue.dart 514:5               StreamQueue._addResult
  package:async/src/stream_queue.dart 486:9               StreamQueue._ensureListening.<fn>
  dart:async                                              _EventSinkWrapper.addError
  package:nexo/src/blocs/UserProfilEditBloc.dart 29:12    new _UserProfilEditBloc&Object&InputValidators.<fn>
  ===== asynchronous gap ===========================
  dart:async                                              _BoundSinkStream.listen
  package:rxdart/src/observables/observable.dart 1724:20  Observable.listen
  package:async/src/stream_queue.dart 483:31              StreamQueue._ensureListening
  package:async/src/stream_queue.dart 542:7               StreamQueue._addRequest
  package:async/src/stream_queue.dart 299:5               StreamQueue.startTransaction
  package:test_api                                        expect
  package:flutter_test/src/widget_tester.dart 196:3       expect
  test/register_form_test.dart 15:5                       main.<fn>

00:02 +0 -1: Some tests failed.
</code>```

If I forget @, the validator fills the sink.addError () that will cause this error. All goes well when the validator performs a sink.add().

答:
I believe, all you are missing is: emitsError.
BehaviourSubject has a cached value, so how you'd go about testing this is:

  test('Email check BehaviorSubject', () {
    expectLater(userProfileEditBloc.email, emitsInOrder([
      emits(anything), // current email if you want to check for that
      emitsError('Enter a valid email'),\
      // emitsDone // in case you also close the stream with the error
    ]));

    userProfilEditBloc.changeEmail('testtest'); //Expected @
  });
```

rxDart test files usually give a pretty good starting point how to test functionality.

Body:
I would like to test the controllers stream that manages my form. Here I am trying to test my email controller which is connected to a validator.

I managed to get the controller value add via the sink method and recover via the stream method.

Declaration

  final emailController = BehaviorSubject<String>();

  Stream<String> get email => emailController.stream.transform(validateEmail);

  Function(String) get changeEmail => emailController.sink.add;

Validator to test

final validateEmail =
      StreamTransformer<String, String>.fromHandlers(handleData: (email, sink) {
    final emailRegExp = new RegExp(
      r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,253}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,253}[a-zA-Z0-9])?)*$",
      caseSensitive: false,
      multiLine: false,
    );

    emailRegExp.hasMatch(email).toString();
    if (email.contains('@')) {
      sink.add(email);
    } else {
      sink.addError('Enter a valid email');
    }
  });

Unit test

void main() {
  UserProfilEditBloc userProfilEditBloc = new UserProfilEditBloc();

  test('Email check BehaviorSubject', () {
    userProfilEditBloc.changeEmail('testtest'); //Expected @

    expect(userProfilEditBloc.email, emits('Enter a valid email'));
  });
}

Error message

00:02 +0 -1: Email check BehaviorSubject [E]
  Enter a valid email
  dart:async                                              _StreamController.addError
  package:async/src/result/error.dart 30:10               ErrorResult.addTo
  package:async/src/stream_queue.dart 959:29              _TransactionRequest.update
  package:async/src/stream_queue.dart 426:31              StreamQueue._updateRequests
  package:async/src/stream_queue.dart 514:5               StreamQueue._addResult
  package:async/src/stream_queue.dart 486:9               StreamQueue._ensureListening.<fn>
  dart:async                                              _EventSinkWrapper.addError
  package:nexo/src/blocs/UserProfilEditBloc.dart 29:12    new _UserProfilEditBloc&Object&InputValidators.<fn>
  ===== asynchronous gap ===========================
  dart:async                                              _BoundSinkStream.listen
  package:rxdart/src/observables/observable.dart 1724:20  Observable.listen
  package:async/src/stream_queue.dart 483:31              StreamQueue._ensureListening
  package:async/src/stream_queue.dart 542:7               StreamQueue._addRequest
  package:async/src/stream_queue.dart 299:5               StreamQueue.startTransaction
  package:test_api                                        expect
  package:flutter_test/src/widget_tester.dart 196:3       expect
  test/register_form_test.dart 15:5                       main.<fn>

00:02 +0 -1: Some tests failed.

If I forget @, the validator fills the sink.addError () that will cause this error. All goes well when the validator performs a sink.add().

Body:
I believe, all you are missing is: emitsError.
BehaviourSubject has a cached value, so how you'd go about testing this is:

  test('Email check BehaviorSubject', () {
    expectLater(userProfileEditBloc.email, emitsInOrder([
      emits(anything), // current email if you want to check for that
      emitsError('Enter a valid email'),\
      // emitsDone // in case you also close the stream with the error
    ]));

    userProfilEditBloc.changeEmail('testtest'); //Expected @
  });

rxDart test files usually give a pretty good starting point how to test functionality.


问:
How to insert date using value from previous column
How to add days using value from the previous column

```<code>CREATE TABLE rent (
    date of first rent DATE NOT NULL,
    date of 2nd rent   DATE NOT NULL,
);

INSERT INTO rent VALUES(
  TO_DATE('2011-02-11 16:00:00', 'YYYY-MM-DD HH24:MI:SS'),
  DATEADD(day,7,'2011-02-11 16:00:00')
);
</code>```

I expect it to write down
date of first rent as 2011-02-11 16:00:00 and
date of 2nd rent as 2011-02-18

But that's not selecting the previous column and instead just adding the date to a known value.

答:
You can use insert . . . select:

```<code>INSERT INTO rent (date1, date2)
    SELECT date1, date1 + interval '7' day
    FROM (SELECT TO_DATE('2011-02-11 16:00:00', 'YYYY-MM-DD HH24:MI:SS') as date1
          FROM dual
         ) x;
</code>```

Note that this lists the columns being inserted.  This is a best practice to avoid unnecessary bugs.

The DATEADD() function is defined (primarily) in SQL Server.  Oracle uses the more standards-compatible INTERVAL arithmetic.

Body:
How to add days using value from the previous column

CREATE TABLE rent (
    date of first rent DATE NOT NULL,
    date of 2nd rent   DATE NOT NULL,
);

INSERT INTO rent VALUES(
  TO_DATE('2011-02-11 16:00:00', 'YYYY-MM-DD HH24:MI:SS'),
  DATEADD(day,7,'2011-02-11 16:00:00')
);

I expect it to write down
date of first rent as 2011-02-11 16:00:00 and
date of 2nd rent as 2011-02-18

But that's not selecting the previous column and instead just adding the date to a known value.

Body:
You can use insert . . . select:

INSERT INTO rent (date1, date2)
    SELECT date1, date1 + interval '7' day
    FROM (SELECT TO_DATE('2011-02-11 16:00:00', 'YYYY-MM-DD HH24:MI:SS') as date1
          FROM dual
         ) x;

Note that this lists the columns being inserted.  This is a best practice to avoid unnecessary bugs.

The DATEADD() function is defined (primarily) in SQL Server.  Oracle uses the more standards-compatible INTERVAL arithmetic.


问:
Solving Binary Gap using Recursion
I am trying to solve binary gap problem using recursion. It can be easily solved without recursion. But I want to solve this with recursion.The below program takes an integer as input and finds the binary gap.

Example:

```<code>input= 9, Binary form = 1001, Answer = 2

input=37, Binary form = 100101, Answer = 2
</code>```

It finds the maximum number of zeros that occur between two 1's in the binary representation.

I want to solve this in O(logn). Right now, the below program simply counts the total number of zeros and gives output 3 instead of 2. How do I correct this to get the right output?

```<code>class BinaryGap {

    public int solution(int N){

     return solution(N, false, 0);
    }
    public int solution(int N, boolean prevFlag, int memo) {

        if(N<2)
            return 0;

        int remainder = N%2 ;

        if(prevFlag){
            if(remainder == 0){
                memo = 1 + solution(N/2, prevFlag, memo);
            } else {
                int newGap = solution(N/2, prevFlag, memo);

                if(newGap > memo)
                    memo = newGap;
            }
        } else {

            prevFlag = (remainder == 1);
            return solution(N/2, prevFlag, 0);
        }

        return memo;

    }

    public static void main(String args[]){
        BinaryGap obj = new BinaryGap();

        System.out.println(obj.solution(37));
    }

}
</code>```

答:
Here is my solution without recursion. 100% tests are passed in Codability's application</p>

```<code>public class Solution {

    int counter = 0;
    Set<Integer> binaryGap = new HashSet<>();
    String binaryNumber;

    public int solution(int N) {
        binaryNumber = convert2Binary(N);

        IntStream.range(1, binaryNumber.length())
                .boxed()
                .forEach(calculateBinaryGapConsumer);

        return getMaxBinaryGap();
    }

    private String convert2Binary(int N) {
        return Integer.toBinaryString(N);
    }

    Consumer<Integer> calculateBinaryGapConsumer = i -> {
        char currentChar = binaryNumber.charAt(i);
        char previousChar = binaryNumber.charAt(i-1);
        if (previousChar == '1' && currentChar == '0') {
            increaseCounter();
        } else if (previousChar == '0' && currentChar == '0') {
            increaseCounter();
        } else if (previousChar == '0' && currentChar == '1') {
            saveBinaryGap();
            makeCounterZero();
        }
        //No need to handle case previousChar == '1' && currentChar == '1'.
    };

    private void saveBinaryGap() {
        binaryGap.add(counter);
    }

    private void increaseCounter() {
        counter++;
    }

    private void makeCounterZero() {
        counter = 0;
    }

    private int getMaxBinaryGap() {
        return binaryGap.stream().mapToInt(v->v).max().orElse(0);
    }

}
</code>```

Title: Solving Binary Gap using Recursion

Body:
I am trying to solve binary gap problem using recursion. It can be easily solved without recursion. But I want to solve this with recursion.The below program takes an integer as input and finds the binary gap.

Example:

input= 9, Binary form = 1001, Answer = 2

input=37, Binary form = 100101, Answer = 2

It finds the maximum number of zeros that occur between two 1's in the binary representation.

I want to solve this in O(logn). Right now, the below program simply counts the total number of zeros and gives output 3 instead of 2. How do I correct this to get the right output?

class BinaryGap {

    public int solution(int N){

     return solution(N, false, 0);
    }
    public int solution(int N, boolean prevFlag, int memo) {

        if(N<2)
            return 0;

        int remainder = N%2 ;

        if(prevFlag){
            if(remainder == 0){
                memo = 1 + solution(N/2, prevFlag, memo);
            } else {
                int newGap = solution(N/2, prevFlag, memo);

                if(newGap > memo)
                    memo = newGap;
            }
        } else {

            prevFlag = (remainder == 1);
            return solution(N/2, prevFlag, 0);
        }

        return memo;

    }

    public static void main(String args[]){
        BinaryGap obj = new BinaryGap();

        System.out.println(obj.solution(37));
    }

}

Body:
Here is my solution without recursion. 100% tests are passed in Codability's application

public class Solution {

    int counter = 0;
    Set<Integer> binaryGap = new HashSet<>();
    String binaryNumber;

    public int solution(int N) {
        binaryNumber = convert2Binary(N);

        IntStream.range(1, binaryNumber.length())
                .boxed()
                .forEach(calculateBinaryGapConsumer);

        return getMaxBinaryGap();
    }

    private String convert2Binary(int N) {
        return Integer.toBinaryString(N);
    }

    Consumer<Integer> calculateBinaryGapConsumer = i -> {
        char currentChar = binaryNumber.charAt(i);
        char previousChar = binaryNumber.charAt(i-1);
        if (previousChar == '1' && currentChar == '0') {
            increaseCounter();
        } else if (previousChar == '0' && currentChar == '0') {
            increaseCounter();
        } else if (previousChar == '0' && currentChar == '1') {
            saveBinaryGap();
            makeCounterZero();
        }
        //No need to handle case previousChar == '1' && currentChar == '1'.
    };

    private void saveBinaryGap() {
        binaryGap.add(counter);
    }

    private void increaseCounter() {
        counter++;
    }

    private void makeCounterZero() {
        counter = 0;
    }

    private int getMaxBinaryGap() {
        return binaryGap.stream().mapToInt(v->v).max().orElse(0);
    }

}


问:
codeigniter - is there a workaround for using flashdata with php sessions?
codeigniter - is there a workaround for using flashdata with php sessions ?</p>

答: You need this library http://codeigniter.com/wiki/Native_session/</p>