问:
handling possible simultaneous errors in Python
I just started studying python and I want to know if my approach is the best on handling possible simultaneous errors.

```<code>Input object is: actor = {"name": "John Cleese", "rank": "awesome"}
</code>```

I defined a function that should return the "X" word from the value of "Y" property:

```<code>def get_property(prop, poz):
    ln = actor[prop].split()[poz]
   return ln

#this is how I call my function
_prop = "fname"
_poz = 12

print("The actor's %s is %s" % (_prop, get_property(_prop, _poz)))
</code>```

My goal is that if the property does not exist then use the "name" and/or if the value cannot be split in as many words as the value of "_poz + 1" then pick the first word of the value of that property.

My solution is below so please let me know if there is a better way. Thank you in advance!

```<code># Handle all the exceptions!
#Setup
actor = {"name": "John Cleese", "rank": "awesome"}

#This function should return the "poz"th word of property "prop". If an  invalid property is passed then use "name". If an invalid index of the word in the value is passed then use return the first word.

def get_property(prop, poz):
    ln = ""
    noerr = 0
    while noerr == 0:
        try:
            ln = actor[prop].split()[poz]
        except IndexError:
            poz = 0
        except KeyError:
            prop = "name"
        else:
            noerr = 1
    return ln

#Test code
_prop = "fname"
_poz = 12

print("The actor's %s is %s" % (_prop, get_property(_prop, _poz)))
</code>```

These are the expected cases and their output:

Case 1: valid property and valid word's index

```<code>_prop = "name"
_poz = 1
get_property(_prop, _poz) = Cleese
</code>```

Case 2: valid property and invalid word's index

```<code>_prop = "name"
_poz = 12
get_property(_prop, _poz) = John
</code>```

Case 3: Invalid property and valid word's index

```<code>_prop = "MIDDLEname"
_poz = 1
get_property(_prop, _poz) = Cleese
</code>```

Case 4: Invalid property and invalid word's index

```<code>_prop = "b-rank"
_poz = 12
get_property(_prop, _poz) = John
</code>```

答:
What you are doing

"Easier to ask for forgiveness than permission" EAFP

In your code you just use the parameters you got and hope that everything works fine (try). If that's not the case (except), you change the parameter accordingly and try it again (while) until it works (else).

So basically what you are doing is validating your input afterwards.
This comes with a lot of extra code (try, except, etc.).
But actually, that's the preferred coding style according of Python

But in your case, especially as beginner, your approach has the following disadvantages:

Your code becomes more complex and harder to read because you use many different techniques in one function (try with multiple except in a while loop)

You can't spot easily if you maybe forgot a case!

Your code becomes slower to execute (you won't feel the difference in this case but it's good to know), for example:

In the worst case (IndexError + KeyError) you have to go through your while loop 3 times

Your code becomes "unsafer", for example:

What would happen if the actor dictionary is changed and the name key gets removed? Your code would stuck in an endless loop, because the try-except construct would catch the exception every time, not executing the else case.

What you should do

"Look before you leap" LBYL

So a better solution in your case would be to validate your input before you try to work with it.

In your case you are working with two different data structures (dict and list):

For your dictionary you can use the get(key, default) method to safely get the value you want from the dictionary

For your list of splitted words you can check if there are enough words with the len(list) method

These methods will help you to avoid the exceptions at all.
Just add the logic to your get_property function to make sure every error case is handled properly:

```<code>actor = {"name": "John Cleese", "rank": "awesome"}

def get_property(prob, pos, default="name"):
    values = actor.get(prob, actor[default]).split()
    return values[pos] if pos < len(values) else values[0]

test_values = [("name", 1), ("name", 12), ("MIDDLEname", 1), ("b-rank", 12)]
for prob, pos in test_values:
    print(f"{prob}, {pos} => {get_property(prob, pos)}")
</code>```

This produces the output:

```<code>name, 1 => Cleese
name, 12 => John
MIDDLEname, 1 => Cleese
b-rank, 12 => John
</code>```

Body:
I just started studying python and I want to know if my approach is the best on handling possible simultaneous errors.

Input object is: actor = {"name": "John Cleese", "rank": "awesome"}

I defined a function that should return the "X" word from the value of "Y" property:

def get_property(prop, poz):
    ln = actor[prop].split()[poz]
   return ln

#this is how I call my function
_prop = "fname"
_poz = 12

print("The actor's %s is %s" % (_prop, get_property(_prop, _poz)))

My goal is that if the property does not exist then use the "name" and/or if the value cannot be split in as many words as the value of "_poz + 1" then pick the first word of the value of that property.

My solution is below so please let me know if there is a better way. Thank you in advance!

# Handle all the exceptions!
#Setup
actor = {"name": "John Cleese", "rank": "awesome"}

#This function should return the "poz"th word of property "prop". If an  invalid property is passed then use "name". If an invalid index of the word in the value is passed then use return the first word.

def get_property(prop, poz):
    ln = ""
    noerr = 0
    while noerr == 0:
        try:
            ln = actor[prop].split()[poz]
        except IndexError:
            poz = 0
        except KeyError:
            prop = "name"
        else:
            noerr = 1
    return ln

#Test code
_prop = "fname"
_poz = 12

print("The actor's %s is %s" % (_prop, get_property(_prop, _poz)))

These are the expected cases and their output:

Case 1: valid property and valid word's index

_prop = "name"
_poz = 1
get_property(_prop, _poz) = Cleese

Case 2: valid property and invalid word's index

_prop = "name"
_poz = 12
get_property(_prop, _poz) = John

Case 3: Invalid property and valid word's index

_prop = "MIDDLEname"
_poz = 1
get_property(_prop, _poz) = Cleese

Case 4: Invalid property and invalid word's index

_prop = "b-rank"
_poz = 12
get_property(_prop, _poz) = John

Body:
What you are doing

"Easier to ask for forgiveness than permission" EAFP

In your code you just use the parameters you got and hope that everything works fine (try). If that's not the case (except), you change the parameter accordingly and try it again (while) until it works (else).

So basically what you are doing is validating your input afterwards.
This comes with a lot of extra code (try, except, etc.).
But actually, that's the preferred coding style according of Python

But in your case, especially as beginner, your approach has the following disadvantages:

Your code becomes more complex and harder to read because you use many different techniques in one function (try with multiple except in a while loop)

You can't spot easily if you maybe forgot a case!

Your code becomes slower to execute (you won't feel the difference in this case but it's good to know), for example:

In the worst case (IndexError + KeyError) you have to go through your while loop 3 times

Your code becomes "unsafer", for example:

What would happen if the actor dictionary is changed and the name key gets removed? Your code would stuck in an endless loop, because the try-except construct would catch the exception every time, not executing the else case.

What you should do

"Look before you leap" LBYL

So a better solution in your case would be to validate your input before you try to work with it.

In your case you are working with two different data structures (dict and list):

For your dictionary you can use the get(key, default) method to safely get the value you want from the dictionary

For your list of splitted words you can check if there are enough words with the len(list) method

These methods will help you to avoid the exceptions at all.
Just add the logic to your get_property function to make sure every error case is handled properly:

actor = {"name": "John Cleese", "rank": "awesome"}

def get_property(prob, pos, default="name"):
    values = actor.get(prob, actor[default]).split()
    return values[pos] if pos < len(values) else values[0]

test_values = [("name", 1), ("name", 12), ("MIDDLEname", 1), ("b-rank", 12)]
for prob, pos in test_values:
    print(f"{prob}, {pos} => {get_property(prob, pos)}")

This produces the output:

name, 1 => Cleese
name, 12 => John
MIDDLEname, 1 => Cleese
b-rank, 12 => John


来源: stackexchange

问:
Android How to remove Empty Space
I want to remove empty space. For example: rama chan dran should become ramachandran.

答:
Use replaceAll() method of String class.
For Example:

```<code>String s = "Test Test Tes t";
System.out.println(s.replaceAll(" ", "");
</code>```

ContentLicense: CC BY-SA 3.0

Title: Android How to remove Empty Space

Body:
Use replaceAll() method of String class.
For Example:

String s = "Test Test Tes t";
System.out.println(s.replaceAll(" ", "");


问:
C# Check if Flags enum has only one value set
I have a Flags enum and want to assert that a given instance of it, is one of the primitive values, i.e. it has exactly one '1' in its binary representation, i.e. it's a power of two.

What's the best way to check this?

(I suppose "best" isn't necessarily well-defined, so ...)

What's the fastest way to check this?

What's the most semantically clear way to check this?

How do I check this, whilst writing the least code?

答:
bit operation will yield the fastest result

```<code>((anInstanceOfTheFlaggedEnum & (anInstanceOfTheFlaggedEnum -1)) != 0)
</code>```

over the more readable built in function

```<code>Enum.IsDefined(typeof(yourFlaggedEnumType), anInstanceOfTheFlaggedEnum)
</code>```

I just ran a test and it was ~175 times faster..

ContentLicense: CC BY-SA 4.0

Body:
bit operation will yield the fastest result

((anInstanceOfTheFlaggedEnum & (anInstanceOfTheFlaggedEnum -1)) != 0)

over the more readable built in function

Enum.IsDefined(typeof(yourFlaggedEnumType), anInstanceOfTheFlaggedEnum)

I just ran a test and it was ~175 times faster..


问:
how can we print the output of a code in gui , not in console?
i have a written piece of code of around 100 lines which is printing some output of around 20 lines. How can I print this output in GUI ??</p>

答:
I just wrote this implementation for a project of mine, its in Python 2.7 but it should be easy to adapt it to Python 3.6</p>

```<code>#!/usr/lib/python2.7/
# -*- coding: utf-8 -*-

from Tkinter import *
import ttk, collections

class GUI():

    def __init__(self) :
        self.window = Tk()

    def draw(self) :
        self.root = Frame(self.window,padx=15,pady=15,width=800,height=200)
        self.root.grid(column=0,row=0)
        self.drawConsole()
        self.window.mainloop()

    def drawConsole(self) :
        self.consoleFrame = Frame(self.root, padx=15)
        self.consoleFrame.grid(column=0,row=4,sticky="EW",pady=10)
        self.logTest = Text(self.consoleFrame, height=15, state='disabled', wrap='word',background='black',foreground='yellow')
        self.logTest.grid(column=0,row=0,sticky="EW")
        self.scrollbar = Scrollbar(self.consoleFrame, orient=VERTICAL,command=self.logTest.yview)
        self.scrollbar.grid(column=1,row=0,sticky=(N,S))
        self.logTest['yscrollcommand'] = self.scrollbar.set

    def writeToLog(self, msg):
        numlines = self.logTest.index('end - 1 line').split('.')[0]
        self.logTest['state'] = 'normal'
        if numlines==24:
            self.logTest.delete(1.0, 2.0)
        if self.logTest.index('end-1c')!='1.0':
            self.logTest.insert('end', '\n')
        self.logTest.insert('end', msg)
        self.logTest.see(END)
        self.logTest['state'] = 'disabled'

if __name__ == "__main__":
    gui = GUI()
    gui.draw()
    gui.writeToLog("Hello World")
</code>```

Body:
I just wrote this implementation for a project of mine, its in Python 2.7 but it should be easy to adapt it to Python 3.6

#!/usr/lib/python2.7/
# -*- coding: utf-8 -*-

from Tkinter import *
import ttk, collections

class GUI():

    def __init__(self) :
        self.window = Tk()

    def draw(self) :
        self.root = Frame(self.window,padx=15,pady=15,width=800,height=200)
        self.root.grid(column=0,row=0)
        self.drawConsole()
        self.window.mainloop()

    def drawConsole(self) :
        self.consoleFrame = Frame(self.root, padx=15)
        self.consoleFrame.grid(column=0,row=4,sticky="EW",pady=10)
        self.logTest = Text(self.consoleFrame, height=15, state='disabled', wrap='word',background='black',foreground='yellow')
        self.logTest.grid(column=0,row=0,sticky="EW")
        self.scrollbar = Scrollbar(self.consoleFrame, orient=VERTICAL,command=self.logTest.yview)
        self.scrollbar.grid(column=1,row=0,sticky=(N,S))
        self.logTest['yscrollcommand'] = self.scrollbar.set

    def writeToLog(self, msg):
        numlines = self.logTest.index('end - 1 line').split('.')[0]
        self.logTest['state'] = 'normal'
        if numlines==24:
            self.logTest.delete(1.0, 2.0)
        if self.logTest.index('end-1c')!='1.0':
            self.logTest.insert('end', '\n')
        self.logTest.insert('end', msg)
        self.logTest.see(END)
        self.logTest['state'] = 'disabled'

if __name__ == "__main__":
    gui = GUI()
    gui.draw()
    gui.writeToLog("Hello World")


问:
Printing information in the command window while running a sqlcmd process in a c# program
I run an update process from my c# wpf program like this:

```<code>Process sql = Process.Start("sqlcmd.exe", param);
sql.WaitForExit(1200000);
</code>```

The variable param is build from user input in the ui, here is a example:

```<code>sqlcmd.exe -S .\SQLEXPRESS -d mydatabase -v db_src = "db\file.bak" -i db\update.sql -o "\log\log_update.txt"
</code>```

Now the black cmd window opens and runs for a while (1-5 minutes). On some machines the white curos blinks. What I want is that something like "Please wait... & " is printed on the cmd window.

I've tried different approaces but the sqlmd erases everything. Like putting a echo Please wait... in front of param.

Displaying something in the c# program is also difficult because while the process runs, the program is frozen. But if anyone knows a solution which makes it possible to display a message in the program this would also be fine.

答:
Using .WaitForExit() blocks your current application thread. Instead you should just start the process in the background, and wait for the Exited event.

To quote MSDN - see the remarks:

WaitForExit() makes the current thread wait until the associated
  process terminates. It should be called after all other methods are
  called on the process. To avoid blocking the current thread, use the
  Exited event.

If your thread isn't blocked you can write progress/status messages that'll actually appear.

Body:
I run an update process from my c# wpf program like this:

Process sql = Process.Start("sqlcmd.exe", param);
sql.WaitForExit(1200000);

The variable param is build from user input in the ui, here is a example:

sqlcmd.exe -S .\SQLEXPRESS -d mydatabase -v db_src = "db\file.bak" -i db\update.sql -o "\log\log_update.txt"

Now the black cmd window opens and runs for a while (1-5 minutes). On some machines the white curos blinks. What I want is that something like "Please wait... & " is printed on the cmd window.

I've tried different approaces but the sqlmd erases everything. Like putting a echo Please wait... in front of param.

Displaying something in the c# program is also difficult because while the process runs, the program is frozen. But if anyone knows a solution which makes it possible to display a message in the program this would also be fine.


问:
How to prevent/override authorization header in Safari?
I have web page under / which requires Basic auth. Under /api/* REST API is served which does require JWT token passed in Authorization header.

In Chrome it works fine: when I load web page it asks me for Basic credentials and then webpage performs AJAX requests to /api/* along with JWT in Authorization header.

In Safari however, all AJAX requests are sent with Authorization header set to Basic credentials, and does not allow to set JWT in Authorization header...

Is there any workaround for this situation?

I am setting JWT for AJAX requests like this:

```<code>$.ajaxSetup({
  headers: {'Authorization': accessToken}
});
</code>```

答:
I have had a similair situation, it worked fine in Chrome/Firefox but Edge and mobile browsers had issues. The only problem i had was that i could not change the header that is used for JWT authentication (Authorization).

So instead, i used a custom header for the JWT token in my client app:

```<code>$.ajaxSetup({
  headers: {'X-JWT': accessToken}
});
</code>```

And in my webserver config (Nginx), i overwrite the Authorization header with my custom JWT header X-JWT:

```<code>        underscores_in_headers on;

        location /api/ {
                auth_basic off;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-NginX-Proxy true;
                proxy_pass http://127.0.0.1:8002/;
                proxy_set_header Authorization $http_x_jwt;
                proxy_ssl_session_reuse off;
                proxy_set_header Host $http_host;
                proxy_redirect off;
        }
</code>```

Body:
I have web page under / which requires Basic auth. Under /api/* REST API is served which does require JWT token passed in Authorization header.

In Chrome it works fine: when I load web page it asks me for Basic credentials and then webpage performs AJAX requests to /api/* along with JWT in Authorization header.

In Safari however, all AJAX requests are sent with Authorization header set to Basic credentials, and does not allow to set JWT in Authorization header...

Is there any workaround for this situation?

I am setting JWT for AJAX requests like this:

$.ajaxSetup({
  headers: {'Authorization': accessToken}
});

Body:
I have had a similair situation, it worked fine in Chrome/Firefox but Edge and mobile browsers had issues. The only problem i had was that i could not change the header that is used for JWT authentication (Authorization).

So instead, i used a custom header for the JWT token in my client app:

$.ajaxSetup({
  headers: {'X-JWT': accessToken}
});

And in my webserver config (Nginx), i overwrite the Authorization header with my custom JWT header X-JWT:

        underscores_in_headers on;

        location /api/ {
                auth_basic off;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-NginX-Proxy true;
                proxy_pass http://127.0.0.1:8002/;
                proxy_set_header Authorization $http_x_jwt;
                proxy_ssl_session_reuse off;
                proxy_set_header Host $http_host;
                proxy_redirect off;
        }


问:
Shuffle linked list in c with pointers
I am trying to shuffle a linked list in C.
I've thinking about do it by run all over the list and for each object I'll try to randomize an index and swap between them.
it's seem the code work, but after couple of time I run the code its seem that part of the list is gone, and sometime I get kicked out from the application.

Here is the code:

void main() {
    Song* head = createSong(1, "aaaa", "aaaa");
    Song* song2 = createSong(2, "bbbb", "bbbb");
    Song* song3 = createSong(3, "cccc", "cccc");
    addSongToTheEndOfTheList(head, song2);
    addSongToTheEndOfTheList(head, song3);
    printPlaylist(head);
    shuffleList(head);
    printPlaylist(head);
    //freePlaylist(head);
}
int countList(Song* head) {
    Song* currentSong = head;
    int i = 0;
    if (currentSong)
    {
        while (currentSong->next)
        {
            currentSong = currentSong->next;
            i++;
        }
        i++;
    }
    return i;
}
void swapSong(Song* head,Song* Source, int id) {
    Song* tempSong = (Song*)malloc(sizeof(Song));
    Song* currentSong = head;
    while(currentSong && currentSong->id != id){
        currentSong = currentSong->next;
    }
    if (currentSong) {
        tempSong->id = currentSong->id;
        tempSong->name = currentSong->name;
        tempSong->artist = currentSong->artist;
        tempSong->next = currentSong->next;
        currentSong->id = Source->id;
        currentSong->name = Source->name;
        currentSong->artist = Source->artist;
        currentSong->next = Source->next;
        Source->id = tempSong->id;
        Source->name = tempSong->name;
        Source->artist = tempSong->artist;
        Source->next = tempSong->next;
        free(tempSong);
    }
    else {
        printf("The list is empty.");
    }

}
void shuffleList(Song* head) {
    Song* currentSong = head;
    int listLength = countList(head);
    int randNum;
    srand(time(NULL));
    if (currentSong) {
        for (int i = 1; currentSong;i++) {
            swapSong(head, currentSong, rand()%listLength+1);
            currentSong = currentSong->next;
        }
    }
    else {
        printf("The list is empty.");
    }
}
```

The full code is here:
https://pastebin.com/fSS3rrTv

Hope you can help me figure it out.
Thanks!

答:
The error lies in swapSong. There are two possible ways to swap elements in a list:

either you swap data and do not touch next pointers

or you do not touch data add change pointers

The former is simpler for singly linked list with few internal data (which is your use case), the latter is more for doubly linked lists.

Here just change swapSong to:

```<code>void swapSong(Song* head,Song* Source, int id) {
    Song* tempSong = (Song*)malloc(sizeof(Song));
    Song* currentSong = head;
    while(currentSong && currentSong->id != id){
        currentSong = currentSong->next;
    }
    if (currentSong) {
        tempSong->id = currentSong->id;
        tempSong->name = currentSong->name;
        tempSong->artist = currentSong->artist;
        //tempSong->next = currentSong->next;
        currentSong->id = Source->id;
        currentSong->name = Source->name;
        currentSong->artist = Source->artist;
        //currentSong->next = Source->next;
        Source->id = tempSong->id;
        Source->name = tempSong->name;
        Source->artist = tempSong->artist;
        //Source->next = tempSong->next;
        free(tempSong);
    }
    else {
        printf("The list is empty.");
    }

}
</code>```

BTW, in Song struct, id is declared as an int *, while it is used as an int. Change to the following to remove some warnings:

```<code>typedef struct Song {
    int id;
    char* name;
    char* artist;
    struct Song* next;
}Song;
</code>```

And as noticed by @500-InternalServerError, you do not need to allocate anything in swapSong: just use a local struct:

```<code>void swapSong(Song* head,Song* Source, int id) {
    Song* currentSong = head;
    while(currentSong && currentSong->id != id){
        currentSong = currentSong->next;
    }
    if (currentSong) {
        Song tempSong = *currentSong;
        currentSong->id = Source->id;
        currentSong->name = Source->name;
        currentSong->artist = Source->artist;
        Source->id = tempSong.id;
        Source->name = tempSong.name;
        Source->artist = tempSong.artist;
    }
    else {
        printf("The list is empty.");
    }
}
</code>```

Title: Shuffle linked list in c with pointers

Body:
I am trying to shuffle a linked list in C.
I've thinking about do it by run all over the list and for each object I'll try to randomize an index and swap between them.
it's seem the code work, but after couple of time I run the code its seem that part of the list is gone, and sometime I get kicked out from the application.

Here is the code:

void main() {
    Song* head = createSong(1, "aaaa", "aaaa");
    Song* song2 = createSong(2, "bbbb", "bbbb");
    Song* song3 = createSong(3, "cccc", "cccc");
    addSongToTheEndOfTheList(head, song2);
    addSongToTheEndOfTheList(head, song3);
    printPlaylist(head);
    shuffleList(head);
    printPlaylist(head);
    //freePlaylist(head);
}
int countList(Song* head) {
    Song* currentSong = head;
    int i = 0;
    if (currentSong)
    {
        while (currentSong->next)
        {
            currentSong = currentSong->next;
            i++;
        }
        i++;
    }
    return i;
}
void swapSong(Song* head,Song* Source, int id) {
    Song* tempSong = (Song*)malloc(sizeof(Song));
    Song* currentSong = head;
    while(currentSong && currentSong->id != id){
        currentSong = currentSong->next;
    }
    if (currentSong) {
        tempSong->id = currentSong->id;
        tempSong->name = currentSong->name;
        tempSong->artist = currentSong->artist;
        tempSong->next = currentSong->next;
        currentSong->id = Source->id;
        currentSong->name = Source->name;
        currentSong->artist = Source->artist;
        currentSong->next = Source->next;
        Source->id = tempSong->id;
        Source->name = tempSong->name;
        Source->artist = tempSong->artist;
        Source->next = tempSong->next;
        free(tempSong);
    }
    else {
        printf("The list is empty.");
    }

}
void shuffleList(Song* head) {
    Song* currentSong = head;
    int listLength = countList(head);
    int randNum;
    srand(time(NULL));
    if (currentSong) {
        for (int i = 1; currentSong;i++) {
            swapSong(head, currentSong, rand()%listLength+1);
            currentSong = currentSong->next;
        }
    }
    else {
        printf("The list is empty.");
    }
}

The full code is here:
https://pastebin.com/fSS3rrTv

Hope you can help me figure it out.
Thanks!

Body:
The error lies in swapSong. There are two possible ways to swap elements in a list:

either you swap data and do not touch next pointers

or you do not touch data add change pointers

The former is simpler for singly linked list with few internal data (which is your use case), the latter is more for doubly linked lists.

Here just change swapSong to:

void swapSong(Song* head,Song* Source, int id) {
    Song* tempSong = (Song*)malloc(sizeof(Song));
    Song* currentSong = head;
    while(currentSong && currentSong->id != id){
        currentSong = currentSong->next;
    }
    if (currentSong) {
        tempSong->id = currentSong->id;
        tempSong->name = currentSong->name;
        tempSong->artist = currentSong->artist;
        //tempSong->next = currentSong->next;
        currentSong->id = Source->id;
        currentSong->name = Source->name;
        currentSong->artist = Source->artist;
        //currentSong->next = Source->next;
        Source->id = tempSong->id;
        Source->name = tempSong->name;
        Source->artist = tempSong->artist;
        //Source->next = tempSong->next;
        free(tempSong);
    }
    else {
        printf("The list is empty.");
    }

}

BTW, in Song struct, id is declared as an int *, while it is used as an int. Change to the following to remove some warnings:

typedef struct Song {
    int id;
    char* name;
    char* artist;
    struct Song* next;
}Song;

And as noticed by @500-InternalServerError, you do not need to allocate anything in swapSong: just use a local struct:

void swapSong(Song* head,Song* Source, int id) {
    Song* currentSong = head;
    while(currentSong && currentSong->id != id){
        currentSong = currentSong->next;
    }
    if (currentSong) {
        Song tempSong = *currentSong;
        currentSong->id = Source->id;
        currentSong->name = Source->name;
        currentSong->artist = Source->artist;
        Source->id = tempSong.id;
        Source->name = tempSong.name;
        Source->artist = tempSong.artist;
    }
    else {
        printf("The list is empty.");
    }
}


问:
Most elegant and fastest way to remove all leading zeroes in perl string
I wrote rmlz function for trimming all leading zeroes from string.

```<code># remove all leading zeroes from string
use strict;
use warnings;
use feature 'say';

sub rmlz {
  my ( $str ) = @_;
  if ( $str =~ /^(.[0])/ ) {
    return substr( $str, length($1));
  }
  return $str;
}

say rmlz('0050625'); # must return 50625
</code>```

Is there most elegant and clear way to rewrite this code ? Or regexp+length+substr is best option ?

答:
Use the substitute operator

```<code>$str =~ s/^0+//
</code>```

Replace the beginning of the string followed by 1 or more 0 with nothing instead of

```<code>if ( $str =~ /^(.[0])/ ) {
    return substr( $str, length($1));
}
</code>```

Body:
I wrote rmlz function for trimming all leading zeroes from string.

# remove all leading zeroes from string
use strict;
use warnings;
use feature 'say';

sub rmlz {
  my ( $str ) = @_;
  if ( $str =~ /^(.[0])/ ) {
    return substr( $str, length($1));
  }
  return $str;
}

say rmlz('0050625'); # must return 50625

Is there most elegant and clear way to rewrite this code ? Or regexp+length+substr is best option ?

Body:
Use the substitute operator

$str =~ s/^0+//

Replace the beginning of the string followed by 1 or more 0 with nothing instead of

if ( $str =~ /^(.[0])/ ) {
    return substr( $str, length($1));
}


问:
error while trying to pass location cordinate from a list view to a map activity
i have a list view contains the locations coordinate (late,long) and i'm trying to pass them to a map activity to show it on map

this is on android studio and Kotlin

```<code>listView.setOnItemClickListener { parent, view, position, id ->

        val time = usersList.get(position).time
        val long:String = usersList.get(position).long
        val late :String = usersList.get(position).late
startActivity(Intent(this, MapsActivity2::class.java).putExtra("long",long).putExtra("late",late))
}
</code>```

```<code>class MapsActivity2 : AppCompatActivity(), OnMapReadyCallback {

private lateinit var mMap: GoogleMap

var long:String = intent.getStringExtra("long")
var late:String = intent.getStringExtra("late")

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_maps2)

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    val mapFragment = supportFragmentManager
        .findFragmentById(R.id.map) as SupportMapFragment
    mapFragment.getMapAsync(this)
}

override fun onMapReady(googleMap: GoogleMap) {
    mMap = googleMap

    // Add a marker in Sydney and move the camera
    val sydney = LatLng(long.toDouble(), late.toDouble())
    mMap.addMarker(MarkerOptions().position(sydney).title("jh"))
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
}
}
</code>```

Process: com.example.firebase, PID: 32463
      java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.firebase/com.example.firebase.MapsActivity2}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3289)
          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3548)
          at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:86)
          at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
          at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2155)
          at android.os.Handler.dispatchMessage(Handler.java:109)
          at android.os.Looper.loop(Looper.java:207)
          at android.app.ActivityThread.main(ActivityThread.java:7539)
          at java.lang.reflect.Method.invoke(Native Method)
          at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:958)
       Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
          at com.example.firebase.MapsActivity2.(MapsActivity2.kt:19)
          at java.lang.Class.newInstance(Native Method)
          at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
          at android.support.v4.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:43)
          at android.app.Instrumentation.newActivity(Instrumentation.java:1224)
          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3274)

答:
```<code>var long:String = intent.getStringExtra("long")
var late:String = intent.getStringExtra("late")
</code>```

Above code should be in onCreate();

Body:
i have a list view contains the locations coordinate (late,long) and i'm trying to pass them to a map activity to show it on map

this is on android studio and Kotlin

listView.setOnItemClickListener { parent, view, position, id ->

        val time = usersList.get(position).time
        val long:String = usersList.get(position).long
        val late :String = usersList.get(position).late
startActivity(Intent(this, MapsActivity2::class.java).putExtra("long",long).putExtra("late",late))
}

class MapsActivity2 : AppCompatActivity(), OnMapReadyCallback {

private lateinit var mMap: GoogleMap

var long:String = intent.getStringExtra("long")
var late:String = intent.getStringExtra("late")

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_maps2)

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    val mapFragment = supportFragmentManager
        .findFragmentById(R.id.map) as SupportMapFragment
    mapFragment.getMapAsync(this)
}

override fun onMapReady(googleMap: GoogleMap) {
    mMap = googleMap

    // Add a marker in Sydney and move the camera
    val sydney = LatLng(long.toDouble(), late.toDouble())
    mMap.addMarker(MarkerOptions().position(sydney).title("jh"))
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
}
}

Process: com.example.firebase, PID: 32463
      java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.firebase/com.example.firebase.MapsActivity2}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3289)
          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3548)
          at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:86)
          at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
          at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2155)
          at android.os.Handler.dispatchMessage(Handler.java:109)
          at android.os.Looper.loop(Looper.java:207)
          at android.app.ActivityThread.main(ActivityThread.java:7539)
          at java.lang.reflect.Method.invoke(Native Method)
          at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:958)
       Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Intent.getStringExtra(java.lang.String)' on a null object reference
          at com.example.firebase.MapsActivity2.(MapsActivity2.kt:19)
          at java.lang.Class.newInstance(Native Method)
          at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
          at android.support.v4.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:43)
          at android.app.Instrumentation.newActivity(Instrumentation.java:1224)
          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3274)

Body:
var long:String = intent.getStringExtra("long")
var late:String = intent.getStringExtra("late")

Above code should be in onCreate();


问:
Custom UIView alert not appearing after successful Login
I'm trying to trigger a small, timed UIView popup after a user successfully logs in, however, I need it to appear on the screen after the LoginController is dismissed. Can anyone help in understanding where I am going wrong here? Perhaps it is necessary to trigger it from the rootViewController after the view is dismissed, but I don't know how to trigger it from the LoginController.

The LoginController dismisses properly, and the print statement is logging so I know the completion block is working properly, however the UIView is not staying on top of other views.

Should I create some sort of extension that allows me to trigger it from another class? Any tips would be greatly appreciated.

LoginController()

```<code>DispatchQueue.main.async {

    self.view.window?.rootViewController?.dismiss(animated: true, completion: {
                // completion handler after successful login
                print("completion handler: logged in")
                self.showAlert()
                })
    }
</code>```

Custom alert/popup functions

```<code>func showAlert()    {
    popupAlert = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 200))
    popupAlert?.backgroundColor = .red
    self.view.addSubview(popupAlert)

    Timer.scheduledTimer(timeInterval: 4.0, target: self, selector: #selector(dismissAlert), userInfo: nil, repeats: false)
}

@objc func dismissAlert()   {
    if popupAlert != nil {
        popupAlert.removeFromSuperview()
    }
}
</code>```

答:
Please try to add popupAlert on app window instead of self.view</p>

```<code> func showAlert()    {
    popupAlert = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 200))
    popupAlert?.backgroundColor = .red
    let app = UIApplication.shared.delegate as! AppDelegate
    app.window?.addSubview(popupAlert)

    Timer.scheduledTimer(timeInterval: 4.0, target: self, selector: #selector(dismissAlert), userInfo: nil, repeats: false)
}
</code>```

Body:
I'm trying to trigger a small, timed UIView popup after a user successfully logs in, however, I need it to appear on the screen after the LoginController is dismissed. Can anyone help in understanding where I am going wrong here? Perhaps it is necessary to trigger it from the rootViewController after the view is dismissed, but I don't know how to trigger it from the LoginController.

The LoginController dismisses properly, and the print statement is logging so I know the completion block is working properly, however the UIView is not staying on top of other views.

Should I create some sort of extension that allows me to trigger it from another class? Any tips would be greatly appreciated.

LoginController()

DispatchQueue.main.async {

    self.view.window?.rootViewController?.dismiss(animated: true, completion: {
                // completion handler after successful login
                print("completion handler: logged in")
                self.showAlert()
                })
    }

Custom alert/popup functions

func showAlert()    {
    popupAlert = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 200))
    popupAlert?.backgroundColor = .red
    self.view.addSubview(popupAlert)

    Timer.scheduledTimer(timeInterval: 4.0, target: self, selector: #selector(dismissAlert), userInfo: nil, repeats: false)
}

@objc func dismissAlert()   {
    if popupAlert != nil {
        popupAlert.removeFromSuperview()
    }
}

Body:
Please try to add popupAlert on app window instead of self.view

 func showAlert()    {
    popupAlert = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 200))
    popupAlert?.backgroundColor = .red
    let app = UIApplication.shared.delegate as! AppDelegate
    app.window?.addSubview(popupAlert)

    Timer.scheduledTimer(timeInterval: 4.0, target: self, selector: #selector(dismissAlert), userInfo: nil, repeats: false)
}


问:
How to make a batch script to run commands on a remote machine using credentials
I have wrote some batch scripts to perform docker commands on a machine and made it run using c# program. I can successfully run those batch scripts in my local machine, but I want it to run on a remote machine. How can I do that by giving remote machine access credentials? I am looking for batch commands that will first connect to the remote machine and then execute its body in remote machine.
A sample batch script is as below.

```<code>::Start an exited container
::Iam expecting some code here to connect to a remote machine
@echo off
docker start %1
</code>```

Or, Is there any option to do it through c# program?

答:
Try using PsExec
https://learn.microsoft.com/en-us/sysinternals/downloads/psexec

This is a light weight replacement for telnet

Body:
I have wrote some batch scripts to perform docker commands on a machine and made it run using c# program. I can successfully run those batch scripts in my local machine, but I want it to run on a remote machine. How can I do that by giving remote machine access credentials? I am looking for batch commands that will first connect to the remote machine and then execute its body in remote machine.
A sample batch script is as below.

::Start an exited container
::Iam expecting some code here to connect to a remote machine
@echo off
docker start %1

Or, Is there any option to do it through c# program?


问:
Why my app gets wrong strings from resources for localization?
I have created three files for localisation: "en","ru","uk" and I saw problem app can get some strings right and some string wrong. What it means? For example one layout during its working can contain several locales instead one single and it is wrong. I saw that some users solved this problem via adding some lines of code to buil.gradle but maybe we have another solution and why did it worked well several weeks ago when my project was in Java. I'm sure that it can't be caused by moving from one language to another. At recyclerView I can see similar problem. At activity I can set my current language like this:

```<code>sp = this.getSharedPreferences("app_data", 0)
        val lang = sp!!.getString("language", Locale.getDefault().language)
        val locale = Locale(lang)
        Locale.setDefault(locale)
        val config = Configuration()
        config.setLocale(locale)

        resources.updateConfiguration(
                config, resources.displayMetrics
        )
</code>```

but updateConfiguration is deprecated and I looked for some new variants which will work. Then I found this question but it didn't help me. I need to set language at RV items, activities and fragments, but I can't do it. Why does it happen and how I can solve this problem?

答:
I actually JUST had to do this myself. Its a pain, especially for newer devices.

First, you need a locale helper:

```<code>package za.co.overtake.onlinetrucks.utils;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.preference.PreferenceManager;

import java.util.Locale;

/**
 * This class is used to change your application locale and persist this change for the next time
 * that your app is going to be used.
 * <p/>
 * You can also change the locale of your application on the fly by using the setLocale method.
 * <p/>
 * Created by gunhansancar on 07/10/15.
 */
public class LocaleHelper {

    private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";

    public static Context onAttach(Context context) {
      String lang = getPersistedData(context, Locale.getDefault().getLanguage());
      return setLocale(context, lang);
    }

    public static Context onAttach(Context context, String defaultLanguage) {
      String lang = getPersistedData(context, defaultLanguage);
      return setLocale(context, lang);
    }

    public static String getLanguage(Context context) {
      return getPersistedData(context, Locale.getDefault().getLanguage());
    }

    public static Context setLocale(Context context, String language) {
      persist(context, language);

      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        return updateResources(context, language);
      }

    return updateResourcesLegacy(context, language);
    }

    private static String getPersistedData(Context context, String defaultLanguage) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
}

private static void persist(Context context, String language) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = preferences.edit();

    editor.putString(SELECTED_LANGUAGE, language);
    editor.apply();
}

