问:
How to increment a foor loop within a nested if statement
Im distinguishing 2 players in TicTacToe by utilising MOD, which is used upon an incrementing for loop. Im having trouble incrementing the foor loop within a nested if statement. </p>

```<code>            for i in range (1,10):
                if i % 2==1:
                    #1st row
                    if click[0]<=250 and click[0]>=100 and click[1]<=250 and click[1]>=100:
                        current_game[0][0] = "X"
                        i+=1
                    elif click[0]<=550 and click[0]>=250 and click[1]<=250 and click[1]>=100:
                        current_game[0][1] = "X"
                        i += 1
                    elif click[0]<=700 and click[0]>=550 and click[1]<=250 and click[1]>=100:
                        current_game[0][2] = "X"
                        i += 1
                    #2nd row
                    elif click[0]<=250 and click[0]>=100 and click[1]<= 550and click[1]>=250:
                        current_game[1][0] = "X"
                        i += 1
                    elif click[0]<=550 and click[0]>=250 and click[1]<=550 and click[1]>=250:
                        current_game[1][1] = "X"
                        i += 1
                    elif click[0] <= 700 and click[0] >= 550 and click[1] <= 550 and click[1] >= 250:
                        current_game[1][2] = "X"
                        i += 1
                    #3rd row
                    elif click[0]<=250 and click[0]>=100 and click[1]<= 700and click[1]>=550:
                        current_game[2][0] = "X"
                        i += 1
                    elif click[0] <= 550 and click[0] >= 250 and click[1] <= 700 and click[1] >= 550:
                        current_game[2][1] = "X"
                        i += 1
                    elif click[0] <= 700 and click[0] >= 550 and click[1] <= 700 and click[1] >= 550:
                        current_game[2][2] = "X"
                        i += 1
                elif i % 2==0:
                    # 1st row
                    if click[0] <= 250 and click[0] >= 100 and click[1] <= 250 and click[1] >= 100:
                        current_game[0][0] = "o"
                        i += 1
                    elif click[0] <= 550 and click[0] >= 250 and click[1] <= 250 and click[1] >= 100:
                        current_game[0][1] = "o"
                        i += 1
                    elif click[0] <= 700 and click[0] >= 550 and click[1] <= 250 and click[1] >= 100:
                        current_game[0][2] = "o"
                        i += 1
                    # 2nd row
                    elif click[0] <= 250 and click[0] >= 100 and click[1] <= 550 and click[1] >= 250:
                        current_game[1][0] = "o"
                        i += 1
                    elif click[0] <= 550 and click[0] >= 250 and click[1] <= 550 and click[1] >= 250:
                        current_game[1][1] = "o"
                        i += 1
                    elif click[0] <= 700 and click[0] >= 550 and click[1] <= 550 and click[1] >= 250:
                        current_game[1][2] = "o"
                        i += 1
                    # 3rd row
                    elif click[0] <= 250 and click[0] >= 100 and click[1] <= 700 and click[1] >= 550:
                        current_game[2][0] = "o"
                        i += 1
                    elif click[0] <= 550 and click[0] >= 250 and click[1] <= 700 and click[1] >= 550:
                        current_game[2][1] = "o"
                        i += 1
                    elif click[0] <= 700 and click[0] >= 550 and click[1] <= 700 and click[1] >= 550:
                        current_game[2][2] = "o"
                        i += 1
</code>```

<p>I want to be able to increment the for loop if someone clicks on a certain co-ordinate space. </p>

答:
Because you use for i in range(1, 10), it doesn't matter what changes you make to i during an iteration, when it comes back to the for loop it will be assigned the next value in the range. example:

```<code>for i in range(5):
    print(i)
    i += 2
</code>```

What you expect to happen is something like

```<code>>>> 0
>>> 3
</code>```

but what actually will happen is this:

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

What happened here? First,i is assigned the value 0, then it was printed and increment (so now it is equal to 2). Next, i is assigned the value 1 (from the range generator), so the increment you made was overridden.

To solve this use a while loop:

```<code>i = 1
while i < 10:
    # do stuff
    i += 1
</code>```

Now the value of i will not be overridden every time the loop executes

Body:
Im distinguishing 2 players in TicTacToe by utilising MOD, which is used upon an incrementing for loop. Im having trouble incrementing the foor loop within a nested if statement.

            for i in range (1,10):
                if i % 2==1:
                    #1st row
                    if click[0]<=250 and click[0]>=100 and click[1]<=250 and click[1]>=100:
                        current_game[0][0] = "X"
                        i+=1
                    elif click[0]<=550 and click[0]>=250 and click[1]<=250 and click[1]>=100:
                        current_game[0][1] = "X"
                        i += 1
                    elif click[0]<=700 and click[0]>=550 and click[1]<=250 and click[1]>=100:
                        current_game[0][2] = "X"
                        i += 1
                    #2nd row
                    elif click[0]<=250 and click[0]>=100 and click[1]<= 550and click[1]>=250:
                        current_game[1][0] = "X"
                        i += 1
                    elif click[0]<=550 and click[0]>=250 and click[1]<=550 and click[1]>=250:
                        current_game[1][1] = "X"
                        i += 1
                    elif click[0] <= 700 and click[0] >= 550 and click[1] <= 550 and click[1] >= 250:
                        current_game[1][2] = "X"
                        i += 1
                    #3rd row
                    elif click[0]<=250 and click[0]>=100 and click[1]<= 700and click[1]>=550:
                        current_game[2][0] = "X"
                        i += 1
                    elif click[0] <= 550 and click[0] >= 250 and click[1] <= 700 and click[1] >= 550:
                        current_game[2][1] = "X"
                        i += 1
                    elif click[0] <= 700 and click[0] >= 550 and click[1] <= 700 and click[1] >= 550:
                        current_game[2][2] = "X"
                        i += 1
                elif i % 2==0:
                    # 1st row
                    if click[0] <= 250 and click[0] >= 100 and click[1] <= 250 and click[1] >= 100:
                        current_game[0][0] = "o"
                        i += 1
                    elif click[0] <= 550 and click[0] >= 250 and click[1] <= 250 and click[1] >= 100:
                        current_game[0][1] = "o"
                        i += 1
                    elif click[0] <= 700 and click[0] >= 550 and click[1] <= 250 and click[1] >= 100:
                        current_game[0][2] = "o"
                        i += 1
                    # 2nd row
                    elif click[0] <= 250 and click[0] >= 100 and click[1] <= 550 and click[1] >= 250:
                        current_game[1][0] = "o"
                        i += 1
                    elif click[0] <= 550 and click[0] >= 250 and click[1] <= 550 and click[1] >= 250:
                        current_game[1][1] = "o"
                        i += 1
                    elif click[0] <= 700 and click[0] >= 550 and click[1] <= 550 and click[1] >= 250:
                        current_game[1][2] = "o"
                        i += 1
                    # 3rd row
                    elif click[0] <= 250 and click[0] >= 100 and click[1] <= 700 and click[1] >= 550:
                        current_game[2][0] = "o"
                        i += 1
                    elif click[0] <= 550 and click[0] >= 250 and click[1] <= 700 and click[1] >= 550:
                        current_game[2][1] = "o"
                        i += 1
                    elif click[0] <= 700 and click[0] >= 550 and click[1] <= 700 and click[1] >= 550:
                        current_game[2][2] = "o"
                        i += 1

I want to be able to increment the for loop if someone clicks on a certain co-ordinate space.

Body:
Because you use for i in range(1, 10), it doesn't matter what changes you make to i during an iteration, when it comes back to the for loop it will be assigned the next value in the range. example:

for i in range(5):
    print(i)
    i += 2

What you expect to happen is something like

>>> 0
>>> 3

but what actually will happen is this:

>>> 0
>>> 1
>>> 2
>>> 3
>>> 4

What happened here? First,i is assigned the value 0, then it was printed and increment (so now it is equal to 2). Next, i is assigned the value 1 (from the range generator), so the increment you made was overridden.

To solve this use a while loop:

i = 1
while i < 10:
    # do stuff
    i += 1

Now the value of i will not be overridden every time the loop executes


来源: stackexchange

问:
How to remove elements in ArrayList?
Below is sample code.

How to remove a specific element in ArrayList?

```<code>
import java.util.ArrayList;

class A {
    int value;

    public A(int newValue) {
        setValue(newValue);
    }

    public int getValue() {
        return value;
    }

    public void setValue(int newValue) {
        value = newValue;
    }
}

class B {

    ArrayList <A> valuesOfA = new ArrayList<>();
    valuesOfA.add(new A(5));
    System.out.println("Adding...");
    for (A value: valueOfA) {
        System.out.println(value); //prints the values added.
    }
    valuesOfA.remove(new A(5));
    System.out.println("Removed");
    for (A value: valueOfA) {
        System.out.println(value);
    }
}
</code>```

Element as still not been removed. What is the solution for this?

答:
Redefine Class A like this:

```<code>Class A
{
    int value;
    public A(int newValue)
    {
        setValue(newValue);
    }
    public int getValue()
    {
         return value;
    }
    public void setValue(int newValue)
    {
         value = newValue;
    }
    public boolean equals(Object o)
    {
         if( o instanceof A)
         {
             return this.value == ((A)o).value;
         }
         return super.equals(o);
    }
}
</code>```

By overriding this method, which uses the object's memory address by default, you are defining how two object should be considered the same.

You should also define the hashcode() method.

ContentLicense: CC BY-SA 4.0

Title: How to remove elements in ArrayList?

Body:
Below is sample code.

How to remove a specific element in ArrayList?

import java.util.ArrayList;

class A {
    int value;

    public A(int newValue) {
        setValue(newValue);
    }

    public int getValue() {
        return value;
    }

    public void setValue(int newValue) {
        value = newValue;
    }
}

class B {

    ArrayList  valuesOfA = new ArrayList<>();
    valuesOfA.add(new A(5));
    System.out.println("Adding...");
    for (A value: valueOfA) {
        System.out.println(value); //prints the values added.
    }
    valuesOfA.remove(new A(5));
    System.out.println("Removed");
    for (A value: valueOfA) {
        System.out.println(value);
    }
}

Element as still not been removed. What is the solution for this?

Body:
Redefine Class A like this:

Class A
{
    int value;
    public A(int newValue)
    {
        setValue(newValue);
    }
    public int getValue()
    {
         return value;
    }
    public void setValue(int newValue)
    {
         value = newValue;
    }
    public boolean equals(Object o)
    {
         if( o instanceof A)
         {
             return this.value == ((A)o).value;
         }
         return super.equals(o);
    }
}

By overriding this method, which uses the object's memory address by default, you are defining how two object should be considered the same.

You should also define the hashcode() method.


问:
Difference between sendkeys(keys.Down) & sendkeys(keys.Arrow_Down)
What is Difference between sendkeys(keys.Down) & sendkeys(keys.Arrow_Down)
In selenium java </p>

答: There is no difference, in previous versions of selenium they were called  ARROW_UP, ARROW_LEFT, ARROW_RIGHT, and ARROW_DOWN, now they are called UP, LEFT, RIGHT,  and DOWN.</p>


