问:
Rename files based on their created time + date
I've just started learning Python and trying to understand what's wrong with the code below.

For the test purpose there are 50 images that I want to rename as Hour.Minute.Second_Year_Month_Day.jpg. The code below executes, but I'm getting the current time and date as file name, not the creation date of the images.

What am I missing? I was reading that getctime is for Windows and for Mac birthtime, or I'm talking nonsense (Bringing this up since I'm on a Mac) ?

```<code>
directory = './'
extensions = (['.jpg', '.jpeg', '.png']);

filelist = os.listdir( directory )

newfilesDictionary = {}

count = 0

for file in filelist:
    filename, extension = os.path.splitext(file)
    if ( extension in extensions ):
        create_time = os.path.getctime( file )
        format_time = datetime.datetime.fromtimestamp( create_time )
        format_time_string = format_time.strftime("%H.%M.%S_%Y-%m-%d")
        newfile = format_time_string + extension;

        if ( newfile in newfilesDictionary.keys() ):
            index = newfilesDictionary[newfile] + 1;
            newfilesDictionary[newfile] = index;
            newfile = format_time_string + '-' + str(index) + extension;
        else:
            newfilesDictionary[newfile] = 0;

        os.rename( file, newfile );
        count = count + 1
        print( file.rjust(35) + '    =>    ' + newfile.ljust(35) )

print( 'All done. ' + str(count) + ' files are renamed. ')
</code>```

答:
RECTIFIED CODE:-

```<code>import os
import datetime

directory = r'Dir_path'
extensions = (['.jpg', '.jpeg', '.png']);

filelist = os.listdir( directory )

newfilesDictionary = {}

count = 0

for file in filelist:
    filename, extension = os.path.splitext(file)
    if ( extension in extensions ):
        create_time = os.path.getctime( os.path.join(directory, file) )
        format_time = datetime.datetime.fromtimestamp( create_time )
        format_time_string = format_time.strftime("%H.%M.%S_%Y-%m-%d")
        newfile = format_time_string + extension;

        if ( newfile in newfilesDictionary.keys() ):
            index = newfilesDictionary[newfile] + 1;
            newfilesDictionary[newfile] = index;
            newfile = format_time_string + '-' + str(index) + extension;
        else:
            newfilesDictionary[newfile] = 0;

        os.rename( os.path.join(directory, file), os.path.join(directory, newfile))
        count = count + 1
        print( file.rjust(35) + '    =>    ' + newfile.ljust(35) )

print( 'All done. ' + str(count) + ' files are renamed. ')
</code>```

Your code run's fine of Windows OS, just did a little improvement by adding os.path.join() to make it a lot more flexible while dealing with files. If you're on Mac, then try using os.stat(file).st_birthtime instead of os.path.getctime().

SUGGESTED IMPROVEMENTS:-

The Timestamp structure that you are using is not the best, as
Timestamps are generally made in descending order of time duration
i.e Year > Month > Day > Hour > Minutes > Seconds.  This timestamp
standard (ISO 8601) is commonly used.

Your should pass the extension of the file via lower() to make the
extension all lowercase. As you code won't be able to deal with Image
files with extension .JPG or .PNG.

Body:
I've just started learning Python and trying to understand what's wrong with the code below.

For the test purpose there are 50 images that I want to rename as Hour.Minute.Second_Year_Month_Day.jpg. The code below executes, but I'm getting the current time and date as file name, not the creation date of the images.

What am I missing? I was reading that getctime is for Windows and for Mac birthtime, or I'm talking nonsense (Bringing this up since I'm on a Mac) ?

directory = './'
extensions = (['.jpg', '.jpeg', '.png']);

filelist = os.listdir( directory )

newfilesDictionary = {}

count = 0

for file in filelist:
    filename, extension = os.path.splitext(file)
    if ( extension in extensions ):
        create_time = os.path.getctime( file )
        format_time = datetime.datetime.fromtimestamp( create_time )
        format_time_string = format_time.strftime("%H.%M.%S_%Y-%m-%d")
        newfile = format_time_string + extension;

        if ( newfile in newfilesDictionary.keys() ):
            index = newfilesDictionary[newfile] + 1;
            newfilesDictionary[newfile] = index;
            newfile = format_time_string + '-' + str(index) + extension;
        else:
            newfilesDictionary[newfile] = 0;

        os.rename( file, newfile );
        count = count + 1
        print( file.rjust(35) + '    =>    ' + newfile.ljust(35) )

print( 'All done. ' + str(count) + ' files are renamed. ')

Body:
RECTIFIED CODE:-

import os
import datetime

directory = r'Dir_path'
extensions = (['.jpg', '.jpeg', '.png']);

filelist = os.listdir( directory )

newfilesDictionary = {}

count = 0

for file in filelist:
    filename, extension = os.path.splitext(file)
    if ( extension in extensions ):
        create_time = os.path.getctime( os.path.join(directory, file) )
        format_time = datetime.datetime.fromtimestamp( create_time )
        format_time_string = format_time.strftime("%H.%M.%S_%Y-%m-%d")
        newfile = format_time_string + extension;

        if ( newfile in newfilesDictionary.keys() ):
            index = newfilesDictionary[newfile] + 1;
            newfilesDictionary[newfile] = index;
            newfile = format_time_string + '-' + str(index) + extension;
        else:
            newfilesDictionary[newfile] = 0;

        os.rename( os.path.join(directory, file), os.path.join(directory, newfile))
        count = count + 1
        print( file.rjust(35) + '    =>    ' + newfile.ljust(35) )

print( 'All done. ' + str(count) + ' files are renamed. ')

Your code run's fine of Windows OS, just did a little improvement by adding os.path.join() to make it a lot more flexible while dealing with files. If you're on Mac, then try using os.stat(file).st_birthtime instead of os.path.getctime().

SUGGESTED IMPROVEMENTS:-

The Timestamp structure that you are using is not the best, as
Timestamps are generally made in descending order of time duration
i.e Year > Month > Day > Hour > Minutes > Seconds.  This timestamp
standard (ISO 8601) is commonly used.

Your should pass the extension of the file via lower() to make the
extension all lowercase. As you code won't be able to deal with Image
files with extension .JPG or .PNG.


来源: stackexchange

问:
Why does the e.preventDefault function in javascript not work for the checkbox?
When writing the code I encountered a problem that I can not solve myself. Well, it did not work for me if (checkbox.checked == false), but if (checkbox.checked == true) works, even though the checkbox is not selected.
I checked it on Opera and Edge. Is this a common problem? Is there any way to get around this?

