问:
jQuery Append: Generic way to move options to bottom of select lists
I have a form with several dozen pages. Across all pages, I need to use jQuery to move specific options in select lists to the bottom of the list.

When I have a single select on the page, this works just fine:

```<code>$('select').find('option[value="optionZ"]').appendTo('select');
</code>```

The issue is when I have more than one select, the optionZ value appends to each list multiple times.

```<code>        <select name="select1">
            <option value="optionA">option A</option>
            <option value="optionZ">option Z</option>
            <option value="optionB">option B</option>
            <option value="optionC">option C</option>
        </select>

        <select name="select2">
            <option value="optionA">option D</option>
            <option value="optionZ">option Z</option>
            <option value="optionB">option E</option>
            <option value="optionC">option F</option>
        </select>
</code>```

The only way I have been able to solve this is by targeting by name:

```<code>$('select[name=select1]').find('option[value="optionZ"]').appendTo('select[name=select1]');

$('select[name=select2]').find('option[value="optionZ"]').appendTo('select[name=select2]');
</code>```

I am looking for a generic way of doing this without referencing the name of the element everytime for maintainability purposes. Essentially "If option Z exists in this select list, append it to this select list". Any ideas?

答:
You just need to combine your select and option selectors, and append to the parent:

$('select option[value = "optionZ"]').each(function () {
  var $opt = $(this);
  $opt.appendTo($opt.parent());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

        <select name="select1">
            <option value="optionA">option A</option>
            <option value="optionZ">option Z</option>
            <option value="optionB">option B</option>
            <option value="optionC">option C</option>
        </select>

        <select name="select2">
            <option value="optionA">option D</option>
            <option value="optionZ">option Z</option>
            <option value="optionB">option E</option>
            <option value="optionC">option F</option>
        </select></code>```

Body:
I have a form with several dozen pages. Across all pages, I need to use jQuery to move specific options in select lists to the bottom of the list.

When I have a single select on the page, this works just fine:

$('select').find('option[value="optionZ"]').appendTo('select');

The issue is when I have more than one select, the optionZ value appends to each list multiple times.

        <select name="select1">
            <option value="optionA">option A</option>
            <option value="optionZ">option Z</option>
            <option value="optionB">option B</option>
            <option value="optionC">option C</option>
        </select>

        <select name="select2">
            <option value="optionA">option D</option>
            <option value="optionZ">option Z</option>
            <option value="optionB">option E</option>
            <option value="optionC">option F</option>
        </select>

The only way I have been able to solve this is by targeting by name:

$('select[name=select1]').find('option[value="optionZ"]').appendTo('select[name=select1]');

$('select[name=select2]').find('option[value="optionZ"]').appendTo('select[name=select2]');

I am looking for a generic way of doing this without referencing the name of the element everytime for maintainability purposes. Essentially "If option Z exists in this select list, append it to this select list". Any ideas?

Body:
You just need to combine your select and option selectors, and append to the parent:

$('select option[value = "optionZ"]').each(function () {
  var $opt = $(this);
  $opt.appendTo($opt.parent());
});

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

        <select name="select1">
            <option value="optionA">option A</option>
            <option value="optionZ">option Z</option>
            <option value="optionB">option B</option>
            <option value="optionC">option C</option>
        </select>

        <select name="select2">
            <option value="optionA">option D</option>
            <option value="optionZ">option Z</option>
            <option value="optionB">option E</option>
            <option value="optionC">option F</option>
        </select>


来源: stackexchange

问:
How to check array of dates are consecutive from todays date?
I have an array of unique dates from each time the user completes a task. I want to check if the dates within the array are consecutive from and including todays date.

If the array contains dates: "2017/6/2, 2017/6/3, 2017/6/4, 2017/6/5" then based on today's date being 2017/6/5 the function would return 4 as there are 4 consecutive dates from and including today.

If the array contains dates "2017/6/2, 2017/6/3, 2017/6/4" then it would return 0 as the array does not include today's date. Otherwise the count would be broken upon a non consecutive date.

```<code>List<Date> dateList = new ArrayList<Date>();
int count = 0;
Date todayDate = new Date();

for (int i=0; i<dateList.size(); i++){
    // Check if dates within the array are consecutive from todayDate, if so then increment count by 1.
}
</code>```

答:
If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.

If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).

Although you can also use JodaTime, it's being discontinued and replaced by the new APIs, do I don't recommend start a new project with joda. Even in joda's website it says: "Note that Joda-Time is considered to be a largely “finished” project. No major enhancements are planned. If using Java SE 8, please migrate to java.time (JSR-310).".

As you want to compare just the date (day/month/year), and not the time (hour/minute/second), the best choice is to use the LocalDate class. For java 8, this class is in java.time package, and in ThreeTen Backport, the package is org.threeten.bp. But the classes and methods names are the same.

The code would be like this:

```<code>public int count(List<LocalDate> dateList, LocalDate today) {
    if (!dateList.contains(today)) { // today is not in the list, return 0
        return 0;
    }

    int count = 0;
    LocalDate prev = dateList.get(0); // get first date from list
    for (int i = 1; i < dateList.size(); i++) {
        LocalDate next = dateList.get(i);
        if (prev.plusDays(1).equals(next)) {
            // difference between dates is one day
            count++;
        } else {
            // difference between dates is not 1
            // Do what? return 0? throw exception?
        }
        prev = next;
    }

    return count + 1; // didn't count the first element, adding 1
}
</code>```

Testing this method:

```<code>List<LocalDate> dateList = new ArrayList<>();
dateList.add(LocalDate.of(2017, 6, 2));
dateList.add(LocalDate.of(2017, 6, 3));
dateList.add(LocalDate.of(2017, 6, 4));
dateList.add(LocalDate.of(2017, 6, 5));
LocalDate today = LocalDate.now();

System.out.println(count(dateList, today)); // 4
</code>```

Another test (when today is not in the list)

```<code>List<LocalDate> dateList = new ArrayList<>();
dateList.add(LocalDate.of(2017, 6, 2));
dateList.add(LocalDate.of(2017, 6, 3));
dateList.add(LocalDate.of(2017, 6, 4));
LocalDate today = LocalDate.now();

System.out.println(count(dateList, today)); // 0
</code>```

Notes:

As it wasn't specified what to do when the days are not consecutive (return 0 or throw exception), I left this part commented. But it should be straightforward to add this to the code

If you want to convert java.util.Date to LocalDate, you can do as follows (using the code of this answer, full explanation is in this link in case you have any questions):

```<code>public LocalDate convert(Date date) {
    return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
}

// if your Date has no toInstant method, try this:
public LocalDate convert(Date date) {
    return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
}
</code>```

I understood that you want to check for consecutive days (so, a 1-day difference between the dates). But if you want to check if the previous date is before the next (no matter how many days), you can change the if (prev.plusDays(1).equals(next)) to if (prev.isBefore(next))

I'm not sure if that's the case, but if you want, you can also parse a String directly to a LocalDate (so you don't need to create lots of Date objects), using a DateTimeFormatter:

```<code>DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/M/d");
LocalDate d = LocalDate.parse("2017/6/2", formatter); // 2017-06-02
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an array of unique dates from each time the user completes a task. I want to check if the dates within the array are consecutive from and including todays date.

If the array contains dates: "2017/6/2, 2017/6/3, 2017/6/4, 2017/6/5" then based on today's date being 2017/6/5 the function would return 4 as there are 4 consecutive dates from and including today.

If the array contains dates "2017/6/2, 2017/6/3, 2017/6/4" then it would return 0 as the array does not include today's date. Otherwise the count would be broken upon a non consecutive date.

List<Date> dateList = new ArrayList<Date>();
int count = 0;
Date todayDate = new Date();

for (int i=0; i<dateList.size(); i++){
    // Check if dates within the array are consecutive from todayDate, if so then increment count by 1.
}

Body:
If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.

If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).

Although you can also use JodaTime, it's being discontinued and replaced by the new APIs, do I don't recommend start a new project with joda. Even in joda's website it says: "Note that Joda-Time is considered to be a largely “finished” project. No major enhancements are planned. If using Java SE 8, please migrate to java.time (JSR-310).".

As you want to compare just the date (day/month/year), and not the time (hour/minute/second), the best choice is to use the LocalDate class. For java 8, this class is in java.time package, and in ThreeTen Backport, the package is org.threeten.bp. But the classes and methods names are the same.

The code would be like this:

public int count(List<LocalDate> dateList, LocalDate today) {
    if (!dateList.contains(today)) { // today is not in the list, return 0
        return 0;
    }

    int count = 0;
    LocalDate prev = dateList.get(0); // get first date from list
    for (int i = 1; i < dateList.size(); i++) {
        LocalDate next = dateList.get(i);
        if (prev.plusDays(1).equals(next)) {
            // difference between dates is one day
            count++;
        } else {
            // difference between dates is not 1
            // Do what? return 0? throw exception?
        }
        prev = next;
    }

    return count + 1; // didn't count the first element, adding 1
}

Testing this method:

List<LocalDate> dateList = new ArrayList<>();
dateList.add(LocalDate.of(2017, 6, 2));
dateList.add(LocalDate.of(2017, 6, 3));
dateList.add(LocalDate.of(2017, 6, 4));
dateList.add(LocalDate.of(2017, 6, 5));
LocalDate today = LocalDate.now();

System.out.println(count(dateList, today)); // 4

Another test (when today is not in the list)

List<LocalDate> dateList = new ArrayList<>();
dateList.add(LocalDate.of(2017, 6, 2));
dateList.add(LocalDate.of(2017, 6, 3));
dateList.add(LocalDate.of(2017, 6, 4));
LocalDate today = LocalDate.now();

System.out.println(count(dateList, today)); // 0

Notes:

As it wasn't specified what to do when the days are not consecutive (return 0 or throw exception), I left this part commented. But it should be straightforward to add this to the code

If you want to convert java.util.Date to LocalDate, you can do as follows (using the code of this answer, full explanation is in this link in case you have any questions):

public LocalDate convert(Date date) {
    return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
}

// if your Date has no toInstant method, try this:
public LocalDate convert(Date date) {
    return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
}

I understood that you want to check for consecutive days (so, a 1-day difference between the dates). But if you want to check if the previous date is before the next (no matter how many days), you can change the if (prev.plusDays(1).equals(next)) to if (prev.isBefore(next))

I'm not sure if that's the case, but if you want, you can also parse a String directly to a LocalDate (so you don't need to create lots of Date objects), using a DateTimeFormatter:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/M/d");
LocalDate d = LocalDate.parse("2017/6/2", formatter); // 2017-06-02


问:
How to get active user's UserDetails
In my controllers, when I need the active (logged in) user, I am doing the following to get my UserDetails implementation:

```<code>User activeUser = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
log.debug(activeUser.getSomeCustomField());
</code>```

It works fine, but I would think Spring could make life easier in a case like this. Is there a way to have the UserDetails autowired into either the controller or the method?

For example, something like:

```<code>public ModelAndView someRequestHandler(Principal principal) { ... }
</code>```

But instead of getting the UsernamePasswordAuthenticationToken, I get a UserDetails instead?

I'm looking for an elegant solution. Any ideas?

答:
And if you need authorized user in templates (e.g. JSP) use

```<code><%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<sec:authentication property="principal.yourCustomField"/>
</code>```

together with

```<code>    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-taglibs</artifactId>
        <version>${spring-security.version}</version>
    </dependency>
</code>```

Title: How to get active user's UserDetails

Body:
In my controllers, when I need the active (logged in) user, I am doing the following to get my UserDetails implementation:

User activeUser = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
log.debug(activeUser.getSomeCustomField());

It works fine, but I would think Spring could make life easier in a case like this. Is there a way to have the UserDetails autowired into either the controller or the method?

For example, something like:

public ModelAndView someRequestHandler(Principal principal) { ... }

But instead of getting the UsernamePasswordAuthenticationToken, I get a UserDetails instead?

I'm looking for an elegant solution. Any ideas?

Body:
And if you need authorized user in templates (e.g. JSP) use

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<sec:authentication property="principal.yourCustomField"/>

together with

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-taglibs</artifactId>
        <version>${spring-security.version}</version>
    </dependency>


问:
Other ways of writing \ in C#
I have a bit of code that writes to a text document and i want to do this:

```<code>pathtxt.Text = pathtxt.Text + treeView1.SelectedNode.Text + "\";
</code>```

but it thinks the \ is the start of a comment or something so how do i make it do a \ . Thank you

答:
Have you tried </p>

```<code>pathtxt.Text = pathtxt.Text + treeView1.SelectedNode.Text + @"\";
</code>```

<p>or </p>

```<code>pathtxt.Text = pathtxt.Text + treeView1.SelectedNode.Text + "\\";
</code>```

Title: Other ways of writing \ in C#

Body:
I have a bit of code that writes to a text document and i want to do this:

pathtxt.Text = pathtxt.Text + treeView1.SelectedNode.Text + "\";

but it thinks the \ is the start of a comment or something so how do i make it do a \ . Thank you

Body:
Have you tried

pathtxt.Text = pathtxt.Text + treeView1.SelectedNode.Text + @"\";

or

pathtxt.Text = pathtxt.Text + treeView1.SelectedNode.Text + "\\";


问:
Perform psycopg2 db search based on user input using python function
I'm trying to perform a database search, based on user input. The DBresults function in the below code is intended to catch the input stored in the "ranumber" and perform an SQL search on that specific record. I can't seem to get this working. I've tried a number of things which have generated various errors, but the latest error I'm getting says "TypeError: not all arguments converted during string formatting".
What am I missing here?

```<code>def connectToDB():
        psycopg2.connect('dbname=reportingdb user=rai_gui password=Rad1oInd host=10.100.51.42')

def DBresults(ranumber):
        conn = psycopg2.connect('dbname=reporting user=rai_user password=Rad1odsfdInd host=10.100.47.42')
        cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
        cur.execute("SELECT * FROM radio_archive_index_gui.radio_archive_index_gui WHERE rai_number= %s", (ranumber))
        searchresults = cur.fetchall()
        print (searchresults)

####Index Page
@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
    exception = ""
        try:
            connectToDB
        except:
            exception = 'Failure to connect to db'

        form = StaffNames()
        if not exception:
            if form.validate_on_submit():
                query = {
                    'staff': dict(staff_choices).get(form.staff.data),
                    'ranumber': form.ranumber.data
                }

                return redirect(url_for('results', **query))

        return render_template(
            'index.html', title='Search Page', exception=exception, form=form
        )

#####Results Page

@app.route('/results')
def results():
    ranumber = request.args.get('ranumber', None)
        staff = request.args.get('staff', None)
        DBresults()

        return render_template(
        'results.html', title='Results', staff=staff, ranumber=ranumber
    )
</code>```

Here's my form.py file if it helps:

```<code>staff_choices=[("", ""), ('1', 'John Jones'), ('2', 'Chris Hughes'), ('                3', 'Lyn bear')]
class StaffNames(Form):
        ranumber = StringField('ranumber', validators=[DataRequired()])
        staff = SelectField('staff',choices=staff_choices,validators=[DataRequired()])
</code>```

答:
Try editing

cur.execute("SELECT * FROM radio_archive_index_gui.radio_archive_index_gui WHERE rai_number= %s", (ranumber))

to

cur.execute("SELECT * FROM radio_archive_index_gui.radio_archive_index_gui WHERE rai_number= %s", (ranumber,))

(ranumber) needs to be in tuple format for string formatting to work properly.

Body:
I'm trying to perform a database search, based on user input. The DBresults function in the below code is intended to catch the input stored in the "ranumber" and perform an SQL search on that specific record. I can't seem to get this working. I've tried a number of things which have generated various errors, but the latest error I'm getting says "TypeError: not all arguments converted during string formatting".
What am I missing here?

def connectToDB():
        psycopg2.connect('dbname=reportingdb user=rai_gui password=Rad1oInd host=10.100.51.42')

def DBresults(ranumber):
        conn = psycopg2.connect('dbname=reporting user=rai_user password=Rad1odsfdInd host=10.100.47.42')
        cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
        cur.execute("SELECT * FROM radio_archive_index_gui.radio_archive_index_gui WHERE rai_number= %s", (ranumber))
        searchresults = cur.fetchall()
        print (searchresults)

####Index Page
@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
    exception = ""
        try:
            connectToDB
        except:
            exception = 'Failure to connect to db'

        form = StaffNames()
        if not exception:
            if form.validate_on_submit():
                query = {
                    'staff': dict(staff_choices).get(form.staff.data),
                    'ranumber': form.ranumber.data
                }

                return redirect(url_for('results', **query))

        return render_template(
            'index.html', title='Search Page', exception=exception, form=form
        )

#####Results Page

@app.route('/results')
def results():
    ranumber = request.args.get('ranumber', None)
        staff = request.args.get('staff', None)
        DBresults()

        return render_template(
        'results.html', title='Results', staff=staff, ranumber=ranumber
    )

Here's my form.py file if it helps:

staff_choices=[("", ""), ('1', 'John Jones'), ('2', 'Chris Hughes'), ('                3', 'Lyn bear')]
class StaffNames(Form):
        ranumber = StringField('ranumber', validators=[DataRequired()])
        staff = SelectField('staff',choices=staff_choices,validators=[DataRequired()])


问:
Regex with nested group and dot causes wacky matching
I cannot understand why the following regex and text yield their results. I am using the regex find function in notepad++ with no Wrap_around and no matching newline. The regex:

```<code>name ="[\w]+\.((?:[\w]*\.?)+)" p
</code>```

when applied to the text:

name ="data.messageHeader.msg_time_tag.$date" pzb

this is line 2

The entire text ends up highlighted, which should be impossible, since the regex should not be able to match the dollar sign or the newline/carriage return.

I have also tried applying the regex to the text with python 're'. In this case, I parsed the full file line by line. Initially, python correctly did not match the lines with dollar signs, but those lines would take a few seconds to finish even though they were only about 100 characters. By the fourth or fifth line that contained the structure of my sample, where the dot-separated words contained a '$', python froze up until I manually stopped it.

The python code used:

```<code>import re
def main():
    pattern = re.compile(r"name =\"\w+\.((?:\w+\.?)+)\" p")
    with open(r"filepath", "r") as f:
        i = 0
        for line in f:
            match = pattern.search(line)
            if (match):
                print('<Match: %r, groups=%r>' % (match.group(), match.groups()))
            else:
                print("line %d nomatch" % (i))
            i+=1
            match = None
            #it = pattern.finditer(f.read())
            #for element in it:
                #displaymatch(element)

def displaymatch(match):
    if match is None:
        return None
    print('<Match: %r, groups=%r>' % (match.group(), match.groups()))
main()
</code>```

Can you explain why this is happening?

答:
As Wiktor said, the regex will cause catastrophic backtracking. Specifically, it is the optional period that upon backtracking, will allow the regex to try exponential permutations of the search string. The following regex prevents catastrophic backtracking by mandating that inner words are followed by periods.</p>

```<code>name ="\w+\.((\w+\.)*\w+)" p
</code>```

Body:
I cannot understand why the following regex and text yield their results. I am using the regex find function in notepad++ with no Wrap_around and no matching newline. The regex:

name ="[\w]+\.((?:[\w]*\.?)+)" p

when applied to the text:

name ="data.messageHeader.msg_time_tag.$date" pzb

this is line 2

The entire text ends up highlighted, which should be impossible, since the regex should not be able to match the dollar sign or the newline/carriage return.

I have also tried applying the regex to the text with python 're'. In this case, I parsed the full file line by line. Initially, python correctly did not match the lines with dollar signs, but those lines would take a few seconds to finish even though they were only about 100 characters. By the fourth or fifth line that contained the structure of my sample, where the dot-separated words contained a '$', python froze up until I manually stopped it.

The python code used:

import re
def main():
    pattern = re.compile(r"name =\"\w+\.((?:\w+\.?)+)\" p")
    with open(r"filepath", "r") as f:
        i = 0
        for line in f:
            match = pattern.search(line)
            if (match):
                print('<Match: %r, groups=%r>' % (match.group(), match.groups()))
            else:
                print("line %d nomatch" % (i))
            i+=1
            match = None
            #it = pattern.finditer(f.read())
            #for element in it:
                #displaymatch(element)

def displaymatch(match):
    if match is None:
        return None
    print('<Match: %r, groups=%r>' % (match.group(), match.groups()))
main()

Can you explain why this is happening?

Body:
As Wiktor said, the regex will cause catastrophic backtracking. Specifically, it is the optional period that upon backtracking, will allow the regex to try exponential permutations of the search string. The following regex prevents catastrophic backtracking by mandating that inner words are followed by periods.

name ="\w+\.((\w+\.)*\w+)" p


问:
How to obtain a list of numbers that are divided by a certain number using the filter function in Python?
I want to write a function that recieves a list and a number and returns another list with all numbers that are divided by the number passed by argument. For example:

```<code>filter_list_by_factor([1, 2, 3, 4, 5], 2)
>>> [2, 4]
</code>```

So I thought about creating a function called is_factor:

```<code>def is_factor(a, b):
    return a % b == 0
</code>```

Then, I wanted to call the function this way:

```<code>def filter_list_by_factor(numbers_list, number):
    return list(filter(is_factor, numbers_list))
</code>```

But it result in this error: TypeError: is_factor() missing 1 required positional argument: 'b'

Can you guys help me?

答:
Filter does not pass the second argument (which shouldn't be suprising - where in that line of code does it get passed the second parameter ('number' in your example)?

Try using a lambda:

```<code>def filter_list_by_factor(numbers_list, number):
    return list(filter(lambda x:is_factor(x,number), numbers_list))
</code>```

Body:
I want to write a function that recieves a list and a number and returns another list with all numbers that are divided by the number passed by argument. For example:

filter_list_by_factor([1, 2, 3, 4, 5], 2)
>>> [2, 4]

So I thought about creating a function called is_factor:

def is_factor(a, b):
    return a % b == 0

Then, I wanted to call the function this way:

def filter_list_by_factor(numbers_list, number):
    return list(filter(is_factor, numbers_list))

But it result in this error: TypeError: is_factor() missing 1 required positional argument: 'b'

Can you guys help me?

Body:
Filter does not pass the second argument (which shouldn't be suprising - where in that line of code does it get passed the second parameter ('number' in your example)?

Try using a lambda:

def filter_list_by_factor(numbers_list, number):
    return list(filter(lambda x:is_factor(x,number), numbers_list))


问:
Is View.show() the same as View.setVisible(true)?
Working on making some views of my app's UI more dynamic. Wanted to know if calling View.show() is equivocal to View.setVisible(true) in order to determine if it's redundant for me to call both in my code when wanting a hidden element to appear. Same goes for hiding a UI element. Doesn't seem to throw a fit if I call both.

I would assume the show() method would have to change the View.visible attribute the same way as its respective set() method. Are they essentially the same functions with different names or is there a specific use-case where one should be used over the other?

答:
Have a look at the SDK:

setVisibility

show

show is calling setVisibility


问:
until in FluentWait cannot be applied - java
I've had a helper class for Selenium that worked like a charm previously, and out of the blue, this issue came up.

I've also attached a screenshot of the affected functions.

until
(java.util.function.Function)
in FluentWait cannot be applied
to
(org.openqa.selenium.support.ui.ExpectedCondition)

 reason: no instance(s) of type variable(s) V exist so that ExpectedCondition conforms to Function

答:
Just use the following in your pom.xml

```<code><build>
   <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
   </plugins>
</build>
</code>```

Body:
Just use the following in your pom.xml

<build>
   <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
   </plugins>
</build>


问:
Show special hidden Files/Directories from Windows 7 in Java
Since Windows 7 the directory windows/system32/drivers/etc is specially hidden. Windows 7 itself doesn't show it, but it is there if I open it manually.

Today I was playing around with a Java JFace Eclipse example (http://www.ibm.com/developerworks/library/os-ecgui1/) and was wondering that java also doesn't show the etc directory.

So how can I get all directories/Files, when using file.listFiles() ?
Any ideas?

答:
As I wrote, I played around with an JFace Example, that builds up a Java based Windows Explorer.
I agree with you, that a Java application should normally not do something in the Windows driver directory tree.
The "specially hidden" files there, are visible with other programs like Total Commander without running this programs with other then normal rights.
I assume, that Windows has some API functions to get that information.
I'm just interested in a Java based solution that can show me everything, that's on my disk...</p>

ContentLicense: CC BY-SA 2.5


问:
Flatten git subdirectory by converting dirs to new branches
I have a git branch which contains a number of directories that I would like to flatten out into all new branches. It looks kind of like this:

git/dev/us -> us-one, us-two, us-three

I would like it to end up like this:

git/dev/us-one
git/dev/us-two
etc

It looks like this is possible using git-filter-branch, but I'm not sure how to use it with all the directories. Could I do something like:

```<code>for branch in `find . -type d -d 1`; do
    git filter-branch --subdirectory-filter $branch --prune-empty -- --all
done
</code>```

答:
Well, I guess there's a way to do it.  Pointing out a few things for posterity first...

Caveats

Since you're talking about using filter-branch, I guess you've thought through the implications of creating separate histories for each of these branches.  Just in case, I'll point out that it may be difficult for someone who's used your old repo to locate the corresponding code version in the new repo.  Also, if changes across directories were coordinated, those coordinations will be lost (unless you do something to recreate them).

Possibly related to that last point, if the structures in each of these directories are similar enough for this to make sense, then it would be surprising if they didn't sometimes need to "share" a change.  Neither the "current state" structure you describe, nor the "goal state" you've asked for, really will support that very well, if it is indeed an issue.

But how would you do it?

In the simplest case you've just got one branch you want to "break out" for each directory.  That's implied in your question, but just in case I'll provide a slightly more general procedure that should work for multiple branches.

So first of all, you need to actually create all the branches you'll want in the end.  If you have tags, you might want to replicate them as well, but I'll come back to that.

For each branch that you have:

```<code>git checkout `branchA`
git branch `branchA-one`
git branch `branchA-two`
...
git checkout `branchB`
git branch `branchB-one`
git branch `branchB-two`
...
...
</code>```

Then you can run filter-branch on each set of refs.  You'll definitely use a subdirectory-filter and if you have tags to preserve you'll want a tag-name-filter as well.  If typical changes would affect some (but not all) subdirectories, then you'll need to decide if you want (a) to preserve parallel histories, or (b) to have filter-branch eliminate empty commits

So in the simplest case

```<code>git filter-branch --subdirectory-filter dir-one -- branchA-one branchB-one ...
</code>```

If you want to preserve tags, the easiest thing is to copy them into each new history (using the same suffix as the branches), so

```<code>git filter-branch --subdirectory dir-one --tag-name-filter 'sed s/$/-one' -- branchA-one branchB-one
</code>```

And you can throw in --prune-empty if you want to remove commits that don't affect the subtree for the branch.

Each run of filte-branch will create some "backup refs" that you'll want to clean up (refs/original/...)

Note that what this doesn't provide, most likely, is a common root commit.  You will end up with literally independent histories in the repo.  Often that doesn't matter.  It's convenient if you decide later to split them into different repos.  It's less convenient if you ever foresee merging across these histories.

In that last case, you can work around the independent histories most of the time (e.g. --allow-unrelated-histories in a merge), but if you don't want to have to, then you'd modify the above procedure.  Before doing the filter-branches you would create an empty "shared root"

```<code>git branch --orphan newRoot
git rm -r *
git commit --allow-empty
</code>```

And then you would include a parent-filter to graft the root of each rewrite onto newRoot.

Body:
I have a git branch which contains a number of directories that I would like to flatten out into all new branches. It looks kind of like this:

git/dev/us -> us-one, us-two, us-three

I would like it to end up like this:

git/dev/us-one
git/dev/us-two
etc

It looks like this is possible using git-filter-branch, but I'm not sure how to use it with all the directories. Could I do something like:

for branch in `find . -type d -d 1`; do
    git filter-branch --subdirectory-filter $branch --prune-empty -- --all
done

Body:
Well, I guess there's a way to do it.  Pointing out a few things for posterity first...

Caveats

Since you're talking about using filter-branch, I guess you've thought through the implications of creating separate histories for each of these branches.  Just in case, I'll point out that it may be difficult for someone who's used your old repo to locate the corresponding code version in the new repo.  Also, if changes across directories were coordinated, those coordinations will be lost (unless you do something to recreate them).

Possibly related to that last point, if the structures in each of these directories are similar enough for this to make sense, then it would be surprising if they didn't sometimes need to "share" a change.  Neither the "current state" structure you describe, nor the "goal state" you've asked for, really will support that very well, if it is indeed an issue.

But how would you do it?

In the simplest case you've just got one branch you want to "break out" for each directory.  That's implied in your question, but just in case I'll provide a slightly more general procedure that should work for multiple branches.

So first of all, you need to actually create all the branches you'll want in the end.  If you have tags, you might want to replicate them as well, but I'll come back to that.

For each branch that you have:

git checkout `branchA`
git branch `branchA-one`
git branch `branchA-two`
...
git checkout `branchB`
git branch `branchB-one`
git branch `branchB-two`
...
...

Then you can run filter-branch on each set of refs.  You'll definitely use a subdirectory-filter and if you have tags to preserve you'll want a tag-name-filter as well.  If typical changes would affect some (but not all) subdirectories, then you'll need to decide if you want (a) to preserve parallel histories, or (b) to have filter-branch eliminate empty commits

So in the simplest case

git filter-branch --subdirectory-filter dir-one -- branchA-one branchB-one ...

If you want to preserve tags, the easiest thing is to copy them into each new history (using the same suffix as the branches), so

git filter-branch --subdirectory dir-one --tag-name-filter 'sed s/$/-one' -- branchA-one branchB-one

And you can throw in --prune-empty if you want to remove commits that don't affect the subtree for the branch.

Each run of filte-branch will create some "backup refs" that you'll want to clean up (refs/original/...)

Note that what this doesn't provide, most likely, is a common root commit.  You will end up with literally independent histories in the repo.  Often that doesn't matter.  It's convenient if you decide later to split them into different repos.  It's less convenient if you ever foresee merging across these histories.

In that last case, you can work around the independent histories most of the time (e.g. --allow-unrelated-histories in a merge), but if you don't want to have to, then you'd modify the above procedure.  Before doing the filter-branches you would create an empty "shared root"

git branch --orphan newRoot
git rm -r *
git commit --allow-empty

And then you would include a parent-filter to graft the root of each rewrite onto newRoot.


问:
Better algorithm to calculate this formula
Given an array of positive integers A, I want to find the following sum S:

S = 2^1 * (S_1) + 2^2 * (S_2) + 2^3 * (S_3) + ... + 2^n * (S_N)

where S_i is sum of product of consecutive i integers in A, for eg:

S_3 = (A[0]*A[1]*A[2]) + (A[1]*A[2]*A[3]) + .... + (A[n-3]*A[n-2]*A[n-1])

For calculating any of the S_i, I am using method similar to rolling hash, which achieve O(N):

```<code>Let tmp = A[0]*A[1]*A[2], S_3 = tmp;
For(i = 3 to n)
    (tmp *= A[i]) /= A[i-3]
    S_3 += tmp
</code>```

And for all two's power I can precompute  beforehand. So now my algorithm to calculate S is O(N^2)

My question is, is it possible to calculate S with a better complexity?

答:
A very similar approach to trincot, but starting at the other end leads to another linear algorithm.

If we had just the array {A[n-1]} then the sum would be:

```<code>T[n-1] = 2*A[n-1]
</code>```

If we then try { A[n-2], A[n-1]} we get

```<code>T[n-2] = 2*A[n-2] + 2*A[n-1] + 4*A[n-2]*A[n-1]
       = T[n-1] + 2*A[n-2]*( 1 + 2*A[n-1])
</code>```

Continuing this way we get the recursions

```<code>T[n-k] = T[n-k+1] + 2*A[n-k]* K[n-k+1]
K[n-k] = 1 + 2*A[n-k]*K[n-k+1]
</code>```

In C

```<code>int64_t sum( int64_t n, const int64_t* A)
{
int64_t K = 1;
int64_t T = 0;
int64_t i = n;
    while( --i >= 0)
    {   T += 2*K*A[i];
        K = 1 + 2*A[i]*K;
    }
    return T;
}
</code>```

Body:
Given an array of positive integers A, I want to find the following sum S:

S = 2^1 * (S_1) + 2^2 * (S_2) + 2^3 * (S_3) + ... + 2^n * (S_N)

where S_i is sum of product of consecutive i integers in A, for eg:

S_3 = (A[0]*A[1]*A[2]) + (A[1]*A[2]*A[3]) + .... + (A[n-3]*A[n-2]*A[n-1])

For calculating any of the S_i, I am using method similar to rolling hash, which achieve O(N):

Let tmp = A[0]*A[1]*A[2], S_3 = tmp;
For(i = 3 to n)
    (tmp *= A[i]) /= A[i-3]
    S_3 += tmp

And for all two's power I can precompute  beforehand. So now my algorithm to calculate S is O(N^2)

My question is, is it possible to calculate S with a better complexity?

Body:
A very similar approach to trincot, but starting at the other end leads to another linear algorithm.

If we had just the array {A[n-1]} then the sum would be:

T[n-1] = 2*A[n-1]

If we then try { A[n-2], A[n-1]} we get

T[n-2] = 2*A[n-2] + 2*A[n-1] + 4*A[n-2]*A[n-1]
       = T[n-1] + 2*A[n-2]*( 1 + 2*A[n-1])

Continuing this way we get the recursions

T[n-k] = T[n-k+1] + 2*A[n-k]* K[n-k+1]
K[n-k] = 1 + 2*A[n-k]*K[n-k+1]

In C

int64_t sum( int64_t n, const int64_t* A)
{
int64_t K = 1;
int64_t T = 0;
int64_t i = n;
    while( --i >= 0)
    {   T += 2*K*A[i];
        K = 1 + 2*A[i]*K;
    }
    return T;
}


答:
Instead of concatenating string (and escaping backslash), you can use Path.Combine like this:

```<code>pathtxt.Text = Path.Combine(pathtxt.Text,treeView1.SelectedNode.Text);
</code>```

Title: Other ways of writing \ in C#

Body:
Instead of concatenating string (and escaping backslash), you can use Path.Combine like this:

pathtxt.Text = Path.Combine(pathtxt.Text,treeView1.SelectedNode.Text);


问:
Can't load Image HTTP
I can't load this image, help me please!
My info.plist >

```<code><key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>localhost</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>
</code>```

my Code >

```<code>      <View style={{flex: 1, flexDirection: 'row'}}>
        <Image
        source={{uri: 'http://ro-character-simulator.ratemyserver.net/charsim.php?gender=1&job=40&hair=1&viewid=0&location=256&direction=0&action=1&hdye=1&dye=0&framenum=0&bg=0&cart=&mount=0&shield=0&weapon=0&animate=1&rand=9725591', width: 50, height: 50}}/>
      </View>
</code>```

答: Need to allow form Xcode settings.

Title: Can't load Image HTTP

Body:
I can't load this image, help me please!
My info.plist >

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>localhost</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>

my Code >

      <View style={{flex: 1, flexDirection: 'row'}}>
        <Image
        source={{uri: 'http://ro-character-simulator.ratemyserver.net/charsim.php?gender=1&job=40&hair=1&viewid=0&location=256&direction=0&action=1&hdye=1&dye=0&framenum=0&bg=0&cart=&mount=0&shield=0&weapon=0&animate=1&rand=9725591', width: 50, height: 50}}/>
      </View>

Body: Need to allow form Xcode settings.


问:
manually set an order number with auto increment in MYSQL
I am looking for a MySQL code to set an order number with auto increments.

This is already in the database, but I want to change the order number
I hope some one can help.

Thank you very much
Regards flemming

答:
You can change the autoincrement increment and offset as says the documentation in https://dev.mysql.com/doc/refman/5.7/en/replication-options-master.html#sysvar_auto_increment_increment:

```<code>SET @@auto_increment_increment=x;
SET @@auto_increment_offset=y;
</code>```

where x & y are the values you need to set

Body:
You can change the autoincrement increment and offset as says the documentation in https://dev.mysql.com/doc/refman/5.7/en/replication-options-master.html#sysvar_auto_increment_increment:

SET @@auto_increment_increment=x;
SET @@auto_increment_offset=y;

where x & y are the values you need to set


答:
\ is used for escape sequences in text literals for C#. The compiler doesn't think it's the start of a comment: it thinks it's the start of an escape sequence. So you either need to use "\\" (i.e. the escape sequence for backslash) or @"\" (a verbatim string literal, which doesn't allow escape sequences).

Path.Combine is a generally preferred way of creating paths from multiple segments, however.

Title: Other ways of writing \ in C#


问:
Scala compiler not recognizing a view bound
I've tried this line of code

```<code>def **[A <% Numeric[A]](l:List[A],m:List[A])=l.zip(m).map({t=>t._1*t._2})
</code>```

However on compilation, I get this error

```<code>error: value * is not a member of type parameter A
def **[A <% Numeric[A]](l:List[A],m:List[A])=l.zip(m).map({t=>t._1*t._2})
</code>```

When I look at the source for the Numeric trait, I see a * op defined.

What am I doing wrong?

答:
The instance of Numeric is not a number itself, but it is an object that offers operations to do the arithmetic. For example, an object num of type Numeric[Int] can add two integers like this: num.plus(3, 5) The result of this operation is the integer 7.

For integers, this is very trivial. However, for all basic numerical types, there is one implicit instance of Numeric available. And if you define your own numeric types, you can provide one.

Therefore, you should leave the bounds for A open and add an implicit parameter of type Numeric[A], with which you do the calculations. Like this:

```<code>def **[A](l:List[A],m:List[A])(implicit num:Numeric[A])=l.zip(m).map({t=>num.times(t._1, t._2)})
</code>```

Of course, num.times(a,b) looks less elegant than a*b. In most of the cases, one can live with that. However, you can wrap the value a in an object of type Ops that supports operators, like this:

```<code>// given are: num:Numeric[A], a:A and b:A
val a_ops = num.mkNumericOps(a)
val product = a_ops * b
</code>```

Since the method mkNumericOps is declared implicit, you can also import it and use it implicitly:

```<code>// given are: num:Numeric[A], a:A and b:A
import num._
val product = a * b
</code>```

Body:
I've tried this line of code

def **[A <% Numeric[A]](l:List[A],m:List[A])=l.zip(m).map({t=>t._1*t._2})

However on compilation, I get this error

error: value * is not a member of type parameter A
def **[A <% Numeric[A]](l:List[A],m:List[A])=l.zip(m).map({t=>t._1*t._2})

When I look at the source for the Numeric trait, I see a * op defined.

What am I doing wrong?

Body:
The instance of Numeric is not a number itself, but it is an object that offers operations to do the arithmetic. For example, an object num of type Numeric[Int] can add two integers like this: num.plus(3, 5) The result of this operation is the integer 7.

For integers, this is very trivial. However, for all basic numerical types, there is one implicit instance of Numeric available. And if you define your own numeric types, you can provide one.

Therefore, you should leave the bounds for A open and add an implicit parameter of type Numeric[A], with which you do the calculations. Like this:

def **[A](l:List[A],m:List[A])(implicit num:Numeric[A])=l.zip(m).map({t=>num.times(t._1, t._2)})

Of course, num.times(a,b) looks less elegant than a*b. In most of the cases, one can live with that. However, you can wrap the value a in an object of type Ops that supports operators, like this:

// given are: num:Numeric[A], a:A and b:A
val a_ops = num.mkNumericOps(a)
val product = a_ops * b

Since the method mkNumericOps is declared implicit, you can also import it and use it implicitly:

// given are: num:Numeric[A], a:A and b:A
import num._
val product = a * b


问:
Running all test scenarios with Sencha Test CLI
With Sencha Test I created some test scenarios and asking myself, whether it is possible to run several test scenarios via CLI on Windows command. I know that I can run a specific scenario with stc run -p Embedded within the scenario's folder or stc run -p Embedded -s [SCENARIO_FOLDER] outside the scenario folder.

Now what I'm wondering: Is it possible to run several test scenarios via CLI? I tried e.g. ANT-style stc run **/* -p Embedded or stc run -p Embedded in the parent folder, but nothing worked. When it comes to CI with Jenkins, it should be possible to run all test scenarios at once / in parallel - but how? I could not find any hint so far.

Or is it a misunderstanding of how Sencha tests should be organized, like having all integration tests in one scenario with several folders?

Thanks in advance.

答: There is no way to run multiple scenarios with STC. I would suggest placing all related tests in one scenario if possible.</p>


问:
Previously working Xamarin iOS project doesn't build and gives MSB6006 Error
When I try to build my Xamarin iOS project, I get this error:

/Library/Frameworks/Mono.framework/Versions/5.0.1/lib/mono/msbuild/15.0/bin/Roslyn/Microsoft.CSharp.Core.targets(5,5):
  Error MSB6006: "csc.exe" exited with code 1. (MSB6006)

Seems it's because of Mono 5.0, but I don't know how to fix it!

答:
There's actually an upstream bug in Roslyn related to compiling projects that include async partial methods that's causing this.

Public bug 56246 on the Xamarin bug tracker has been filed to track the inclusion of the upstream "csc.exe" fix into Mono 5.0.

Mono 5.0 and Mono 4.8.1 both include mcs (Mono's compiler) and csc, however, Mono 4.8.1 uses mcs by default while 5.0 uses csc by default.

While waiting for the fix to make it to the Xamarin environment, there is a temporary workaround that should get you up and running. You can temporarily switch back to using mcs and xbuild in Mono 5.0:

Add the following PropertyGroup element to the bottom of the .csproj file for your app project just before the closing </Project> tag:

<PropertyGroup Condition=" '$(OS)' == 'Unix' ">
    <CscToolExe>mcs.exe</CscToolExe>
</PropertyGroup>

Disable Visual Studio > Preferences > Build > Build with MSBuild instead of xbuild.

Close, then reopen the solution and double check the new setting.

Clean and rebuild.


问:
How to insert a single row data in a excel in c#?
I have a method where i pass four parameters, like,

```<code>public void loggeneration(DateTime datetime, string projectname, int totallines,int sum,int max)
{
}
</code>```

within the above method, i have to create a excel sheet(if file is present already, just append the data in the last blank row) and insert the data(datetime, projectname, totallines,sum,max) in a row of five columns.

The first row by default, should be the column names.

I have tried my best, could not find the exact solution. Can somebody provide the solution? Thanks in Advance

答:
Indeed, this question already exists in stack overflow. By the way you can try this simple solution.</p>

```<code>  public void loggeneration(DateTime datetime, string projectname, int totallines, int sum, int max)
    {
        // this is the variable to your xls file
        string path = @"c:\temp\log.xls";

        // This text is added only once to the file.
        if (!File.Exists(path))
        {
            // Create a file to write to.
            using (StreamWriter sw = File.CreateText(path))
            {
                //once file was created insert the columns
                sw.WriteLine("date;projectname;totallines;sum;max");

            }
        }
        // This text is always added, making the file longer over time
        using (StreamWriter sw = File.AppendText(path))
        {
            sw.WriteLine(String.Format("{0};{1};{2};{3};{4}", datetime, projectname, totallines, sum, max));
        }
    }
</code>```

Body:
I have a method where i pass four parameters, like,

public void loggeneration(DateTime datetime, string projectname, int totallines,int sum,int max)
{
}

within the above method, i have to create a excel sheet(if file is present already, just append the data in the last blank row) and insert the data(datetime, projectname, totallines,sum,max) in a row of five columns.

The first row by default, should be the column names.

I have tried my best, could not find the exact solution. Can somebody provide the solution? Thanks in Advance

Body:
Indeed, this question already exists in stack overflow. By the way you can try this simple solution.

  public void loggeneration(DateTime datetime, string projectname, int totallines, int sum, int max)
    {
        // this is the variable to your xls file
        string path = @"c:\temp\log.xls";

        // This text is added only once to the file.
        if (!File.Exists(path))
        {
            // Create a file to write to.
            using (StreamWriter sw = File.CreateText(path))
            {
                //once file was created insert the columns
                sw.WriteLine("date;projectname;totallines;sum;max");

            }
        }
        // This text is always added, making the file longer over time
        using (StreamWriter sw = File.AppendText(path))
        {
            sw.WriteLine(String.Format("{0};{1};{2};{3};{4}", datetime, projectname, totallines, sum, max));
        }
    }


问:
Can't get ng-repeat to work in angularjs with array in controller
Below is my code. Not sure why ng-repeat shows up completely blank.

Any help greatly appreciated.

Larry

```<code>    <!DOCTYPE html>
    <html>
     <script
  src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
     </script>
     <body>

         <div ng-app="myApp" ng-controller="myCtrl">
        <ul><li ngrepeat="x in names">{{x}}</li></ul> </div>

<script>
 var app = angular.module('myApp', []);
 app.controller('myCtrl', function($scope) {
 $scope.names = ["Emil","Tobias","Linus"];
});
</script>

</body>
</html>
</code>```

答:
Fix the typo </p>

```<code>  <!DOCTYPE html>
  <html>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"> </script>
  <body>
  <div ng-app="myApp" ng-controller="myCtrl">
      <ul><li ng-repeat="x in names">{{x}}</li></ul> </div>
<script>
   var app = angular.module('myApp', []);
   app.controller('myCtrl', function($scope) {
   $scope.names = ["Emil","Tobias","Linus"];
    });
</script>

</body>
</html>
</code>```

Body:
Below is my code. Not sure why ng-repeat shows up completely blank.

Any help greatly appreciated.

Larry

    <!DOCTYPE html>

{{x}}

Body:
Fix the typo

  <!DOCTYPE html>
  <html>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"> </script>
  <body>
  <div ng-app="myApp" ng-controller="myCtrl">
      <ul><li ng-repeat="x in names">{{x}}</li></ul> </div>
<script>
   var app = angular.module('myApp', []);
   app.controller('myCtrl', function($scope) {
   $scope.names = ["Emil","Tobias","Linus"];
    });
</script>

</body>
</html>


问:
After adding Maven framework support in IntelliJ, it moved all /src/com/... files into /src/main/java/com/... without updating git history. How fix?
I added Maven support to a project that previously did not have it. IntelliJ then moved all the java files, but even though it's a git project, did not use git mv and so there's no file history.

How do I fix this?

Example:

```<code>//The below structure was before Maven
/src
.../com
    .../test
        .../SomeClass.java

//After Maven
/src
.../main
    .../java
        .../com
            .../test
                .../SomeClass.java
</code>```

答:
Renames are not first class citizens in Git.
Git detects renames based on file content changes.
As such, the main purpose of git mv is to simplify staging.
If files get renamed without git mv,
that causes only a minor inconvenience,
which you can rectify by appropriate git add commands.
That is, for each renamed file, one git add for the old name ("deleted file" from the perspective of Git), and one git add for the new name ("new file" from the perspective of Git).

In your particular example,
a simple fix could be staging everything by running git add . at the project root.
After that, check the output of git status -sb.
There's a good chance that Git will figure out all the renames.

Body:
I added Maven support to a project that previously did not have it. IntelliJ then moved all the java files, but even though it's a git project, did not use git mv and so there's no file history.

How do I fix this?

Example:

//The below structure was before Maven
/src
.../com
    .../test
        .../SomeClass.java

//After Maven
/src
.../main
    .../java
        .../com
            .../test
                .../SomeClass.java


问:
Server Side Form Validation PHP with multi-file Upload
HTML:

```<code>Owner: input type="text" name="owner[]" />
Category:
<select name="cat[]">
      <option value="clothes">Clothes</option>
      <option value="shoes">Shoes</option>
      <option value="accessories">Accessories</option>
</select>
Upload: <input type="file" name="image[]" />
</code>```

whith function that clone the same fields when click on "+ button"

I count the POST field with:

```<code>$num = count($_FILES['image']['name']);
</code>```

because i want to know how many times the end user clone the fields.

what i want is Make sure that the user has to fill all fields which he opend with "+ button" i cant check all the hidden fields i want to check just the field he opend.

so what can i do ?

i cant do like this:

```<code>$owner = $_POST['owner'][$i];
$cat = $_POST['cat'][$i];
$file = $_FILES['image'][$i];

if ($owner && $cat && $file)
   echo "bla bla bla";
else
   echo "fill all the fields!";
</code>```

can anyone help me ?

thank you

答:
There are some points which you need to make sure beforehand. Whenever you are using any input field's name attribute as "owner[]" or "cat[]" or "image[]", you will get an array then. But since, input file's property accessing capability is already 2D array by default, so now you will be able to access those properties as a 3D array.

When you have added a "[]" for the input file field's name attribute, you will now get the name of the 1st file as "$_FILES['image'][0]['name']", because array indices start with 0. As per your question, you can validate using the following way:-

```<code><?php
$numOwners = count($_POST['owner']);
$numCats = count($_POST['cat']);
$numFiles = count($_FILES['image']);

// Check to see if the number of Fields for each (Owners, Categories & Files) are the same
if ($numFiles === $numCats && $numFiles === $numOwners) {
    $boolInconsistencyOwners = FALSE;
    $boolInconsistencyCats = FALSE;
    $boolInconsistencyFiles = FALSE;

    for ($i = 0; $i < $numFiles; $i++) {
        if (empty($_POST['owner'][$i])) {
            $boolInconsistencyOwners = TRUE;
            break;
        }

        if (empty($_POST['cat'][$i])) {
            $boolInconsistencyCats = TRUE;
            break;
        }

        if (!is_uploaded_file($_FILES['image'][$i]['tmp_name'])) {
            $boolInconsistencyFiles = TRUE;
            break;
        }
    }

    if ($boolInconsistencyOwners || $boolInconsistencyCats || $boolInconsistencyFiles) {
        echo "I knew that there will be some problems with users' mentality!";
        // Redirect with proper Error Messages
    }
    else {
        echo "Wow, Users have improved & have become quite obedient!";
        // Proceed with normal requirements
    }
}
else {
    echo "Something fishy is going on!";
}
?>
</code>```

Hope it helps.

Body:
HTML:

Owner: input type="text" name="owner[]" />
Category:
<select name="cat[]">
      <option value="clothes">Clothes</option>
      <option value="shoes">Shoes</option>
      <option value="accessories">Accessories</option>
</select>
Upload: <input type="file" name="image[]" />

whith function that clone the same fields when click on "+ button"

I count the POST field with:

$num = count($_FILES['image']['name']);

because i want to know how many times the end user clone the fields.

what i want is Make sure that the user has to fill all fields which he opend with "+ button" i cant check all the hidden fields i want to check just the field he opend.

so what can i do ?

i cant do like this:

$owner = $_POST['owner'][$i];
$cat = $_POST['cat'][$i];
$file = $_FILES['image'][$i];

if ($owner && $cat && $file)
   echo "bla bla bla";
else
   echo "fill all the fields!";

can anyone help me ?

thank you

Body:
There are some points which you need to make sure beforehand. Whenever you are using any input field's name attribute as "owner[]" or "cat[]" or "image[]", you will get an array then. But since, input file's property accessing capability is already 2D array by default, so now you will be able to access those properties as a 3D array.

When you have added a "[]" for the input file field's name attribute, you will now get the name of the 1st file as "$_FILES['image'][0]['name']", because array indices start with 0. As per your question, you can validate using the following way:-

<?php
$numOwners = count($_POST['owner']);
$numCats = count($_POST['cat']);
$numFiles = count($_FILES['image']);

// Check to see if the number of Fields for each (Owners, Categories & Files) are the same
if ($numFiles === $numCats && $numFiles === $numOwners) {
    $boolInconsistencyOwners = FALSE;
    $boolInconsistencyCats = FALSE;
    $boolInconsistencyFiles = FALSE;

    for ($i = 0; $i < $numFiles; $i++) {
        if (empty($_POST['owner'][$i])) {
            $boolInconsistencyOwners = TRUE;
            break;
        }

        if (empty($_POST['cat'][$i])) {
            $boolInconsistencyCats = TRUE;
            break;
        }

        if (!is_uploaded_file($_FILES['image'][$i]['tmp_name'])) {
            $boolInconsistencyFiles = TRUE;
            break;
        }
    }

    if ($boolInconsistencyOwners || $boolInconsistencyCats || $boolInconsistencyFiles) {
        echo "I knew that there will be some problems with users' mentality!";
        // Redirect with proper Error Messages
    }
    else {
        echo "Wow, Users have improved & have become quite obedient!";
        // Proceed with normal requirements
    }
}
else {
    echo "Something fishy is going on!";
}
?>

Hope it helps.


问:
Combine search and will_paginate
User can do a quick search for a specific record in a database. I also added a will paginate, but when I did, the search bar didn't work. How can I fix this?

my controller

```<code>class VendorsController < ApplicationController
    def index
        @vendors = Vendor.search(params[:search])

        @vendors = Vendor.all.paginate(page: params[:page], per_page: 10)

    end

#...
end
</code>```

index

```<code>#...
<table>
    <tr>
        <% if user_signed_in? %>
            <%= button_to "New Vendor", new_vendor_path, :method => "get" %>
        <% end %>
        <%= button_to "Inventory", inventories_path, :method => "get" %>
        <%= form_tag vendors_path, :method => "get" do %>
            <%= text_field_tag :search, params[:search] %>
            <%= submit_tag "Search", :contact_name => nil %>
        <% end %>
        <div class = "pag" >
            <%= will_paginate @vendors %>
        </div>
    </tr>
</table>
#...
</code>```

答:
In the index you are replacing the value of @vendors from the search results, with the value from the paginate results.

```<code>class VendorsController < ApplicationController
    def index
        @vendors = Vendor.search(params[:search])

        @vendors = Vendor.all.paginate(page: params[:page], per_page: 10)

    end

#...
end
</code>```

Try this to paginate the search results...

```<code>class VendorsController < ApplicationController
    def index
        @vendors = Vendor.search(params[:search]).paginate(page: params[:page], per_page: 10)

    end

#...
end
</code>```

Title: Combine search and will_paginate

Body:
User can do a quick search for a specific record in a database. I also added a will paginate, but when I did, the search bar didn't work. How can I fix this?

my controller

class VendorsController < ApplicationController
    def index
        @vendors = Vendor.search(params[:search])

        @vendors = Vendor.all.paginate(page: params[:page], per_page: 10)

    end

#...
end

index

#...

        <% if user_signed_in? %>
            <%= button_to "New Vendor", new_vendor_path, :method => "get" %>
        <% end %>
        <%= button_to "Inventory", inventories_path, :method => "get" %>
        <%= form_tag vendors_path, :method => "get" do %>
            <%= text_field_tag :search, params[:search] %>
            <%= submit_tag "Search", :contact_name => nil %>
        <% end %>

            <%= will_paginate @vendors %>

#...

Body:
In the index you are replacing the value of @vendors from the search results, with the value from the paginate results.

class VendorsController < ApplicationController
    def index
        @vendors = Vendor.search(params[:search])

        @vendors = Vendor.all.paginate(page: params[:page], per_page: 10)

    end

#...
end

Try this to paginate the search results...

class VendorsController < ApplicationController
    def index
        @vendors = Vendor.search(params[:search]).paginate(page: params[:page], per_page: 10)

    end

#...
end


问:
Is java actually faster than C# in bubble sort?
I wanted to check whether c# or java is faster with executing bubble sort function to sort 100000 unsorted records.

For C#, I used this code for bubble sort:

```<code>        static void sort(int[] table)
    {
        int n = table.Length;
        do
        {
            for (int i = 0; i < n - 1; i++)
            {
                if (table[i] > table[i + 1])
                {
                    int tmp = table[i];
                    table[i] = table[i + 1];
                    table[i + 1] = tmp;
                }
            }
            n--;
        }
        while (n > 1);
    }
</code>```

For java, It's almost the same:

```<code>static void sort(int[] table)
    {
        int n = table.length;
        do
        {
            for (int i = 0; i < n - 1; i++)
            {
                if (table[i] > table[i + 1])
                {
                    int tmp = table[i];
                    table[i] = table[i + 1];
                    table[i + 1] = tmp;
                }
            }
            n--;
        }
        while (n > 1);
    }
</code>```

To measure execution time, in C# I used Stopwatch class:

```<code>Stopwatch sw = new Stopwatch();
            sw.Start();
            sort(arr);
            sw.Stop();
</code>```

I couldn't find Stopwatch class in Java and I used this code to measure execution time in Java:

```<code> class ExecutionTimer {
  private long start;
  private long end;

  public ExecutionTimer() {
    start = System.nanoTime();
  }

  public void end() {
    end = System.nanoTime();
  }

  public float duration(){
    return (end-start);
  }

  public void reset() {
    start = 0;
    end   = 0;
  }}
</code>```

I run algorithm 5 times in C# and 5 times in Java. The average time for execution time in C# was: 40,13s , in JAVA was: 18,44s.

Why the difference is so big? Is it because I used StopWatch to measure time in C#?
I had closed every program, browser and anti-virus on my laptop during the test.

Thank you.

答:
I would not be surprised if C# runs slower than java, but the difference here is so big because your testing methodology is not up to snuff.

You cannot just invoke the code to be benchmarked sandwitched between clock readings.  You have to first allow the code to be jitted, by running it many times over.  In benchmarking circles, this is known as "warmup", and it is necessary for languages that are compiled into bytecode (or MSIL at the case may be) and then just-in-time-compiled during runtime.

How many times is enough to warm up?  Opinions differ; I have heard you have to run it once, I have heard you have to run it 10000 times.  Try and see what you get.

Body:
I wanted to check whether c# or java is faster with executing bubble sort function to sort 100000 unsorted records.

For C#, I used this code for bubble sort:

        static void sort(int[] table)
    {
        int n = table.Length;
        do
        {
            for (int i = 0; i < n - 1; i++)
            {
                if (table[i] > table[i + 1])
                {
                    int tmp = table[i];
                    table[i] = table[i + 1];
                    table[i + 1] = tmp;
                }
            }
            n--;
        }
        while (n > 1);
    }

For java, It's almost the same:

static void sort(int[] table)
    {
        int n = table.length;
        do
        {
            for (int i = 0; i < n - 1; i++)
            {
                if (table[i] > table[i + 1])
                {
                    int tmp = table[i];
                    table[i] = table[i + 1];
                    table[i + 1] = tmp;
                }
            }
            n--;
        }
        while (n > 1);
    }

To measure execution time, in C# I used Stopwatch class:

Stopwatch sw = new Stopwatch();
            sw.Start();
            sort(arr);
            sw.Stop();

I couldn't find Stopwatch class in Java and I used this code to measure execution time in Java:

 class ExecutionTimer {
  private long start;
  private long end;

  public ExecutionTimer() {
    start = System.nanoTime();
  }

  public void end() {
    end = System.nanoTime();
  }

  public float duration(){
    return (end-start);
  }

  public void reset() {
    start = 0;
    end   = 0;
  }}

I run algorithm 5 times in C# and 5 times in Java. The average time for execution time in C# was: 40,13s , in JAVA was: 18,44s.

Why the difference is so big? Is it because I used StopWatch to measure time in C#?
I had closed every program, browser and anti-virus on my laptop during the test.

Thank you.


问:
Text not displaying in D3 SVG
I have a problem with appending text to my SVG in d3.
What I want to achieve is for text to appear in the red circle as displayed in this image: Circle d3 graph.

For some reason I cannot make the text display and after spending a few hours on this I really don't have any ideas how to solve this... I found a few similar questions on SO but nothing helped me to solve this...

Here are the fragments of the code that I think are crucial to solve this problem:

```<code>.on("mousemove", function (d) {
  svg.select("text.text-tooltip1")
    .text(function(d){
    return d3.time.format("%B %d, %Y")(d["data"]);
  })

  svg.select("text.text-tooltip2")
    .text(function(d){
    return "PM emmision:" + d3.round(x(d["ug_mean"]),2);
  })

  svg.select("text.text-tooltip3")
    .text(function(d){
    return "Benzen emmision:" + d3.round(x(d["Precipitationmm"]),2);
  })
})
</code>```

and

```<code>svg.append("circle")
      .attr("class", "exp")
      .attr("cx", 0)
      .attr("cy", 0)
      .attr("r", 130)
      .attr("fill", "#e74747")
      .attr("opacity", "0.8");

svg.append("text")
            .attr("class", "text-tooltip1")
            .attr("dy", "-2em")
            .style("text-anchor", "middle")
            .attr("class", "data");

svg.append("text")
            .attr("class", "text-tooltip2")
            .attr("dy", "1.5em")
            .style("text-anchor", "middle")
            .attr("class", "data");

svg.append("text")
            .attr("z-index", 100)
            .attr("class", "text-tooltip3")
            .attr("dy", "2.5em")
            .style("text-anchor", "middle")
            .attr("class", "data");
</code>```

And here is full code on Plunkr: https://plnkr.co/edit/b6PjicI0vOoYSHaDnWS0?p=preview

Thanks a lot for your help!

答:
You need to make two small changes. First, when you append the <text> elements, you are setting class twice. But the second time overwrites the first, so those elements don't have the .text-tooltipN class you expect them to have. In D3 v4, you can use .classed('class-name', true) multiple times without overwriting other classes, but it's easier to just set all at once:

```<code>svg.append("text")
  .attr("class", "data text-tooltip1")
  .attr("dy", "-2em")
  .style("text-anchor", "middle");
</code>```

Second, you don't need two functions inside the mouse event -- notice that you're nesting two cases of function(d){} which means d no longer has the value you want:

```<code>.on("mousemove", function (d) {
   svg.select("text.text-tooltip1")
     .text(d3.time.format("%B %d, %Y")(d["data"]))
</code>```

Title: Text not displaying in D3 SVG

Body:
I have a problem with appending text to my SVG in d3.
What I want to achieve is for text to appear in the red circle as displayed in this image: Circle d3 graph.

For some reason I cannot make the text display and after spending a few hours on this I really don't have any ideas how to solve this... I found a few similar questions on SO but nothing helped me to solve this...

Here are the fragments of the code that I think are crucial to solve this problem:

.on("mousemove", function (d) {
  svg.select("text.text-tooltip1")
    .text(function(d){
    return d3.time.format("%B %d, %Y")(d["data"]);
  })

  svg.select("text.text-tooltip2")
    .text(function(d){
    return "PM emmision:" + d3.round(x(d["ug_mean"]),2);
  })

  svg.select("text.text-tooltip3")
    .text(function(d){
    return "Benzen emmision:" + d3.round(x(d["Precipitationmm"]),2);
  })
})

and

svg.append("circle")
      .attr("class", "exp")
      .attr("cx", 0)
      .attr("cy", 0)
      .attr("r", 130)
      .attr("fill", "#e74747")
      .attr("opacity", "0.8");

svg.append("text")
            .attr("class", "text-tooltip1")
            .attr("dy", "-2em")
            .style("text-anchor", "middle")
            .attr("class", "data");

svg.append("text")
            .attr("class", "text-tooltip2")
            .attr("dy", "1.5em")
            .style("text-anchor", "middle")
            .attr("class", "data");

svg.append("text")
            .attr("z-index", 100)
            .attr("class", "text-tooltip3")
            .attr("dy", "2.5em")
            .style("text-anchor", "middle")
            .attr("class", "data");

And here is full code on Plunkr: https://plnkr.co/edit/b6PjicI0vOoYSHaDnWS0?p=preview

Thanks a lot for your help!

Body:
You need to make two small changes. First, when you append the <text> elements, you are setting class twice. But the second time overwrites the first, so those elements don't have the .text-tooltipN class you expect them to have. In D3 v4, you can use .classed('class-name', true) multiple times without overwriting other classes, but it's easier to just set all at once:

svg.append("text")
  .attr("class", "data text-tooltip1")
  .attr("dy", "-2em")
  .style("text-anchor", "middle");

Second, you don't need two functions inside the mouse event -- notice that you're nesting two cases of function(d){} which means d no longer has the value you want:

.on("mousemove", function (d) {
   svg.select("text.text-tooltip1")
     .text(d3.time.format("%B %d, %Y")(d["data"]))


答: It looks like you're assigning the value of @venders twice in your Index action, with the second one always overriding the first.

Title: Combine search and will_paginate


问:
Wepay integration
I'm trying to create a simple checkout page with wepay and my checkout code (taken from the SDK sample) works great for the owner (me) when I'm signed in, but when logged in as a different user who hasn't created the account (under theirs?) it says the account is invalid or does not belong to the user.

So how are new logged in users supposed to pay to the account (mine), in other words make payments?

Here is the code for reference. The account_id doesn't work for new logged in users because they haven't created it.

```<code>$wepay = new WePay($_SESSION['wepay_access_token']);

$checkout = $wepay->request('checkout/create', array(
    'account_id' => 501999810,
    'amount' => 1.00,
    'currency'=> 'USD',
    'short_description'=> 'Selling 42 Pens',
    'type'=> 'goods'
));
</code>```

Maybe I have something completely off, but that account_id is where I want to receive payments?

Any help would be appreciated!

答:
Once you register the user, you have to create an actual merchant account by calling /account/create.

Once you have the user's access token, you can call /account/create with the user's access token and the relevant info to actually attach an account to the user.  The /account/create call will return an account_id.  That account_id is the one you use in the /checkout/create call.

So until you create an account via /account/create the user cannot accept payments.

Title: Wepay integration

Body:
I'm trying to create a simple checkout page with wepay and my checkout code (taken from the SDK sample) works great for the owner (me) when I'm signed in, but when logged in as a different user who hasn't created the account (under theirs?) it says the account is invalid or does not belong to the user.

So how are new logged in users supposed to pay to the account (mine), in other words make payments?

Here is the code for reference. The account_id doesn't work for new logged in users because they haven't created it.

$wepay = new WePay($_SESSION['wepay_access_token']);

$checkout = $wepay->request('checkout/create', array(
    'account_id' => 501999810,
    'amount' => 1.00,
    'currency'=> 'USD',
    'short_description'=> 'Selling 42 Pens',
    'type'=> 'goods'
));

Maybe I have something completely off, but that account_id is where I want to receive payments?

Any help would be appreciated!


问:
Loading SSIS Package Programmatically in C#
I'm loading a ssis package from my application which works fine.  However, what I'm trying to work out and failing miserably is that the package executes in 1 second (which is great) but the loading of the package takes 9 seconds.

Working locally in visual studio 2015 connecting remotely to a SQL Server 2014 instance.

The package is being loaded in a business object behind an async web api call from a console application.

Heres the code (standard stuff)...

```<code>Application application = new Application();
DTSExecResult result;
DTSPackageEventListener eventListener = new DTSPackageEventListener();

packageLocation = request.packageLocation;

//using (Package package = application.LoadPackage(packageLocation, eventListener)) // 9 seconds to load
using (Package package = application.LoadFromDtsServer(@"File System\<PACKAGENAME>", @"<SERVERNAME>", eventListener)) // 9 seconds to load
{
.
.
.
</code>```

Does anyone have any tips? Any help/guidance would be much appreciated.

Simon.

答: This is normal, dtsx file is an xml file and the DtsRuntime library need to deserialize the file to load it as dot net class. Also there are some validation that are done on package loading.</p>

Body:
I'm loading a ssis package from my application which works fine.  However, what I'm trying to work out and failing miserably is that the package executes in 1 second (which is great) but the loading of the package takes 9 seconds.

Working locally in visual studio 2015 connecting remotely to a SQL Server 2014 instance.

The package is being loaded in a business object behind an async web api call from a console application.

Heres the code (standard stuff)...

Application application = new Application();
DTSExecResult result;
DTSPackageEventListener eventListener = new DTSPackageEventListener();

packageLocation = request.packageLocation;

//using (Package package = application.LoadPackage(packageLocation, eventListener)) // 9 seconds to load
using (Package package = application.LoadFromDtsServer(@"File System\<PACKAGENAME>", @"<SERVERNAME>", eventListener)) // 9 seconds to load
{
.
.
.

Does anyone have any tips? Any help/guidance would be much appreciated.

Simon.


问:
In socket programming, why are the "client" and "server" reversed?
Why in socket programming does the "server" receive packets, and the "client" send them?

I'm taking a deep-dive into socket programming in both C/C++ and Nodejs; everywhere, in literature and examples alike, the "server" receives packets, while the "client" transmits them.

This does not make sense to me. Should not the "server" transmit packets, and the "client" receive them? Why is the naming convention this way?

EDIT: A couple examples.

1. Beej's Datagram Example for C/C++

http://beej.us/guide/bgnet/output/html/multipage/clientserver.html#datagram

2. A nodejs example:

https://www.hacksparrow.com/node-js-udp-server-and-client-example.html

答:
These terms are part of the client-server architecture model which runs across many different types of systems, according Wikipedia this dates from 1964...

Although servers and clients have capabilites to send/receive information a server has resources and computing capabilities to process information that a client don't.

A client is just a lightweight util which package and send information to a server in the way that server expects to receive information or to receive certain instructions, but a client do not require as much resources as a server does.

Examples of server-client relationships:

Puppet Server (Manages all rules, send information and order to clients, etc...)

Puppet Agent (Receives orders from Puppet Servers and is installed in several nodes and send information about statuses)

Web Servers (HTTP Apache or Ngnix i.e) (process requests/code to deliver HTML results)

Web Clients (wget, Chrome, Firefox, CURL, links) send requests to the Web Server to be processed.

Having that in mind check your own example the UDP Server is listening (waiting for information):

```<code>server.bind(PORT, HOST);
</code>```

and the UDP Client is the one with the function to "send" information:

```<code>client.send
</code>```

Which answer your own question:

Should not the "server" transmit packets, and the "client" receive
  them? Why is the naming convention this way?

Body:
These terms are part of the client-server architecture model which runs across many different types of systems, according Wikipedia this dates from 1964...

Although servers and clients have capabilites to send/receive information a server has resources and computing capabilities to process information that a client don't.

A client is just a lightweight util which package and send information to a server in the way that server expects to receive information or to receive certain instructions, but a client do not require as much resources as a server does.

Examples of server-client relationships:

Puppet Server (Manages all rules, send information and order to clients, etc...)

Puppet Agent (Receives orders from Puppet Servers and is installed in several nodes and send information about statuses)

Web Servers (HTTP Apache or Ngnix i.e) (process requests/code to deliver HTML results)

Web Clients (wget, Chrome, Firefox, CURL, links) send requests to the Web Server to be processed.

Having that in mind check your own example the UDP Server is listening (waiting for information):

server.bind(PORT, HOST);

and the UDP Client is the one with the function to "send" information:

client.send

Which answer your own question:

Should not the "server" transmit packets, and the "client" receive
  them? Why is the naming convention this way?


问:
C99: The existence of a strrpbrk (reverse strpbrk)
I am almost sure there is no reverse strpbrk() in C99. But:

Is there a reason for that? I mean, why does strchr() have strrchr() but strpbrk() doesn't hae strrpbrk()?

How do you get the last occurrence in a string of any of the characters in another string?

答:
Because int lastMatchIdx=strlen(haystack)-strpbrk(strrev(haystack),needles) is too easy to write? And has the same complexity (though somewhat less empirical performance)

for(char* h=haystack;(h=strpbrk(h,needles))!=NULL;rightMostMatch=h++); is similarly simple


问:
Parse JSON using Linux bash shell and Underscore
The code below doesn't do what I need it to. I want to pass $STR to Underscore and pluck out the "name" attribute from the JSON data.

```<code>#!/bin/bash
STR='['$@']';
RESULT=`underscore pluck --data '+$STR+' name`;
echo $RESULT;
</code>```

JSON Data:

```<code>{"maxResults":1,"resultList":[{"@class":"com.sohnar.trafficlite.transfer.crm.refactor.ClientCRMEntryTO","id":331458,"version":2,"dateCreated":"2017-05-31T13:20:22.960+0000","dateModified":"2017-06-05T14:23:59.961+0000","lastUpdatedUserId":71954,"name":"ACME_CLIENT","website":null,"description":null,"billingLocation":null,"primaryLocation":null,"crmEntryType":"CLIENT","industryType":null,"accountManagerId":103049,"crmClientClassificationListItemId":{"id":12405},"companyProfile":{"id":486024,"version":1,"dateCreated":"2017-05-31T13:20:22.960+0000","dateModified":"2017-06-05T14:23:59.962+0000","sourceOfBusinessListItemId":null,"creditTermsListItemId":{"id":4215},"relationshipSince":"2017-05-30T23:00:00.000+0000","turnover":0,"employees":0,"taxNumber":null,"companyNumber":null,"nominalCode":null,"accountPackageId":null,"optOutMarketing":false,"optOutEmail":false,"optOutTelephone":false,"notes":null},"colorCode":0,"externalCode":"SAP-01","clientState":"CLIENT","defaultCustomRateSetId":null,"preferredCurrencyId":{"id":48},"freeTags":[]}],"windowSize":5,"currentPage":1}
</code>```

答:
Several problems here.  First you should use double quotes, not single.   Double quotes allows the expansion of variable.  Second, I am assuming that you don't want the + as part of the data - they are not a string concatenation operator in bash (there is no need for one).

```<code>str="[$@]"
result=$(underscore pluck --data "$str" name)
echo $result
</code>```

I used the $( ) notation rather than back-ticks ( `` ). Back-ticks are considered deprecated and difficult to read.

I have replaced uppercase variable names with lower case. This is because there are many uppercase variable names used by the shell so using uppercase risks a name collision. Best to use lower or mixed-case variable names.

I have also removed the superfluous semi-colons ;.  They are not doing any harm, but they are of no use either.  In bash a semi-colon is a statement separator, whereas in languages like C and Java they are a statement terminator.

Edit:  double-quoted $@

Body:
The code below doesn't do what I need it to. I want to pass $STR to Underscore and pluck out the "name" attribute from the JSON data.

#!/bin/bash
STR='['$@']';
RESULT=`underscore pluck --data '+$STR+' name`;
echo $RESULT;

JSON Data:

{"maxResults":1,"resultList":[{"@class":"com.sohnar.trafficlite.transfer.crm.refactor.ClientCRMEntryTO","id":331458,"version":2,"dateCreated":"2017-05-31T13:20:22.960+0000","dateModified":"2017-06-05T14:23:59.961+0000","lastUpdatedUserId":71954,"name":"ACME_CLIENT","website":null,"description":null,"billingLocation":null,"primaryLocation":null,"crmEntryType":"CLIENT","industryType":null,"accountManagerId":103049,"crmClientClassificationListItemId":{"id":12405},"companyProfile":{"id":486024,"version":1,"dateCreated":"2017-05-31T13:20:22.960+0000","dateModified":"2017-06-05T14:23:59.962+0000","sourceOfBusinessListItemId":null,"creditTermsListItemId":{"id":4215},"relationshipSince":"2017-05-30T23:00:00.000+0000","turnover":0,"employees":0,"taxNumber":null,"companyNumber":null,"nominalCode":null,"accountPackageId":null,"optOutMarketing":false,"optOutEmail":false,"optOutTelephone":false,"notes":null},"colorCode":0,"externalCode":"SAP-01","clientState":"CLIENT","defaultCustomRateSetId":null,"preferredCurrencyId":{"id":48},"freeTags":[]}],"windowSize":5,"currentPage":1}

Body:
Several problems here.  First you should use double quotes, not single.   Double quotes allows the expansion of variable.  Second, I am assuming that you don't want the + as part of the data - they are not a string concatenation operator in bash (there is no need for one).

str="[$@]"
result=$(underscore pluck --data "$str" name)
echo $result

I used the $( ) notation rather than back-ticks ( `` ). Back-ticks are considered deprecated and difficult to read.

I have replaced uppercase variable names with lower case. This is because there are many uppercase variable names used by the shell so using uppercase risks a name collision. Best to use lower or mixed-case variable names.

I have also removed the superfluous semi-colons ;.  They are not doing any harm, but they are of no use either.  In bash a semi-colon is a statement separator, whereas in languages like C and Java they are a statement terminator.

Edit:  double-quoted $@


问:
Add a div to create padding
I have a span.  Inside it I have two divs.  One used as padding and a second with content.  If the content is multi-line it wraps around my padding div, which I want to prevent.

This jsfiddle shows what I currently have. https://jsfiddle.net/ju637z98/

```<code><span>
  <span style="width: 20px; display: inline-block;">

  </span>
  <span style="display: inline; " >
    This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.
  </span>
</span>
</code>```

If I change the content div to

```<code>display: inline-block
</code>```

the two divs end up being stacked on top of each other.

I'm trying to avoid styling the content div because the the padding div won't always be present so I'd like to avoid having two different styles to achieve what I need.

Any help would be appreciated.

Edit: updated the snipped above and the jsfiddle to use spans instead of divs.

答:
You can make the parent flex and use flex-basis on the first div to control that column width.

span {
  display: flex;
}
.padding {
  flex: 0 0 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span>
  <div class="padding">
  </div>
  <div>
    This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.
  </div>
</span></code>```

You could also float the padding div and use overflow: auto on the non-floating to contain the text.

.padding {
  float: left;
  width: 20px;
  height: 1em;
}
span div:nth-child(2) {
  overflow: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span>
  <div class="padding">
  </div>
  <div>
    This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.
  </div>
</span></code>```

Title: Add a div to create padding

Body:
I have a span.  Inside it I have two divs.  One used as padding and a second with content.  If the content is multi-line it wraps around my padding div, which I want to prevent.

This jsfiddle shows what I currently have. https://jsfiddle.net/ju637z98/

    This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.

If I change the content div to

display: inline-block

the two divs end up being stacked on top of each other.

I'm trying to avoid styling the content div because the the padding div won't always be present so I'd like to avoid having two different styles to achieve what I need.

Any help would be appreciated.

Edit: updated the snipped above and the jsfiddle to use spans instead of divs.

Body:
You can make the parent flex and use flex-basis on the first div to control that column width.

span {
  display: flex;
}
.padding {
  flex: 0 0 20px;
}

<span>
  <div class="padding">
  </div>
  <div>
    This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.
  </div>
</span>

You could also float the padding div and use overflow: auto on the non-floating to contain the text.

.padding {
  float: left;
  width: 20px;
  height: 1em;
}
span div:nth-child(2) {
  overflow: auto;
}

<span>
  <div class="padding">
  </div>
  <div>
    This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.This is a lot of text. This is a lot of text. This is a lot of text.
  </div>
</span>


问:
Java Scanners: How to keep the same line after an input
I have a small code segment that I do not know how to fix.  This is it:

```<code>System.out.print("y=");
while(!scan.hasNextInt()) scan.next();
m = scan.nextInt();
System.out.print("x+");
while(!scan.hasNextInt()) scan.next();
b = scan.nextInt();
</code>```

The output is: y=3 on one line, and x+4 on the next.  I would like them to be on the same line.  How do I do this?

答:
Looks like this is how your program looks:

```<code>y=3<newline>
x+5<newline>
</code>```

But you want it to look like:

```<code>y=3x+5
</code>```

The problematic newlines come from using the scanner and the inherently buffered nature of standard input. In order for the scanner to know that it's reached the end of the number, there has to be whitespace (space, newline, etc.) And in order for the program to receive the input from STDIN, the character length of the int has to be larger than the buffer size, or ENTER has to be pushed.

TL;DR - What you want is very difficult to do, and maybe impossible, just using basic standard in. If you really want the output you desire you'll probably need to find a library for interacting with the console and use that.

However, if you reframe your input, you might be able to get something almost as good:

```<code>enter intercept: 5<enter>
enter slope:     3<enter>
y=3x+5
</code>```

Your code, modified to produce that output:

```<code>System.out.print("enter intercept:");
while(!scan.hasNextInt()) scan.next();
m = scan.nextInt();
System.out.print("enter slope:    ");
while(!scan.hasNextInt()) scan.next();
b = scan.nextInt();
System.out.println("y="+m+"x+"+b);
</code>```

Body:
I have a small code segment that I do not know how to fix.  This is it:

System.out.print("y=");
while(!scan.hasNextInt()) scan.next();
m = scan.nextInt();
System.out.print("x+");
while(!scan.hasNextInt()) scan.next();
b = scan.nextInt();

The output is: y=3 on one line, and x+4 on the next.  I would like them to be on the same line.  How do I do this?

Body:
Looks like this is how your program looks:

y=3<newline>
x+5<newline>

But you want it to look like:

y=3x+5

The problematic newlines come from using the scanner and the inherently buffered nature of standard input. In order for the scanner to know that it's reached the end of the number, there has to be whitespace (space, newline, etc.) And in order for the program to receive the input from STDIN, the character length of the int has to be larger than the buffer size, or ENTER has to be pushed.

TL;DR - What you want is very difficult to do, and maybe impossible, just using basic standard in. If you really want the output you desire you'll probably need to find a library for interacting with the console and use that.

However, if you reframe your input, you might be able to get something almost as good:

enter intercept: 5<enter>
enter slope:     3<enter>
y=3x+5

Your code, modified to produce that output:

System.out.print("enter intercept:");
while(!scan.hasNextInt()) scan.next();
m = scan.nextInt();
System.out.print("enter slope:    ");
while(!scan.hasNextInt()) scan.next();
b = scan.nextInt();
System.out.println("y="+m+"x+"+b);


问:
In Linux, how do I know if an ACK is received to a certain TCP packet?
Long story short: in Linux, how do I ensure that an ACK message is received for a certain TCP packet?

Full story:

I'm debugging an Asterisk/OpenH323 <-> Panasonic IP-GW16 issue.

An H323 connection involves two sessions: H225.0 and H245. These are just two TCP sessions, over which some data are transmitted.

Let's call them Session 1 (for H225.0) and Session 2 (for H245).

Session 1 has well-known TCP port number of 1720, while port for Session 2 is chosen at runtime.

Control flow goes as follows:

Panasonic calls Asterisk: it opens Session 1 (TCP/1720) to Asterisk and sends a SETUP message over Session 1, which contains the port 2 that Panasonic will listen to.

Asterisk sends Panasonic a CALL PROCEEDING message over Session 1

Panasonic starts listening on the port 2

Panasonic sends a TCP ACK over Session 1.

Asterisk opens TCP Session 2 on port 2.

Order of steps 2 and 3 is important: Panasonic will not listen to port 2 unless it has received a CALL PROCEEDING message on step 2.

But in OpenH323 code, step 2 and step 5 are only several lines away.

That's why connection sometimes works in debug mode and quite never works in release.

It is clearly seen in a packet dump. I made a series of experiments, and in 52 cases out of 52, if step 5 goes before step 4, the connection fails; if not, the connection succeeds.

There are no other messages sent from Panasonic except that ACK in step 4, and it seems that the only way Asterisk may know that port 2 is listened to is receiving that ACK.

Of course I may implement a timed wait, but I want a cleaner solution.

So the question goes again: after sending a message over TCP connection in step 2, how do I know if an ACK is received to the packet containing the message?

答:
In this specific case, I'd say you would find that your tcp_info structure would hold a nonzero tcp_info.tcpi_unacked. You'd get this via getsockopt(TCP_INFO).

Note: unstable interface apparently.

OwnerDisplayName: Quassnoi

OwnerDisplayName: MSalters

LastEditorDisplayName: Quassnoi