问:
Why can't I reach 100% CPU utilization with my parallel tasks code?
```<code>private static async Task<int> SumParallel()
        {
            var intList = Enumerable.Range(1, 1000_000_000);
            int count = intList.Count();
            int total = 0;
            for(int i = 1; i < 5; i++)
            {
                int skip = ((i - 1) * count) / 4;
                int take = count / 4;
                Interlocked.Add(ref total,
                    await GetSum(intList, skip, take));
            }
            return total;
        }

private static async Task<int> GetSum(IEnumerable<int> list, int skip, int take)
        {
            return await Task.Run(() =>
             {
                 int temp = 0;
                 foreach(int n in list.Skip(skip).Take(take))
                 {
                     if (n % 2 == 0)
                         temp -= n;
                     else
                         temp += n;
                 }
                 return temp;
             });
        }
</code>```

I am trying to perform compute intensive task, just to practice the task parallel library. So, I wrote this code. If I try to compute the same sum using Parallel Linq, I can see the CPU utilization going to 100% as follows:

```<code>int sum = Enumerable.Range(1, 1000_000_000)
                .AsParallel()
                .Select(i => i % 2 == 0 ? -i : i).Sum();
</code>```

Manual parallel tasks code = 10 seconds time, cpu = 25% only

Parallel Linq code = 18 seconds time, cpu = 100% (And still takes 18 seconds)

Linq code without parallel: 14 seconds, cpu = 25% only

Why is it so? When I am also starting 4 threads in parallel, why my cpu utilization doesn't go to 100%? It is just 25% like there is in unparallel code (with just one thread). Am I really running 4 threads in parallel or not?

My laptop is Core i3 - 2 cores = 4 logical processors

答:
The SumParallel is not doing parallel job, because it creates and awaits each task sequentially:

```<code>for(int i = 1; i < 5; i++) {
    //...
    await GetSum(intList, skip, take)
</code>```

To make it parallel you must start all five tasks, and then await all of them to complete with await Task.WhenAll(tasks);.

As for the Parallel Linq being slower than the standard Linq, it is because your workload is too granular. As a result the overhead of parallelism negates any benefits of the parallel execution. In other words it is more work to distribute the items to the threads and collect the results back, than the actual calculation (n % 2). To make the most out of parallelism, your workload must be chunky.

Body:
private static async Task<int> SumParallel()
        {
            var intList = Enumerable.Range(1, 1000_000_000);
            int count = intList.Count();
            int total = 0;
            for(int i = 1; i < 5; i++)
            {
                int skip = ((i - 1) * count) / 4;
                int take = count / 4;
                Interlocked.Add(ref total,
                    await GetSum(intList, skip, take));
            }
            return total;
        }

private static async Task<int> GetSum(IEnumerable<int> list, int skip, int take)
        {
            return await Task.Run(() =>
             {
                 int temp = 0;
                 foreach(int n in list.Skip(skip).Take(take))
                 {
                     if (n % 2 == 0)
                         temp -= n;
                     else
                         temp += n;
                 }
                 return temp;
             });
        }

I am trying to perform compute intensive task, just to practice the task parallel library. So, I wrote this code. If I try to compute the same sum using Parallel Linq, I can see the CPU utilization going to 100% as follows:

int sum = Enumerable.Range(1, 1000_000_000)
                .AsParallel()
                .Select(i => i % 2 == 0 ? -i : i).Sum();

Manual parallel tasks code = 10 seconds time, cpu = 25% only

Parallel Linq code = 18 seconds time, cpu = 100% (And still takes 18 seconds)

Linq code without parallel: 14 seconds, cpu = 25% only

Why is it so? When I am also starting 4 threads in parallel, why my cpu utilization doesn't go to 100%? It is just 25% like there is in unparallel code (with just one thread). Am I really running 4 threads in parallel or not?

My laptop is Core i3 - 2 cores = 4 logical processors

Body:
The SumParallel is not doing parallel job, because it creates and awaits each task sequentially:

for(int i = 1; i < 5; i++) {
    //...
    await GetSum(intList, skip, take)

To make it parallel you must start all five tasks, and then await all of them to complete with await Task.WhenAll(tasks);.

As for the Parallel Linq being slower than the standard Linq, it is because your workload is too granular. As a result the overhead of parallelism negates any benefits of the parallel execution. In other words it is more work to distribute the items to the threads and collect the results back, than the actual calculation (n % 2). To make the most out of parallelism, your workload must be chunky.


问:
Find given row in a matrix
I have an m by n matrix in MATLAB, say M. I have an n-element row vector, i.e. a one by n column matrix, say X.

I know X is a row somewhere in M. How can I find the index in M?

答:
EDIT:

gnovice's suggestion is even simpler than mine:

```<code>[~,indx]=ismember(X,M,'rows')

indx =

     3
</code>```

FIRST SOLUTION:

You can easily do it using find and ismember. Here's an example:

```<code>M=magic(4);        %#your matrix

M =

    16     2     3    13
     5    11    10     8
     9     7     6    12
     4    14    15     1

X=[9 7 6 12];      %#your row vector

find(ismember(M,X),1)

ans =

     3
</code>```

ContentLicense: CC BY-SA 3.0

Title: Find given row in a matrix

Body:
EDIT:

gnovice's suggestion is even simpler than mine:

[~,indx]=ismember(X,M,'rows')

indx =

     3

FIRST SOLUTION:

You can easily do it using find and ismember. Here's an example:

M=magic(4);        %#your matrix

M =

    16     2     3    13
     5    11    10     8
     9     7     6    12
     4    14    15     1

X=[9 7 6 12];      %#your row vector

find(ismember(M,X),1)

ans =

     3


问:
Remove unused resources from XCode project
I am working on iOs application and in this application i have big changes in app design every day so code of my application is going to touch about 200 Mb. But in this code i have big numbers of  unused images are available. So i want to remove those images from my XCode project so i can reduce my project code size.

I had used some scripts thats already given on stackoverflow.com but i found that script removing used images also so thats not reliable.
I also had used app named "Slender". Its really good but its trial version so i cant use it more.

So please any one suggest me effective way (any application) for remove unused images from xCode project.

答:
I have answered a similar question over here: https://stackoverflow.com/a/62078601/217586

Adding the same details, here:

I have created a python script to identify the unused images: 'unused_assets.py' @ gist. It can be used like this:

```<code>python3 unused_assets.py '/Users/DevK/MyProject' '/Users/DevK/MyProject/MyProject/Assets/Assets.xcassets'
</code>```

Here are few rules to use the script:

It is important to pass project folder path as first argument, assets
folder path as second argument

It is assumed that all the images are maintained within Assets.xcassets folder and are used either within swift files or within storyboards

Limitations in first version:

Doesn't work for objective c files

I will try to improve it over the time, based on feedback, however the first version should be good for most.

Please find below the code. The code should be self explanatory as I have added appropriate comments to each important step.

```<code># Usage e.g.: python3 unused_assets.py '/Users/DevK/MyProject' '/Users/DevK/MyProject/MyProject/Assets/Assets.xcassets'
# It is important to pass project folder path as first argument, assets folder path as second argument
# It is assumed that all the images are maintained within Assets.xcassets folder and are used either within swift files or within storyboards

"""
@author = "Devarshi Kulshreshtha"
@copyright = "Copyright 2020, Devarshi Kulshreshtha"
@license = "GPL"
@version = "1.0.1"
@contact = "kulshreshtha.devarshi@gmail.com"
"""

import sys
import glob
from pathlib import Path
import mmap
import os
import time

# obtain start time
start = time.time()

arguments = sys.argv

# pass project folder path as argument 1
projectFolderPath = arguments[1].replace("\\", "") # replacing backslash with space
# pass assets folder path as argument 2
assetsPath = arguments[2].replace("\\", "") # replacing backslash with space

print(f"assetsPath: {assetsPath}")
print(f"projectFolderPath: {projectFolderPath}")

# obtain all assets / images
# obtain paths for all assets

assetsSearchablePath = assetsPath + '/**/*.imageset'  #alternate way to append: fr"{assetsPath}/**/*.imageset"
print(f"assetsSearchablePath: {assetsSearchablePath}")

imagesNameCountDict = {} # empty dict to store image name as key and occurrence count
for imagesetPath in glob.glob(assetsSearchablePath, recursive=True):
    # storing the image name as encoded so that we save some time later during string search in file
    encodedImageName = str.encode(Path(imagesetPath).stem)
    # initializing occurrence count as 0
    imagesNameCountDict[encodedImageName] = 0

print("Names of all assets obtained")

# search images in swift files
# obtain paths for all swift files

swiftFilesSearchablePath = projectFolderPath + '/**/*.swift' #alternate way to append: fr"{projectFolderPath}/**/*.swift"
print(f"swiftFilesSearchablePath: {swiftFilesSearchablePath}")

for swiftFilePath in glob.glob(swiftFilesSearchablePath, recursive=True):
    with open(swiftFilePath, 'rb', 0) as file, \
        mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
        # search all the assests within the swift file
        for encodedImageName in imagesNameCountDict:
            # file search
            if s.find(encodedImageName) != -1:
                # updating occurrence count, if found
                imagesNameCountDict[encodedImageName] += 1

print("Images searched in all swift files!")

# search images in storyboards
# obtain path for all storyboards

storyboardsSearchablePath = projectFolderPath + '/**/*.storyboard' #alternate way to append: fr"{projectFolderPath}/**/*.storyboard"
print(f"storyboardsSearchablePath: {storyboardsSearchablePath}")
for storyboardPath in glob.glob(storyboardsSearchablePath, recursive=True):
    with open(storyboardPath, 'rb', 0) as file, \
        mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
        # search all the assests within the storyboard file
        for encodedImageName in imagesNameCountDict:
            # file search
            if s.find(encodedImageName) != -1:
                # updating occurrence count, if found
                imagesNameCountDict[encodedImageName] += 1

print("Images searched in all storyboard files!")
print("Here is the list of unused assets:")

# printing all image names, for which occurrence count is 0
print('\n'.join({encodedImageName.decode("utf-8", "strict") for encodedImageName, occurrenceCount in imagesNameCountDict.items() if occurrenceCount == 0}))

print(f"Done in {time.time() - start} seconds!")
</code>```

Body:
I have answered a similar question over here: https://stackoverflow.com/a/62078601/217586

Adding the same details, here:

I have created a python script to identify the unused images: 'unused_assets.py' @ gist. It can be used like this:

python3 unused_assets.py '/Users/DevK/MyProject' '/Users/DevK/MyProject/MyProject/Assets/Assets.xcassets'

Here are few rules to use the script:

It is important to pass project folder path as first argument, assets
folder path as second argument

It is assumed that all the images are maintained within Assets.xcassets folder and are used either within swift files or within storyboards

Limitations in first version:

Doesn't work for objective c files

I will try to improve it over the time, based on feedback, however the first version should be good for most.

Please find below the code. The code should be self explanatory as I have added appropriate comments to each important step.

# Usage e.g.: python3 unused_assets.py '/Users/DevK/MyProject' '/Users/DevK/MyProject/MyProject/Assets/Assets.xcassets'
# It is important to pass project folder path as first argument, assets folder path as second argument
# It is assumed that all the images are maintained within Assets.xcassets folder and are used either within swift files or within storyboards

"""
@author = "Devarshi Kulshreshtha"
@copyright = "Copyright 2020, Devarshi Kulshreshtha"
@license = "GPL"
@version = "1.0.1"
@contact = "kulshreshtha.devarshi@gmail.com"
"""

import sys
import glob
from pathlib import Path
import mmap
import os
import time

# obtain start time
start = time.time()

arguments = sys.argv

# pass project folder path as argument 1
projectFolderPath = arguments[1].replace("\\", "") # replacing backslash with space
# pass assets folder path as argument 2
assetsPath = arguments[2].replace("\\", "") # replacing backslash with space

print(f"assetsPath: {assetsPath}")
print(f"projectFolderPath: {projectFolderPath}")

# obtain all assets / images
# obtain paths for all assets

assetsSearchablePath = assetsPath + '/**/*.imageset'  #alternate way to append: fr"{assetsPath}/**/*.imageset"
print(f"assetsSearchablePath: {assetsSearchablePath}")

imagesNameCountDict = {} # empty dict to store image name as key and occurrence count
for imagesetPath in glob.glob(assetsSearchablePath, recursive=True):
    # storing the image name as encoded so that we save some time later during string search in file
    encodedImageName = str.encode(Path(imagesetPath).stem)
    # initializing occurrence count as 0
    imagesNameCountDict[encodedImageName] = 0

print("Names of all assets obtained")

# search images in swift files
# obtain paths for all swift files

swiftFilesSearchablePath = projectFolderPath + '/**/*.swift' #alternate way to append: fr"{projectFolderPath}/**/*.swift"
print(f"swiftFilesSearchablePath: {swiftFilesSearchablePath}")

for swiftFilePath in glob.glob(swiftFilesSearchablePath, recursive=True):
    with open(swiftFilePath, 'rb', 0) as file, \
        mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
        # search all the assests within the swift file
        for encodedImageName in imagesNameCountDict:
            # file search
            if s.find(encodedImageName) != -1:
                # updating occurrence count, if found
                imagesNameCountDict[encodedImageName] += 1

print("Images searched in all swift files!")

# search images in storyboards
# obtain path for all storyboards

storyboardsSearchablePath = projectFolderPath + '/**/*.storyboard' #alternate way to append: fr"{projectFolderPath}/**/*.storyboard"
print(f"storyboardsSearchablePath: {storyboardsSearchablePath}")
for storyboardPath in glob.glob(storyboardsSearchablePath, recursive=True):
    with open(storyboardPath, 'rb', 0) as file, \
        mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
        # search all the assests within the storyboard file
        for encodedImageName in imagesNameCountDict:
            # file search
            if s.find(encodedImageName) != -1:
                # updating occurrence count, if found
                imagesNameCountDict[encodedImageName] += 1

print("Images searched in all storyboard files!")
print("Here is the list of unused assets:")

# printing all image names, for which occurrence count is 0
print('\n'.join({encodedImageName.decode("utf-8", "strict") for encodedImageName, occurrenceCount in imagesNameCountDict.items() if occurrenceCount == 0}))

print(f"Done in {time.time() - start} seconds!")


问:
Using SVM with different kernels as a last layer in CNN network
I'm trying to replace the last fully connected layer of a CNN network with SVM using pytorch in a multi-classification problem. I've done some research and it says, that I should just replace the nn.CrossEntropyLoss with nn.MultiMarginLoss.

How does changing the criterion only actually corresponds with the "replacing fully connected layer with SVM" task? Another thing is that I'd like to use the SVM with different kernel, like for example the quadratic one.

答:
This question can actually be interpreted as the difference between Logistic regression and SVM in classification.

We can naively look at the whole platform of your deep learning as if you have a magician, and that magician accepts the input data, and give you a set of engineered featured, and you use those features to do the classification.

Depending on which loss you minimize, you can solve this classification issue with different sorts of functions. If you use cross-entropy, it is like you are applying a logistic regression classification. On the other hand, if you minimize the marginal loss, it is actually equal to finding the support vectors, which is indeed how SVM works.

You need to read about the role of kernels in the calculation of the loss(for ex, here ), but TL;DR is that for loss computation, you have a component of K(xi,xj) which is actually the kernel function and indicate the similarity of xi and xj.

So you can implement a custom loss, where you have a polynomial kernel (quadratic in your case), and imitate the margin loss calculation there.


问:
CSV Filtering a column with mixed data types
I have a CSV with many columns and rows.  Column 4 has some strings and some not.  When I attempt to filter out duplicates it removes ones I want to keep.

When I run:

```<code>awk -F ',' '!seen[$4]++' oldfile.csv > newfile.csv
</code>```

on

```<code>71523180,PRASAD  JAMES ANAND, ,#3 ALEX BOYD LINK HILLSBORO
71523190,PRASAD  SHAKUNPALA, ,#3 ALEX BOYD LINK HILLSBORO
71523200,PRASAD  BOBBY UMENDRA, ,#3 ALEX BOYD LINK HILLSBORO
</code>```

it returns what I want:

```<code>71523180,PRASAD  JAMES ANAND, ,#3 ALEX BOYD LINK HILLSBORO
</code>```

But, when I run that line of code on

```<code>71508050,"HUNT,  RICHARD F", ,1009 # B FATHOM DR
71508060,"HUNT,  RICHARD F", ,1009 # B FATHOM DR
71561950,"HUNT,  RICHARD F", ,1009 # B FATHOM DR
71562840,"HUNT,  RICHARD F", ,1009 # B FATHOM DR
</code>```

it deletes all those entries.

What to do? Thanks

FOLLOW UP

Using perl seems to work, but gives me a small error.  Is this an issue?

```$ perl -w -MText::CSV_XS=csv -e 'csv(in => \*STDIN, filter => { 4 => sub { ! $seen{$_}++ }})' < combined4.csv > combined6.csv
Name "main::seen" used only once: possible typo at -e line 1.```

答:
using Miller (https://github.com/johnkerl/miller) on this CSV

```<code>71523180,PRASAD  JAMES ANAND, ,#3 ALEX BOYD LINK HILLSBORO
71523190,PRASAD  SHAKUNPALA, ,#3 ALEX BOYD LINK HILLSBORO
71523200,PRASAD  BOBBY UMENDRA, ,#3 ALEX BOYD LINK HILLSBORO
71508050,"HUNT,  RICHARD F", ,1009 # B FATHOM DR
71508060,"HUNT,  RICHARD F", ,1009 # B FATHOM DR
71561950,"HUNT,  RICHARD F", ,1009 # B FATHOM DR
71562840,"HUNT,  RICHARD F", ,1009 # B FATHOM DR
</code>```

and running

```<code>mlr --csv -N sort -f 4 then step -a counter -f 4 -g 4 then filter '$4_counter==1' then cut -x -f 4_counter input.csv >output.csv
</code>```

you will have

```<code>71523180,PRASAD  JAMES ANAND, ,#3 ALEX BOYD LINK HILLSBORO
71508050,"HUNT,  RICHARD F", ,1009 # B FATHOM DR
</code>```

Body:
I have a CSV with many columns and rows.  Column 4 has some strings and some not.  When I attempt to filter out duplicates it removes ones I want to keep.

When I run:

awk -F ',' '!seen[$4]++' oldfile.csv > newfile.csv

on

71523180,PRASAD  JAMES ANAND, ,#3 ALEX BOYD LINK HILLSBORO
71523190,PRASAD  SHAKUNPALA, ,#3 ALEX BOYD LINK HILLSBORO
71523200,PRASAD  BOBBY UMENDRA, ,#3 ALEX BOYD LINK HILLSBORO

it returns what I want:

71523180,PRASAD  JAMES ANAND, ,#3 ALEX BOYD LINK HILLSBORO

But, when I run that line of code on

71508050,"HUNT,  RICHARD F", ,1009 # B FATHOM DR
71508060,"HUNT,  RICHARD F", ,1009 # B FATHOM DR
71561950,"HUNT,  RICHARD F", ,1009 # B FATHOM DR
71562840,"HUNT,  RICHARD F", ,1009 # B FATHOM DR

it deletes all those entries.

What to do? Thanks

FOLLOW UP

Using perl seems to work, but gives me a small error.  Is this an issue?

$ perl -w -MText::CSV_XS=csv -e 'csv(in => \*STDIN, filter => { 4 => sub { ! $seen{$_}++ }})' < combined4.csv > combined6.csv
Name "main::seen" used only once: possible typo at -e line 1.

Body:
using Miller (https://github.com/johnkerl/miller) on this CSV

71523180,PRASAD  JAMES ANAND, ,#3 ALEX BOYD LINK HILLSBORO
71523190,PRASAD  SHAKUNPALA, ,#3 ALEX BOYD LINK HILLSBORO
71523200,PRASAD  BOBBY UMENDRA, ,#3 ALEX BOYD LINK HILLSBORO
71508050,"HUNT,  RICHARD F", ,1009 # B FATHOM DR
71508060,"HUNT,  RICHARD F", ,1009 # B FATHOM DR
71561950,"HUNT,  RICHARD F", ,1009 # B FATHOM DR
71562840,"HUNT,  RICHARD F", ,1009 # B FATHOM DR

and running

mlr --csv -N sort -f 4 then step -a counter -f 4 -g 4 then filter '$4_counter==1' then cut -x -f 4_counter input.csv >output.csv

you will have

71523180,PRASAD  JAMES ANAND, ,#3 ALEX BOYD LINK HILLSBORO
71508050,"HUNT,  RICHARD F", ,1009 # B FATHOM DR


问:
How do you make every text display perfectly in the center of the image?
Look that every text is displayed below the picture. I would like every text to be displayed perfectly in the center of the picture.

Here is the code:
https://jsfiddle.net/Krzysiek_35/Ljybwz97/37/

body {
  left: 8%;
  top: 10%;
  position: absolute;
  background-color: #6699cc;
}

.box3 {
    background-color: #191919;
    position: absolute;
    padding: 15px 40px 15px;
    font-size: 12px;
    color: #DDDDDD;
    font-family: Verdana;
    font-size: 12px;
    width: 400px;
}

.box3 > li {
    display: block;
}

.box3 > li span {
    display: inline-block;
    vertical-align: middle;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="box3">
    <li>
      <img src="pictures/contact/skype.png" width="34px" height="34px" />
      <span>Skype name</span>
    </li>
    <li>
      <img src="pictures/contact/gadu-gadu.png" width="34px" height="34px" />
      <span>Gadu-Gadu number</span>
    </li>
    <li>
      <img src="pictures/contact/email.png" width="34px" height="34px" />
      <span>Email address</span>
    </li>
  </div>
</body></code>```

How do you make every text display perfectly in the center of the image?

I will be very grateful for effective help.

答:
you can use this also</p>

```<code>.box3 > li span
{
display: inline-block;
vertical-align: middle;
margin-top:-30px;
}
</code>```

Body:
Look that every text is displayed below the picture. I would like every text to be displayed perfectly in the center of the picture.

Here is the code:
https://jsfiddle.net/Krzysiek_35/Ljybwz97/37/

body {
  left: 8%;
  top: 10%;
  position: absolute;
  background-color: #6699cc;
}

.box3 {
    background-color: #191919;
    position: absolute;
    padding: 15px 40px 15px;
    font-size: 12px;
    color: #DDDDDD;
    font-family: Verdana;
    font-size: 12px;
    width: 400px;
}

.box3 > li {
    display: block;
}

.box3 > li span {
    display: inline-block;
    vertical-align: middle;
}

      Skype name

      Gadu-Gadu number

      Email address

How do you make every text display perfectly in the center of the image?

I will be very grateful for effective help.

Body:
you can use this also

.box3 > li span
{
display: inline-block;
vertical-align: middle;
margin-top:-30px;
}


问:
whoami command is showing different user name in jenkins cli and linux cli although workspace i
enter image description hereHi All,

"whoami" command is showing as different user. when I am giving this command in jenkins cli it is showing as jenkins but in the same workspace when I am giving this command in linux CLI it is showing as lokeshk.I have followed many forum, link and community in the internet but still I am facing this issue. I have attached screenshot please have a look.Any leads will be appreciated.

enter image description here

答:
While installing jenkins, by default it creates a user with name jenkins and all operations get executed under same user. So, when you are using jenkins-cli to check whoami, it shows jenkins user.

Seeing your attached screeshot, I believe you logged in to linux-cli with lokeshk user so when you check for whoami in linux-cli it is showing lokeshk user.

Note: whoami command is used to print the loggedin user name, irrespective of the workspace where you are right now and by whom it was created.

Example:

Lets assume a system have two users user1 and user2. user1 created a directory named user1_dir. If you loggin with user2 and perform whoami in user1_dir(or anywhere), it will result in user2 as user2 is the logged in user.


问:
Contain snippet of word in array (Python)
I don't know where to start asking but here's some rough code what am I going to do

```<code>arr = ['cat', 'dog']
if('housecat' not in arr):
        return TRUE
else return FALSE
</code>```

What I want is: it return as TRUE because 'cat' was in the array while 'housecat' contain 'cat'.

==Edit==

I've tried code suggested

```<code>arr = ['cat', 'dog']
for i in arr:
        if(i not in 'housecat'):
                return TRUE
        else return FALSE
</code>```

It return as TRUE as intended, but if there's symbol in the input (e.g: house-cat, cat.I (Only tested with those 2 symbol because input is automated)) it'll return as FALSE which should be TRUE (because there's 'cat' in house-'cat').

Edit 3: Should be return as TRUE not FALSE, my bad, edited the whole writing.

Edit 4: Case closed, bug appeared when I run the whole code and it has nothing to do with this case.

答:
One liner

```<code>arr = ['cat', 'dog']
is_housecat = lambda x: not any([i in 'housecat' for i in arr])

print(is_housecat(arr))
</code>```

Output

False

Body:
I don't know where to start asking but here's some rough code what am I going to do

arr = ['cat', 'dog']
if('housecat' not in arr):
        return TRUE
else return FALSE

What I want is: it return as TRUE because 'cat' was in the array while 'housecat' contain 'cat'.

==Edit==

I've tried code suggested

arr = ['cat', 'dog']
for i in arr:
        if(i not in 'housecat'):
                return TRUE
        else return FALSE

It return as TRUE as intended, but if there's symbol in the input (e.g: house-cat, cat.I (Only tested with those 2 symbol because input is automated)) it'll return as FALSE which should be TRUE (because there's 'cat' in house-'cat').

Edit 3: Should be return as TRUE not FALSE, my bad, edited the whole writing.

Edit 4: Case closed, bug appeared when I run the whole code and it has nothing to do with this case.

Body:
One liner

arr = ['cat', 'dog']
is_housecat = lambda x: not any([i in 'housecat' for i in arr])

print(is_housecat(arr))

Output

False


问:
Linear regression with infinite slope
I know how to perform simple linear regression in R but how to perform the regression with infinite slope (see an example with same dataset from excel) with R1 on x-axis and LAI1 on the y-axis.

```<code>   R1 LAI1
233.7 1.34
411.3 4.42
143.4 3.57
136.7 3.27
249.0 5.53
 59.0 1.79
186.0 4.32
185.0 2.58
</code>```

答:
What do you mean with "infinite slope"? This is how you would do it in R:

```<code>library(dplyr)
df <- tibble::tribble(
    ~R1, ~LAI1,
  233.7,  1.34,
  411.3,  4.42,
  143.4,  3.57,
  136.7,  3.27,
    249,  5.53,
     59,  1.79,
    186,  4.32,
    185,  2.58
  )

model1 <- lm(LAI1 ~ R1, data = df)
summary(model1)

plot(df$R1, df$LAI1)
abline(model1)
</code>```

Title: Linear regression with infinite slope

Body:
I know how to perform simple linear regression in R but how to perform the regression with infinite slope (see an example with same dataset from excel) with R1 on x-axis and LAI1 on the y-axis.

   R1 LAI1
233.7 1.34
411.3 4.42
143.4 3.57
136.7 3.27
249.0 5.53
 59.0 1.79
186.0 4.32
185.0 2.58

Body:
What do you mean with "infinite slope"? This is how you would do it in R:

library(dplyr)
df <- tibble::tribble(
    ~R1, ~LAI1,
  233.7,  1.34,
  411.3,  4.42,
  143.4,  3.57,
  136.7,  3.27,
    249,  5.53,
     59,  1.79,
    186,  4.32,
    185,  2.58
  )

model1 <- lm(LAI1 ~ R1, data = df)
summary(model1)

plot(df$R1, df$LAI1)
abline(model1)


问:
Method not found: void Amazon.S3.AmazonS3Client..ctor() | AmazonS3 w/ .NET / Xamarin
I am currently following Amazon's AWSSDK documentation (in particular: this) in an attempt to access AmazonS3 data on a Xamarin forms application. I ran into an error, so I started a fresh project with fresh packages, all up to date as far as I can tell, and am still encountering the same problem.

Here is the current code for the main code behind class:

```<code>public partial class MainPage : ContentPage
{
    private static IAmazonS3 client;
    private static readonly RegionEndpoint bucketRegion = RegionEndpoint.USWest2;

    public MainPage()
    {
        InitializeComponent();

        // I have tried each of the following:

        client = new AmazonS3Client();   <--- ERROR
        client = new AmazonS3Client(RegionEndpoint.USWest2);  <-- SIMILAR ERROR
        client = new AmazonS3Client(bucketRegion);  <-- SAME ERROR

        // This has a different error, lack of RegionEndpoint, which is expected, but at least this seems to be recognized
        client = new AmazonS3Client(new AnonymousAWSCredentials());

    }
}
</code>```

This results in the following runtime error on the indicated line:

Method not found: void Amazon.S3.AmazonS3Client..ctor()

I understand that MethodNotFoundExceptions often are the result of old versions of DLLs hanging around, outdated dependencies, duplicate assemblies, etc, but I have deployed this from a completely fresh project with the only packages installed being the up-to-date standard Xamarin packages and the Amazon.S3 package.

What is causing this error?

答:
The issue has nothing to do with "old dlls, outdated dependencies", etc. If you look at the example that you are following, they are not trying to call the default ctor, but instead they are initialising it through a bucket region.

If you take a look at Simple cross-platform application using the AWS SDK for .NET (or even in the documentation inside the IDE that you are using), you can see that when the default ctor is being used, you need to:

Before running this app, credentials must be specified either in the [default] profile or in another profile and then by setting the AWS_PROFILE environment variable. A region must be specified either in the [default] profile or by setting the AWS_REGION environment variable.

The docs also say that App.config can be used.

But since we will be using it for Xamarin, it will be a lot easier to use some of the others overloads. Here are some of them:

Let's say that you want to use AWSCredentials in order to generate your client. Again, you have many options here:

NB: When you initialise your client, it is a good practice to specify the RegionEndpoint. In most of the cases, if you forget, you will get a AmazonClientException: No RegionEndpoint or ServiceURL configured so it will remind you that it is required.

Edit: Due to an update in your question, here is an update from me:
The same rules apply for there ctors, that you have tried with. They are looking for credentials in config files, that are not present for a Xamarin.Forms app. In order to use the client, it needs to know about its credentials. If you need to use the client, then provide it with some credentials, during initialisation - use either some of the other AWSCredentials - Basic, Federated, etc, or use the simples one - with accessKeyId + accessKey.

If you are curious why the ctors, that you have tried, are not working, or what they are doing behind-the-scenes, their SDK is open-sourced here. The empty ctor's code is here and the more interesting FallbackCredentialsFactory here.

Body:
I am currently following Amazon's AWSSDK documentation (in particular: this) in an attempt to access AmazonS3 data on a Xamarin forms application. I ran into an error, so I started a fresh project with fresh packages, all up to date as far as I can tell, and am still encountering the same problem.

Here is the current code for the main code behind class:

public partial class MainPage : ContentPage
{
    private static IAmazonS3 client;
    private static readonly RegionEndpoint bucketRegion = RegionEndpoint.USWest2;

    public MainPage()
    {
        InitializeComponent();

        // I have tried each of the following:

        client = new AmazonS3Client();   <--- ERROR
        client = new AmazonS3Client(RegionEndpoint.USWest2);  <-- SIMILAR ERROR
        client = new AmazonS3Client(bucketRegion);  <-- SAME ERROR

        // This has a different error, lack of RegionEndpoint, which is expected, but at least this seems to be recognized
        client = new AmazonS3Client(new AnonymousAWSCredentials());

    }
}

This results in the following runtime error on the indicated line:

Method not found: void Amazon.S3.AmazonS3Client..ctor()

I understand that MethodNotFoundExceptions often are the result of old versions of DLLs hanging around, outdated dependencies, duplicate assemblies, etc, but I have deployed this from a completely fresh project with the only packages installed being the up-to-date standard Xamarin packages and the Amazon.S3 package.

What is causing this error?


问:
why doesn't my javascript function display my message?
So i connected a javascript file to my html file. When a button is clicked, it's supposed to display a message but for some reason it doesn't display anything. What am i doing wrong?
(p.s. i know very little about js)

function calc() {
  greeting = "hello"
  var usname = document.getElementById("name").innerHTML = greeting;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <p> BMI Calculator</p>
</header>
<div class="grid">
  <div class=input>
    <form>
      <p> Fill in the form below</p>
      Name: <br>
      <input type="text" name="name" id="name"><br> Weight: <br>
      <input type="number" name="weight"><br> Height: <br>
      <input type="number" name="height"><br>
      <input type="radio" name="gender" value="female">Female
      <input type="radio" name="gender" value="male">Male
      <input type="radio" name="gender" value="other">Other<br>
      <br><input type="button" onclick="calc()" name="calculate" value="calculate">
    </form>
  </div>
  <div class="result">
    <p> Your Results</p>
  </div>
</div></code>```

答:
use the following modified function :

```<code>function calc() {
greeting = "hello"
var usname = document.getElementById("name").value = greeting;
</code>```

}

Body:
So i connected a javascript file to my html file. When a button is clicked, it's supposed to display a message but for some reason it doesn't display anything. What am i doing wrong?
(p.s. i know very little about js)

function calc() {
  greeting = "hello"
  var usname = document.getElementById("name").innerHTML = greeting;
}

 BMI Calculator

    <form>

 Fill in the form below

      Name:

      <input type="text" name="name" id="name">
 Weight:

      <input type="number" name="weight">
 Height:

      <input type="number" name="height">

      <input type="radio" name="gender" value="female">Female
      <input type="radio" name="gender" value="male">Male
      <input type="radio" name="gender" value="other">Other

<input type="button" onclick="calc()" name="calculate" value="calculate">
    </form>

 Your Results

Body:
use the following modified function :

function calc() {
greeting = "hello"
var usname = document.getElementById("name").value = greeting;

}


问:
Conditional mean with groupby
For example, here is a DataFrame:

```<code>df = pd.DataFrame({'year': ['2019', '2019', '2019', '2019', '2020', '2020', '2020'],
                   'key': ['a', 'a', 'b', 'c', 'd', 'e', 'f'],
                   'val': [3, 4, 3, 5, 6, 1, 2]})
</code>```

It looks like

```<code>    year    key val
0   2019    a   3
1   2019    a   4
2   2019    b   3
3   2019    c   5
4   2020    d   6
5   2020    e   1
6   2020    f   2
</code>```

What I want to obtain is

```<code>year  key    mean_except_current_key
2019  a      4
      b      4
      c      3.33
2020  d      1.5
      e      4
      f      3.5
</code>```

That is, group df by year and key, and mean_except_current_key is defined as mean of val over year except all rows with the same key as current row.

I hope I have made this problem clear. But I can't figure out it. And I have found this question. However, it is different from mine.

Thanks for any help.

答:
Not sure if there is a better way, but here is some simple math using multiple groupby and transform:

```<code>x = df.groupby("year")["val"].transform(sum)- df.groupby(["year","key"])["val"].transform(sum)
y = df.groupby("year")["key"].transform("count").sub(df.groupby(["year","key"])["val"].transform("count"))
df["new"] = x/y
print (df)

   year key  val       new
0  2019   a    3  4.000000
1  2019   a    4  4.000000
2  2019   b    3  4.000000
3  2019   c    5  3.333333
4  2020   d    6  1.500000
5  2020   e    1  4.000000
6  2020   f    2  3.500000
</code>```

Title: Conditional mean with groupby

Body:
For example, here is a DataFrame:

df = pd.DataFrame({'year': ['2019', '2019', '2019', '2019', '2020', '2020', '2020'],
                   'key': ['a', 'a', 'b', 'c', 'd', 'e', 'f'],
                   'val': [3, 4, 3, 5, 6, 1, 2]})

It looks like

    year    key val
0   2019    a   3
1   2019    a   4
2   2019    b   3
3   2019    c   5
4   2020    d   6
5   2020    e   1
6   2020    f   2

What I want to obtain is

year  key    mean_except_current_key
2019  a      4
      b      4
      c      3.33
2020  d      1.5
      e      4
      f      3.5

That is, group df by year and key, and mean_except_current_key is defined as mean of val over year except all rows with the same key as current row.

I hope I have made this problem clear. But I can't figure out it. And I have found this question. However, it is different from mine.

Thanks for any help.

Body:
Not sure if there is a better way, but here is some simple math using multiple groupby and transform:

x = df.groupby("year")["val"].transform(sum)- df.groupby(["year","key"])["val"].transform(sum)
y = df.groupby("year")["key"].transform("count").sub(df.groupby(["year","key"])["val"].transform("count"))
df["new"] = x/y
print (df)

   year key  val       new
0  2019   a    3  4.000000
1  2019   a    4  4.000000
2  2019   b    3  4.000000
3  2019   c    5  3.333333
4  2020   d    6  1.500000
5  2020   e    1  4.000000
6  2020   f    2  3.500000


问:
How to develop a composer app with external lib projects?
With Symfony 5, I am developing an application, with bundles. Each bundle have its own repository.

In dev (local) environnement, I want my app composer, takes package via symlink, and on production , from git repositories:

```<code>{
    "type": "path",
    "url": "../common",
    "options": {
        "symlink": true
    }
},
{
    "type": "vcs",
    "url": "https://gitlab.bewizyu.com/XXX/common"
}
</code>```

What the best practice for that?

答:
The best practice is to have a local app as similar to production as possible.

Why can't you simply install your bundles from git repositories all the time? You develop a bundle, tag new version and update your main application and you are 100% sure it is the same as production.

With the symlinks, you can face a situation when production crashes and local works because there is a different setup.

Body:
With Symfony 5, I am developing an application, with bundles. Each bundle have its own repository.

In dev (local) environnement, I want my app composer, takes package via symlink, and on production , from git repositories:

{
    "type": "path",
    "url": "../common",
    "options": {
        "symlink": true
    }
},
{
    "type": "vcs",
    "url": "https://gitlab.bewizyu.com/XXX/common"
}

What the best practice for that?


问:
order and fill with 2 different variables geom_bar ggplot2 R
I have a question concerning the fill field in geom_bar of the ggplot2 package.

I would like to fill my geom_bar with a variable (in the next example the variable is called var_fill) but order the geom_plot with another variable (called clarity in the example).

How can I do that?

Thank you very much!

The example:

```<code>rm(list=ls())

set.seed(1)

library(dplyr)
data_ex <- diamonds %>%
  group_by(cut, clarity) %>%
  summarise(count = n()) %>%
  ungroup() %>%
  mutate(var_fill= LETTERS[sample.int(3, 40, replace = TRUE)])

head(data_ex)

# A tibble: 6 x 4
   cut  clarity count var_fill
  <ord>   <ord> <int>    <chr>
1  Fair      I1   210        A
2  Fair     SI2   466        B
3  Fair     SI1   408        B
4  Fair     VS2   261        C
5  Fair     VS1   170        A
6  Fair    VVS2    69        C
</code>```

I would like this order of the boxes [clarity] :

```<code>library(ggplot2)
ggplot(data_ex) +
  geom_bar(aes(x = cut, y = count, fill=clarity),stat = "identity", position = "fill", color="black")
</code>```

with this fill (color) of the boxes [var_fill] :

```<code>ggplot(data_ex) +
  geom_bar(aes(x = cut, y = count, fill=var_fill),stat = "identity", position = "fill", color="black")
</code>```

EDIT1 : answer found by missuse :

```<code>p1 <- ggplot(data_ex) + geom_bar(aes(x = cut, y = count, group = clarity, fill = var_fill), stat = "identity", position = "fill", color="black")+ ggtitle("var fill")

p2 <- ggplot(data_ex) +  geom_bar(aes(x = cut, y = count, fill = clarity), stat = "identity", position = "fill", color = "black")+ ggtitle("clarity")

library(cowplot)
cowplot::plot_grid(p1, p2)
</code>```

EDIT2 : Now i tried to do this with ggmosaic extension with the help of missuse

```<code>rm(list=ls())
set.seed(1)
library(ggplot2)
library(dplyr)
library(ggmosaic)

data_ex <- diamonds %>%
  group_by(cut, clarity) %>%
  summarise(count = n()) %>%
  ungroup() %>%
  mutate(residu= runif(nrow(.), min=-4.5, max=5)) %>%
  mutate(residu_classe = case_when(residu < -4~"< -4 (p<0.001)",(residu >= -4 & residu < -2)~"[-4;-2[ (p<0.05)",(residu >= -2 & residu < 2)~"[-2;2[ non significatif",(residu >= 2 & residu < 4)~"[2;4[ (p<0.05)",residu >= 4~">= 4 (p<0.001)")) %>%
  mutate(residu_color = case_when(residu < -4~"#D04864",(residu >= -4 & residu < -2)~"#E495A5",(residu >= -2 & residu < 2)~"#CCCCCC",(residu >= 2 & residu < 4)~"#9DA8E2",residu >= 4~"#4A6FE3"))

ggplot(data_ex) +
  geom_mosaic(aes(weight= count, x=product(clarity, cut)),  fill = data_ex$residu_color, na.rm=T)+
  scale_y_productlist() +
  theme_classic() +
  theme(axis.ticks=element_blank(), axis.line=element_blank())+
  labs(x = "cut",y="clarity")
</code>```

But I would like to add this legend (below) on the right of the plot but I don't know how I could do it because the fill field is outside aes so scale_fill_manual does not work...

答:
In the current version of ggplot2 3.3.0 this should work</p>

```<code>ggplot(data_ex) +
  geom_bar(aes(x = cut, y = count, fill=var_fill, group=clarity),stat = "identity", position = "fill", color="black")
</code>```

Body:
I have a question concerning the fill field in geom_bar of the ggplot2 package.

I would like to fill my geom_bar with a variable (in the next example the variable is called var_fill) but order the geom_plot with another variable (called clarity in the example).

How can I do that?

Thank you very much!

The example:

rm(list=ls())

set.seed(1)

library(dplyr)
data_ex <- diamonds %>%
  group_by(cut, clarity) %>%
  summarise(count = n()) %>%
  ungroup() %>%
  mutate(var_fill= LETTERS[sample.int(3, 40, replace = TRUE)])

head(data_ex)

# A tibble: 6 x 4
   cut  clarity count var_fill
  <ord>   <ord> <int>    <chr>
1  Fair      I1   210        A
2  Fair     SI2   466        B
3  Fair     SI1   408        B
4  Fair     VS2   261        C
5  Fair     VS1   170        A
6  Fair    VVS2    69        C

I would like this order of the boxes [clarity] :

library(ggplot2)
ggplot(data_ex) +
  geom_bar(aes(x = cut, y = count, fill=clarity),stat = "identity", position = "fill", color="black")

with this fill (color) of the boxes [var_fill] :

ggplot(data_ex) +
  geom_bar(aes(x = cut, y = count, fill=var_fill),stat = "identity", position = "fill", color="black")

EDIT1 : answer found by missuse :

p1 <- ggplot(data_ex) + geom_bar(aes(x = cut, y = count, group = clarity, fill = var_fill), stat = "identity", position = "fill", color="black")+ ggtitle("var fill")

p2 <- ggplot(data_ex) +  geom_bar(aes(x = cut, y = count, fill = clarity), stat = "identity", position = "fill", color = "black")+ ggtitle("clarity")

library(cowplot)
cowplot::plot_grid(p1, p2)

EDIT2 : Now i tried to do this with ggmosaic extension with the help of missuse

rm(list=ls())
set.seed(1)
library(ggplot2)
library(dplyr)
library(ggmosaic)

data_ex <- diamonds %>%
  group_by(cut, clarity) %>%
  summarise(count = n()) %>%
  ungroup() %>%
  mutate(residu= runif(nrow(.), min=-4.5, max=5)) %>%
  mutate(residu_classe = case_when(residu < -4~"< -4 (p<0.001)",(residu >= -4 & residu < -2)~"[-4;-2[ (p<0.05)",(residu >= -2 & residu < 2)~"[-2;2[ non significatif",(residu >= 2 & residu < 4)~"[2;4[ (p<0.05)",residu >= 4~">= 4 (p<0.001)")) %>%
  mutate(residu_color = case_when(residu < -4~"#D04864",(residu >= -4 & residu < -2)~"#E495A5",(residu >= -2 & residu < 2)~"#CCCCCC",(residu >= 2 & residu < 4)~"#9DA8E2",residu >= 4~"#4A6FE3"))

ggplot(data_ex) +
  geom_mosaic(aes(weight= count, x=product(clarity, cut)),  fill = data_ex$residu_color, na.rm=T)+
  scale_y_productlist() +
  theme_classic() +
  theme(axis.ticks=element_blank(), axis.line=element_blank())+
  labs(x = "cut",y="clarity")

But I would like to add this legend (below) on the right of the plot but I don't know how I could do it because the fill field is outside aes so scale_fill_manual does not work...

Body:
In the current version of ggplot2 3.3.0 this should work

ggplot(data_ex) +
  geom_bar(aes(x = cut, y = count, fill=var_fill, group=clarity),stat = "identity", position = "fill", color="black")


问:
How to add all the items of a list box to a textbox
I have a number of ListBox items, which I need to copy to a TextBox. I have somewhat got it working, but the TextBox seems to be adding a vbnewline after my Value1. I feel like I'm missing something obvious.

Here is my code:

TextBox2.Text = ""
For Each I As String In ListBox1.Items
    TextBox2.Text = TextBox2.Text & I
Next
```

Here is a screenshot because this I can’t post the TextBox since it will come out looking the same as the ‘ListBox`.

答:
Your list items probably have newlines in them. ListBox wont show these, but TextBox will

```<code>TextBox2.Clear()
For Each I As String In ListBox1.Items
    TextBox2.AppendText(I.Replace(vbCr, "").Replace(vbLf, ""))
    TextBox2.AppendText(Environment.NewLine)
Next
</code>```

Please name your controls something more meaningful than "ListBox1" (how about "_SiteList" ?) or "TextBox2". It takes a couple of seconds to click the (Name) line in the properties grid and type something else, after you drop a control on a form.

By the time you're done adding 27 textboxes, 54 labels, 6 lists, 9 numeric updowns, a few grids, checkboxes, radio buttons etc your entire program code is going to be unbelievably hard to understand and you'll constantly be flicking back and forth between the deisgner and the code wondering "what did I call the textbox with the URL in.. TextBox37, or TextBox38?"

You'll also struggle to get help if your code looks like TextBox16.Text = List5.Items.Count & If(NumericUpDown38.Value > Grid13.Count, Checkbox62.Checked, Checkbox12.Checked) - good naming is vital; just think if Microsoft didn't choose clear and relevant property names like .Text or .Items, coding wouldn't be much fun writing urlTextBox.String1 = "" or For Each x as String in siteList.ObjectCollection1

Body:
I have a number of ListBox items, which I need to copy to a TextBox. I have somewhat got it working, but the TextBox seems to be adding a vbnewline after my Value1. I feel like I'm missing something obvious.

Here is my code:

TextBox2.Text = ""
For Each I As String In ListBox1.Items
    TextBox2.Text = TextBox2.Text & I
Next

Here is a screenshot because this I can’t post the TextBox since it will come out looking the same as the ‘ListBox`.

Body:
Your list items probably have newlines in them. ListBox wont show these, but TextBox will

TextBox2.Clear()
For Each I As String In ListBox1.Items
    TextBox2.AppendText(I.Replace(vbCr, "").Replace(vbLf, ""))
    TextBox2.AppendText(Environment.NewLine)
Next

Please name your controls something more meaningful than "ListBox1" (how about "_SiteList" ?) or "TextBox2". It takes a couple of seconds to click the (Name) line in the properties grid and type something else, after you drop a control on a form.

By the time you're done adding 27 textboxes, 54 labels, 6 lists, 9 numeric updowns, a few grids, checkboxes, radio buttons etc your entire program code is going to be unbelievably hard to understand and you'll constantly be flicking back and forth between the deisgner and the code wondering "what did I call the textbox with the URL in.. TextBox37, or TextBox38?"

You'll also struggle to get help if your code looks like TextBox16.Text = List5.Items.Count & If(NumericUpDown38.Value > Grid13.Count, Checkbox62.Checked, Checkbox12.Checked) - good naming is vital; just think if Microsoft didn't choose clear and relevant property names like .Text or .Items, coding wouldn't be much fun writing urlTextBox.String1 = "" or For Each x as String in siteList.ObjectCollection1


问:
Actually delete a git commit in such a way that it disappears from the log
I cannot find a way to delete a targeted commit from the log. Documentation about deleting commits either just resets a pointer using reset (which does not delete anything, it just resets pointers), or rebase, which creates a new structure of some sort at the deleted commit. The hash of the targeted commit still appears. There may be old documentation out there related to

```<code>git rebase -i fork1~1 fork1~3
</code>```

because in older messages, it states to delete a line in the editor, that is, the line corresponding to the targeted commit. When I get into the interactive editor, one of the choices is "drop", which it says removes the commit. However, I have not successfully removed any commits in the sense that they disappear from the log. I insert the word drop, and it creates some sort of fork-looking thing in the log output. But I can still see the hash of the commit I am trying to remove. Simply put, I want to identify a hash to remove and have it no longer appear in the log.

So, the idea here is to drop 1bc7112:

```<code>*   4518859 (refs/stash) WIP on fork3: 8c438a9 Added first.bsh back in
|\
| * 1bc7112 index on fork3: 8c438a9 Added first.bsh back in
|/
* 8c438a9 Added first.bsh back in
* eef828f (HEAD -> fork4) Removed using git rm
* c21cda0 Third change.
</code>```

答:
When making a git rebase -i HEAD~X where X is the number of commits to rebase, you can rebase in interactive mode. You'll see (for example) the following options :

```<code>pick 0a3e7b9 other commit
pick 7cfa14c commit to remove

# Rebase 04ec4b7..7cfa14c onto 04ec4b7 (2 commands)
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
# d, drop = remove commit
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out
</code>```

Type i in order to edit, next you can add d or drop, before the commit you want to remove, for example :

```<code>d 7cfa14c commit to remove
</code>```

Let pick before all other commits, then type esc in order to escape edit mode and :wq in order to save and quit.

Now commit will be removed locally, next push update on remote branch using git push --force origin <remote_branch>, note the --force option, required because of rebase.

Body:
I cannot find a way to delete a targeted commit from the log. Documentation about deleting commits either just resets a pointer using reset (which does not delete anything, it just resets pointers), or rebase, which creates a new structure of some sort at the deleted commit. The hash of the targeted commit still appears. There may be old documentation out there related to

git rebase -i fork1~1 fork1~3

because in older messages, it states to delete a line in the editor, that is, the line corresponding to the targeted commit. When I get into the interactive editor, one of the choices is "drop", which it says removes the commit. However, I have not successfully removed any commits in the sense that they disappear from the log. I insert the word drop, and it creates some sort of fork-looking thing in the log output. But I can still see the hash of the commit I am trying to remove. Simply put, I want to identify a hash to remove and have it no longer appear in the log.

So, the idea here is to drop 1bc7112:

*   4518859 (refs/stash) WIP on fork3: 8c438a9 Added first.bsh back in
|\
| * 1bc7112 index on fork3: 8c438a9 Added first.bsh back in
|/
* 8c438a9 Added first.bsh back in
* eef828f (HEAD -> fork4) Removed using git rm
* c21cda0 Third change.

Body:
When making a git rebase -i HEAD~X where X is the number of commits to rebase, you can rebase in interactive mode. You'll see (for example) the following options :

pick 0a3e7b9 other commit
pick 7cfa14c commit to remove

# Rebase 04ec4b7..7cfa14c onto 04ec4b7 (2 commands)
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
# d, drop = remove commit
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out

Type i in order to edit, next you can add d or drop, before the commit you want to remove, for example :

d 7cfa14c commit to remove

Let pick before all other commits, then type esc in order to escape edit mode and :wq in order to save and quit.

Now commit will be removed locally, next push update on remote branch using git push --force origin <remote_branch>, note the --force option, required because of rebase.


问:
C# BackgroundWorker blocking on Database call in DoWork handler
I am trying to follow the BackgroundWorker example listed here http://msdn.microsoft.com/en-us/library/wkays279.aspx under the heading of "Returning Values from Multithreaded Procedures
"

I put a time consuming call to the database in the DoWork event handler of the BackgroundWorker. I expect that once I call BackgroundWorkerAsync(object) that this call will happen in the background and not block the rest of the application from executing. The problem is this does not happen. The whole application locks up and waits for the database call to return. Once it returns, the application is responsive again.

Here is my code

```<code>    //initialization in a method.
    Worker.DoWork += new DoWorkEventHandler(Worker_DoWork);
    Worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Worker_RunWorkerCompleted);

    private void Worker_DoWork(object sender, DoWorkEventArgs e)
    {
        Retriever temp = (Retriever)e.Argument;
        e.Result = temp.RetrieveLongDBCallThatReturnsADataSet()  //App blocks until done.
    }

   private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        System.Data.DataSet result = (System.Data.DataSet)e.Result;

        //Do stuff with the DataSet.
    }

    public void Retrieve(object arg1, object arg2, object arg3)
    {
        Retriever temp = new Retriever();

        InitializeBackgroundWorker(); //wire up events

        temp.Prop1 = arg1;
        temp.Prop2 = arg2;
        temp.Prop3 = arg3;

        Worker.RunWorkerAsync(temp);

        //Code that is expected to start executing, but instead blocks until temp.RetrieveLongDBCallThatReturnsADataSet() finishes.
    }
</code>```

Can anyone see what I am missing here? I did the same type of thing with a call to a WebService and that seems to be working fine.

答:
This should not happen unless:

You are waiting for the database result (or something which blocks UI thread) on the next lines after calling DoWork asynchronously.

Put a Break Point on the next line after calling RunWorkerAsync and you should get the flow immediately (or add that code to your question)

Body:
I am trying to follow the BackgroundWorker example listed here http://msdn.microsoft.com/en-us/library/wkays279.aspx under the heading of "Returning Values from Multithreaded Procedures
"

I put a time consuming call to the database in the DoWork event handler of the BackgroundWorker. I expect that once I call BackgroundWorkerAsync(object) that this call will happen in the background and not block the rest of the application from executing. The problem is this does not happen. The whole application locks up and waits for the database call to return. Once it returns, the application is responsive again.

Here is my code

    //initialization in a method.
    Worker.DoWork += new DoWorkEventHandler(Worker_DoWork);
    Worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Worker_RunWorkerCompleted);

    private void Worker_DoWork(object sender, DoWorkEventArgs e)
    {
        Retriever temp = (Retriever)e.Argument;
        e.Result = temp.RetrieveLongDBCallThatReturnsADataSet()  //App blocks until done.
    }

   private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        System.Data.DataSet result = (System.Data.DataSet)e.Result;

        //Do stuff with the DataSet.
    }

    public void Retrieve(object arg1, object arg2, object arg3)
    {
        Retriever temp = new Retriever();

        InitializeBackgroundWorker(); //wire up events

        temp.Prop1 = arg1;
        temp.Prop2 = arg2;
        temp.Prop3 = arg3;

        Worker.RunWorkerAsync(temp);

        //Code that is expected to start executing, but instead blocks until temp.RetrieveLongDBCallThatReturnsADataSet() finishes.
    }

Can anyone see what I am missing here? I did the same type of thing with a call to a WebService and that seems to be working fine.


答:
Good morning @samuelallain, yes, I have used library(data.table) before.
I've edited it in the main commentary.

I have tried its solution and RStudio returns the following error:

```<code>library(data.table)
df_joined = df_bestquotes[df_transactions, on=.("day", "time"), roll = TRUE]
</code>```

Error in [.data.frame(df_bestquotes, df_transactions, on = .(day, time), :

  unused arguments (on = .("day", "time"), roll = TRUE)

Thank you.

Title: Merge two data frames in R by the closest default options, not by excess

Body:
i have two dataframes:

df_bestquotes

df_transactions

df_transactions:

day time        vol price   buy ask     bid
1   43688,08    100 195,8   1   195,8   195,74
1   56357,34    20  192,87  1   192,87  192,86
1   57576,14    14  192,48  -1  192,48  192,46
2   50468,29    3   193,83  1   193,86  193,77
2   56107,54    11  194,17  -1  194,2   194,16
7   42549,66    100 188,81  -1  188,85  188,78
7   42724,38    200 188,62  -1  188,66  188,61
7   48924,66    5   189,59  -1  189,62  189,59
8   48950,14    52  187,66  -1  187,7   187,66
9   36242,86    89  186,61  1   186,62  186,56
9   53910,46    1   189,81  -1  189,87  189,81
10  47041,94    15  187,87  -1  187,88  187,86
13  34380,73    87  187,29  -1  187,42  187,27
13  36037,18    100 188,94  1   188,95  188,94
14  46644,64    100 189,29  -1  189,34  189,29
14  57571,12    52  190,03  1   190,03  190
15  36418,71    45  192,07  1   192,07  192,04
15  37223,77    100 191,09  -1  191,07  191,06
17  37245,59    100 186,45  -1  186,47  186,45
23  34200,39    50  189,29  -1  189,29  189,27
24  40294,73    60  193,52  -1  193,54  193,5
29  52813,68    5   202,99  -1  203,01  202,99
29  55279,13    93  203,97  -1  203,98  203,9
30  51356,91    68  204,41  -1  204,45  204,4
30  53530,24    40  204,14  -1  204,18  204,14

df_bestquotes:

day time       best_ask best_bid
1   51384,613   31,78   31,75
1   56593,74    31,6    31,55
3   40568,217   31,36   31,32
7   39169,237   31,34   31,28
8   44715,713   31,2    31,17
8   53730,707   31,24   31,19
8   55851,75    31,17   31,14
10  49376,267   31,06   30,99
16  48610,483   30,75   30,66
16  57360,917   30,66   30,64
17  53130,717   30,39   30,32
20  46353,133   30,72   30,63
23  46429,67    29,7    29,64
24  37627,727   29,81   29,63
24  46354,647   29,92   29,77
24  53863,69    30,04   29,93
24  53889,923   30,03   29,95
24  59047,223   29,99   29,2
28  39086,407   30,87   30,83
28  41828,703   30,87   30,8
28  50489,367   30,99   30,87
29  54264,467   30,97   30,85
30  34365,95    31,21   30,99
30  39844,357   31,06   31
30  57550,523   31,18   31,15

For each record of the df_transactions, from the day and time, I need to find the best_ask and the best_bid that was just before that moment, and incorporate this information to df_transactions.

df_joined: df_transactions + df_bestquotes

day time        vol price   buy ask     bid     best_ask   best_bid
1   43688,08    100 195,8   1   195,8   195,74
1   56357,34    20  192,87  1   192,87  192,86
1   57576,14    14  192,48  -1  192,48  192,46
2   50468,29    3   193,83  1   193,86  193,77
2   56107,54    11  194,17  -1  194,2   194,16
7   42549,66    100 188,81  -1  188,85  188,78
7   42724,38    200 188,62  -1  188,66  188,61
7   48924,66    5   189,59  -1  189,62  189,59
8   48950,14    52  187,66  -1  187,7   187,66
9   36242,86    89  186,61  1   186,62  186,56
9   53910,46    1   189,81  -1  189,87  189,81
10  47041,94    15  187,87  -1  187,88  187,86
13  34380,73    87  187,29  -1  187,42  187,27
13  36037,18    100 188,94  1   188,95  188,94
14  46644,64    100 189,29  -1  189,34  189,29
14  57571,12    52  190,03  1   190,03  190
15  36418,71    45  192,07  1   192,07  192,04
15  37223,77    100 191,09  -1  191,07  191,06
17  37245,59    100 186,45  -1  186,47  186,45
23  34200,39    50  189,29  -1  189,29  189,27
24  40294,73    60  193,52  -1  193,54  193,5
29  52813,68    5   202,99  -1  203,01  202,99
29  55279,13    93  203,97  -1  203,98  203,9
30  51356,91    68  204,41  -1  204,45  204,4
30  53530,24    40  204,14  -1  204,18  204,14

I have tried with the next code, but it doesn't work:

library(data.table)
df_joined = df_bestquotes[df_transactions, on="time", roll = "nearest"]

Here are the real files with a lot more records, the ones I put before are an example of only 25 records.

df_transactions_original

df_bestquotes_original

And my code in R:

matching.R

Any suggestions on how to get it? Thanks a lot, guys.

Body:
Good morning @samuelallain, yes, I have used library(data.table) before.
I've edited it in the main commentary.

I have tried its solution and RStudio returns the following error:

library(data.table)
df_joined = df_bestquotes[df_transactions, on=.("day", "time"), roll = TRUE]

Error in [.data.frame(df_bestquotes, df_transactions, on = .(day, time), :

  unused arguments (on = .("day", "time"), roll = TRUE)

Thank you.


问:
Getting "No file" or empty file when trying to download PDF file with Node.js
The issue:

I need to download a PDF file from my server but getting either "No file" or empty file

Details:

Here is my server-side code:

```<code>let fileBuffered = '';

// authentication for downloading a file from Dropbox API to my server
    const dropbox = dropboxV2Api.authenticate({
        token: process.env.DEV_DROPBOX_SECRET_KEY
    });

    // configuring parameters
    const params = Object.freeze({
        resource: "files/download",
        parameters: {
            path: `/${customerFileFolder}/${fileName}`
        }
    });

    let dropboxPromise = new Promise(function (resolve, reject) {
        dropbox(params, function (err, result) {
            if (err) {
                reject(err);
            } else {
                resolve(result);
            }
        }).on('data',function(data) {
                fileBuffered += data;
        })
    const file = fileBuffered;

    res.setHeader("Content-Type", "application/octet-stream");
    res.send(file);
</code>```

The PDF file's that I'm trying to download size is 139,694 bytes. The length of the fileBuffered variable is 132,597. Here is the content of the variable as it is shown in the debugger:

Seems like a legit PDF file

Here is the client-side

```<code>function documentFileDownload(fileName) {
    const ip = location.host;
    let request = $.ajax({
        type: "POST",
        url: `${http() + ip}/documentFileDownload`,

        headers: {
            "Accept": "application/octet-stream"
        },

        data: {
            fileName: fileName
        },
        error: function (err) {
            console.log("ERROR: " + err);
        }
    });

    console.log(request);

    return request;
}
</code>```

Problem:
Then I get the response on a client-side it looks like this:

Note the size of the responseText: 254Kb.
What I actually get in the browser is a "Failed - No file" message

What else I tried:

I tried to play with different Content-Types (application/pdf, text/pdf) on a server-side and tried to convert the variable to base64 buffer

```<code>const file = `data:application/pdf;base64, ${Buffer.from(fileBuffered).toString("base64")}`;
</code>```

and added res.setHeader("Accept-Encoding", "base64");
but still getting the same result.

Any ideas?

答:
Try adding dataType: "blob" in your $.ajax method

and within the headers object add this 'Content-Type', 'application/json'.

Body:
The issue:

I need to download a PDF file from my server but getting either "No file" or empty file

Details:

Here is my server-side code:

let fileBuffered = '';

// authentication for downloading a file from Dropbox API to my server
    const dropbox = dropboxV2Api.authenticate({
        token: process.env.DEV_DROPBOX_SECRET_KEY
    });

    // configuring parameters
    const params = Object.freeze({
        resource: "files/download",
        parameters: {
            path: `/${customerFileFolder}/${fileName}`
        }
    });

    let dropboxPromise = new Promise(function (resolve, reject) {
        dropbox(params, function (err, result) {
            if (err) {
                reject(err);
            } else {
                resolve(result);
            }
        }).on('data',function(data) {
                fileBuffered += data;
        })
    const file = fileBuffered;

    res.setHeader("Content-Type", "application/octet-stream");
    res.send(file);

The PDF file's that I'm trying to download size is 139,694 bytes. The length of the fileBuffered variable is 132,597. Here is the content of the variable as it is shown in the debugger:

Seems like a legit PDF file

Here is the client-side

function documentFileDownload(fileName) {
    const ip = location.host;
    let request = $.ajax({
        type: "POST",
        url: `${http() + ip}/documentFileDownload`,

        headers: {
            "Accept": "application/octet-stream"
        },

        data: {
            fileName: fileName
        },
        error: function (err) {
            console.log("ERROR: " + err);
        }
    });

    console.log(request);

    return request;
}

Problem:
Then I get the response on a client-side it looks like this:

Note the size of the responseText: 254Kb.
What I actually get in the browser is a "Failed - No file" message

What else I tried:

I tried to play with different Content-Types (application/pdf, text/pdf) on a server-side and tried to convert the variable to base64 buffer

const file = `data:application/pdf;base64, ${Buffer.from(fileBuffered).toString("base64")}`;

and added res.setHeader("Accept-Encoding", "base64");
but still getting the same result.

Any ideas?


问:
How to install 'warnings' package in Python?
I've seen Python programs using

```<code>import warnings
</code>```

How to install that package? I tried

```<code>pip install --upgrade warnings
</code>```

and got an error

```<code>Collecting warnings
  Could not find a version that satisfies the requirement warnings (from versions: )
No matching distribution found for warnings
</code>```

答:
pip install pytest-warnings

Use this command for warnings installation

Body:
I've seen Python programs using

import warnings

How to install that package? I tried

pip install --upgrade warnings

and got an error

Collecting warnings
  Could not find a version that satisfies the requirement warnings (from versions: )
No matching distribution found for warnings


问:
Android sockets not reveving data from server
I am trying to send data from python server to android client but it is not accepting any data from the server. but it is showing that it is connected with the server. i cant recognize any error.

here is my client code in android java.

```<code>package com.example.socketinput;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {
    Thread Thread1 = null;
    String SERVER_IP="192.168.1.6";
    int SERVER_PORT=9857;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Thread1 = new Thread(new Thread1());
        Thread1.start();
    }
    private PrintWriter output;
    private BufferedReader input;
    class Thread1 implements Runnable {
        public void run() {
            Socket socket;
            try {
                socket = new Socket(SERVER_IP, SERVER_PORT);
                output = new PrintWriter(socket.getOutputStream());
                input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.i("Server", "Connected");
                    }
                });
                new Thread(new Thread2()).start();
            } catch (IOException e) {
                Log.i("Server", "Error in thread 1");
            }
        }
    }
    class Thread2 implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    final String message = input.readLine();
                    if (message != null) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Log.i("Server", message);
                            }
                        });
                    } else {
                        Thread1 = new Thread(new Thread1());
                        Thread1.start();
                        return;
                    }
                } catch (IOException e) {
                    Log.i("Server", "Error in thread 2");
                    e.printStackTrace();
                }
            }
        }
    }
}
</code>```

here is my python server code .

```<code>#!/usr/bin/env python
# coding: utf-8