JSFiddle: [https://jsfiddle.net/mk5j6170/)

答:
You have an spelling-error in your code: querySelecotr should be querySelector.
You can also use getElementById to get an element by its id-property.

Both versions work in the browsers i tested (Firefox, Chrome, Safari).

If you use preventDefault(), the checked-state will be restored after the event-handler is completed. So any change inside that event-handler will be reverted. A workaround would be to toggle the state with inside an setTimeout-call (see checkbox3-example below).

let idCheckbox = document.getElementById("checkbox");
idCheckbox.addEventListener("click", function(e) {
  e.preventDefault();
});

let idCheckbox2 = document.querySelector("#checkbox2");
idCheckbox2.addEventListener("click", function (e) {
  e.preventDefault();
});

let idCheckbox3 = document.querySelector("#checkbox3");
idCheckbox3.addEventListener("click", function (e) {
  e.preventDefault();
  setTimeout(() => {
    if (idCheckbox3.checked == false) {
      idCheckbox3.checked = true;
    } else {
      idCheckbox3.checked = false;
    }
  }, 50);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="checkbox" name="checkbox" type="checkbox"/>
<label class="sub-label" for="checkbox">Accept checkbox 1</label>
<br>
<input id="checkbox2" name="checkbox2" type="checkbox"/>
<label class="sub-label" for="checkbox2">Accept checkbox 2</label>
<br>
<input id="checkbox3" name="checkbox3" type="checkbox"/>
<label class="sub-label" for="checkbox3">Accept checkbox 3</label>
<br></code>```

ContentLicense: CC BY-SA 4.0

Body:
You have an spelling-error in your code: querySelecotr should be querySelector.
You can also use getElementById to get an element by its id-property.

Both versions work in the browsers i tested (Firefox, Chrome, Safari).

If you use preventDefault(), the checked-state will be restored after the event-handler is completed. So any change inside that event-handler will be reverted. A workaround would be to toggle the state with inside an setTimeout-call (see checkbox3-example below).

let idCheckbox = document.getElementById("checkbox");
idCheckbox.addEventListener("click", function(e) {
  e.preventDefault();
});

let idCheckbox2 = document.querySelector("#checkbox2");
idCheckbox2.addEventListener("click", function (e) {
  e.preventDefault();
});

let idCheckbox3 = document.querySelector("#checkbox3");
idCheckbox3.addEventListener("click", function (e) {
  e.preventDefault();
  setTimeout(() => {
    if (idCheckbox3.checked == false) {
      idCheckbox3.checked = true;
    } else {
      idCheckbox3.checked = false;
    }
  }, 50);
});

<input id="checkbox" name="checkbox" type="checkbox"/>
<label class="sub-label" for="checkbox">Accept checkbox 1</label>
<br>
<input id="checkbox2" name="checkbox2" type="checkbox"/>
<label class="sub-label" for="checkbox2">Accept checkbox 2</label>
<br>
<input id="checkbox3" name="checkbox3" type="checkbox"/>
<label class="sub-label" for="checkbox3">Accept checkbox 3</label>
<br>


问:
how to turn a list of strings in a list of objects?
I have a list of strings from an external text file. Each string is like this: name job location. What is the fastest way to turn each string into an object, creating a list of objects?

The objects are like this:

class Person:
    def __init__(self, name, job, location):
        self.name = name
        self.job = job
        self.location = location
```

答:
I think "people" is a bad name for this class. Typically, standard naming convention says classes should start with a capital letter. Also, a single instance of this class represents one person, not several people. I think a better name for this class is "Person".

Assuming you have a text file (data.txt) which looks like this:

```<code>Bob Teacher Alabama
Frasier Psychiatrist Seattle
</code>```

And the code:

```<code>class Person:

    def __init__(self, name, job, location):
        self.name = name
        self.job = job
        self.location = location

    def get_info(self):
        return f"My name is {self.name}, and I'm a {self.job} in {self.location}."

def main():

    people = []

    filename = "data.txt"
    with open(filename, "r") as file:
        for line in file:
            person = Person(*line.split())
            people.append(person)

    for person in people:
        print(person.get_info())

    return 0

if __name__ == "__main__":
    from sys import exit
    exit(main())
</code>```

The output:

```<code>My name is Bob, and I'm a Teacher in Alabama.
My name is Frasier, and I'm a Psychiatrist in Seattle.
</code>```

Body:
I think "people" is a bad name for this class. Typically, standard naming convention says classes should start with a capital letter. Also, a single instance of this class represents one person, not several people. I think a better name for this class is "Person".

Assuming you have a text file (data.txt) which looks like this:

Bob Teacher Alabama
Frasier Psychiatrist Seattle

And the code:

class Person:

    def __init__(self, name, job, location):
        self.name = name
        self.job = job
        self.location = location

    def get_info(self):
        return f"My name is {self.name}, and I'm a {self.job} in {self.location}."

def main():

    people = []

    filename = "data.txt"
    with open(filename, "r") as file:
        for line in file:
            person = Person(*line.split())
            people.append(person)

    for person in people:
        print(person.get_info())

    return 0

if __name__ == "__main__":
    from sys import exit
    exit(main())

The output:

My name is Bob, and I'm a Teacher in Alabama.
My name is Frasier, and I'm a Psychiatrist in Seattle.


问:
How efficiently we can get the required output from the list in java?
```<code>CircuitID   Department  Hours

--------------------------------

Circuit A   Electricity      60

Circuit A   Hydel            70

Circuit B   Hydel            30

Circuit C   Electricity      40

Circuit B   Electricity      80

Circuit C   Hydel            50

Circuit A   Electricity      70
</code>```

Now i have to create one list which will have records on following criteria:

In each circuit id i need to get the record with highest hours but if duplicate hours are present than i need to take the one with Electricity department.

Result for the above result should be like below:

```<code>Circuit A  Electricity   70

Circuit B  Electricity   80

Circuit C  Hydel          50
</code>```

Let me know how can i iterate effectively and in most efficient way to get the final list using java 8/ java.

The code i wrote is not at all working perfectly and my approch was shown below:

```<code>for (int i = 0; i < circuitList.size(); i++) {

  for (int j = 0; j < circuitList.size(); {
    if (circuitList.get(i).getCircuitId().equals(circuitList.get(j).getCircuitId()) && i != j) {

     if (circuitList().get(i).getHours() == circuitList().get(j).getHours()) {

      if (circuitList().get(i).getDepartment().equals(“Electricity”) {

        newList.add(circuitList().get(i));

        }

        // some more conditions on getHours
</code>```

Circuit class is having pojo objects with getter setters of this three objects.

```<code> public class Circuit {

        String circuitID;
        int hours;
        String department;
}
</code>```

答:
You can do it by toMap() collectors with merge function.

```<code>Map<String, Circuit> map = circuitList
             .stream()
             .collect(Collectors.toMap(Circuit::getCircuitID, Function.identity(),merge));
</code>```

and merge function is:

```<code>BinaryOperator<Circuit> merge = (left, right) -> {
        if (left.hours > right.hours) return left;
        else if (left.hours < right.hours) return right;
        //if (left.department.equals("Electricity")) return left;
        if (right.department.equals("Electricity")) return right;
        return left;
};
</code>```

and get final result:

```<code>List<Circuit> result = new ArrayList<>(map.values());
</code>```

Body:
CircuitID   Department  Hours

--------------------------------

Circuit A   Electricity      60

Circuit A   Hydel            70

Circuit B   Hydel            30

Circuit C   Electricity      40

Circuit B   Electricity      80

Circuit C   Hydel            50

Circuit A   Electricity      70

Now i have to create one list which will have records on following criteria:

In each circuit id i need to get the record with highest hours but if duplicate hours are present than i need to take the one with Electricity department.

Result for the above result should be like below:

Circuit A  Electricity   70

Circuit B  Electricity   80

Circuit C  Hydel          50

Let me know how can i iterate effectively and in most efficient way to get the final list using java 8/ java.

The code i wrote is not at all working perfectly and my approch was shown below:

for (int i = 0; i < circuitList.size(); i++) {

  for (int j = 0; j < circuitList.size(); {
    if (circuitList.get(i).getCircuitId().equals(circuitList.get(j).getCircuitId()) && i != j) {

     if (circuitList().get(i).getHours() == circuitList().get(j).getHours()) {

      if (circuitList().get(i).getDepartment().equals(“Electricity”) {

        newList.add(circuitList().get(i));

        }

        // some more conditions on getHours

Circuit class is having pojo objects with getter setters of this three objects.

 public class Circuit {

        String circuitID;
        int hours;
        String department;
}

Body:
You can do it by toMap() collectors with merge function.

Map<String, Circuit> map = circuitList
             .stream()
             .collect(Collectors.toMap(Circuit::getCircuitID, Function.identity(),merge));

and merge function is:

BinaryOperator<Circuit> merge = (left, right) -> {
        if (left.hours > right.hours) return left;
        else if (left.hours < right.hours) return right;
        //if (left.department.equals("Electricity")) return left;
        if (right.department.equals("Electricity")) return right;
        return left;
};

and get final result:

List<Circuit> result = new ArrayList<>(map.values());


问:
Violation Long running JavaScript task took xx ms
Recently, I got this kind of warning, and this is my first time getting it:

[Violation] Long running JavaScript task took 234ms
[Violation] Forced reflow while executing JavaScript took 45ms
```
</blockquote>

<p>I'm working on a group project and I have no idea where this is coming from. This never happened before. Suddenly, it appeared when someone else got involved in the project. How do I find what file/function causes this warning? I've been looking for the answer, but mostly about the solution on how to solve it. I can't solve it if I can't even find the source of the problem.</p>

<p>In this case, the warning appears only on Chrome. I tried to use Edge, but I didn't get any similar warnings, and I haven't tested it on Firefox yet.</p>

<p>I even get the error from <code>jquery.min.js</code>:</p>

<blockquote>
  <pre class="lang-none prettyprint-override"><code>[Violation] Handler took 231ms of runtime (50ms allowed)            jquery.min.js:2
</code>```

答:
This is not an error just simple a message. To execute this message change

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> (example)

to

<!DOCTYPE html>(the Firefox source expect this)

The message was shown in Google Chrome 74 and Opera 60 . After changing it was clear, 0 verbose.

A solution approach

Body:
Recently, I got this kind of warning, and this is my first time getting it:

[Violation] Long running JavaScript task took 234ms
[Violation] Forced reflow while executing JavaScript took 45ms

I'm working on a group project and I have no idea where this is coming from. This never happened before. Suddenly, it appeared when someone else got involved in the project. How do I find what file/function causes this warning? I've been looking for the answer, but mostly about the solution on how to solve it. I can't solve it if I can't even find the source of the problem.

In this case, the warning appears only on Chrome. I tried to use Edge, but I didn't get any similar warnings, and I haven't tested it on Firefox yet.

I even get the error from jquery.min.js:

[Violation] Handler took 231ms of runtime (50ms allowed)            jquery.min.js:2


问:
How to fix TypeError: can only concatenate str (not "list") to str
I am trying to learn python from the python crash course but this one task has stumped me and I can’t find an answer to it anywhere

The task is
Think of your favourite mode of transportation and make a list that stores several examples
Use your list to print a series of statements about these items

```<code>cars = ['rav4'], ['td5'], ['yaris'], ['land rover tdi']

print("I like the "+cars[0]+" ...")
</code>```

I’m assuming that this is because I have letters and numbers together, but I don’t know how to produce a result without an error and help would be gratefully received
The error I get is

TypeError: can only concatenate str (not "list") to str**

答:
Your first line actually produces a tuple of lists, hence cars[0] is a list.

If you print cars you'll see that it looks like this:

```<code>(['rav4'], ['td5'], ['yaris'], ['land rover tdi'])
</code>```

Get rid of all the square brackets in between and you'll have a single list that you can index into.

Body:
I am trying to learn python from the python crash course but this one task has stumped me and I can’t find an answer to it anywhere

The task is
Think of your favourite mode of transportation and make a list that stores several examples
Use your list to print a series of statements about these items

cars = ['rav4'], ['td5'], ['yaris'], ['land rover tdi']

print("I like the "+cars[0]+" ...")

I’m assuming that this is because I have letters and numbers together, but I don’t know how to produce a result without an error and help would be gratefully received
The error I get is

TypeError: can only concatenate str (not "list") to str**

Body:
Your first line actually produces a tuple of lists, hence cars[0] is a list.

If you print cars you'll see that it looks like this:

(['rav4'], ['td5'], ['yaris'], ['land rover tdi'])

Get rid of all the square brackets in between and you'll have a single list that you can index into.


问:
How to clear sfdx cache (if such thing exists)
When I apply:

```<code>sfdx force:source:push -f
</code>```

(Sorry, orginally posted wrong command)
The deployment fails because the compiler throws errors regarding files that are no longer part of my local filesystem.

I cleared following files:

metadataTypeInfos.json

sourcePathInfos.json

To no avail.

Is there some cache anywhere that I need to clear?

答:
I think something has gone wrong with the diffing mechanism.
Deleting files / folders and meanwhile clearing sourcePathInfos.json.

Anyhow, I deleted the import to the file that was no longer needed and the problem went away with it.

It doesn't really solve the problem as sfdx still thinks that the folder exists (the logs show unresolved imports in files that no longer exist) but I don't really care about it a I'm working scratch org).

It can just be fixed by creating a new scratch org too:

```<code>sfdx force:org:create -f config/project-scratch-def.json -a <scratch-name> -s
</code>```

Body:
When I apply:

sfdx force:source:push -f

(Sorry, orginally posted wrong command)
The deployment fails because the compiler throws errors regarding files that are no longer part of my local filesystem.

I cleared following files:

metadataTypeInfos.json

sourcePathInfos.json

To no avail.

Is there some cache anywhere that I need to clear?

Body:
I think something has gone wrong with the diffing mechanism.
Deleting files / folders and meanwhile clearing sourcePathInfos.json.

Anyhow, I deleted the import to the file that was no longer needed and the problem went away with it.

It doesn't really solve the problem as sfdx still thinks that the folder exists (the logs show unresolved imports in files that no longer exist) but I don't really care about it a I'm working scratch org).

It can just be fixed by creating a new scratch org too:

sfdx force:org:create -f config/project-scratch-def.json -a <scratch-name> -s


问:
How to repeatedly perform glm over multiple dependent variables after mice?
I have a data frame, nrow=4312, ncol=105, with which I performed multiple imputations using mice:

```<code>imp <- mice(data, m=20, maxit=10, method=meth, predictorMatrix=pred2, visitSequence=vis)
</code>```

Now, I need to perform multiple logistic regressions repeatedly and separately with 40 different dependent variables and extract particular values into different data frame. The example for one such regression and value extraction being:

```<code>fit.HDP <- with(imp, glm(HDP ~ P0 + BMI + WtChange + MATAGE, family=binomial, subset=(P1==1)))
est.HDP <- pool(fit.HDP)
HDP <- summary(est.HDP)

HDP.OR <- exp(HDP[2,1])
HDP.95CI <- exp(HDP[2,c(6,7)])
HDP.pvalue <- HDP[2,5]
</code>```

How can I do this faster than writing this out 40 times over for each variable?

Is it possible to do it using a for loop?

Thank you for all help!

答:
Update with purrr package, included in the tidyverse

You can now write the correct answer by @Prolix with purrr:map, which makes it a little more intuitive to read, like this:

```<code>library(tidyverse)

independent.variables.formula <- "~ P0 + BMI + WtChange + MATAGE"
dependent.variables <- c("HDP", "DV2", "DV3")

models.list <- map(dependent.variables, function(DV) {

  paste(DV, independent.variables.formula) %>%
    as.formula %>%
    lm(family=binomial, subset=(P1==1))
})
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a data frame, nrow=4312, ncol=105, with which I performed multiple imputations using mice:

imp <- mice(data, m=20, maxit=10, method=meth, predictorMatrix=pred2, visitSequence=vis)

Now, I need to perform multiple logistic regressions repeatedly and separately with 40 different dependent variables and extract particular values into different data frame. The example for one such regression and value extraction being:

fit.HDP <- with(imp, glm(HDP ~ P0 + BMI + WtChange + MATAGE, family=binomial, subset=(P1==1)))
est.HDP <- pool(fit.HDP)
HDP <- summary(est.HDP)

HDP.OR <- exp(HDP[2,1])
HDP.95CI <- exp(HDP[2,c(6,7)])
HDP.pvalue <- HDP[2,5]

How can I do this faster than writing this out 40 times over for each variable?

Is it possible to do it using a for loop?

Thank you for all help!

Body:
Update with purrr package, included in the tidyverse

You can now write the correct answer by @Prolix with purrr:map, which makes it a little more intuitive to read, like this:

library(tidyverse)

independent.variables.formula <- "~ P0 + BMI + WtChange + MATAGE"
dependent.variables <- c("HDP", "DV2", "DV3")

models.list <- map(dependent.variables, function(DV) {

  paste(DV, independent.variables.formula) %>%
    as.formula %>%
    lm(family=binomial, subset=(P1==1))
})


问:
Regex splitting strings on a character, not contained in ()
I'm trying to split a string on a , where that character is not contained in ().

Example String:

```<code>`table1`.`lname`,`table1`.`fname`,if(foo is not null,foo,if(bar is not null,bar,table3.baz)),`table3`.`shu`
</code>```

I want to split it into an array looking like

```<code>(
  0=>`table1`.`lname`
  1=>`table1`.`fname`
  2=>if(foo is not null,foo,if(bar is not null,bar,table3.baz))
  3=>`table3`.`shu`
)
</code>```

Any ideas on how to tackle this problem?

--
Dave

答:
If you know that you are only going to receive one pair of parenthesis, then this might work:

```<code>/(([^,]*\(.*\))|[^,]*)/g
</code>```

Just remember that this will fail if you have a ) somewhere miscellaneous or if you have more than one set of parenthesis that need to be parsed out.

OwnerDisplayName: david walker

LastEditorDisplayName: Lawrence Johnston

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to split a string on a , where that character is not contained in ().

Example String:

`table1`.`lname`,`table1`.`fname`,if(foo is not null,foo,if(bar is not null,bar,table3.baz)),`table3`.`shu`

I want to split it into an array looking like

(
  0=>`table1`.`lname`
  1=>`table1`.`fname`
  2=>if(foo is not null,foo,if(bar is not null,bar,table3.baz))
  3=>`table3`.`shu`
)

Any ideas on how to tackle this problem?

--
Dave

Body:
If you know that you are only going to receive one pair of parenthesis, then this might work:

/(([^,]*\(.*\))|[^,]*)/g

Just remember that this will fail if you have a ) somewhere miscellaneous or if you have more than one set of parenthesis that need to be parsed out.


问:
I am entering birthdate inside edittext using datepicker. How to catch this?

Possible Duplicate:

  getDate with Jquery Datepicker

I have a registration page inside that I have birthdate box.
I am entering birthdate inside edittext using datepicker. How to catch this and put into web server. Do I need to parse to get integer ?

答:
you can try the following, whereby you can get the various components (day, month and year) as integers</p>

```<code>final DatePicker datePick = (DatePicker) findViewById(R.id.proposeDate);

int day = datePick.getDayOfMonth();
int month = datePick.getMonth();
int year = datePick.getYear();
</code>```

Body:
you can try the following, whereby you can get the various components (day, month and year) as integers

final DatePicker datePick = (DatePicker) findViewById(R.id.proposeDate);

int day = datePick.getDayOfMonth();
int month = datePick.getMonth();
int year = datePick.getYear();


问:
Javascript: Sort object array by number properties which include undefined
I can define an array of numbers and sort them like this

var array = ['2', undefined, '1'];
array.sort((a, b) => a - b);
console.log(array);```
</div>
</div>
</p>

<p>The output is <code>1, 2, null</code>.</p>

<p>I have an array of objects that can include a number property, which I can define like this. Not all objects have the number property. Now I want to sort this array of objects by the number property. So I tried this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var array = [
  { number: 2 },
  {},
  { number: 1 }
];
array.sort((a, b) => a.number - b.number);
console.log(array);</code>```

The output is not what I want. I get 2, undefined, 1.

If all objects in the array have the number property defined, the same sort function produces 1, 2, which is the result I would expect.

var array = [
  { number: 2 },
  { number: 1 }
];
array.sort((a, b) => a.number - b.number);
console.log(array);```

So my question is, what is the best way to sort an array of objects by a property, where the property is not always defined. The intended result is that the objects are ordered by the property (number), with objects that do not define that property at the end of the array.

My only solution so far is to iterate the set, and if the property is not defined, set the property to 0 or null. I can then pass the object array to the sort function and it works as I want. Is there a better way than this?

Jfiddle: https://jsfiddle.net/t2r6z13e/1/

答:
A bit unreadable :

var array = [ { number: 2 }, { }, { number: 1 } ];

array.sort((a, b) => 'number' in a ? 'number' in b ? a.number - b.number : -1 : 1);

console.log(array);```
</div>
</div>
</p>

<p>Or maybe a bit more readable :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var array = [ { number: 2 }, { }, { number: 1 } ];

array.sort((a, b) => !('number' in a) ? 1 : !('number' in b) ? -1 : a.number - b.number);

console.log(array);</code>```

Body:
I can define an array of numbers and sort them like this

var array = ['2', undefined, '1'];
array.sort((a, b) => a - b);
console.log(array);

The output is 1, 2, null.

I have an array of objects that can include a number property, which I can define like this. Not all objects have the number property. Now I want to sort this array of objects by the number property. So I tried this:

var array = [
  { number: 2 },
  {},
  { number: 1 }
];
array.sort((a, b) => a.number - b.number);
console.log(array);

The output is not what I want. I get 2, undefined, 1.

If all objects in the array have the number property defined, the same sort function produces 1, 2, which is the result I would expect.

var array = [
  { number: 2 },
  { number: 1 }
];
array.sort((a, b) => a.number - b.number);
console.log(array);

So my question is, what is the best way to sort an array of objects by a property, where the property is not always defined. The intended result is that the objects are ordered by the property (number), with objects that do not define that property at the end of the array.

My only solution so far is to iterate the set, and if the property is not defined, set the property to 0 or null. I can then pass the object array to the sort function and it works as I want. Is there a better way than this?

Jfiddle: https://jsfiddle.net/t2r6z13e/1/

Body:
A bit unreadable :

var array = [ { number: 2 }, { }, { number: 1 } ];

array.sort((a, b) => 'number' in a ? 'number' in b ? a.number - b.number : -1 : 1);

console.log(array);

Or maybe a bit more readable :

var array = [ { number: 2 }, { }, { number: 1 } ];

array.sort((a, b) => !('number' in a) ? 1 : !('number' in b) ? -1 : a.number - b.number);

console.log(array);


问:
Choose the valid methods for navigating to a fragment identifier
What are the valid methods for navigating to a fragment identifier ? What are the detail of fragment identifier and their use in HTML5. Could anybody explain in brief.</p>

答:
So basically you have all you need to know about fragment identifiers here but in short, the way you want to navigate to a fragment identifier is as follows:</p>

```<code><a href="#E2">Go to episode 2</a>
.
.
.
<div id="E2"> ...... </div>
</code>```

Body:
So basically you have all you need to know about fragment identifiers here but in short, the way you want to navigate to a fragment identifier is as follows:

<a href="#E2">Go to episode 2</a>
.
.
.
<div id="E2"> ...... </div>


答:
You can provide defaults for array elements with object spreads: {default, ...item}

var array = [
  { number: 2 },
  {},
  { number: 1 },
  {},
  { number: 0 },
];

array.sort((a, b) => (
    {number: Number.MAX_VALUE, ...a}.number -
    {number: Number.MAX_VALUE, ...b}.number));

console.log(array);```

If your target doesn't support object spreads yet, replace them with Object.assign.

Title: Javascript: Sort object array by number properties which include undefined

Body:
You can provide defaults for array elements with object spreads: {default, ...item}

var array = [
  { number: 2 },
  {},
  { number: 1 },
  {},
  { number: 0 },
];

array.sort((a, b) => (
    {number: Number.MAX_VALUE, ...a}.number -
    {number: Number.MAX_VALUE, ...b}.number));

console.log(array);

If your target doesn't support object spreads yet, replace them with Object.assign.


问:
Reduce sum of digits recursively down to one digit number
How do I make a function return the sum of all digits until it becomes a 1 digit number, using recursion?  I was able to make a function that gets the sum of all digits, but cant seem to find a way to recursively sum the digits of the sum itself:

```<code>class sum_of_digits
{

    static int sum_of_digit(int n)
    {
        if (n == 0)
            return 0;
        return (n % 10 + sum_of_digit(n / 10));
    }

    public static void main(String args[])
    {
        int num = 12345;
        int result = sum_of_digit(num);
        System.out.println("Sum of digits in " +
                           num + " is " + result);
    }
}
</code>```

This code prints the sum of '12345', which is 15. But I need to change it so it prints the sum of 1 + 5, which is 6.

答:
Things will become a lot easier if you define an additional recursive "layer" in conjunction with sum_of_digit. This new function can call sum_of_digit until it has a single digit as a result. Here is what I mean:

```<code>static int sum_to_one_digit(int n) {
    if(n/10 == 0) return n;
    return sum_to_one_digit(sum_of_digit(n));
}
</code>```

The code from main will be:

```<code>public static void main(String args[])
{
    int num = 12345;
    int result = sum_to_one_digit(num);
    System.out.println("Sum of digits in " +
                   num + " is " + result);
}
</code>```

Body:
How do I make a function return the sum of all digits until it becomes a 1 digit number, using recursion?  I was able to make a function that gets the sum of all digits, but cant seem to find a way to recursively sum the digits of the sum itself:

class sum_of_digits
{

    static int sum_of_digit(int n)
    {
        if (n == 0)
            return 0;
        return (n % 10 + sum_of_digit(n / 10));
    }

    public static void main(String args[])
    {
        int num = 12345;
        int result = sum_of_digit(num);
        System.out.println("Sum of digits in " +
                           num + " is " + result);
    }
}

This code prints the sum of '12345', which is 15. But I need to change it so it prints the sum of 1 + 5, which is 6.

Body:
Things will become a lot easier if you define an additional recursive "layer" in conjunction with sum_of_digit. This new function can call sum_of_digit until it has a single digit as a result. Here is what I mean:

static int sum_to_one_digit(int n) {
    if(n/10 == 0) return n;
    return sum_to_one_digit(sum_of_digit(n));
}

The code from main will be:

public static void main(String args[])
{
    int num = 12345;
    int result = sum_to_one_digit(num);
    System.out.println("Sum of digits in " +
                   num + " is " + result);
}


问:
Kivy and Google Play 64-bit
As you may know, from August 1, 2019 all Android-releases must be compliant with the Google Play 64-bit requirement.
Will Kivy + Buildozer allow us to create such apps?

Thank you in advance!

答:
Buildozer already allows you to create such apps, just change the android.arch configuration token in buildozer.spec to arm64-v8a instead of the default armeabi-v7a.

We don't support APKs with multiple architectures bundled together, mostly because this would significantly increase their size due to all the compiled components, but you can upload one APK of each type to Google Play.

We'll probably update the defaults and provide more documentation about it within the next few months.

Title: Kivy and Google Play 64-bit


问:
What's the difference between activity and intent in Android?
Can anyone explain to me the difference between an "Activity" and an "Intent" on the Android platform?</p>

答:
Though there are many good explanations here, I would like to give my own view with respect to Activity and Intent. Activity is a UI component which you see on your screen. An Intent is a message object which is used to request an action from the same/different app component.

Reference : Intent, Activity


问:
nginx perl set variables
Having this nginx rule:

```<code>  location ~ /test/ {
    set $color '?';
    set $subpath $1;
    perl test::handle;
    add_header Content-Type "text/html";
    return 200 $color;
  }
</code>```

and this perl file:

```<code>package test;

use nginx;
sub handle {
    my $r = shift;
    $r->variable('color', 'blue');
    return OK;
}

1;
__END__
</code>```

I would expect nginx to serve the string blue

but ? is served instead.

I tested a sub handle like this: (modifying properly the rule commenting the return)

```<code>sub handle {
    my $r = shift;
    $r->send_http_header;
    $r->print($r->variable('color'),'<br/>');
    $r->variable('color', 'blue');
    $r->print($r->variable('color'),'<br/>');
    $r->flush();
    return OK;
}
</code>```

and i get expected result :

```<code>?
blue
</code>```

in first case does nginx serves $color before having it being set by perl ?
How to avoid this?

To clarify:

I need to set a bunch of variables in perl script, depending on request, i could trigger one perl_set for each variable i need to set, but i would like to integrate all in one function.

[EDIT]

it's actually illegal to use perl_set directive inside location block, so, perl_set is not on per-request basis.

答:
I know that this answer is very over due. but i have experimented with it now.

you were wrong on this :

it's actually illegal to use perl_set directive inside location block, so, perl_set is not on per-request basis.

actually even if you should include perl_set in http block of config file the code will be re-evaluated on every request. so if you include below config in you http block $color will be blue;

```<code>perl_set $color '
    sub {
        my $r = shift;
        return \'blue\';
    }
';
</code>```

but remember perl_set in http block will be eveluated before location block so if you include set $color '?'; in your location block variable will always have ? value.

Title: nginx perl set variables

Body:
Having this nginx rule:

  location ~ /test/ {
    set $color '?';
    set $subpath $1;
    perl test::handle;
    add_header Content-Type "text/html";
    return 200 $color;
  }

and this perl file:

package test;

use nginx;
sub handle {
    my $r = shift;
    $r->variable('color', 'blue');
    return OK;
}

1;
__END__

I would expect nginx to serve the string blue

but ? is served instead.

I tested a sub handle like this: (modifying properly the rule commenting the return)

sub handle {
    my $r = shift;
    $r->send_http_header;
    $r->print($r->variable('color'),'
');
    $r->variable('color', 'blue');
    $r->print($r->variable('color'),'
');
    $r->flush();
    return OK;
}

and i get expected result :

?
blue

in first case does nginx serves $color before having it being set by perl ?
How to avoid this?

To clarify:

I need to set a bunch of variables in perl script, depending on request, i could trigger one perl_set for each variable i need to set, but i would like to integrate all in one function.

[EDIT]

it's actually illegal to use perl_set directive inside location block, so, perl_set is not on per-request basis.

Body:
I know that this answer is very over due. but i have experimented with it now.

you were wrong on this :

it's actually illegal to use perl_set directive inside location block, so, perl_set is not on per-request basis.

actually even if you should include perl_set in http block of config file the code will be re-evaluated on every request. so if you include below config in you http block $color will be blue;

perl_set $color '
    sub {
        my $r = shift;
        return \'blue\';
    }
';

but remember perl_set in http block will be eveluated before location block so if you include set $color '?'; in your location block variable will always have ? value.


问:
How do I access a php file from another domain
Say I got 3 websites. Every time I do an action on site (1), I need to access file.php from (2) and (3) with the parameter of the site the action has been done ( (1) in this case ), so, for this example, I need to access:

```<code>(2).com/file.php?site=1
(3).com/file.php?site=1
</code>```

The same applies if the action is done from the website (2) and (3).

What is the best way to approach this? ( I don't want to manually access the file from my browser every time said action happens on the website (x) )

I tried doing a simple:

```<code><form method="get" action="(2).com/file.php?site=1"> </form>
<form method="get" action="(3).com/file.php?site=1"> </form>
</code>```

It doesn't work.

I tried doing some kind of ajax/XMLHttpRequest and also tried using the "file" PHP function.

So, my question is, how do I approach this? What is the best way to "virtually" open a browser, and load a PHP file?

答:
You can use PHP files from other domains normally (to handle requests, echo results etc.), but you need to add the following headers to the PHP files on your other domains. This is needed for ajax or xmlhttprequests.</p>

```<code>header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
</code>```

Body:
Say I got 3 websites. Every time I do an action on site (1), I need to access file.php from (2) and (3) with the parameter of the site the action has been done ( (1) in this case ), so, for this example, I need to access:

(2).com/file.php?site=1
(3).com/file.php?site=1

The same applies if the action is done from the website (2) and (3).

What is the best way to approach this? ( I don't want to manually access the file from my browser every time said action happens on the website (x) )

I tried doing a simple:

<form method="get" action="(2).com/file.php?site=1"> </form>
<form method="get" action="(3).com/file.php?site=1"> </form>

It doesn't work.

I tried doing some kind of ajax/XMLHttpRequest and also tried using the "file" PHP function.

So, my question is, how do I approach this? What is the best way to "virtually" open a browser, and load a PHP file?

Body:
You can use PHP files from other domains normally (to handle requests, echo results etc.), but you need to add the following headers to the PHP files on your other domains. This is needed for ajax or xmlhttprequests.

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");


问:
How can I manually trigger a pull from Mercurial in a Jenkins/Hudson job?
I've set up a job in Jenkins that polls my Mercurial repository, using the Mercurial plugin. This works well once I push to the repository. I can trigger a build of the job manually, but I can't trigger the hg pull/update that happens as part of the poll, which means I have to wait up to 60 seconds for the build to start with my new changes. Sometimes I'm pushing changes that I know will affect and possibly break the system build and want faster feedback. What's the best way to pull/update before a manual build?</p>

答: It seems that I am wrong. I must have missed something in the log when I was initially testing this, or maybe I hit the manual build link before the push went through to the server. Jenkins seems to perform a hg incoming then hg unbundle then hg update at the start of each build, even when the build is triggered manually, which is exactly what I wanted.


问:
Exact replacing a string (a sentence or a word) in a long file
I would like to replace sentences by a code in a large file.
I've tried to use str_replace, but because in the file there some of the same words of the sentence, my code replaces them and doesn't recognize the sentence!

```<code><?php
// sentences,txt
// 12345Temple of Cheope
// ..........
// 99999Cheope

set_time_limit(0);
$GetCodice=@fopen("sentences.txt", "r");
if ($GetCodice) {
while(!feof($GetCodice)) {
    $StoreCodice=fgets($GetCodice,4096);
    $codice='".'.substr($StoreCodice, 0, 6).'."';  // abcd
    $msg=trim(substr($StoreCodice, 6));  // abcd
    echo $msg."<br>";
    $n=0;
            $file = 'longfile.php';
            replace_file($file, $msg, $codice);
   }
   fclose($GetCodice);
}

// From https://stackoverflow.com/questions/2159059/string-replace-in-a-large-file-with-php
function replace_file($path,$string, $replace)
{
    set_time_limit(0);

    if (is_file($path) === true)
    {
        $file = fopen($path, 'r');
        $temp = tempnam('./', 'tmp');

        if (is_resource($file) === true)
        {
            while (feof($file) === false)
            {
            file_put_contents($temp, str_replace($string, $replace, fgets($file)), FILE_APPEND);
            }

            fclose($file);
        }
        unlink($path);
    }
    echo $replace."<BR>";
     return rename($temp, $path);
}
?>
</code>```

The sentences are ordered according to their descending length. I thought that this order would avoid replacing a shorter sentence or word in a longer sentence.
I expect the output

```<code>12345
.....
99999
</code>```

but the actual output is

```<code>Temple of 9999
.....
99999
</code>```

Can I get some help?

Thank you in advance

答:
according to what you said and what I understand from you , this is what you need: </p>

```<code>set_time_limit( 0 );
//  Initialization
$inputfile           = "sentences.txt";
$outputFile          = 'longfile.php';
$matches             = array();
$extractedNumbers    = array();
$numberOfLines       = count( file( $inputfile ) );
$numberOfReadedLines = 1; // this will be used to check if the counter is on the last line or not;
//  Implementation
$GetCodice  = @fopen( $inputfile, "r" );
$newfile    = @fopen( $outputFile, 'w+' );
if ( $GetCodice ) {
    while ( ( $line = fgets( $GetCodice ) ) !== false ) {
        preg_match( '/^[0-9]+/m', $line, $matches );
        array_push( $extractedNumbers, $matches[0] );
        $position = sizeof( $extractedNumbers ) - 1;
        if ( $numberOfReadedLines == $numberOfLines ) { // if the counter is in the last line then we don't need to write a new empty line with the "\r"
            $newOutputLine = $extractedNumbers[ $position ];
        } else {
            $newOutputLine = $extractedNumbers[ $position ] . "\r";
        }
        fwrite( $newfile, $newOutputLine );
        $numberOfReadedLines++;
        //replace_file($file, $msg, $codice);

    }
    fclose( $newfile );
    fclose( $GetCodice );

}
</code>```

<p>(if this is not what you need so feel free to comment, we can find an ameliorations, i just need more examples to understand your need more)</p>

Body:
I would like to replace sentences by a code in a large file.
I've tried to use str_replace, but because in the file there some of the same words of the sentence, my code replaces them and doesn't recognize the sentence!

<?php
// sentences,txt
// 12345Temple of Cheope
// ..........
// 99999Cheope

set_time_limit(0);
$GetCodice=@fopen("sentences.txt", "r");
if ($GetCodice) {
while(!feof($GetCodice)) {
    $StoreCodice=fgets($GetCodice,4096);
    $codice='".'.substr($StoreCodice, 0, 6).'."';  // abcd
    $msg=trim(substr($StoreCodice, 6));  // abcd
    echo $msg."
";
    $n=0;
            $file = 'longfile.php';
            replace_file($file, $msg, $codice);
   }
   fclose($GetCodice);
}

// From https://stackoverflow.com/questions/2159059/string-replace-in-a-large-file-with-php
function replace_file($path,$string, $replace)
{
    set_time_limit(0);

    if (is_file($path) === true)
    {
        $file = fopen($path, 'r');
        $temp = tempnam('./', 'tmp');

        if (is_resource($file) === true)
        {
            while (feof($file) === false)
            {
            file_put_contents($temp, str_replace($string, $replace, fgets($file)), FILE_APPEND);
            }

            fclose($file);
        }
        unlink($path);
    }
    echo $replace."
";
     return rename($temp, $path);
}
?>

The sentences are ordered according to their descending length. I thought that this order would avoid replacing a shorter sentence or word in a longer sentence.
I expect the output

12345
.....
99999

but the actual output is

Temple of 9999
.....
99999

Can I get some help?

Thank you in advance

Body:
according to what you said and what I understand from you , this is what you need:

set_time_limit( 0 );
//  Initialization
$inputfile           = "sentences.txt";
$outputFile          = 'longfile.php';
$matches             = array();
$extractedNumbers    = array();
$numberOfLines       = count( file( $inputfile ) );
$numberOfReadedLines = 1; // this will be used to check if the counter is on the last line or not;
//  Implementation
$GetCodice  = @fopen( $inputfile, "r" );
$newfile    = @fopen( $outputFile, 'w+' );
if ( $GetCodice ) {
    while ( ( $line = fgets( $GetCodice ) ) !== false ) {
        preg_match( '/^[0-9]+/m', $line, $matches );
        array_push( $extractedNumbers, $matches[0] );
        $position = sizeof( $extractedNumbers ) - 1;
        if ( $numberOfReadedLines == $numberOfLines ) { // if the counter is in the last line then we don't need to write a new empty line with the "\r"
            $newOutputLine = $extractedNumbers[ $position ];
        } else {
            $newOutputLine = $extractedNumbers[ $position ] . "\r";
        }
        fwrite( $newfile, $newOutputLine );
        $numberOfReadedLines++;
        //replace_file($file, $msg, $codice);

    }
    fclose( $newfile );
    fclose( $GetCodice );

}

(if this is not what you need so feel free to comment, we can find an ameliorations, i just need more examples to understand your need more)


问:
how to maintain model properties
i am new to ROR, just setup the enviroment
ruby 1.9.2 with rails 3.0.6

just notice one thing.
after create model.. propeties has been add into database but couldn`t see from the class..
and it just work for me.

looks like rails will scan my database schema before launching the application..

but i have a question for it:

if i frequently add or remove columns...
how do i know what properties do i have if i do not define in the class?
can i manually add properties into ActiceRecord class(es) ??

```<code>class User < ActiveRecord::Base
  has_one :contact
  validates_confirmation_of :password
end

class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.string :username
      t.string :password

      t.timestamps
    end
  end

  def self.down
    drop_table :users
  end
end
</code>```

答:
i;m not sure i understand the question, but you can just view the schema.rb

any migration that you make will update the schema

Title: how to maintain model properties

Body:
i am new to ROR, just setup the enviroment
ruby 1.9.2 with rails 3.0.6

just notice one thing.
after create model.. propeties has been add into database but couldn`t see from the class..
and it just work for me.

looks like rails will scan my database schema before launching the application..

but i have a question for it:

if i frequently add or remove columns...
how do i know what properties do i have if i do not define in the class?
can i manually add properties into ActiceRecord class(es) ??

class User < ActiveRecord::Base
  has_one :contact
  validates_confirmation_of :password
end

class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.string :username
      t.string :password

      t.timestamps
    end
  end

  def self.down
    drop_table :users
  end
end


问:
How efficiently we can get the required output from the list in java?
```<code>CircuitID   Department  Hours

--------------------------------

Circuit A   Electricity      60

Circuit A   Hydel            70

Circuit B   Hydel            30

Circuit C   Electricity      40

Circuit B   Electricity      80

Circuit C   Hydel            50

Circuit A   Electricity      70
</code>```

Now i have to create one list which will have records on following criteria:

In each circuit id i need to get the record with highest hours but if duplicate hours are present than i need to take the one with Electricity department.

Result for the above result should be like below:

```<code>Circuit A  Electricity   70

Circuit B  Electricity   80

Circuit C  Hydel          50
</code>```

Let me know how can i iterate effectively and in most efficient way to get the final list using java 8/ java.

The code i wrote is not at all working perfectly and my approch was shown below:

```<code>for (int i = 0; i < circuitList.size(); i++) {

  for (int j = 0; j < circuitList.size(); {
    if (circuitList.get(i).getCircuitId().equals(circuitList.get(j).getCircuitId()) && i != j) {

     if (circuitList().get(i).getHours() == circuitList().get(j).getHours()) {

      if (circuitList().get(i).getDepartment().equals(“Electricity”) {

        newList.add(circuitList().get(i));

        }

        // some more conditions on getHours
</code>```

Circuit class is having pojo objects with getter setters of this three objects.

```<code> public class Circuit {

        String circuitID;
        int hours;
        String department;
}
</code>```

答:
We have to group by CircuitID first and write custom comparator to filter based on our requirement. It can be done as shown below: </p>

```<code>List<Circuits> filteredList = new ArrayList<>();
list.stream().collect(Collectors.groupingBy(Circuits::getCircuitID)).forEach((key, value) -> filteredList.add(compare(value)));

private static Circuits compare (List<Circuits> list) {
    Circuits circuits = null;
    for (Circuits c : list) {
        if (null == circuits) {
            circuits = c;
        }
        if (c.getHours() > circuits.getHours()) {
            circuits = c;
        } else if (c.getHours() == circuits.getHours()) {
            circuits = c.getDepartment().equalsIgnoreCase("Electricity") ? c : circuits;
        }
    }
    return circuits;
}
</code>```

Body:
CircuitID   Department  Hours

--------------------------------

Circuit A   Electricity      60

Circuit A   Hydel            70

Circuit B   Hydel            30

Circuit C   Electricity      40

Circuit B   Electricity      80

Circuit C   Hydel            50

Circuit A   Electricity      70

Now i have to create one list which will have records on following criteria:

In each circuit id i need to get the record with highest hours but if duplicate hours are present than i need to take the one with Electricity department.

Result for the above result should be like below:

Circuit A  Electricity   70

Circuit B  Electricity   80

Circuit C  Hydel          50

Let me know how can i iterate effectively and in most efficient way to get the final list using java 8/ java.

The code i wrote is not at all working perfectly and my approch was shown below:

for (int i = 0; i < circuitList.size(); i++) {

  for (int j = 0; j < circuitList.size(); {
    if (circuitList.get(i).getCircuitId().equals(circuitList.get(j).getCircuitId()) && i != j) {

     if (circuitList().get(i).getHours() == circuitList().get(j).getHours()) {

      if (circuitList().get(i).getDepartment().equals(“Electricity”) {

        newList.add(circuitList().get(i));

        }

        // some more conditions on getHours

Circuit class is having pojo objects with getter setters of this three objects.

 public class Circuit {

        String circuitID;
        int hours;
        String department;
}

Body:
We have to group by CircuitID first and write custom comparator to filter based on our requirement. It can be done as shown below:

List<Circuits> filteredList = new ArrayList<>();
list.stream().collect(Collectors.groupingBy(Circuits::getCircuitID)).forEach((key, value) -> filteredList.add(compare(value)));

private static Circuits compare (List<Circuits> list) {
    Circuits circuits = null;
    for (Circuits c : list) {
        if (null == circuits) {
            circuits = c;
        }
        if (c.getHours() > circuits.getHours()) {
            circuits = c;
        } else if (c.getHours() == circuits.getHours()) {
            circuits = c.getDepartment().equalsIgnoreCase("Electricity") ? c : circuits;
        }
    }
    return circuits;
}


答:
This is one of the possibilities you can use to get the result needed.
It learns you to import, use the format method and store datatypes in variables and also how to convert different datatypes into the string datatype!
But the main thing you have to do is convert the list or your wished index into a string. By using str(----) function. But the problem is that you've created 4 lists, you should only have one!

```<code>from pprint import pprint
cars = ['rav4'], ['td5'], ['yaris'], ['land rover tdi']
Word = str(cars[0])
pprint("I like the {0} ...".format(Word))
</code>```

Title: How to fix TypeError: can only concatenate str (not "list") to str

Body:
I am trying to learn python from the python crash course but this one task has stumped me and I can’t find an answer to it anywhere

The task is
Think of your favourite mode of transportation and make a list that stores several examples
Use your list to print a series of statements about these items

cars = ['rav4'], ['td5'], ['yaris'], ['land rover tdi']

print("I like the "+cars[0]+" ...")

I’m assuming that this is because I have letters and numbers together, but I don’t know how to produce a result without an error and help would be gratefully received
The error I get is

TypeError: can only concatenate str (not "list") to str**

Body:
This is one of the possibilities you can use to get the result needed.
It learns you to import, use the format method and store datatypes in variables and also how to convert different datatypes into the string datatype!
But the main thing you have to do is convert the list or your wished index into a string. By using str(----) function. But the problem is that you've created 4 lists, you should only have one!

from pprint import pprint
cars = ['rav4'], ['td5'], ['yaris'], ['land rover tdi']
Word = str(cars[0])
pprint("I like the {0} ...".format(Word))


问:
Set multiple domains in one wordpress
I have wordpress in this domain:

```<code>http://www.Dummy.com/en
</code>```

And want to use second domain such this:

```<code> http://www.Dummy2.com
</code>```

for this wordpress.

How can I redirect Dummy2 to Dummy?

This is some codes that I find out but I couldn't understand them:

wp-config.php

```<code>define('WP_SITEURL', ((is_ssl() == true) ? 'https://' : 'http://').$_SERVER['HTTP_HOST']);
define('WP_HOME', ((is_ssl() == true) ? 'https://' : 'http://').$_SERVER['HTTP_HOST']);
</code>```

答:
The best practice is to setup a redirect on a web server side rather than trying to make your website to do so when WordPress doesn't support multiple domains out-of-the-box. Depending on your chosen web server setup there are two answers for you.

1. Apache

You can use the RedirectPermanent directive with a simple VirtualHost, read more here

```<code>#Location:/etc/httpd/conf/httpd.conf
<VirtualHost *:80>
        ServerName www.Dummy2.com
        RedirectPermanent / http://www.Dummy.com/en
</VirtualHost>
</code>```

If only your Dummy2 website would be configured as a WordPress-based site too then,a ternatively, you can add a redirect rule to .htaccess inside of your DocumentRoot configured for www.Dummy2.com site.

```<code>RewriteEngine On
RewriteRule ^(.*)$ http://www.Dummy.com/en/$1 [R=301,L]
</code>```

2. IIS

Make sure that you have an URL Rewrite module installed and simply create a new rewrite rule as follows:

```<code><rule name="Dummy2.com" stopProcessing="true">
     <match url=".*" />
     <conditions>
         <add input="{HTTP_HOST}" pattern="^(.*)?Dummy2.com" />
     </conditions>
     <action type="Redirect" url="http://www.Dummy.com/en/{R:0}" />
 </rule>
</code>```

Title: Set multiple domains in one wordpress

Body:
I have wordpress in this domain:

http://www.Dummy.com/en

And want to use second domain such this:

 http://www.Dummy2.com

for this wordpress.

How can I redirect Dummy2 to Dummy?

This is some codes that I find out but I couldn't understand them:

wp-config.php

define('WP_SITEURL', ((is_ssl() == true) ? 'https://' : 'http://').$_SERVER['HTTP_HOST']);
define('WP_HOME', ((is_ssl() == true) ? 'https://' : 'http://').$_SERVER['HTTP_HOST']);

Body:
The best practice is to setup a redirect on a web server side rather than trying to make your website to do so when WordPress doesn't support multiple domains out-of-the-box. Depending on your chosen web server setup there are two answers for you.

1. Apache

You can use the RedirectPermanent directive with a simple VirtualHost, read more here

#Location:/etc/httpd/conf/httpd.conf
<VirtualHost *:80>
        ServerName www.Dummy2.com
        RedirectPermanent / http://www.Dummy.com/en
</VirtualHost>

If only your Dummy2 website would be configured as a WordPress-based site too then,a ternatively, you can add a redirect rule to .htaccess inside of your DocumentRoot configured for www.Dummy2.com site.

RewriteEngine On
RewriteRule ^(.*)$ http://www.Dummy.com/en/$1 [R=301,L]

2. IIS

Make sure that you have an URL Rewrite module installed and simply create a new rewrite rule as follows:

<rule name="Dummy2.com" stopProcessing="true">
     <match url=".*" />
     <conditions>
         <add input="{HTTP_HOST}" pattern="^(.*)?Dummy2.com" />
     </conditions>
     <action type="Redirect" url="http://www.Dummy.com/en/{R:0}" />
 </rule>


问:
How to convert list of tuples to multiple lists?
Suppose I have a list of tuples and I want to convert to multiple lists.

For example, the list of tuples is

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

Is there any built-in function in Python that convert it to:

```<code>[1,3,5],[2,4,6]
</code>```

This can be a simple program. But I am just curious about the existence of such built-in function in Python.

答:
In addition to Claudiu's answer, you can use:

```<code>>>>a, b = map(list, zip(*[(1, 2), (3, 4), (5, 6)]))
>>>a
[1,3,5]
>>>b
[2,4,6]
</code>```

Edited according to @Peyman mohseni kiasari

Body:
Suppose I have a list of tuples and I want to convert to multiple lists.

For example, the list of tuples is

[(1,2),(3,4),(5,6),]

Is there any built-in function in Python that convert it to:

[1,3,5],[2,4,6]

This can be a simple program. But I am just curious about the existence of such built-in function in Python.

Body:
In addition to Claudiu's answer, you can use:

>>>a, b = map(list, zip(*[(1, 2), (3, 4), (5, 6)]))
>>>a
[1,3,5]
>>>b
[2,4,6]

Edited according to @Peyman mohseni kiasari


问:
How to load and draw emojis on canvas efficiently?
I would like to print an emoji on html canvas.

It can be done using images, but it is cumbersome. Is there a better way?

const canvas = document.querySelector("#canvas");
const contex = canvas.getContext("2d");

var img = new Image();
img.src = "emoji.jpg";
img.addEventListener(
  "load",
  () => {
    context.drawImage(img, 0, 0, 200, 200);
  }
);
img.src = "img.jpg";```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#canvas {
  background: red;
}</code>```

<canvas id="canvas"></canvas>```

Edit:

Okey, I think my question is misunderstood. I am able to draw emoji as an image on canvas. I don't want to do that. Because I have to screenshot all the emojis and crop them before printing them on canvas, which is cumbersome. I am looking for a more efficient way.

答:
You can use fillText to draw the unicode emoji.

You can copy and paste the emojis from emojipedia.

I'm certainly not an expert on this so I don't know if there's big drawbacks to doing it this way, but here are some things to consider regardless.

This might not work on all browsers / operating systems.

The standard emoji will likely look different between browsers/systems unless you use a custom font

You should make sure your js is being read as UTF-8 for this to work. This is standard with HTML5, so you probably don't have to change anything unless it doesn't work for you.

const canvas = document.querySelector("#canvas");
const contex = canvas.getContext("2d");

// The size of the emoji is set with the font
contex.font = '100px serif'
// use these alignment properties for "better" positioning
contex.textAlign = "center";
contex.textBaseline = "middle";
// draw the emoji
contex.fillText('', canvas.width / 2, canvas.height / 2)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#canvas {
  background: #ccc;
}</code>```

<canvas id="canvas"></canvas>```

Body:
I would like to print an emoji on html canvas.

It can be done using images, but it is cumbersome. Is there a better way?

const canvas = document.querySelector("#canvas");
const contex = canvas.getContext("2d");

var img = new Image();
img.src = "emoji.jpg";
img.addEventListener(
  "load",
  () => {
    context.drawImage(img, 0, 0, 200, 200);
  }
);
img.src = "img.jpg";

#canvas {
  background: red;
}

<canvas id="canvas"></canvas>

Edit:

Okey, I think my question is misunderstood. I am able to draw emoji as an image on canvas. I don't want to do that. Because I have to screenshot all the emojis and crop them before printing them on canvas, which is cumbersome. I am looking for a more efficient way.

Body:
You can use fillText to draw the unicode emoji.

You can copy and paste the emojis from emojipedia.

I'm certainly not an expert on this so I don't know if there's big drawbacks to doing it this way, but here are some things to consider regardless.

This might not work on all browsers / operating systems.

The standard emoji will likely look different between browsers/systems unless you use a custom font

You should make sure your js is being read as UTF-8 for this to work. This is standard with HTML5, so you probably don't have to change anything unless it doesn't work for you.

const canvas = document.querySelector("#canvas");
const contex = canvas.getContext("2d");

// The size of the emoji is set with the font
contex.font = '100px serif'
// use these alignment properties for "better" positioning
contex.textAlign = "center";
contex.textBaseline = "middle";
// draw the emoji
contex.fillText('', canvas.width / 2, canvas.height / 2)

#canvas {
  background: #ccc;
}

<canvas id="canvas"></canvas>


问:
Missing information on Spotify Developer "Audio Analysis for a Track"
On Spotify Developer there is a description of the JSON format that is returned on "Get Audio Analysis for a Track". However, there is no information on "track.codestring", "track.echoprintstring" and "track.rhythmstring". Anyone who knows the definition of the information that is hidden in these long strings?

I'm currently embarking on machine/deep learning applied for Music Information Retrieval.

There seems to be no way to directly adress this question on developer.spotify. So I roamed the web but couldn't find an answer.

This is in the JSON-example on 'https://developer.spotify.com/documentation/web-api/reference/tracks/get-audio-analysis/'

```<code>"codestring": "eJxVnAmS5DgOBL-ST-B9_P9j4x7M6qoxW9tpsZQSCeI...",
"code_version": 3.15,

"echoprintstring": "eJzlvQmSHDmStHslxw4cB-v9j_A-tahhVKV0IH9...",
"echoprint_version": 4.12,

"synchstring": "eJx1mIlx7ToORFNRCCK455_YoE9Dtt-vmrKsK3EBsTY...",
"synch_version": 1,

"rhythmstring": "eJyNXAmOLT2r28pZQuZh_xv7g21Iqu_3pCd160xV...",
"rhythm_version": 1
</code>```

答:
This document for EchoNest seems to be describing the same properties as the Spotify API returns. (For an older version unfortunately)

Analyzer Documentation

I also recommend checking out kaleidosync a visualisation app based on Spotify/EchoNest.

kaleidosync demo

source on github

Body:
On Spotify Developer there is a description of the JSON format that is returned on "Get Audio Analysis for a Track". However, there is no information on "track.codestring", "track.echoprintstring" and "track.rhythmstring". Anyone who knows the definition of the information that is hidden in these long strings?

I'm currently embarking on machine/deep learning applied for Music Information Retrieval.

There seems to be no way to directly adress this question on developer.spotify. So I roamed the web but couldn't find an answer.

This is in the JSON-example on 'https://developer.spotify.com/documentation/web-api/reference/tracks/get-audio-analysis/'

"codestring": "eJxVnAmS5DgOBL-ST-B9_P9j4x7M6qoxW9tpsZQSCeI...",
"code_version": 3.15,

"echoprintstring": "eJzlvQmSHDmStHslxw4cB-v9j_A-tahhVKV0IH9...",
"echoprint_version": 4.12,

"synchstring": "eJx1mIlx7ToORFNRCCK455_YoE9Dtt-vmrKsK3EBsTY...",
"synch_version": 1,

"rhythmstring": "eJyNXAmOLT2r28pZQuZh_xv7g21Iqu_3pCd160xV...",
"rhythm_version": 1


问:
How to make script type both text/babel and module?
It works perfectly because I haven't included JSX, but when I replace the script type with text/babel, it doesn't work because the module fails to load. browser.js the Babel compiler.

Here... JSX works only when i replace script type with text/babel but the problem is module fails to load since the script is not module. Any idea how make it work with JSX?

```<code><div id="root">

</div>
<script type="module">
    import  './react.min.js';
    import  './react-dom.min.js';
    import  './browser.js';
    class Hello extends React.Component {
        render() {
            return React.createElement('div', null, `Hello ${this.props.toWhat}`);
        }
    }
    ReactDOM.render(
        React.createElement(Hello, {toWhat: 'World'}, null),
        document.getElementById('root')
    );
</script>
</code>```

答:
I think the question was if it is possible to use a script tag with two or more types at the same time (e.g. something like type="module, txt/babel"). As far as I know the answer is NO.

JonDotsoy's answer helps with reduce typing React.createElement over and over again but even with such a "variable shortcut" it's not as comfortable as JSX when using larger templates with nested elements because h('div', {}, 'hello!!')... is difficult to maintain in such cases.

The only way I found to combine native browser module support and in-browser Babel for JSX without using any build tool is this ... a rather dirty hack that uses eval and should not be used for production apps:

index.html

```<code><body>

    <div id="app"></div>

    <!-- Scripts ------- -->
    <script src="vendor/js/babel.min.js"></script>
    <script src="vendor/js/react.development.js"></script>
    <script src="vendor/js/react-dom.development.js"></script>
    <script src="app/app.js" type="module"></script>

</body>
</code>```

app/app.js

```<code>import ComponentOne from "./ComponentOne.js";

let template = `
<div>
    <h1>Heading</h1>
    <hr />
    <ComponentOne msg="MsgText-ComponentOne" />
</div>
`;

const App = () => {
    return (
        eval(Babel.transform(template, { presets: ['es2017', 'react'] }).code)
    );
};

ReactDOM.render(
    React.createElement(App, null),
    document.getElementById("app")
);
</code>```

app/ComponentOne.js

```<code>import ComponentTwo from "./ComponentTwo.js";

let template = `
<div>
    <h2>This is ComponentOne</h2>
    <p key="2">Property "msg" content: {props.msg}</p>

    <ComponentTwo msg="MsgText-ComponentTwo" />
</div>
`;

const ComponentOne = (props) => {
    return(
        eval(Babel.transform(template, { presets: ['es2017', 'react'] }).code)
    );
};

export default ComponentOne;
</code>```

app/ComponentTwo.js

```<code>let template = `
<div>
    <h2>This is ComponentTwo</h2>
    <p key="2">Property "msg" content: {props.msg}</p>
</div>
`;

const ComponentTwo = (props) => {
    return(
        eval(Babel.transform(template, { presets: ['es2017', 'react'] }).code)
    );
};

export default ComponentTwo;
</code>```

Body:
I think the question was if it is possible to use a script tag with two or more types at the same time (e.g. something like type="module, txt/babel"). As far as I know the answer is NO.

JonDotsoy's answer helps with reduce typing React.createElement over and over again but even with such a "variable shortcut" it's not as comfortable as JSX when using larger templates with nested elements because h('div', {}, 'hello!!')... is difficult to maintain in such cases.

The only way I found to combine native browser module support and in-browser Babel for JSX without using any build tool is this ... a rather dirty hack that uses eval and should not be used for production apps:

index.html

<body>

    <div id="app"></div>

    <!-- Scripts ------- -->
    <script src="vendor/js/babel.min.js"></script>
    <script src="vendor/js/react.development.js"></script>
    <script src="vendor/js/react-dom.development.js"></script>
    <script src="app/app.js" type="module"></script>

</body>

app/app.js

import ComponentOne from "./ComponentOne.js";

let template = `
<div>
    <h1>Heading</h1>
    <hr />
    <ComponentOne msg="MsgText-ComponentOne" />
</div>
`;

const App = () => {
    return (
        eval(Babel.transform(template, { presets: ['es2017', 'react'] }).code)
    );
};

ReactDOM.render(
    React.createElement(App, null),
    document.getElementById("app")
);

app/ComponentOne.js

import ComponentTwo from "./ComponentTwo.js";

let template = `
<div>
    <h2>This is ComponentOne</h2>
    <p key="2">Property "msg" content: {props.msg}</p>

    <ComponentTwo msg="MsgText-ComponentTwo" />
</div>
`;

const ComponentOne = (props) => {
    return(
        eval(Babel.transform(template, { presets: ['es2017', 'react'] }).code)
    );
};

export default ComponentOne;

app/ComponentTwo.js

let template = `
<div>
    <h2>This is ComponentTwo</h2>
    <p key="2">Property "msg" content: {props.msg}</p>
</div>
`;

const ComponentTwo = (props) => {
    return(
        eval(Babel.transform(template, { presets: ['es2017', 'react'] }).code)
    );
};

export default ComponentTwo;


问:
I use Xcode distributing app to App Store Connect. Xcode upload fail and show "ERROR ITMS-90037"
I distribute my app to App Store Connect. Xcode run some process. Then Xcode upload fail and show ERROR ITMS-90037.

This project developed using Objective-C. I used Sublime Text finding following regular expression [\x00-\x08\x0b-\x1f\x7f]. I didn't find anything in my Info.plist.

This is my Info.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>LSApplicationCategoryType</key>
    <string></string>
    <key>CFBundleDevelopmentRegion</key>
    <string>$(DEVELOPMENT_LANGUAGE)</string>
    <key>CFBundleDisplayName</key>
    <string>My App Name</string>
    <key>CFBundleExecutable</key>
    <string>$(EXECUTABLE_NAME)</string>
    <key>CFBundleIdentifier</key>
    <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>${PRODUCT_NAME}</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleSignature</key>
    <string>????</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0</string>
    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLName</key>
            <string>sina</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>str</string>
            </array>
        </dict>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLName</key>
            <string>wx</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>str</string>
            </array>
        </dict>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLName</key>
            <string>qq</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>str</string>
            </array>
        </dict>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLName</key>
            <string>tencent</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>str</string>
            </array>
        </dict>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLName</key>
            <string>lineredsport</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>com.myteam.myapp</string>
            </array>
        </dict>
    </array>
    <key>CFBundleVersion</key>
    <string>1</string>
    <key>LSApplicationQueriesSchemes</key>
    <array>
        ...
    </array>
    <key>LSRequiresIPhoneOS</key>
    <true/>
    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoadsInWebContent</key>
        <true/>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>
    <key>NSAppleMusicUsageDescription</key>
    <string>访问媒体资料库</string>
    <key>NSBluetoothPeripheralUsageDescription</key>
    <string>访问蓝牙</string>
    <key>NSCalendarsUsageDescription</key>
    <string>访问日历</string>
    <key>NSCameraUsageDescription</key>
    <string>访问相机</string>
    <key>NSLocationAlwaysUsageDescription</key>
    <string>始终访问位置</string>
    <key>NSLocationUsageDescription</key>
    <string>访问位置</string>
    <key>NSLocationWhenInUseUsageDescription</key>
    <string>试用期间访问位置</string>
    <key>NSMicrophoneUsageDescription</key>
    <string>访问麦克风</string>
    <key>NSMotionUsageDescription</key>
    <string>访问运动与健康</string>
    <key>NSPhotoLibraryUsageDescription</key>
    <string>滚球体育会在修改头像和发布推荐时使用您的相机，是否允许?</string>
    <key>NSRemindersUsageDescription</key>
    <string>访问提醒事项</string>
    <key>UIAppFonts</key>
    <array>
        <string>DIN-Bold.TTF</string>
    </array>
    <key>UIBackgroundModes</key>
    <array>
        <string>remote-notification</string>
    </array>
    <key>UIMainStoryboardFile</key>
    <string>Main</string>
    <key>UIRequiredDeviceCapabilities</key>
    <array>
        <string>armv7</string>
    </array>
    <key>UIStatusBarStyle</key>
    <string>UIStatusBarStyleDefault</string>
    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
    </array>
    <key>UISupportedInterfaceOrientations~ipad</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
    </array>
    <key>UIViewControllerBasedStatusBarAppearance</key>
    <true/>
</dict>
</plist>
```

following is full error message

ERROR ITMS-90037: "This bundle is invalid. The Info.plist file is missing or could not be parsed. Please check it for embedded control characters."

答:
Here are the ITMS-90037 upload error stack overflow notes.

https://www.e-learn.cn/content/wangluowenzhang/1116413

Body:
I distribute my app to App Store Connect. Xcode run some process. Then Xcode upload fail and show ERROR ITMS-90037.

This project developed using Objective-C. I used Sublime Text finding following regular expression [\x00-\x08\x0b-\x1f\x7f]. I didn't find anything in my Info.plist.

This is my Info.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>LSApplicationCategoryType</key>
    <string></string>
    <key>CFBundleDevelopmentRegion</key>
    <string>$(DEVELOPMENT_LANGUAGE)</string>
    <key>CFBundleDisplayName</key>
    <string>My App Name</string>
    <key>CFBundleExecutable</key>
    <string>$(EXECUTABLE_NAME)</string>
    <key>CFBundleIdentifier</key>
    <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>${PRODUCT_NAME}</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleSignature</key>
    <string>????</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0</string>
    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLName</key>
            <string>sina</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>str</string>
            </array>
        </dict>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLName</key>
            <string>wx</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>str</string>
            </array>
        </dict>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLName</key>
            <string>qq</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>str</string>
            </array>
        </dict>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLName</key>
            <string>tencent</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>str</string>
            </array>
        </dict>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLName</key>
            <string>lineredsport</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>com.myteam.myapp</string>
            </array>
        </dict>
    </array>
    <key>CFBundleVersion</key>
    <string>1</string>
    <key>LSApplicationQueriesSchemes</key>
    <array>
        ...
    </array>
    <key>LSRequiresIPhoneOS</key>
    <true/>
    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoadsInWebContent</key>
        <true/>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>
    <key>NSAppleMusicUsageDescription</key>
    <string>访问媒体资料库</string>
    <key>NSBluetoothPeripheralUsageDescription</key>
    <string>访问蓝牙</string>
    <key>NSCalendarsUsageDescription</key>
    <string>访问日历</string>
    <key>NSCameraUsageDescription</key>
    <string>访问相机</string>
    <key>NSLocationAlwaysUsageDescription</key>
    <string>始终访问位置</string>
    <key>NSLocationUsageDescription</key>
    <string>访问位置</string>
    <key>NSLocationWhenInUseUsageDescription</key>
    <string>试用期间访问位置</string>
    <key>NSMicrophoneUsageDescription</key>
    <string>访问麦克风</string>
    <key>NSMotionUsageDescription</key>
    <string>访问运动与健康</string>
    <key>NSPhotoLibraryUsageDescription</key>
    <string>滚球体育会在修改头像和发布推荐时使用您的相机，是否允许?</string>
    <key>NSRemindersUsageDescription</key>
    <string>访问提醒事项</string>
    <key>UIAppFonts</key>
    <array>
        <string>DIN-Bold.TTF</string>
    </array>
    <key>UIBackgroundModes</key>
    <array>
        <string>remote-notification</string>
    </array>
    <key>UIMainStoryboardFile</key>
    <string>Main</string>
    <key>UIRequiredDeviceCapabilities</key>
    <array>
        <string>armv7</string>
    </array>
    <key>UIStatusBarStyle</key>
    <string>UIStatusBarStyleDefault</string>
    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
    </array>
    <key>UISupportedInterfaceOrientations~ipad</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
    </array>
    <key>UIViewControllerBasedStatusBarAppearance</key>
    <true/>
</dict>
</plist>

following is full error message

ERROR ITMS-90037: "This bundle is invalid. The Info.plist file is missing or could not be parsed. Please check it for embedded control characters."


问:
i want to make multiple mouseover functions with minimum codes
I have 10 links and each of them is different from the others.I want when user hovers on them background image of the div changes and a tooltip text be shown on top of the links with a fade-in animation .

i have tried to make several functions using JS and it works but it's a lot of code and mostly repetitive.I want a good shortcut through all of that useless coding.

document.getElementById("d1").onmouseover = function() {
  mouseOver1()
};
document.getElementById("d2").onmouseover = function() {
  mouseOver2()
};
document.getElementById("d3").onmouseover = function() {
  mouseOver3()
};
document.getElementById("d1").onmouseout = function() {
  mouseOut1()
};
document.getElementById("d2").onmouseout = function() {
  mouseOut2()
};
document.getElementById("d3").onmouseout = function() {
  mouseOut3()
};

function mouseOver1() {
  document.getElementById("dogs").style.background = "blue";
  document.getElementById("tooltiptext1").style.visibility = "visible";
}

function mouseOut1() {
  document.getElementById("dogs").style.background = "black";
  document.getElementById("tooltiptext1").style.visibility = "hidden";
}

function mouseOver2() {
  document.getElementById("dogs").style.background = "green";
  document.getElementById("tooltiptext2").style.visibility = "visible";
}

function mouseOut2() {
  document.getElementById("dogs").style.background = "black";
  document.getElementById("tooltiptext2").style.visibility = "hidden";
}

function mouseOver3() {
  document.getElementById("dogs").style.background = "red";
  document.getElementById("tooltiptext3").style.visibility = "visible";
}

function mouseOut3() {
  document.getElementById("dogs").style.background = "black";
  document.getElementById("tooltiptext3").style.visibility = "hidden";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#dogs {
  float: right;
  margin-top: 5%;
  background: black;
  width: 150px;
  height: 150px;
}

#d-list {
  color: white;
  direction: ltr;
  float: right;
  width: 60%;
  height: 60%;
}

#tooltiptext1,
#tooltiptext2,
#tooltiptext3 {
  color: black;
  background-color: gray;
  width: 120px;
  height: 30px;
  border-radius: 6px;
  text-align: center;
  padding-top: 5px;
  visibility: hidden;
}</code>```

dogs```<br />

    ```white Husky```
    <p id="tooltiptext1">Tooltip text1</p>

    ```black Bull```
    <p id="tooltiptext2">Tooltip text2</p>

    ```brown Rex```
    <p id="tooltiptext3">Tooltip text3</p>
  </div>
</div></code>```

Please have in mind that all of links will change same outer div object and the idea is to change the background image of that div and the tooltip shoud appear on the top of the links....so,
any ideas?

答:
edit: added animation requested.
CSS is almost always better done in script by using classes when multiple elements are being manipulated with similar functions so I used that here.  Rather than put some complex set of logic in place I simply added data attributes for the colors - now it works for any new elements you wish to add as well.

I did find your markup to be somewhat strangely chosen and would have done it differently but that was not part of the question as stated.

I took the liberty of removing the style attribute from your dogs element and put it in the CSS also as it seemed to belong there and mixing markup and css will probably make it harder to maintain over time and puts all the style in one place.

Since you DID tag this with jQuery here is an example of that.

$(function() {
  $('#d-list').on('mouseenter', 'a', function(event) {
    $('#dogs').css('backgroundColor', $(this).data('colorin'));
    $(this).parent().next('.tooltip').animate({
      opacity: 1
    });
  }).on('mouseleave', 'a', function(event) {
    $('#dogs').css('backgroundColor', $(this).data('colorout'));
    $(this).parent().next('.tooltip').animate({
      opacity: 0
    });
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#dogs {
  float: right;
  margin-top: 5%;
  background: black;
  width: 150px;
  height: 150px;
}

#d-list {
  color: white;
  direction: ltr;
  float: right;
  width: 60%;
  height: 60%;
}

.dog-header {
  font-size: 22px;
  color: darkorange;
  margin-bottom: 2em;
}

.tooltip {
  color: black;
  background-color: gray;
  width: 120px;
  height: 30px;
  border-radius: 6px;
  text-align: center;
  padding-top: 5px;
  opacity: 0;
  position:relative;
  top:-4.5em;
}</code>```

dogs```
    ```white Husky```
    <p id="tooltiptext1" class="tooltip">Tooltip text1</p>
    ```black Bull```
    <p id="tooltiptext2" class="tooltip">Tooltip text2</p>
    ```brown Rex```
    <p id="tooltiptext3" class="tooltip">Tooltip text3</p>
  </div>
</div></code>```

Body:
I have 10 links and each of them is different from the others.I want when user hovers on them background image of the div changes and a tooltip text be shown on top of the links with a fade-in animation .

i have tried to make several functions using JS and it works but it's a lot of code and mostly repetitive.I want a good shortcut through all of that useless coding.

document.getElementById("d1").onmouseover = function() {
  mouseOver1()
};
document.getElementById("d2").onmouseover = function() {
  mouseOver2()
};
document.getElementById("d3").onmouseover = function() {
  mouseOver3()
};
document.getElementById("d1").onmouseout = function() {
  mouseOut1()
};
document.getElementById("d2").onmouseout = function() {
  mouseOut2()
};
document.getElementById("d3").onmouseout = function() {
  mouseOut3()
};

function mouseOver1() {
  document.getElementById("dogs").style.background = "blue";
  document.getElementById("tooltiptext1").style.visibility = "visible";
}

function mouseOut1() {
  document.getElementById("dogs").style.background = "black";
  document.getElementById("tooltiptext1").style.visibility = "hidden";
}

function mouseOver2() {
  document.getElementById("dogs").style.background = "green";
  document.getElementById("tooltiptext2").style.visibility = "visible";
}

function mouseOut2() {
  document.getElementById("dogs").style.background = "black";
  document.getElementById("tooltiptext2").style.visibility = "hidden";
}

function mouseOver3() {
  document.getElementById("dogs").style.background = "red";
  document.getElementById("tooltiptext3").style.visibility = "visible";
}

function mouseOut3() {
  document.getElementById("dogs").style.background = "black";
  document.getElementById("tooltiptext3").style.visibility = "hidden";
}

#dogs {
  float: right;
  margin-top: 5%;
  background: black;
  width: 150px;
  height: 150px;
}

#d-list {
  color: white;
  direction: ltr;
  float: right;
  width: 60%;
  height: 60%;
}

#tooltiptext1,
#tooltiptext2,
#tooltiptext3 {
  color: black;
  background-color: gray;
  width: 120px;
  height: 30px;
  border-radius: 6px;
  text-align: center;
  padding-top: 5px;
  visibility: hidden;
}

dogs

white Husky

Tooltip text1

black Bull

Tooltip text2

brown Rex

Tooltip text3

Please have in mind that all of links will change same outer div object and the idea is to change the background image of that div and the tooltip shoud appear on the top of the links....so,
any ideas?

Body:
edit: added animation requested.
CSS is almost always better done in script by using classes when multiple elements are being manipulated with similar functions so I used that here.  Rather than put some complex set of logic in place I simply added data attributes for the colors - now it works for any new elements you wish to add as well.

I did find your markup to be somewhat strangely chosen and would have done it differently but that was not part of the question as stated.

I took the liberty of removing the style attribute from your dogs element and put it in the CSS also as it seemed to belong there and mixing markup and css will probably make it harder to maintain over time and puts all the style in one place.

Since you DID tag this with jQuery here is an example of that.

$(function() {
  $('#d-list').on('mouseenter', 'a', function(event) {
    $('#dogs').css('backgroundColor', $(this).data('colorin'));
    $(this).parent().next('.tooltip').animate({
      opacity: 1
    });
  }).on('mouseleave', 'a', function(event) {
    $('#dogs').css('backgroundColor', $(this).data('colorout'));
    $(this).parent().next('.tooltip').animate({
      opacity: 0
    });
  });
});

#dogs {
  float: right;
  margin-top: 5%;
  background: black;
  width: 150px;
  height: 150px;
}

#d-list {
  color: white;
  direction: ltr;
  float: right;
  width: 60%;
  height: 60%;
}

.dog-header {
  font-size: 22px;
  color: darkorange;
  margin-bottom: 2em;
}

.tooltip {
  color: black;
  background-color: gray;
  width: 120px;
  height: 30px;
  border-radius: 6px;
  text-align: center;
  padding-top: 5px;
  opacity: 0;
  position:relative;
  top:-4.5em;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div id="animals">
  <div id="dogs"></div>
  <div id="d-list">
    <pre class="dog-header">dogs</pre>
    <pre><a href="#burger" id="d1" data-colorin="blue" data-colorout="black">white Husky</a></pre>
    <p id="tooltiptext1" class="tooltip">Tooltip text1</p>
    <pre><a href="#burger" id="d2" data-colorin="green" data-colorout="black">black Bull</a></pre>
    <p id="tooltiptext2" class="tooltip">Tooltip text2</p>
    <pre><a href="#burger" id="d3" data-colorin="red" data-colorout="black">brown Rex</a></pre>
    <p id="tooltiptext3" class="tooltip">Tooltip text3</p>
  </div>
</div>


问:
How to fix TypeError: can only concatenate str (not "list") to str
I am trying to learn python from the python crash course but this one task has stumped me and I can’t find an answer to it anywhere

The task is
Think of your favourite mode of transportation and make a list that stores several examples
Use your list to print a series of statements about these items

```<code>cars = ['rav4'], ['td5'], ['yaris'], ['land rover tdi']

print("I like the "+cars[0]+" ...")
</code>```

I’m assuming that this is because I have letters and numbers together, but I don’t know how to produce a result without an error and help would be gratefully received
The error I get is

TypeError: can only concatenate str (not "list") to str**

答:
First, create a list (not tuple of lists) of strings and then you can access first element (string) of list.

```<code>cars = ['rav4', 'td5', 'yaris', 'land rover tdi']
print("I like the "+cars[0]+" ...")
</code>```

The above code outputs: I like the rav4 ...

Body:
First, create a list (not tuple of lists) of strings and then you can access first element (string) of list.

cars = ['rav4', 'td5', 'yaris', 'land rover tdi']
print("I like the "+cars[0]+" ...")

The above code outputs: I like the rav4 ...


问:
Filter one record in table with Request ID
I have tabel request_process as follows:

```<code>requestID Status
1            0
1            1
1            2
2            0
2            1
</code>```

I want to get one row per request with maximum status but only those rows whose status for request is not 2

I want to apply this on where clause of query

```<code>$UserRequests = UserRequests::leftJoin('request_process', function($join){
$join->on('user_requests.id', '=', 'request_id')->where('status', '!=',2);})
->select('*')
->get();
</code>```

答:
We filter all rows which doesn't have this max status and do a group by on request_process.requestID and use an aggregate function max() to receive max status for each user request process.

SQL:

```<code><?php

$max_status = 2; // hard coded but you need more tables to make this more flexible.

$UserRequests =  UserRequests::leftJoin('request_process','user_requests.id','=','request_process.request_id')
                    ->select('user_requests.*',DB::raw('max(request_process.status) as status'))
                    ->where('request_process.status','!=',$max_status)
                    ->groupBy('request_process.requestID')
                    ->get();

dd($UserRequests);
</code>```

Body:
I have tabel request_process as follows:

requestID Status
1            0
1            1
1            2
2            0
2            1

I want to get one row per request with maximum status but only those rows whose status for request is not 2

I want to apply this on where clause of query

$UserRequests = UserRequests::leftJoin('request_process', function($join){
$join->on('user_requests.id', '=', 'request_id')->where('status', '!=',2);})
->select('*')
->get();

Body:
We filter all rows which doesn't have this max status and do a group by on request_process.requestID and use an aggregate function max() to receive max status for each user request process.

SQL:

<?php

$max_status = 2; // hard coded but you need more tables to make this more flexible.

$UserRequests =  UserRequests::leftJoin('request_process','user_requests.id','=','request_process.request_id')
                    ->select('user_requests.*',DB::raw('max(request_process.status) as status'))
                    ->where('request_process.status','!=',$max_status)
                    ->groupBy('request_process.requestID')
                    ->get();

dd($UserRequests);