@TargetApi(Build.VERSION_CODES.N)
private static Context updateResources(Context context, String language) {
    Locale locale = new Locale(language);
    Locale.setDefault(locale);

    Configuration configuration = context.getResources().getConfiguration();
    configuration.setLocale(locale);
    configuration.setLayoutDirection(locale);

    return context.createConfigurationContext(configuration);
}

@SuppressWarnings("deprecation")
private static Context updateResourcesLegacy(Context context, String language)
{
    Locale locale = new Locale(language);
    Locale.setDefault(locale);

    Resources resources = context.getResources();

    Configuration configuration = resources.getConfiguration();
    configuration.locale = locale;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        configuration.setLayoutDirection(locale);
    }

    resources.updateConfiguration(configuration,
resources.getDisplayMetrics());

    return context;
}
}
</code>```

This takes care of switching the language as well as using the deprecated or non-deprecated method.

THEN in each activity, you need to override this method ( I suggest you just make a base activity that each activity extends):

```<code>@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(LocaleHelper.onAttach(base));
}
</code>```

This should take care of MOST cases. However, I use ViewModels, and for some reason when I do getApplication.getResources().getString() it would sometimes return the wrong string. In such a case, I made a Utility method to take care of this issue:

```<code>public static Resources getResources(Context context) {
    return LocaleHelper.onAttach(context).getResources();
}
</code>```

So now I can use this method instead of the usual getResources().

It's a REAL pain, but it's the only way I could get translations to work on both devices higher than android 8 AND lower than android8.

I will post the links to some of this in a bit...

EDIT: Also, like previous answers stated, you need to recreate the activity from which you had changed the language.

Links: https://proandroiddev.com/change-language-programmatically-at-runtime-on-android-5e6bc15c758

https://gunhansancar.com/change-language-programmatically-in-android/

Body:
I have created three files for localisation: "en","ru","uk" and I saw problem app can get some strings right and some string wrong. What it means? For example one layout during its working can contain several locales instead one single and it is wrong. I saw that some users solved this problem via adding some lines of code to buil.gradle but maybe we have another solution and why did it worked well several weeks ago when my project was in Java. I'm sure that it can't be caused by moving from one language to another. At recyclerView I can see similar problem. At activity I can set my current language like this:

sp = this.getSharedPreferences("app_data", 0)
        val lang = sp!!.getString("language", Locale.getDefault().language)
        val locale = Locale(lang)
        Locale.setDefault(locale)
        val config = Configuration()
        config.setLocale(locale)

        resources.updateConfiguration(
                config, resources.displayMetrics
        )

but updateConfiguration is deprecated and I looked for some new variants which will work. Then I found this question but it didn't help me. I need to set language at RV items, activities and fragments, but I can't do it. Why does it happen and how I can solve this problem?

Body:
I actually JUST had to do this myself. Its a pain, especially for newer devices.

First, you need a locale helper:

package za.co.overtake.onlinetrucks.utils;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.preference.PreferenceManager;

import java.util.Locale;

/**
 * This class is used to change your application locale and persist this change for the next time
 * that your app is going to be used.
 * <p/>
 * You can also change the locale of your application on the fly by using the setLocale method.
 * <p/>
 * Created by gunhansancar on 07/10/15.
 */
public class LocaleHelper {

    private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";

    public static Context onAttach(Context context) {
      String lang = getPersistedData(context, Locale.getDefault().getLanguage());
      return setLocale(context, lang);
    }

    public static Context onAttach(Context context, String defaultLanguage) {
      String lang = getPersistedData(context, defaultLanguage);
      return setLocale(context, lang);
    }

    public static String getLanguage(Context context) {
      return getPersistedData(context, Locale.getDefault().getLanguage());
    }

    public static Context setLocale(Context context, String language) {
      persist(context, language);

      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        return updateResources(context, language);
      }

    return updateResourcesLegacy(context, language);
    }

    private static String getPersistedData(Context context, String defaultLanguage) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
}

private static void persist(Context context, String language) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = preferences.edit();

    editor.putString(SELECTED_LANGUAGE, language);
    editor.apply();
}

@TargetApi(Build.VERSION_CODES.N)
private static Context updateResources(Context context, String language) {
    Locale locale = new Locale(language);
    Locale.setDefault(locale);

    Configuration configuration = context.getResources().getConfiguration();
    configuration.setLocale(locale);
    configuration.setLayoutDirection(locale);

    return context.createConfigurationContext(configuration);
}

@SuppressWarnings("deprecation")
private static Context updateResourcesLegacy(Context context, String language)
{
    Locale locale = new Locale(language);
    Locale.setDefault(locale);

    Resources resources = context.getResources();

    Configuration configuration = resources.getConfiguration();
    configuration.locale = locale;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        configuration.setLayoutDirection(locale);
    }

    resources.updateConfiguration(configuration,
resources.getDisplayMetrics());

    return context;
}
}

This takes care of switching the language as well as using the deprecated or non-deprecated method.

THEN in each activity, you need to override this method ( I suggest you just make a base activity that each activity extends):

@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(LocaleHelper.onAttach(base));
}

This should take care of MOST cases. However, I use ViewModels, and for some reason when I do getApplication.getResources().getString() it would sometimes return the wrong string. In such a case, I made a Utility method to take care of this issue:

public static Resources getResources(Context context) {
    return LocaleHelper.onAttach(context).getResources();
}

So now I can use this method instead of the usual getResources().

It's a REAL pain, but it's the only way I could get translations to work on both devices higher than android 8 AND lower than android8.

I will post the links to some of this in a bit...

EDIT: Also, like previous answers stated, you need to recreate the activity from which you had changed the language.

Links: https://proandroiddev.com/change-language-programmatically-at-runtime-on-android-5e6bc15c758

https://gunhansancar.com/change-language-programmatically-in-android/


问:
partial row-sums in multidimensional arrays
I have a question on how to apply R functions to multidimensional arrays.

For example, consider this operation, where I reduce an entry by the sum of other entries.

```<code>ppl["2012",,,,,1] <- ppl["2012",,,,,1]
- ppl["2012",,,,,2] - ppl["2012",,,,,3] - ppl["2012",,,,,4]
- ppl["2012",,,,,5] - ppl["2012",,,,,6] - ppl["2012",,,,,7]
- ppl["2012",,,,,8]
</code>```

While in this case subtracting individual values might be feasible, I would prefer a vector-oriented approach.

If I was familiar with multidimensional matrix algebra I could probably come up with the matrix that performs the necessary operation when applied, but this is too complex given the number of dimensions involved.

sum(ppl["2012",,,,,2:8]) is not the correct solution, as sum() always returns scalars.

I could use loops that perform the necessary operations, but that contradicts the paradigm of vector-oriented programming.

Thanks for your help!

Edit: And here is the solution to the original problem, based on Andrie's suggestion:
ppl[paste(i),land,,,,1] <- ppl[paste(i),land,,,,1] - apply(ppl[paste(i),land,,,,2:8],c(1,2,3),sum)

答:
EDITED

Here is an example of using apply and sum to return the sum computed across a multi-dimensional table:

```<code>mat <- array(1:27, dim=c(3, 3, 3))
</code>```

Let's say you'd like to compute the sum of the third dimension for each combination of the first two dimension.

Then the code to do this becomes:

```<code>apply(mat, c(1,2), sum)

     [,1] [,2] [,3]