# In[1]:

import socket

# In[2]:
socket.gethostname()

s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 9857))
s.listen(5)

# In[ ]:

while True:
    clientsocket, address = s.accept()
    print(f"connection from {address} has been established!")
    clientsocket.send(bytes("welcome to the server!","utf-8"))

    while True:
        msg=input()
        clientsocket.send(bytes(msg,"utf-8"))
</code>```

android manifent file is-:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.socketinput">
    <uses-permission android:name = "android.permission.INTERNET" />
    <uses-permission android:name = "android.permission.ACCESS_NETWORK_STATE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

Note-Android app and python code is connected on same server.

答:
final String message = input.readLine(); wait until get '\n'

You need to clientsocket.send(bytes("\n")) when you want to stop sending.

```<code>while True:
    clientsocket, address = s.accept()
    print(f"connection from {address} has been established!")
    clientsocket.send(bytes("welcome to the server!\n","utf-8"))
</code>```

Body:
I am trying to send data from python server to android client but it is not accepting any data from the server. but it is showing that it is connected with the server. i cant recognize any error.

here is my client code in android java.

package com.example.socketinput;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {
    Thread Thread1 = null;
    String SERVER_IP="192.168.1.6";
    int SERVER_PORT=9857;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Thread1 = new Thread(new Thread1());
        Thread1.start();
    }
    private PrintWriter output;
    private BufferedReader input;
    class Thread1 implements Runnable {
        public void run() {
            Socket socket;
            try {
                socket = new Socket(SERVER_IP, SERVER_PORT);
                output = new PrintWriter(socket.getOutputStream());
                input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.i("Server", "Connected");
                    }
                });
                new Thread(new Thread2()).start();
            } catch (IOException e) {
                Log.i("Server", "Error in thread 1");
            }
        }
    }
    class Thread2 implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    final String message = input.readLine();
                    if (message != null) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Log.i("Server", message);
                            }
                        });
                    } else {
                        Thread1 = new Thread(new Thread1());
                        Thread1.start();
                        return;
                    }
                } catch (IOException e) {
                    Log.i("Server", "Error in thread 2");
                    e.printStackTrace();
                }
            }
        }
    }
}

here is my python server code .

#!/usr/bin/env python
# coding: utf-8

# In[1]:

import socket

# In[2]:
socket.gethostname()

s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 9857))
s.listen(5)

# In[ ]:

while True:
    clientsocket, address = s.accept()
    print(f"connection from {address} has been established!")
    clientsocket.send(bytes("welcome to the server!","utf-8"))

    while True:
        msg=input()
        clientsocket.send(bytes(msg,"utf-8"))

android manifent file is-:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.socketinput">
    <uses-permission android:name = "android.permission.INTERNET" />
    <uses-permission android:name = "android.permission.ACCESS_NETWORK_STATE" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Note-Android app and python code is connected on same server.

Body:
final String message = input.readLine(); wait until get '\n'

You need to clientsocket.send(bytes("\n")) when you want to stop sending.

while True:
    clientsocket, address = s.accept()
    print(f"connection from {address} has been established!")
    clientsocket.send(bytes("welcome to the server!\n","utf-8"))


问:
Drawing on a canvas control in WPF using MVVM
I'm trying to convert my application to use the MVVM pattern. I currently have a custom canvas object that inherits form the standard canvas object, and overrides the OnRender event.

I am not quite sure how to convert this method to use the MVVM pattern.

Currently, I have an event wired up to different keypresses, to control the canvas and allows the user to scroll. I have gotten the event stuff wired up in MVVM using MvvmLight. I am just unsure about how when the Command fires in the view, that it updates the canvas. Currently there is a method that is called, that tells the control which direction the user has moved. (I basically pass in a location which is the index of an array).

Just not sure what I should be doing here.

答: I ended up going with DependencyProperties and using the DependencyProperties OnPropertyChanged Event Callback to update the graphics. </p>


问:
(KDB+/q) Get diagonal elements of a matrix
I want to get all the diagonal elements of a matrix in kdb+/q.

E.g.

```<code>q)A:(1 2 3; 4 5 6; 7 8 9)
q)A
1 2 3
4 5 6
7 8 9
</code>```

would return 1 5 9

My idea is to use "." to get the elements.

```<code>q) A . 1 1 / one of the diagonal elements
5
q) 2 #' til 3 / indices
0 0
1 1
2 2
</code>```

But I tried many ways and can't get it working.

答:
Following code returns diagonal elements of matrix

```<code>(1 2 3; 4 5 6; 7 8 9) @' til 3
</code>```

The code

generates continuous list 0, 1, 2 on the right

Gets an element from every list on the left by applying corresponding index on the right (@' adverb)

Generic form looks like:

```<code>getDiagonal: {x@'til count x};
getDiagonal (1 2 3; 4 5 6; 7 8 9)
</code>```

Body:
I want to get all the diagonal elements of a matrix in kdb+/q.

E.g.

q)A:(1 2 3; 4 5 6; 7 8 9)
q)A
1 2 3
4 5 6
7 8 9

would return 1 5 9

My idea is to use "." to get the elements.

q) A . 1 1 / one of the diagonal elements
5
q) 2 #' til 3 / indices
0 0
1 1
2 2

But I tried many ways and can't get it working.

Body:
Following code returns diagonal elements of matrix

(1 2 3; 4 5 6; 7 8 9) @' til 3

The code

generates continuous list 0, 1, 2 on the right

Gets an element from every list on the left by applying corresponding index on the right (@' adverb)

Generic form looks like:

getDiagonal: {x@'til count x};
getDiagonal (1 2 3; 4 5 6; 7 8 9)


问:
How do i convert my existing REST Api to a GraphQL API
I'm new to GraphQL and I'm trying to covert one of my existing REST Api to GraphQL API

Here are the operations available today for REST API
1. POST - Creates Single/Multiple documents(Bulk Operation)Responds with Http 204
2. GET - Fetches a single document Responds with single doc Http 200
3. PUT - Updates Single/Multiple documents (Bulk Operation) responds with Http 204

答:
GraphQL has two types of requests, queries (which get stuff), and mutations (which change stuff).

For a simple GraphQL starter I can recommend Apollo Server. It has one of the best documentations I have ever seen and provides you with a sandbox where you can test your requests.

The next step is to define a GraphQL schema, types and resolvers.

A relevant schema might be something along the lines of

```<code>type Document {
    id: String
    ...
}

type Query {
    documentById(id: String!): Document
}

type Mutation {
    createDocument(document: Document!): Document!
    createDocuments(documents: [Document!]): [Document!]
    updateDocument(document: Document!): Document!
    updateDocuments(documents: Document!): [Document!]
}

schema {
    query: Query
    mutation: Mutation
}
</code>```

Resolvers are handlers for your requests and these can be highly specific, but should be very similar to what you already implemented in REST.

Also, keep in mind gql will not use HTTP statuses to denote errors, all requests will result in a 200, even if they fail. Gql provides you with a error object in the result if something fails, so error handling on the consumers of your API have to reflect that.

Body:
GraphQL has two types of requests, queries (which get stuff), and mutations (which change stuff).

For a simple GraphQL starter I can recommend Apollo Server. It has one of the best documentations I have ever seen and provides you with a sandbox where you can test your requests.

The next step is to define a GraphQL schema, types and resolvers.

A relevant schema might be something along the lines of

type Document {
    id: String
    ...
}

type Query {
    documentById(id: String!): Document
}

type Mutation {
    createDocument(document: Document!): Document!
    createDocuments(documents: [Document!]): [Document!]
    updateDocument(document: Document!): Document!
    updateDocuments(documents: Document!): [Document!]
}

schema {
    query: Query
    mutation: Mutation
}

Resolvers are handlers for your requests and these can be highly specific, but should be very similar to what you already implemented in REST.

Also, keep in mind gql will not use HTTP statuses to denote errors, all requests will result in a 200, even if they fail. Gql provides you with a error object in the result if something fails, so error handling on the consumers of your API have to reflect that.


问:
How to get multiple checkbox value on button click from an Onsen Checkbox?
I am using ons-checkbox provided by Onsen-UI, I have multiple checbox

<ons-checkbox input-id = "brand" value = "example" class = "checkbox"></ons-checkbox>

on the button click I want to get the values of all the checked checkboxes

答:
checkbox.html

```<code><ons-page>
  <div style="text-align: center; margin-top: 30px;">
    <p style="margin-top: 30px;">
      <ons-button onclick="checkedData()">Data</ons-button>
    </p>
    <ons-list>
    <ons-list-item tappable>
      <label class="left">
        <ons-checkbox input-id="check-1" value="Apple"></ons-checkbox>
      </label>
      <label for="check-1" class="center">
        Apple
      </label>
    </ons-list-item>
    <ons-list-item tappable>
      <label class="left">
        <ons-checkbox input-id="check-2" value="Banana"></ons-checkbox>
      </label>
      <label for="check-2" class="center">
        Banana
      </label>
    </ons-list-item>
  </ons-list>

  </div>
</ons-page>
</code>```

checkbox.js

```<code>var checkedData = function() {
  var ons = document.getElementsByTagName('ons-checkbox');
  for (var i=0; i<ons.length; i++) {
    if(ons[i].checked) {
      // Below will give all checked values
      console.log('Checked Values : , ons[i].value);
    } else {
      // Below will give all un-checked values
      console.log('Un-Checked Values : , ons[i].value);
    }
  }
};
</code>```

Body:
checkbox.html

<ons-page>
  <div style="text-align: center; margin-top: 30px;">
    <p style="margin-top: 30px;">
      <ons-button onclick="checkedData()">Data</ons-button>
    </p>
    <ons-list>
    <ons-list-item tappable>
      <label class="left">
        <ons-checkbox input-id="check-1" value="Apple"></ons-checkbox>
      </label>
      <label for="check-1" class="center">
        Apple
      </label>
    </ons-list-item>
    <ons-list-item tappable>
      <label class="left">
        <ons-checkbox input-id="check-2" value="Banana"></ons-checkbox>
      </label>
      <label for="check-2" class="center">
        Banana
      </label>
    </ons-list-item>
  </ons-list>

  </div>
</ons-page>

checkbox.js

var checkedData = function() {
  var ons = document.getElementsByTagName('ons-checkbox');
  for (var i=0; i<ons.length; i++) {
    if(ons[i].checked) {
      // Below will give all checked values
      console.log('Checked Values : , ons[i].value);
    } else {
      // Below will give all un-checked values
      console.log('Un-Checked Values : , ons[i].value);
    }
  }
};