[1,]   30   39   48
[2,]   33   42   51
[3,]   36   45   54
</code>```

Body:
I have a question on how to apply R functions to multidimensional arrays.

For example, consider this operation, where I reduce an entry by the sum of other entries.

ppl["2012",,,,,1] <- ppl["2012",,,,,1]
- ppl["2012",,,,,2] - ppl["2012",,,,,3] - ppl["2012",,,,,4]
- ppl["2012",,,,,5] - ppl["2012",,,,,6] - ppl["2012",,,,,7]
- ppl["2012",,,,,8]

While in this case subtracting individual values might be feasible, I would prefer a vector-oriented approach.

If I was familiar with multidimensional matrix algebra I could probably come up with the matrix that performs the necessary operation when applied, but this is too complex given the number of dimensions involved.

sum(ppl["2012",,,,,2:8]) is not the correct solution, as sum() always returns scalars.

I could use loops that perform the necessary operations, but that contradicts the paradigm of vector-oriented programming.

Thanks for your help!

Edit: And here is the solution to the original problem, based on Andrie's suggestion:
ppl[paste(i),land,,,,1] <- ppl[paste(i),land,,,,1] - apply(ppl[paste(i),land,,,,2:8],c(1,2,3),sum)

Body:
EDITED

Here is an example of using apply and sum to return the sum computed across a multi-dimensional table:

mat <- array(1:27, dim=c(3, 3, 3))

Let's say you'd like to compute the sum of the third dimension for each combination of the first two dimension.

Then the code to do this becomes:

apply(mat, c(1,2), sum)

     [,1] [,2] [,3]
[1,]   30   39   48
[2,]   33   42   51
[3,]   36   45   54


问:
Protractor Not able to click the element While iterating the list of Elements
clickClaimIDFromList(claimId) {

```<code>   element.all(by.xpath('//*[@data-qa="dashboard.claim"]')).then(async (items) => {
            // console.log(items[0].getText());
            await expect(items[0].getText()).to.eventually.equal('12345');

            items.forEach(item => {
                     item.getText().then(async (text) => {
                            if (text === '12345') {
                                await console.log(item.getText());
                                await this.wait(10000);
                                return item.click();
                            }
                        }
                    );
                }
            );
        }

     );

}
</code>```

This code is getting executed successfully with out clicking the element. Could some one help me to rewrite it?

答:
As you are using async/await keywords I am assuming your have the control flow disabled in your framework (by setting SELENIUM_PROMISE_MANAGER: false in conf.js).

If that is the case there is no need to be using so many .then's as await provides a much easier way to handle them.

Your test could be passing because it is hitting the failing the text === '12345' check in your if and therefore never attempting to click.

```<code>//Make function async
async clickClaimIDFromList(claimId) {

  let allElems = await element.all(by.xpath('//*[@data-qa="dashboard.claim"]'));

  //don't await expects, await what is occuring inside them if you need to
  expect(await allElems[0].getText()).to.eventually.equal('12345');

  for (let i = 0; i < allElems.length; i++) {
    let item = allElems[i];

    //Save the result of the getText to a variable
    let itemText = await item.getText();
    console.log(itemText);

    if (itemText === '12345') {
      await this.wait(10000);

      //No need to return the click, we can await it here
      await item.click();
    } else {
      console.log('else is being hit');
  }
}
</code>```

Note: I have not tested this code but the logic should be correct

Body:
clickClaimIDFromList(claimId) {

   element.all(by.xpath('//*[@data-qa="dashboard.claim"]')).then(async (items) => {
            // console.log(items[0].getText());
            await expect(items[0].getText()).to.eventually.equal('12345');

            items.forEach(item => {
                     item.getText().then(async (text) => {
                            if (text === '12345') {
                                await console.log(item.getText());
                                await this.wait(10000);
                                return item.click();
                            }
                        }
                    );
                }
            );
        }

     );

}

This code is getting executed successfully with out clicking the element. Could some one help me to rewrite it?

Body:
As you are using async/await keywords I am assuming your have the control flow disabled in your framework (by setting SELENIUM_PROMISE_MANAGER: false in conf.js).

If that is the case there is no need to be using so many .then's as await provides a much easier way to handle them.

Your test could be passing because it is hitting the failing the text === '12345' check in your if and therefore never attempting to click.

//Make function async
async clickClaimIDFromList(claimId) {

  let allElems = await element.all(by.xpath('//*[@data-qa="dashboard.claim"]'));

  //don't await expects, await what is occuring inside them if you need to
  expect(await allElems[0].getText()).to.eventually.equal('12345');

  for (let i = 0; i < allElems.length; i++) {
    let item = allElems[i];

    //Save the result of the getText to a variable
    let itemText = await item.getText();
    console.log(itemText);

    if (itemText === '12345') {
      await this.wait(10000);

      //No need to return the click, we can await it here
      await item.click();
    } else {
      console.log('else is being hit');
  }
}

Note: I have not tested this code but the logic should be correct


问:
Scaling an SVG that is not inline
First, let me apologise for not knowing the proper terms for things. I'm new to SVG and am working to a tight deadline.

I wanted some scalable icons for a website I am redesigning and I persuaded a graphic artist friend of mine to create these icons for me in Inkscape. These icons are meant to be very small, roughly 25 pixels x 25 pixels and to indicate email links, internal links and external links. I plan to use the appropriate one on each anchor tag in my site.

The icons she created are quite nice but render very large in the browser. Opening the icons in the Eclipse text editor, I can see the following values:

```<code>viewBox="0 0 540 540"
height="540"
width="540"

 y="0"

 preserveAspectRatio="none"
 height="540"
 width="540" />
</code>```

In the course of trying to figure out how to make the icons smaller, I've seen multiple references to this article as a good one for scaling SVGs: https://css-tricks.com/scale-svg/

Unfortunately, I'm getting quite confused on what I need to do in my case since I don't have an inline SVG. (I'm not sure what mine is properly called: an external SVG?) Also, I'm not using IMG or SVG tags in my HTML markup. I've created special classes of anchors called internal-link, external-link, and email-link and I'm pointing to my SVGs via ::before pseudo-selectors as in this example:

```<code>/* External link */
.external-link {
    background-color: green;
}
.external-link::before {
    content: url("../images/link-external-ana.svg") "  ";
}
</code>```

This approach allows me to keep my HTML markup nice and simple, as in this example:

```<code><p>Skype is a widely used
communications program that works on many computers, tablets, and WiFi-   connected smartphones.
Skype can be downloaded at <a class="external-link"   href="https://www.skype.com/en/" target="_blank">the Skype website</a>.</p>
</code>```

Unfortunately, the article doesn't address my approach where I am NOT using IMG or SRC tags or the content property of a ::before selector so I'm really not sure what to do to make my icon suitably small.

For what it's worth, I have tinkered with the icons themselves and changed the aforementioned values so that the 540 was changed to 35 in each instance and y was changed to 10 to push it down a bit to be roughly lined up with the baseline of the text shown in the anchor but I have to believe there is a better approach. Editing the icon itself would seem to limit it to being only one size forever and forcing me to make multiple versions of the icon for each size I want, which would appear to defeat the purpose of making them scalable in the first place. I'm hoping I can leave the icon unaltered and ONLY adjust the CSS to control the scaling.

Is that possible? If so, how?

答:
I understand you need to use the svg icons with the ::before

In the next example I'm using the svg image as background image of the ::before and background-size:cover. I'm also setting the width and the height of ::before proportional to the size of the image.

.external-link{width:100px; height:100px;margin:20px auto;}

.external-link:before{
content:"";
display:block;
width:30px;
height:35px;
background:skyblue;
background-image:url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/apple.svg);
background-size:cover}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="external-link"></div></code>```

Title: Scaling an SVG that is not inline

Body:
First, let me apologise for not knowing the proper terms for things. I'm new to SVG and am working to a tight deadline.

I wanted some scalable icons for a website I am redesigning and I persuaded a graphic artist friend of mine to create these icons for me in Inkscape. These icons are meant to be very small, roughly 25 pixels x 25 pixels and to indicate email links, internal links and external links. I plan to use the appropriate one on each anchor tag in my site.

The icons she created are quite nice but render very large in the browser. Opening the icons in the Eclipse text editor, I can see the following values:

viewBox="0 0 540 540"
height="540"
width="540"

 y="0"

 preserveAspectRatio="none"
 height="540"
 width="540" />

In the course of trying to figure out how to make the icons smaller, I've seen multiple references to this article as a good one for scaling SVGs: https://css-tricks.com/scale-svg/

Unfortunately, I'm getting quite confused on what I need to do in my case since I don't have an inline SVG. (I'm not sure what mine is properly called: an external SVG?) Also, I'm not using IMG or SVG tags in my HTML markup. I've created special classes of anchors called internal-link, external-link, and email-link and I'm pointing to my SVGs via ::before pseudo-selectors as in this example:

/* External link */
.external-link {
    background-color: green;
}
.external-link::before {
    content: url("../images/link-external-ana.svg") "  ";
}

This approach allows me to keep my HTML markup nice and simple, as in this example:

Skype is a widely used
communications program that works on many computers, tablets, and WiFi-   connected smartphones.
Skype can be downloaded at the Skype website.

Unfortunately, the article doesn't address my approach where I am NOT using IMG or SRC tags or the content property of a ::before selector so I'm really not sure what to do to make my icon suitably small.

For what it's worth, I have tinkered with the icons themselves and changed the aforementioned values so that the 540 was changed to 35 in each instance and y was changed to 10 to push it down a bit to be roughly lined up with the baseline of the text shown in the anchor but I have to believe there is a better approach. Editing the icon itself would seem to limit it to being only one size forever and forcing me to make multiple versions of the icon for each size I want, which would appear to defeat the purpose of making them scalable in the first place. I'm hoping I can leave the icon unaltered and ONLY adjust the CSS to control the scaling.

Is that possible? If so, how?

Body:
I understand you need to use the svg icons with the ::before

In the next example I'm using the svg image as background image of the ::before and background-size:cover. I'm also setting the width and the height of ::before proportional to the size of the image.

.external-link{width:100px; height:100px;margin:20px auto;}

.external-link:before{
content:"";
display:block;
width:30px;
height:35px;
background:skyblue;
background-image:url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/222579/apple.svg);
background-size:cover}

<div class="external-link"></div>


问:
Truncate span inside td
I'm using Materialize classes to create a "photo placeholder" to the user which contains the first letter of his name.

I'm having trouble with long names inside the  tag. I do not want the name to break when it's too long. Because of that, I've tried to apply class="truncate" into the spam that contains the name, but it failed to truncate.

How can I solve this?

main {
  padding: 16px;
}

table {
  table-layout: fixed;
}

td {
  width: 33.33%;
}

.photo-placeholder {
  width: 40px;
  height: 40px;
  line-height: 40px;
  border-radius: 50%;
  text-align: center;
  display: inline-block;
  background-color: crimson;
  color: white;
}

.truncate {
    display: block;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

<main>

  <table id="table1" class="white z-depth-1 centered">
    <thead>
      <tr>
        <th>Col 1</th>
        <th>Col 2</th>
        <th>Col 3</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td data-label="Col 1">
          <span class="photo-placeholder">P</span>
          <span class="truncate">Pedro Luis Arend Gonçalves</span>
        </td>
        <td data-label="Col 2">Info 2</td>
        <td data-label="Col 3">Info 3</td>
      </tr>
    </tbody>
  </table>

</main></code>```

JSFiddle

Expected result:

答:
It seems that the "truncate" class sets the element to display:block, which puts it on its own line.

One solution might be to set it to display:inline-block and set it's width to the remaining space in the table cell. Below, I've calculated the appropriate width by using calc(). I've also eliminated the white space between the two  elements so it won't contribute extra width.

main {
  padding: 16px;
}

table {
  table-layout: fixed;
}

td {
  width: 33.33%;
}

.photo-placeholder {
  width: 40px;
  height: 40px;
  line-height: 40px;
  border-radius: 50%;
  text-align: center;
  display: inline-block;
  background-color: crimson;
  color: white;
}

#table1 .truncate {
  display: inline-block;
  width: calc(100% - 40px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

<main>

  <table id="table1" class="white z-depth-1 centered">
    <thead>
      <tr>
        <th>Col 1</th>
        <th>Col 2</th>
        <th>Col 3</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td data-label="Col 1">
          <span class="photo-placeholder">P
          </span><span class="truncate">Pedro Luis Arend Gonçalves</span>
        </td>
        <td data-label="Col 2">Info 2</td>
        <td data-label="Col 3">Info 3</td>
      </tr>
    </tbody>
  </table>

</main></code>```

To avoid having to calculate the width, you can simply float the placeholder left, like this:

main {
  padding: 16px;
}

table {
  table-layout: fixed;
}

td {
  width: 33.33%;
}

.photo-placeholder {
  float: left;
  width: 40px;
  height: 40px;
  line-height: 40px;
  border-radius: 50%;
  text-align: center;
  background-color: crimson;
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

<main>

  <table id="table1" class="white z-depth-1 centered">
    <thead>
      <tr>
        <th>Col 1</th>
        <th>Col 2</th>
        <th>Col 3</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td data-label="Col 1">
          <span class="photo-placeholder">P</span>
          <span class="truncate">Pedro Luis Arend Gonçalves</span>
        </td>
        <td data-label="Col 2">Info 2</td>
        <td data-label="Col 3">Info 3</td>
      </tr>
    </tbody>
  </table>

</main></code>```

Here's a different method that uses a flexbox container. I like this one because it's easier to vertically center the two elements with align-items:center.

main {
  padding: 16px;
}

table {
  table-layout: fixed;
}

td {
  width: 33.33%;
}

.photoContent {
  display: flex;
  align-items: center;
}

.photo-placeholder {
  flex: 0 0 40px;
  height: 40px;
  line-height: 40px;
  border-radius: 50%;
  text-align: center;
  background-color: crimson;
  color: white;
  margin: 0 0.5em 0 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

<main>

  <table id="table1" class="white z-depth-1 centered">
    <thead>
      <tr>
        <th>Col 1</th>
        <th>Col 2</th>
        <th>Col 3</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td data-label="Col 1">
          <div class="photoContent">
            <span class="photo-placeholder">P</span>
            <span class="truncate">Pedro Luis Arend Gonçalves</span>
          </div>
        </td>
        <td data-label="Col 2">Info 2</td>
        <td data-label="Col 3">Info 3</td>
      </tr>
    </tbody>
  </table>

</main></code>```

Title: Truncate span inside td

Body:
I'm using Materialize classes to create a "photo placeholder" to the user which contains the first letter of his name.

I'm having trouble with long names inside the  tag. I do not want the name to break when it's too long. Because of that, I've tried to apply class="truncate" into the spam that contains the name, but it failed to truncate.

How can I solve this?

main {
  padding: 16px;
}

table {
  table-layout: fixed;
}

td {
  width: 33.33%;
}

.photo-placeholder {
  width: 40px;
  height: 40px;
  line-height: 40px;
  border-radius: 50%;
  text-align: center;
  display: inline-block;
  background-color: crimson;
  color: white;
}

.truncate {
    display: block;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet" />

        Col 1
        Col 2
        Col 3

          P
          Pedro Luis Arend Gonçalves

        Info 2
        Info 3

JSFiddle

Expected result:

Body:
It seems that the "truncate" class sets the element to display:block, which puts it on its own line.

One solution might be to set it to display:inline-block and set it's width to the remaining space in the table cell. Below, I've calculated the appropriate width by using calc(). I've also eliminated the white space between the two <span> elements so it won't contribute extra width.

main {
  padding: 16px;
}

table {
  table-layout: fixed;
}

td {
  width: 33.33%;
}

.photo-placeholder {
  width: 40px;
  height: 40px;
  line-height: 40px;
  border-radius: 50%;
  text-align: center;
  display: inline-block;
  background-color: crimson;
  color: white;
}

#table1 .truncate {
  display: inline-block;
  width: calc(100% - 40px);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

<main>

  <table id="table1" class="white z-depth-1 centered">
    <thead>
      <tr>
        <th>Col 1</th>
        <th>Col 2</th>
        <th>Col 3</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td data-label="Col 1">
          <span class="photo-placeholder">P
          </span><span class="truncate">Pedro Luis Arend Gonçalves</span>
        </td>
        <td data-label="Col 2">Info 2</td>
        <td data-label="Col 3">Info 3</td>
      </tr>
    </tbody>
  </table>

</main>

To avoid having to calculate the width, you can simply float the placeholder left, like this:

main {
  padding: 16px;
}

table {
  table-layout: fixed;
}

td {
  width: 33.33%;
}

.photo-placeholder {
  float: left;
  width: 40px;
  height: 40px;
  line-height: 40px;
  border-radius: 50%;
  text-align: center;
  background-color: crimson;
  color: white;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

<main>

  <table id="table1" class="white z-depth-1 centered">
    <thead>
      <tr>
        <th>Col 1</th>
        <th>Col 2</th>
        <th>Col 3</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td data-label="Col 1">
          <span class="photo-placeholder">P</span>
          <span class="truncate">Pedro Luis Arend Gonçalves</span>
        </td>
        <td data-label="Col 2">Info 2</td>
        <td data-label="Col 3">Info 3</td>
      </tr>
    </tbody>
  </table>

</main>

Here's a different method that uses a flexbox container. I like this one because it's easier to vertically center the two elements with align-items:center.

main {
  padding: 16px;
}

table {
  table-layout: fixed;
}

td {
  width: 33.33%;
}

.photoContent {
  display: flex;
  align-items: center;
}

.photo-placeholder {
  flex: 0 0 40px;
  height: 40px;
  line-height: 40px;
  border-radius: 50%;
  text-align: center;
  background-color: crimson;
  color: white;
  margin: 0 0.5em 0 0;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

<main>

  <table id="table1" class="white z-depth-1 centered">
    <thead>
      <tr>
        <th>Col 1</th>
        <th>Col 2</th>
        <th>Col 3</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td data-label="Col 1">
          <div class="photoContent">
            <span class="photo-placeholder">P</span>
            <span class="truncate">Pedro Luis Arend Gonçalves</span>
          </div>
        </td>
        <td data-label="Col 2">Info 2</td>
        <td data-label="Col 3">Info 3</td>
      </tr>
    </tbody>
  </table>

</main>


问:
Calculate image file size before saving to Disk in PHP
I am kind of experimenting with the PHP Image saving.
I want to compare the image's actual file sizes before upload and after  resize/compress processing, but want to know the file size that will going to be if I save it to the disk.

So that if the file size is less, then the newly processed file will replace old one, else no change will be made.

This is the code I am using to save jpeg image.

```<code>imagejpeg($this->newImage, $savePath, $imageQuality);
</code>```

I tried getting the actual file size and size after

```<code>print_r(filesize($actual_file_size));
print_r($this->newImage);
</code>```

where $actual_file_size gives the data by reading from tmp object file, however $this->newImage is giving blank (no value).

I am using ResizeImage class from github

Is there any way I can get the file size before saving to disk? So that I can keep the minimal size version.

答:
This is how you do it:

```<code>$original_file = 'original.jpg';
$resized_file = 'resized.jpg';
$max_file_size = '10000';

$original_image = imagecreatefromjpeg($original_file);

$image_quality = 100;

do {
    $temp_stream = fopen('php://temp', 'w+');
    $saved = imagejpeg($original_image, $temp_stream, $image_quality--);
    rewind($temp_stream);
    $fstat = fstat($temp_stream);
    fclose($temp_stream);

    $file_size = $fstat['size'];
}
while (($file_size > $max_file_size) && ($image_quality >= 0));

if (-1 == $image_quality) {
    echo "Unable to get the file that small. Best I could do was $file_size bytes at image quality 0.\n";
}
else {
    echo "Successfully resized $original_file to $file_size bytes using image quality $image_quality. Resized file saved as $resized_file.\n";
    imagejpeg($new_image, $resized_file, $image_quality + 1);
}
</code>```

This requires no file to be written until you've successfully found the ideal compression ratio.

This loop starts with an $image_quality of 100, then counts downward trying each new value on a temporary in-memory buffer. If gets down to trying 0 and the file would still be too big, it returns an error message. Otherwise, if it gets to a value that works, it reports that and saves the new file using that image quality setting.

If you're feeling adventurous, you could implement a binary search algorithm to find the ideal compression ratio more quickly, but this quick-fix gives the same result, albeit possibly a tad slower.

Body:
I am kind of experimenting with the PHP Image saving.
I want to compare the image's actual file sizes before upload and after  resize/compress processing, but want to know the file size that will going to be if I save it to the disk.

So that if the file size is less, then the newly processed file will replace old one, else no change will be made.

This is the code I am using to save jpeg image.

imagejpeg($this->newImage, $savePath, $imageQuality);

I tried getting the actual file size and size after

print_r(filesize($actual_file_size));
print_r($this->newImage);

where $actual_file_size gives the data by reading from tmp object file, however $this->newImage is giving blank (no value).

I am using ResizeImage class from github

Is there any way I can get the file size before saving to disk? So that I can keep the minimal size version.

Body:
This is how you do it:

$original_file = 'original.jpg';
$resized_file = 'resized.jpg';
$max_file_size = '10000';

$original_image = imagecreatefromjpeg($original_file);

$image_quality = 100;

do {
    $temp_stream = fopen('php://temp', 'w+');
    $saved = imagejpeg($original_image, $temp_stream, $image_quality--);
    rewind($temp_stream);
    $fstat = fstat($temp_stream);
    fclose($temp_stream);

    $file_size = $fstat['size'];
}
while (($file_size > $max_file_size) && ($image_quality >= 0));

if (-1 == $image_quality) {
    echo "Unable to get the file that small. Best I could do was $file_size bytes at image quality 0.\n";
}
else {
    echo "Successfully resized $original_file to $file_size bytes using image quality $image_quality. Resized file saved as $resized_file.\n";
    imagejpeg($new_image, $resized_file, $image_quality + 1);
}

This requires no file to be written until you've successfully found the ideal compression ratio.

This loop starts with an $image_quality of 100, then counts downward trying each new value on a temporary in-memory buffer. If gets down to trying 0 and the file would still be too big, it returns an error message. Otherwise, if it gets to a value that works, it reports that and saves the new file using that image quality setting.

If you're feeling adventurous, you could implement a binary search algorithm to find the ideal compression ratio more quickly, but this quick-fix gives the same result, albeit possibly a tad slower.


问:
how do i do round-robin in python 3
i have to do a rotation of a list. I get a sorted list and i have to get minimum of pairs and maximum of tree numbers in a permutation of this sorted list as an answear. It has to have different numbers sorted from lowest to highest. For example:

```<code>MyList=[1, 1, 1, 2, 2, 2, 3, 3, 3, 3]
</code>```

and the output must be:

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

and for :

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

and the output must be:

```<code>1 2
1 3
1 4
1 5
1 6
</code>```

I saw i can do it with a method called round-robin but i don't know how.
Thank you for your help!

答:
from itertools import cycle

A = [[1,2,3],[4,5,6],[7]]
B = [[8],[9,10,11],[12,13]]

for p in A:
   max1 = len(p) if  max1 <len(p) else max1

for p in B:
   max1 = len(p) if  max1 <len(p) else max1

i = len(A)
j = 0
C = []
list_num = cycle(k for k in range(i))

for x in list_num:
   j += 1
   if j == i*3:
       break
   if A[x]:
       C.append(A[x].pop(0))
   if B[x]:
       C.append(B[x].pop(0))
```

<p>Output:</p>

```[1, 8, 4, 9, 7, 12, 2, 5, 10, 13, 3, 6, 11]
```

Title: how do i do round-robin in python 3

Body:
i have to do a rotation of a list. I get a sorted list and i have to get minimum of pairs and maximum of tree numbers in a permutation of this sorted list as an answear. It has to have different numbers sorted from lowest to highest. For example:

MyList=[1, 1, 1, 2, 2, 2, 3, 3, 3, 3]

and the output must be:

1 2 3
1 2 3
1 3
2 3

and for :

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

and the output must be:

1 2
1 3
1 4
1 5
1 6

I saw i can do it with a method called round-robin but i don't know how.
Thank you for your help!

Body:
from itertools import cycle

A = [[1,2,3],[4,5,6],[7]]
B = [[8],[9,10,11],[12,13]]

for p in A:
   max1 = len(p) if  max1 <len(p) else max1

for p in B:
   max1 = len(p) if  max1 <len(p) else max1

i = len(A)
j = 0
C = []
list_num = cycle(k for k in range(i))

for x in list_num:
   j += 1
   if j == i*3:
       break
   if A[x]:
       C.append(A[x].pop(0))
   if B[x]:
       C.append(B[x].pop(0))

Output:

[1, 8, 4, 9, 7, 12, 2, 5, 10, 13, 3, 6, 11]


问:
Why might a react app perform poorly in the layout rendering stage?
In here we have boxes which can have children. If you click on a box, it will add a child for it.

https://codesandbox.io/s/suspicious-fire-e2jes

What I struggle to understand is why does it take increasingly long to create a child as the max depth increases?

According to performance audit, the problem is not in the data structure format where you define parent for a node, rather than defining all children for a node.

So the issue is layout. From what I could find, one anti-pattern is where you read-write-read-write styles over and over which forces browser to calculate layout before each read. I don't see anything of this sort in my code.

答:
The issue is definitely layout. But not your layout.
I tried your code without loading your style.css file.
And it works as expected.

I created a similar use case without react. Pure css here with same dom structure:

const node = (id, children) => `

${id}

      ${children}

`

document.getElementById("app").innerHTML = `

  ${node(0, node(1, node(2, node(3, node(4, node(5, node(6, node(7, 'end'))))))))}

`;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.App {
  font-family: sans-serif;
  text-align: center;
}

.nodeAndChildren {
  display: grid;
  grid-auto-flow: column;
}

.node {
  width: 100px;
  border: 1px solid black;
}

.children {
  display: grid;
}</code>```

```

You can see how slow this is, even here.

This seems like a weird pattern matching issue for css or grid layout.
So, i tried it only with inline styling, was still slow
https://codesandbox.io/embed/displaygrid-bug-bcgsm

My suggestion is to use css columns instead of grid. Or just flex boxes with wrap.

Body:
The issue is definitely layout. But not your layout.
I tried your code without loading your style.css file.
And it works as expected.

I created a similar use case without react. Pure css here with same dom structure:

const node = (id, children) => `
  <div class='node'>${id}</div>
  <div class='children'>
    <div class='nodeAndChildren'>
      ${children}
    </div>
  </div>

`

document.getElementById("app").innerHTML = `
<div class='nodeAndChildren'>
  ${node(0, node(1, node(2, node(3, node(4, node(5, node(6, node(7, 'end'))))))))}
</div>
`;

.App {
  font-family: sans-serif;
  text-align: center;
}

.nodeAndChildren {
  display: grid;
  grid-auto-flow: column;
}

.node {
  width: 100px;
  border: 1px solid black;
}

.children {
  display: grid;
}

<div id='app'/>

You can see how slow this is, even here.

This seems like a weird pattern matching issue for css or grid layout.
So, i tried it only with inline styling, was still slow
https://codesandbox.io/embed/displaygrid-bug-bcgsm

My suggestion is to use css columns instead of grid. Or just flex boxes with wrap.


问:
Not able to install appium using npm due to permissions error
I am not able to install appium on my mac due to permissions error.

```<code>npm install -g appium
npm WARN checkPermissions Missing write access to
/usr/local/lib/node_modules
npm ERR! path /usr/local/lib/node_modules
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall access
npm ERR! Error: EACCES: permission denied, access
'/usr/local/lib/node_modules'
npm ERR!  { [Error: EACCES: permission denied, access
'/usr/local/lib/node_modules']
npm ERR!   stack:
npm ERR!    'Error: EACCES: permission denied, access
\'/usr/local/lib/node_modules\'',
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'access',
npm ERR!   path: '/usr/local/lib/node_modules' }
</code>```

is there a way to install it without using sudo?
I am able to install it like this:

```<code>sudo npm install -g appium --unsafe-perm=true --allow-root
</code>```

But it causes me issues.

Thanks

答:
I was able to solve the issue.
I manually uninstalled node and npm from my computer.
Then i installed nvm.
After that I installed node using:
nvm install node
After that I was able to install appium</p>

Body:
I am not able to install appium on my mac due to permissions error.

npm install -g appium
npm WARN checkPermissions Missing write access to
/usr/local/lib/node_modules
npm ERR! path /usr/local/lib/node_modules
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall access
npm ERR! Error: EACCES: permission denied, access
'/usr/local/lib/node_modules'
npm ERR!  { [Error: EACCES: permission denied, access
'/usr/local/lib/node_modules']
npm ERR!   stack:
npm ERR!    'Error: EACCES: permission denied, access
\'/usr/local/lib/node_modules\'',
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'access',
npm ERR!   path: '/usr/local/lib/node_modules' }

is there a way to install it without using sudo?
I am able to install it like this:

sudo npm install -g appium --unsafe-perm=true --allow-root

But it causes me issues.

Thanks


问:
how to conntracking in suse9 ? ( ip_conntrack )
I'm working on SUSE-10 Environment and am using /proc/net/ip_conntrack file to monitor net conntracking :

tcp 6 431982 ESTABLISHED src=.. dst=.. sport=34846 dport=993 packets=169 bytes=14322 ...

But now I'm working SUSE-9 environment and the weevil also need this file to monitor net conntracking!

in the suse-9 /proc/net/ip_conntrack file show :

udp 17 30 src=.. dst=.. sport=57767 dport=53 [UNREPLIED] src=.. dst=.. sport=53 dport=57767

this do not show packets and bytes !
i needed packets and bytes

答:
I am quite sure this is because the connection is [UNREPLIED] - as soon as you get a reply you will see bytes and packets.

If this is not true try to install the conntrack tool:

```<code># which conntrack
/usr/sbin/conntrack</code>```

conntrack -L will show the data as the file /proc/net/ip_conntrack does. conntrack is great for monitoring it allows you to show events using: conntrack -E, this way you don't have to poll /proc/net/ip_conntrack anymore.

Body:
I am quite sure this is because the connection is [UNREPLIED] - as soon as you get a reply you will see bytes and packets.

If this is not true try to install the conntrack tool:

# which conntrack
/usr/sbin/conntrack

conntrack -L will show the data as the file /proc/net/ip_conntrack does. conntrack is great for monitoring it allows you to show events using: conntrack -E, this way you don't have to poll /proc/net/ip_conntrack anymore.


问:
Inheritance in JavaScript
I have a class Person like this:

```<code> class Person {
    constructor(name, age, gender, interests) {
        Object.assign(this, {name, age, gender, interests});
    }
}
</code>```

And I can make sub-class like this:

```<code>class Teacher extends Person {
    constructor(name, age, gender, interests, subject, grade) {
        super(name, age, gender, interests);
        Object.assign(this, {subject, grade});
    }
}
</code>```

But what if I want to make sub-class but I don't want to inherit all the properties from the Person class. For example I don't want to inherit the interests property. Do I just exclude it like this:

```<code>class Student extends Person {
    constructor(name, age, gender, height, weight) {
        super(name, age, gender); // I haven't included the interests property here
        Object.assign(this, {height, weight});
    }
}
</code>```

I am still beginner so I am not sure if this is good practice or not. Have a nice day!

答:
```<code>  super(name, age, gender); // I haven't included the interests property here
</code>```

By not adding an argument to a function call, the parameter will implicitly be undefined. The upper therefore equals:

```<code> super(name, age, gender, undefined)
</code>```

Therefore the interests property does still exist, it is just undefined. That is actually a good solution if all your code assumes that interests could not be defined. If not, e.g. if you are doing calculations with it without an explicit check, your calculations might suddenly be NaN, which gets you into some trouble:

```<code>  if(person.age > 18) {
   alert("adult");
  } else alert("child"); // or maybe the person is not a child, and it's age property was just not set?
</code>```

Now instead of setting that existing property to a value that indicates that it is undefined, you could omit the interests property at all, by:

1) Moving it to a subclass:

```<code> class Person {
   constructor(name, age, gender) {
    Object.assign(this, {name, age, gender });
  }
 }

 class PersonWithInterests extends Person  {
   constructor(name, age, gender, interests) {
    super(name, age, gender);
    Object.assign(this, { interests });
  }
}
</code>```

2) Create a Mixin:

A Mixin is a class, that can extend more than one class. If more than a Person has an interest, it might be benefitial to create a mixin for it:

```<code> const Interested = Super => class InterestMixin extends Super {
  constructor(args) { // passing in an object here makes the Mixin more flexible, all superclasses have to deal with it though
    super(args);
    this.interests = args.interests;
  }
};

class Animal { }

const PersonWithInterest = Interested(Person);
const AnimalWithInterest = Interested(Animal);

new PersonWithInterest({ name: "Jonas", interests: 10 })
new AnimalWithInterest({ type: "bear", interests: 20 })
</code>```

(If you end up creating a new Mixin for every single property, this solution is not really viable anymore. If you can't group multiple properties into a useful Mixin, go with the first way instead (having optional properties)).

Title: Inheritance in JavaScript

Body:
I have a class Person like this:

 class Person {
    constructor(name, age, gender, interests) {
        Object.assign(this, {name, age, gender, interests});
    }
}

And I can make sub-class like this:

class Teacher extends Person {
    constructor(name, age, gender, interests, subject, grade) {
        super(name, age, gender, interests);
        Object.assign(this, {subject, grade});
    }
}

But what if I want to make sub-class but I don't want to inherit all the properties from the Person class. For example I don't want to inherit the interests property. Do I just exclude it like this:

class Student extends Person {
    constructor(name, age, gender, height, weight) {
        super(name, age, gender); // I haven't included the interests property here
        Object.assign(this, {height, weight});
    }
}

I am still beginner so I am not sure if this is good practice or not. Have a nice day!

Body:
  super(name, age, gender); // I haven't included the interests property here

By not adding an argument to a function call, the parameter will implicitly be undefined. The upper therefore equals:

 super(name, age, gender, undefined)

Therefore the interests property does still exist, it is just undefined. That is actually a good solution if all your code assumes that interests could not be defined. If not, e.g. if you are doing calculations with it without an explicit check, your calculations might suddenly be NaN, which gets you into some trouble:

  if(person.age > 18) {
   alert("adult");
  } else alert("child"); // or maybe the person is not a child, and it's age property was just not set?

Now instead of setting that existing property to a value that indicates that it is undefined, you could omit the interests property at all, by:

1) Moving it to a subclass:

 class Person {
   constructor(name, age, gender) {
    Object.assign(this, {name, age, gender });
  }
 }

 class PersonWithInterests extends Person  {
   constructor(name, age, gender, interests) {
    super(name, age, gender);
    Object.assign(this, { interests });
  }
}

2) Create a Mixin:

A Mixin is a class, that can extend more than one class. If more than a Person has an interest, it might be benefitial to create a mixin for it:

 const Interested = Super => class InterestMixin extends Super {
  constructor(args) { // passing in an object here makes the Mixin more flexible, all superclasses have to deal with it though
    super(args);
    this.interests = args.interests;
  }
};

class Animal { }

const PersonWithInterest = Interested(Person);
const AnimalWithInterest = Interested(Animal);

new PersonWithInterest({ name: "Jonas", interests: 10 })
new AnimalWithInterest({ type: "bear", interests: 20 })

(If you end up creating a new Mixin for every single property, this solution is not really viable anymore. If you can't group multiple properties into a useful Mixin, go with the first way instead (having optional properties)).