问:
C++ How do I create objects from different classes in another class?
I have a program with two classes, one for points and one for a rectangle. I need to make two objects of point class within my rectangle class and make them private. I can't figure out how to use the rectangle constructor to make the points with the points constructor, every time I do so I get the error "no default constructor exists for class "Point2d"". Even when I make a default constructor I still get this. I'm at a loss here.</p>
```<code>#include <iostream>
#include <cmath>
using namespace std;

class point2D {
private:
    int x = 0;
    int y = 0;

public:
    int getX() {
        return x;
    }
    int getY() {
        return y;
    }
    point2D(int ax, int ay) {
        x = ax;
        y = ay;
    }
};

class rectangleType {
private:
    point2D p0;
    point2D p1;

public:
    int getX0() {
        return p0.getX();
    }
    int getY0() {
        return p0.getY();
    }
    int getX1() {
        return p1.getX();
    }
    int getY1() {
        return p1.getY();
    }
    int getWidth() {
        return abs(getX1() - getX0());
    }
    int getLength() {
        return abs(getY1() - getY0());
    }
    int getPerimeter() {
        return 2 * (getWidth() + getLength());
    }
    int getArea() {
        return (getWidth() * getLength());
    }
    rectangleType(int ax0, int ay0, int ax1, int ay1) {
        point2D p0(ax0, ay0);
        point2D p1(ax1, ay1);
    }
};
</code>```

答:
Your error tells you that you have to create a default constructor for the points class, e.g.

```<code>point2D() {}
</code>```

or if you want to move the x & y initialization to the constructor

```<code>point2D()
    : x { 0 }, y { 0 } {}

</code>```

It happens because you've created a specialized constructor that takes two parameters. If not for that, the compiler would have generated a default constructor for you. :)

As for the initialization in the rectangle class try this:

```<code>rectangleType(int ax0, int ay0, int ax1, int ay1)
        : p { { ax0, ay0 } }, p1 { { ax1, ay1 } } {}
</code>```

Also, to remove redundant assignment (thanks @user4581301) you could transform your current 2D(int ax, int ay) into this:

```<code>point2D(int ax, int ay)
        : x { ax }, y { ay } {}
</code>```

Further reading:

https://en.cppreference.com/w/cpp/language/constructor (again thank you @user4581301)

Body:
I have a program with two classes, one for points and one for a rectangle. I need to make two objects of point class within my rectangle class and make them private. I can't figure out how to use the rectangle constructor to make the points with the points constructor, every time I do so I get the error "no default constructor exists for class "Point2d"". Even when I make a default constructor I still get this. I'm at a loss here.

#include <iostream>
#include <cmath>
using namespace std;

class point2D {
private:
    int x = 0;
    int y = 0;

public:
    int getX() {
        return x;
    }
    int getY() {
        return y;
    }
    point2D(int ax, int ay) {
        x = ax;
        y = ay;
    }
};

class rectangleType {
private:
    point2D p0;
    point2D p1;

public:
    int getX0() {
        return p0.getX();
    }
    int getY0() {
        return p0.getY();
    }
    int getX1() {
        return p1.getX();
    }
    int getY1() {
        return p1.getY();
    }
    int getWidth() {
        return abs(getX1() - getX0());
    }
    int getLength() {
        return abs(getY1() - getY0());
    }
    int getPerimeter() {
        return 2 * (getWidth() + getLength());
    }
    int getArea() {
        return (getWidth() * getLength());
    }
    rectangleType(int ax0, int ay0, int ax1, int ay1) {
        point2D p0(ax0, ay0);
        point2D p1(ax1, ay1);
    }
};

Body:
Your error tells you that you have to create a default constructor for the points class, e.g.

point2D() {}

or if you want to move the x & y initialization to the constructor

point2D()
    : x { 0 }, y { 0 } {}

It happens because you've created a specialized constructor that takes two parameters. If not for that, the compiler would have generated a default constructor for you. :)

As for the initialization in the rectangle class try this:

rectangleType(int ax0, int ay0, int ax1, int ay1)
        : p { { ax0, ay0 } }, p1 { { ax1, ay1 } } {}

Also, to remove redundant assignment (thanks @user4581301) you could transform your current 2D(int ax, int ay) into this:

point2D(int ax, int ay)
        : x { ax }, y { ay } {}

Further reading:

https://en.cppreference.com/w/cpp/language/constructor (again thank you @user4581301)


来源: stackexchange

问:
Why is `declare` word used in the `d.ts` files
Whenever tsc generates d.ts files, it includes declare word there, like this:

```<code>export declare class Moment {
    name: string;
}
</code>```

Now, declare in ts files is used to say to tsc that no js should be generated for the type with declare. So it makes sense in the ts files. However, no js is generated from d.ts files anyway, why use the word there?

I tried to remove declare word from the above code:

```<code>export class Moment {
    name: string;
}
</code>```

and it worked the same.

I've found the following here:

If a file has the extension .d.ts then each root level definition must
  have the declare keyword prefixed to it. This helps make it clear to
  the author that there will be no code emitted by TypeScript. The
  author needs to ensure that the declared item will exist at runtime.

So is it the only purpose of the declare in d.ts files?

Plese note, this is not the same question as this one, as my question is about using declare in d.ts files, not ts files.

答:
It's pretty simple.

when you want to export a declaration of variable or function you have two ways to do that:

you can create a variable or a function in one line and after that you can export it in a new line.

To do that you need first "declare" the variable or the function, after that you can export it.

for example:

declare class Moment {
    name: string;
}

export Moment;```
</div>
</div>
</p>
<ol start="2">
<li>you can export it in one line without declaring it first.
for example:</li>
</ol>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>export class Moment {
    name: string;
}</code>```

ContentLicense: CC BY-SA 3.0

Body:
Whenever tsc generates d.ts files, it includes declare word there, like this:

export declare class Moment {
    name: string;
}

Now, declare in ts files is used to say to tsc that no js should be generated for the type with declare. So it makes sense in the ts files. However, no js is generated from d.ts files anyway, why use the word there?

I tried to remove declare word from the above code:

export class Moment {
    name: string;
}

and it worked the same.

I've found the following here:

If a file has the extension .d.ts then each root level definition must
  have the declare keyword prefixed to it. This helps make it clear to
  the author that there will be no code emitted by TypeScript. The
  author needs to ensure that the declared item will exist at runtime.

So is it the only purpose of the declare in d.ts files?

Plese note, this is not the same question as this one, as my question is about using declare in d.ts files, not ts files.

Body:
It's pretty simple.

when you want to export a declaration of variable or function you have two ways to do that:

you can create a variable or a function in one line and after that you can export it in a new line.

To do that you need first "declare" the variable or the function, after that you can export it.

for example:

declare class Moment {
    name: string;
}

export Moment;

you can export it in one line without declaring it first.
for example:

export class Moment {
    name: string;
}

ContentLicense: CC BY-SA 4.0


问:
Python Speech Recognition how to extract only main transcript with show_all enabled
I'm trying to learn speech recognition for a program I'm making. I'm currently having it contentiously listen and display what I say.

```<code>
def record():
    repeat = True
    with sr.Microphone() as source:
        r.adjust_for_ambient_noise(source)
        while repeat:
            audio = r.listen(source)
            user = r.recognize_google(audio, language= 'en-US', show_all = True)
            print(str(user))
</code>```

The code works, but at times when it doesn't understand me or I make a sound effect (cough or sneeze) It outputs with this error:

```<code>Traceback (most recent call last):
  File "main.py", line 57, in <module>
    record()
  File "main.py", line 24, in record
    user = r.recognize_google(audio, language= 'en-US')
  File "C:\Users\vorte\AppData\Local\Programs\Python\Python38-32\lib\site-packages\speech_recognition\__init__.py", line 858, in recognize_google
    if not isinstance(actual_result, dict) or len(actual_result.get("alternative", [])) == 0: raise UnknownValueError()
speech_recognition.UnknownValueError
</code>```

I fixed this by changing user = r.recognize_google(audio, language= 'en-US') to user = r.recognize_google(audio, language= 'en-US', show_all = True)

But the problem now is I get a tuple, list, dictionary mixed string with unnecessary information that displays what it thinks I said + all the alternatives.

```<code>{'alternative': [{'transcript': 'Sun even working anymore', 'confidence': 0.88974512}, {'transcript': 'son even working anymore'}, {'transcript': 'some even working anymore'}, {'transcript': 'send even working anymore'}, {'transcript': 'Saint even working anymore'}], 'final': True}
</code>```

My question is if there is any way I could pull or receive the transcript with the highest confidence while the show_all is enabled, because if I turn it off it will bring up errors again.

答:
You can write something like that:</p>
```<code>def record():

    with sr.Microphone() as source:
        r.adjust_for_ambient_noise(source)
        try:
            audio = r.listen(source)
            user = r.recognize_google(audio, language= 'en-US')
            print(str(user))
        except:
            record()

</code>```

Body:
I'm trying to learn speech recognition for a program I'm making. I'm currently having it contentiously listen and display what I say.

def record():
    repeat = True
    with sr.Microphone() as source:
        r.adjust_for_ambient_noise(source)
        while repeat:
            audio = r.listen(source)
            user = r.recognize_google(audio, language= 'en-US', show_all = True)
            print(str(user))

The code works, but at times when it doesn't understand me or I make a sound effect (cough or sneeze) It outputs with this error:

Traceback (most recent call last):
  File "main.py", line 57, in <module>
    record()
  File "main.py", line 24, in record
    user = r.recognize_google(audio, language= 'en-US')
  File "C:\Users\vorte\AppData\Local\Programs\Python\Python38-32\lib\site-packages\speech_recognition\__init__.py", line 858, in recognize_google
    if not isinstance(actual_result, dict) or len(actual_result.get("alternative", [])) == 0: raise UnknownValueError()
speech_recognition.UnknownValueError

I fixed this by changing user = r.recognize_google(audio, language= 'en-US') to user = r.recognize_google(audio, language= 'en-US', show_all = True)

But the problem now is I get a tuple, list, dictionary mixed string with unnecessary information that displays what it thinks I said + all the alternatives.

{'alternative': [{'transcript': 'Sun even working anymore', 'confidence': 0.88974512}, {'transcript': 'son even working anymore'}, {'transcript': 'some even working anymore'}, {'transcript': 'send even working anymore'}, {'transcript': 'Saint even working anymore'}], 'final': True}

My question is if there is any way I could pull or receive the transcript with the highest confidence while the show_all is enabled, because if I turn it off it will bring up errors again.

Body:
You can write something like that:

def record():

    with sr.Microphone() as source:
        r.adjust_for_ambient_noise(source)
        try:
            audio = r.listen(source)
            user = r.recognize_google(audio, language= 'en-US')
            print(str(user))
        except:
            record()


问:
Fastest way of numbering instances of a value within a vector
I am looking to number each instance of a value in a vector as it appears. For example the first instance of a value with get '1' the second instance will get '2' and so on - counting how many this value has appeared before it in the vector. I can do this with a for loop in R using the EuStockMarkets example data in datasets.

```<code>#load data
data <- as.data.frame(datasets::EuStockMarkets)
df <- data.frame(order = 1:nrow(data),value = data$DAX)
head(df)

#calculate number of instances
start_time <- Sys.time()
for (i in 1:nrow(df)) {
 df[i,"instance"]<- sum(df[1:i,"value"] == df[i,"value"])
}
end_time <- Sys.time()
end_time - start_time
#Time difference of 0.1126978 secs
</code>```

This is fine but I would rather not use a for loop if there was a faster option for much larger datasets and was wondering if their was a preexisting function that - perhaps with tidyverse package.

答:
The trick is to use the apply() function:

```<code># Loading data.
data = as.data.frame(datasets::EuStockMarkets)
df = data.frame(order = 1:nrow(data), value = data$DAX)
head(df)

# Your solution.
for (i in 1:nrow(df))
{
  df[i, "instance"] = sum(df[1:i, "value"] == df[i, "value"])
}

# My solution.
useful.function = function(x)
{
  temp.idx = x[1]
  sum(x[2] == df$value[1:temp.idx])
}

df$instance2 = apply(df, MARGIN = 1, useful.function)

# Double check.
identical(df$instance, df$instance2)

# Benchmarking.
microbenchmark::microbenchmark(
  your.solution =
  {
    for (i in 1:nrow(df))
    {
      sum(df[1:i, "value"] == df[i, "value"])
    }
  },
  my.solution =
  {
    apply(df, MARGIN = 1, useful.function)
  }
)

# Unit: milliseconds
# expr              min       lq     mean    median     uq     max neval
# your.solution() 37.7382 39.92370 44.29684 42.99385 44.67285 98.0862   100
# my.solution()   15.0171 16.52995 21.60575 20.41060 21.32430 75.8235   100
</code>```

Basically, I have written a useful.function() that relies on the df$order to use only df$values up to the position of a certain value to compute what you ask. Then, this function is applied to each row of df with apply(). The results of microbenchmarking (which evaluates both solutions 100 times so to see which one is faster) shows that using apply() is about twice as faster than the for loop. This derives from the fact that the loop needs to make a lot of call (nrow(df) in your case) to other functions (possibly written in C), while apply() makes a single call.

Body:
I am looking to number each instance of a value in a vector as it appears. For example the first instance of a value with get '1' the second instance will get '2' and so on - counting how many this value has appeared before it in the vector. I can do this with a for loop in R using the EuStockMarkets example data in datasets.

#load data
data <- as.data.frame(datasets::EuStockMarkets)
df <- data.frame(order = 1:nrow(data),value = data$DAX)
head(df)

#calculate number of instances
start_time <- Sys.time()
for (i in 1:nrow(df)) {
 df[i,"instance"]<- sum(df[1:i,"value"] == df[i,"value"])
}
end_time <- Sys.time()
end_time - start_time
#Time difference of 0.1126978 secs

This is fine but I would rather not use a for loop if there was a faster option for much larger datasets and was wondering if their was a preexisting function that - perhaps with tidyverse package.

Body:
The trick is to use the apply() function:

# Loading data.
data = as.data.frame(datasets::EuStockMarkets)
df = data.frame(order = 1:nrow(data), value = data$DAX)
head(df)

# Your solution.
for (i in 1:nrow(df))
{
  df[i, "instance"] = sum(df[1:i, "value"] == df[i, "value"])
}

# My solution.
useful.function = function(x)
{
  temp.idx = x[1]
  sum(x[2] == df$value[1:temp.idx])
}

df$instance2 = apply(df, MARGIN = 1, useful.function)

# Double check.
identical(df$instance, df$instance2)

# Benchmarking.
microbenchmark::microbenchmark(
  your.solution =
  {
    for (i in 1:nrow(df))
    {
      sum(df[1:i, "value"] == df[i, "value"])
    }
  },
  my.solution =
  {
    apply(df, MARGIN = 1, useful.function)
  }
)

# Unit: milliseconds
# expr              min       lq     mean    median     uq     max neval
# your.solution() 37.7382 39.92370 44.29684 42.99385 44.67285 98.0862   100
# my.solution()   15.0171 16.52995 21.60575 20.41060 21.32430 75.8235   100

Basically, I have written a useful.function() that relies on the df$order to use only df$values up to the position of a certain value to compute what you ask. Then, this function is applied to each row of df with apply(). The results of microbenchmarking (which evaluates both solutions 100 times so to see which one is faster) shows that using apply() is about twice as faster than the for loop. This derives from the fact that the loop needs to make a lot of call (nrow(df) in your case) to other functions (possibly written in C), while apply() makes a single call.


问:
Linux command to check the count returned from grep command is greater than specific no
Iam new to linux.

Iam trying to count the  occurance of a string in a file and have to check the count is greater than particular no.

I have following command to get the count of the string from a file

```<code>grep -c "CPU" /opt/core.log
</code>```

It will returns  the count of that string from that file

Along with this command can I compare that result with any number .
I tried many ways but getting the o/p

like  grep -c "CPU" /opt/core.log | awk '{print $1>=30}'

答:
first count using grep -o because grep -c will count only one occurence per line. then use if else logic to know if it is greater than or not your number.</p>
```<code>    cat test.txt
    CPU is main part of computer. CPU should be 32 bit or 64 bit.
    laptop with less CPU is not good.

    a=$(grep -ow "CPU" test.txt|wc -l|sed 's/^$//g')
    echo $a
    3

    if [[ $a -gt 2 ]]; then; echo "Greater"; else; echo "Equal or Smaller"; fi
    Greater

    if [[ $a -gt 3 ]]; then; echo "Greater"; else; echo "Equal or Smaller"; fi
    Equal or Smaller

</code>```

Body:
Iam new to linux.

Iam trying to count the  occurance of a string in a file and have to check the count is greater than particular no.

I have following command to get the count of the string from a file

grep -c "CPU" /opt/core.log

It will returns  the count of that string from that file

Along with this command can I compare that result with any number .
I tried many ways but getting the o/p

like  grep -c "CPU" /opt/core.log | awk '{print $1>=30}'

Body:
first count using grep -o because grep -c will count only one occurence per line. then use if else logic to know if it is greater than or not your number.

    cat test.txt
    CPU is main part of computer. CPU should be 32 bit or 64 bit.
    laptop with less CPU is not good.

    a=$(grep -ow "CPU" test.txt|wc -l|sed 's/^$//g')
    echo $a
    3

    if [[ $a -gt 2 ]]; then; echo "Greater"; else; echo "Equal or Smaller"; fi
    Greater

    if [[ $a -gt 3 ]]; then; echo "Greater"; else; echo "Equal or Smaller"; fi
    Equal or Smaller


问:
Error: The non-abstract class 'InternalSelectableMathState'
I just updated flutter version from 2.5.3 to 2.8. I have the following error that i dont know how resolve it. There is no error on any plugin installed, It seems that the error comes from the inner classes themselves and I don't know in which part of my application the error is throwed:

```<code>../../AppData/Local/Pub/Cache/hosted/pub.dartlang.org/flutter_math_fork-0.3.3+1/lib/src/widgets/selectable.dart:407:7: Error: The non-abstract class 'InternalSelectableMathState' is missing implementations for these members:
 - TextSelectionDelegate.copySelection
 - TextSelectionDelegate.cutSelection
 - TextSelectionDelegate.pasteText
 - TextSelectionDelegate.selectAll
Try to either
 - provide an implementation,
 - inherit an implementation from a superclass or mixin,
 - mark the class as abstract, or
 - provide a 'noSuchMethod' implementation.

class InternalSelectableMathState extends State<InternalSelectableMath>
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^
/C:/desarrollo/flutter/packages/flutter/lib/src/services/text_input.dart:985:8: Context: 'TextSelectionDelegate.copySelection' is defined here.
  void copySelection(SelectionChangedCause cause);
       ^^^^^^^^^^^^^
/C:/desarrollo/flutter/packages/flutter/lib/src/services/text_input.dart:965:8: Context: 'TextSelectionDelegate.cutSelection' is defined here.
  void cutSelection(SelectionChangedCause cause);
       ^^^^^^^^^^^^
/C:/desarrollo/flutter/packages/flutter/lib/src/services/text_input.dart:973:16: Context: 'TextSelectionDelegate.pasteText' is defined here.
  Future<void> pasteText(SelectionChangedCause cause);
               ^^^^^^^^^
/C:/desarrollo/flutter/packages/flutter/lib/src/services/text_input.dart:979:8: Context: 'TextSelectionDelegate.selectAll' is defined here.
  void selectAll(SelectionChangedCause cause);
       ^^^^^^^^^

FAILURE: Build failed with an exception.

* Where:
Script 'C:\desarrollo\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1070

* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\desarrollo\flutter\bin\flutter.bat'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 8m 5s
Exception: Gradle task assembleDebug failed with exit code 1
</code>```

I dont have declared flutter_math_fork on my pubspec.

My flutter doctor output:

```<code>Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.8.0, on Microsoft Windows [VersiÃ³n 10.0.19041.1348], locale es-ES)
[√] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
[√] Chrome - develop for the web
[√] Android Studio (version 2020.3)
[√] VS Code (version 1.62.3)
[√] Connected device (3 available)

• No issues found!
</code>```

I have tried: flutter clean, flutter upgrade and invalidate cache / restart.

Any suggestion is appreciated.

答:
In my case:

Step 1: Update the dependencies in pubspec.yaml with the following:

provider: ^6.0.0

flutter_svg: ^0.23.0+1

flutter_math_fork: ^0.5.0

Step 2: Run flutter pub get

Step 3: Run: flutter run

Good luck!

Body:
I just updated flutter version from 2.5.3 to 2.8. I have the following error that i dont know how resolve it. There is no error on any plugin installed, It seems that the error comes from the inner classes themselves and I don't know in which part of my application the error is throwed:

../../AppData/Local/Pub/Cache/hosted/pub.dartlang.org/flutter_math_fork-0.3.3+1/lib/src/widgets/selectable.dart:407:7: Error: The non-abstract class 'InternalSelectableMathState' is missing implementations for these members:
 - TextSelectionDelegate.copySelection
 - TextSelectionDelegate.cutSelection
 - TextSelectionDelegate.pasteText
 - TextSelectionDelegate.selectAll
Try to either
 - provide an implementation,
 - inherit an implementation from a superclass or mixin,
 - mark the class as abstract, or
 - provide a 'noSuchMethod' implementation.

class InternalSelectableMathState extends State<InternalSelectableMath>
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^
/C:/desarrollo/flutter/packages/flutter/lib/src/services/text_input.dart:985:8: Context: 'TextSelectionDelegate.copySelection' is defined here.
  void copySelection(SelectionChangedCause cause);
       ^^^^^^^^^^^^^
/C:/desarrollo/flutter/packages/flutter/lib/src/services/text_input.dart:965:8: Context: 'TextSelectionDelegate.cutSelection' is defined here.
  void cutSelection(SelectionChangedCause cause);
       ^^^^^^^^^^^^
/C:/desarrollo/flutter/packages/flutter/lib/src/services/text_input.dart:973:16: Context: 'TextSelectionDelegate.pasteText' is defined here.
  Future<void> pasteText(SelectionChangedCause cause);
               ^^^^^^^^^
/C:/desarrollo/flutter/packages/flutter/lib/src/services/text_input.dart:979:8: Context: 'TextSelectionDelegate.selectAll' is defined here.
  void selectAll(SelectionChangedCause cause);
       ^^^^^^^^^

FAILURE: Build failed with an exception.

* Where:
Script 'C:\desarrollo\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1070

* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\desarrollo\flutter\bin\flutter.bat'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 8m 5s
Exception: Gradle task assembleDebug failed with exit code 1

I dont have declared flutter_math_fork on my pubspec.

My flutter doctor output:

Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.8.0, on Microsoft Windows [VersiÃ³n 10.0.19041.1348], locale es-ES)
[√] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
[√] Chrome - develop for the web
[√] Android Studio (version 2020.3)
[√] VS Code (version 1.62.3)
[√] Connected device (3 available)

• No issues found!

I have tried: flutter clean, flutter upgrade and invalidate cache / restart.

Any suggestion is appreciated.


问:
mutate columns with labels attributes in r
I have imported data from SPSS and I want to transform some variables to factors, without having to list them all. These variables can be distinguished from the others by having the attribute labels, so I want to use the condition length(get_labels(variable.name))>0 to mutate (or, if not possible, to select) them.

Using the following example (despite not being a tbl_df as would be if imported with haven::read_sav)

```<code>dt <- data.table(a = 1:4,
                 b = factor(c(1,2,1,1), levels=1:2, labels=c("Yes","No")),
                 d = c("xxx", "yyy", "zzz", "kkk"),
                 e = factor(c(1,1,3,2), levels=1:4, labels=c("A","B","C","D")))

</code>```

I have tried

dt %>% mutate_at(vars(length(get_labels(.))>0), haven::as_factor)

dt %>% mutate_if((length(get_labels(.))>0), haven::as_factor)

but that didn't work.

How can I achieve the desired result, that is, mutate/select the columns band e?

Thanks!

答:
I recommend selection before mutating. Something like the following to get all the columns of interest:

all_cols = colnames(dt)
focus_cols = all_cols[{logic that returns T/F for each column you want}]
```
<p>You can then iterate over all such columns as follows:</p>
<pre class="lang-r prettyprint-override"><code>for(cc in focus_cols){
  dt = mutate(dt, !!sym(cc) := as.factor(!!sym(cc)))
}
</code>```

Where !!sym(cc) transforms the string stored in cc into a variable, and := is equivalent to = but allows us to use !!sym(.) on the left side too.

Body:
I have imported data from SPSS and I want to transform some variables to factors, without having to list them all. These variables can be distinguished from the others by having the attribute labels, so I want to use the condition length(get_labels(variable.name))>0 to mutate (or, if not possible, to select) them.

Using the following example (despite not being a tbl_df as would be if imported with haven::read_sav)

dt <- data.table(a = 1:4,
                 b = factor(c(1,2,1,1), levels=1:2, labels=c("Yes","No")),
                 d = c("xxx", "yyy", "zzz", "kkk"),
                 e = factor(c(1,1,3,2), levels=1:4, labels=c("A","B","C","D")))

I have tried

dt %>% mutate_at(vars(length(get_labels(.))>0), haven::as_factor)

dt %>% mutate_if((length(get_labels(.))>0), haven::as_factor)

but that didn't work.

How can I achieve the desired result, that is, mutate/select the columns band e?

Thanks!

Body:
I recommend selection before mutating. Something like the following to get all the columns of interest:

all_cols = colnames(dt)
focus_cols = all_cols[{logic that returns T/F for each column you want}]

You can then iterate over all such columns as follows:

for(cc in focus_cols){
  dt = mutate(dt, !!sym(cc) := as.factor(!!sym(cc)))
}

Where !!sym(cc) transforms the string stored in cc into a variable, and := is equivalent to = but allows us to use !!sym(.) on the left side too.


问:
GET and POST between a UWP Application and an HTTP Server
I've just recently started trying to setup an HTTP server with Python on my computer to try to communicate with a UWP application that I'm building. My overall goal is to host this server online and send photos from the UWP application to the HTTP server and then run a Python/C++ script on the images. Once that has finished processing, I want to output some data into a file and then send that back to the UWP application. I'm new to servers and databases and so I'm not quite sure where to go from here.

As I mentioned, I've set up a very basic server with the following Python code:

```<code>from http.server import BaseHTTPRequestHandler, HTTPServer
import time

hostName = "localhost"
serverPort = 8080

class MyServer(BaseHTTPRequestHandler):
    def do_GET(self):

self.send_response(200)
    self.send_header("Content-type", "text/html")
    self.end_headers()
    self.wfile.write(bytes("<p>Request: %s</p>" % self.path, "utf-8"))
    if(self.path == "/test"):
        exec(open("test.py").read())

def do_POST(self):
    content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
    post_data = self.rfile.read(content_length) # <--- Gets the data itself

    self.send_response(200)
    self.send_header('Content-type', 'text/html')
    self.end_headers()
    self.wfile.write("POST request for {}".format(self.path).encode('utf-8'))

if __name__ == "__main__":
    webServer = HTTPServer((hostName, serverPort), MyServer)
    print("Server started http://%s:%s" % (hostName, serverPort))

    try:
        webServer.serve_forever()
    except KeyboardInterrupt:
        print("Server stopped.")
        webServer.server_close()
</code>```

And I am able to successfully GET and POST but now I'm not sure what to do. Do I need to setup a database to store any of the data that I post? If so, what's the best way to go about that?

Any help would be greatly appreciated!

答:
No, you don't need a database.

Use the code below to set up a secure socket-based http server. It has some basic protections against specific types of DOS-Attacks, and allows you to ban specific addresses from accessing your service.

Pay attention to the comments: They explain the important code parts. Make sure to configure your server safely. Do not rely on data coming from your application. An Attacker, for example, could create a malicious request, looking like a normal request from your application. DONT insert invalid data into the Response structure, or you will end up with a 500 Internal Server Error reply.

This code has no dependencies; it can run on any OS, as it is not using OS-specific API's. (Tested on Python 3.9.0, Windows 10.)

```<code>import socket
import threading
import ssl
import time
import tempfile
import os
hostname="localhost"    #hostName in your code
port=8080               #serverPort in your code - default HTTP Port is 80
banned_IPs=()           #Every IP in this list is denied access to your service

#SSL-Specific settings
SSLEnabled=False        #set to True if you got a valid SSL/TLS configuration for your server, and want to provide a secure version of the service
SSLContext=None         #must be set if SSLEnabled - set to ssl.SSLContext with proper configuration - see documentation: https://docs.python.org/3/library/ssl.html
SSLPort=None            #Port for the secure version of your service - must be set if SSLEnabled is True and may not hav the same value as port

#These are some security limits - change them if necessary
MaxIpConnections=1024   #Maximum Connections per IP address per minute - DDOS-Protection
MaxHeaderSize=8192      #8 KB maximum Header Size - Protection against malicious clients trying to fill up device-memory
MaxBodySize=1073741824  #1 GB maximum Payload Size - malicious clients may try

to overload memory with extremely large payloads

#Internal variables:
_clientRegister={}      #DDOS-Protection
_max_blank_packets=128  #Detect wheter a socket has been closed

#Configuration - I use IPv4 here - replace AF_INET by AF_INET6 for IPv6
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
if SSLEnabled:
    SSLSock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

def IO(request,response):
    """do something with the data here.
As i don't know, what you want to do, I will do nothing here."""
    pass
class Request(object):
    """A HTTP request"""
    method=None     #GET,POST,PUT,DELETE,...
    route=None      #path, /example,/foo/example,/,...
    body=None       #Filename of a File containing the request's Body, None if no body was present.
    proto="HTTP/1.1"#Protocol, either "HTTP/1.1" or "HTTP/1.0"
    headers={}      #Headers, having a structure like {key:[value[,value[,...]]],[key:[...][,...]]}
    ip=None         #I don't need to explain that
    localport=None  #The Locally used port, one of port, SSLPort
    secure=False    #wheter the request wa made over TLS/SSL
    remoteport=None #Client-Side port. Your'e probaly not gonna need it
    socket=None     #underlying socket. Your'e probaly not gonna need it
    def __init__(self,method,route,proto,headers,bodyfile,addr,lport,sock):
        self.method=method.decode("ascii")
        self.route=route.decode("ascii")
        self.proto=proto.decode("ascii")
        for i in headers:
            k=i
            self.headers[k.decode("ascii")]=[]
            for v in headers[i]:
                self.headers[k.decode("ascii")].append(v.decode("ascii"))
        self.body=bodyfile
        self.ip=addr[0]
        self.port=addr[1]
        self.localport=lport
        self.secure=(self.localport==SSLPort)
        self.socket=sock
class Response(object):
    """A HTTP Response"""
    status=200      #Statuscode
    statustext="OK" #Statustext
    proto="HTTP/1.1"#Protocol, either "HTTP/1.1" or "HTTP/1.0"
    headers={"Connection":["close"]}#Same structure as in Request
    body=None       #Filename for Responsebody, use tempfile.mktemp() for temporary file.
    socket=None     #underlying socket. Your'e probaly not gonna need it
"Now some Internal functions - just ignore them"
#Some binding + listening stuff
sock.bind((hostname,port))
sock.listen(32)
if SSLEnabled:
    SSLSock.bind((hostname,SSLPort))
    SSLSock.listen(32)
def checkIp(ip):
    if _clientRegister[ip][1]<=time.time():
        del _clientRegister[ip]
def garbage_collector_thread():
    while True:
        try:
            for i in _clientRegister:
                checkIp(i)
        except:
            pass
        time.sleep(30)#Garbage-Collection every half minute
def client_thread(cli,addr):
    ip=addr[0]
    if ip in banned_IPs:
        cli.close()
        return
    if ip in _clientRegister:
        _clientRegister[ip][0]+=1
        if _clientRegister[ip][0]>MaxIpConnections:
            cli.close()
            return
    else:
        _clientRegister[ip]=[0,time.time()+60]
    if cli.getsockname()[1]==SSLPort:
        cli=SSLContext.wrap(cli,True)
    header=b""
    blank=0
    try:
        while not b"\r\n\r\n" in header:
            block=cli.recv(1024)
            if block==b"":
                blank+=1
            else:
                blank=0
            if blank>=_max_blank_packets:
                cli.close()
                return
            if len(header)>MaxHeaderSize:
                cli.sendall(b"HTTP/1.1 431 Header Fields Too Large\r\nConnection: closed\r\n\r\n")
                cli.close()
                return
            header+=block
        header,body=header.split(b"\r\n\r\n",1)
        head={}
        status,*header=header.split(b"\r\n")
        for i in header:
            k,v=i.split(b": ",1)
            if k in header:
                head[k].append(v)
            else:
                head[k]=[v]
        method,route,proto=status.split(b" ",2)
        if b"Content-Length" in header:
            v=int(header[b"Content-Length"][0])
            if v>MaxBodySize:
                cli.sendall(b"HTTP/1.1 413 Payload too large\r\nConnection: close\r\n\r\n")
                cli.close()
                return
            size=len(body)
            returnfile=tempfile.mktemp()
            f=open(returnfile,"wb")
            f.write(returnfile)
            while size<v:
                block=cli.recv(1024)
                if block==b"":
                    blank+=1
                else:
                    blank=0
                if blank>=_max_blank_packets:
                    cli.close()
                    f.close()
                    os.remove(returnfile)
                    return
                size+=len(block)
                f.write(block)
            f.close()
        elif body!=b"":
            cli.sendall(b"HTTP/1.1 411 Length Required\r\nConnection: close\r\n\r\n")
            cli.close()
            return
        else:
            returnfile=None
        request=Request(method,route,proto,head,returnfile,addr,cli.getsockname()[1],cli)
        response=Response()
        response.socket=cli
    except ConnectionError:
        cli.close()
        return
    except:
        try:
            cli.sendall(b"HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n")
        except:
            pass
        cli.close()
        return
    try:
        IO(request,response)
    except:
        try:
            cli.sendall(b"HTTP/1.1 500 Internal Server Error\r\nConnection: close\r\n\r\n")
            cli.close()
            return
        except:
            cli.close()
            return
    try:
        if response.body!=None:
            response.headers["Content-Length"]=[str(os.path.getsize(response.body))]
        r=b" ".join([response.proto.encode("ascii"),str(response.status).encode("ascii"),response.statustext.encode("ascii")])
        r+=b"\r\n"
        for i in response.headers:
            k=i
            for v in response.headers[k]:
                r+=k.encode("ascii")+b": "+v.encode("ascii")+b"\r\n"
        r+=b"\r\n"
        cli.sendall(r)
        if response.body!=None:
            f=open(response.body,"rb")
            while True:
                block=f.read(1024)
                if block==b"":
                    break
                cli.sendall(block)
            f.close()
        cli.close()
        return
    except:
        try:
            cli.sendall(b"HTTP/1.1 500 Internal Server Error\r\nConnection: close\r\n\r\n")
            cli.close()
            return
        except:
            cli.close()
            return
def SSLAccept(sock):
    while True:
        cli,addr=sock.accept()
        threading.Thread(target=client_thread,args=(cli,addr)).start()
if SSLEnabled:
    threading.Thread(target=SSLAccept,args=(SSLSock,)).start()
threading.Thread(target=garbage_collector_thread).start()
while True:
    cli,addr=sock.accept()
    threading.Thread(target=client_thread,args=(cli,addr)).start()
</code>```

Body:
I've just recently started trying to setup an HTTP server with Python on my computer to try to communicate with a UWP application that I'm building. My overall goal is to host this server online and send photos from the UWP application to the HTTP server and then run a Python/C++ script on the images. Once that has finished processing, I want to output some data into a file and then send that back to the UWP application. I'm new to servers and databases and so I'm not quite sure where to go from here.

As I mentioned, I've set up a very basic server with the following Python code:

from http.server import BaseHTTPRequestHandler, HTTPServer
import time

hostName = "localhost"
serverPort = 8080

class MyServer(BaseHTTPRequestHandler):
    def do_GET(self):

self.send_response(200)
    self.send_header("Content-type", "text/html")
    self.end_headers()
    self.wfile.write(bytes("
Request: %s
" % self.path, "utf-8"))
    if(self.path == "/test"):
        exec(open("test.py").read())

def do_POST(self):
    content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
    post_data = self.rfile.read(content_length) # <--- Gets the data itself

    self.send_response(200)
    self.send_header('Content-type', 'text/html')
    self.end_headers()
    self.wfile.write("POST request for {}".format(self.path).encode('utf-8'))

if __name__ == "__main__":
    webServer = HTTPServer((hostName, serverPort), MyServer)
    print("Server started http://%s:%s" % (hostName, serverPort))

    try:
        webServer.serve_forever()
    except KeyboardInterrupt:
        print("Server stopped.")
        webServer.server_close()

And I am able to successfully GET and POST but now I'm not sure what to do. Do I need to setup a database to store any of the data that I post? If so, what's the best way to go about that?

Any help would be greatly appreciated!

Body:
No, you don't need a database.

Use the code below to set up a secure socket-based http server. It has some basic protections against specific types of DOS-Attacks, and allows you to ban specific addresses from accessing your service.

Pay attention to the comments: They explain the important code parts. Make sure to configure your server safely. Do not rely on data coming from your application. An Attacker, for example, could create a malicious request, looking like a normal request from your application. DONT insert invalid data into the Response structure, or you will end up with a 500 Internal Server Error reply.

This code has no dependencies; it can run on any OS, as it is not using OS-specific API's. (Tested on Python 3.9.0, Windows 10.)

import socket
import threading
import ssl
import time
import tempfile
import os
hostname="localhost"    #hostName in your code
port=8080               #serverPort in your code - default HTTP Port is 80
banned_IPs=()           #Every IP in this list is denied access to your service

#SSL-Specific settings
SSLEnabled=False        #set to True if you got a valid SSL/TLS configuration for your server, and want to provide a secure version of the service
SSLContext=None         #must be set if SSLEnabled - set to ssl.SSLContext with proper configuration - see documentation: https://docs.python.org/3/library/ssl.html
SSLPort=None            #Port for the secure version of your service - must be set if SSLEnabled is True and may not hav the same value as port

#These are some security limits - change them if necessary
MaxIpConnections=1024   #Maximum Connections per IP address per minute - DDOS-Protection
MaxHeaderSize=8192      #8 KB maximum Header Size - Protection against malicious clients trying to fill up device-memory
MaxBodySize=1073741824  #1 GB maximum Payload Size - malicious clients may try

to overload memory with extremely large payloads

#Internal variables:
_clientRegister={}      #DDOS-Protection
_max_blank_packets=128  #Detect wheter a socket has been closed

#Configuration - I use IPv4 here - replace AF_INET by AF_INET6 for IPv6
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
if SSLEnabled:
    SSLSock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

def IO(request,response):
    """do something with the data here.
As i don't know, what you want to do, I will do nothing here."""
    pass
class Request(object):
    """A HTTP request"""
    method=None     #GET,POST,PUT,DELETE,...
    route=None      #path, /example,/foo/example,/,...
    body=None       #Filename of a File containing the request's Body, None if no body was present.
    proto="HTTP/1.1"#Protocol, either "HTTP/1.1" or "HTTP/1.0"
    headers={}      #Headers, having a structure like {key:[value[,value[,...]]],[key:[...][,...]]}
    ip=None         #I don't need to explain that
    localport=None  #The Locally used port, one of port, SSLPort
    secure=False    #wheter the request wa made over TLS/SSL
    remoteport=None #Client-Side port. Your'e probaly not gonna need it
    socket=None     #underlying socket. Your'e probaly not gonna need it
    def __init__(self,method,route,proto,headers,bodyfile,addr,lport,sock):
        self.method=method.decode("ascii")
        self.route=route.decode("ascii")
        self.proto=proto.decode("ascii")
        for i in headers:
            k=i
            self.headers[k.decode("ascii")]=[]
            for v in headers[i]:
                self.headers[k.decode("ascii")].append(v.decode("ascii"))
        self.body=bodyfile
        self.ip=addr[0]
        self.port=addr[1]
        self.localport=lport
        self.secure=(self.localport==SSLPort)
        self.socket=sock
class Response(object):
    """A HTTP Response"""
    status=200      #Statuscode
    statustext="OK" #Statustext
    proto="HTTP/1.1"#Protocol, either "HTTP/1.1" or "HTTP/1.0"
    headers={"Connection":["close"]}#Same structure as in Request
    body=None       #Filename for Responsebody, use tempfile.mktemp() for temporary file.
    socket=None     #underlying socket. Your'e probaly not gonna need it
"Now some Internal functions - just ignore them"
#Some binding + listening stuff
sock.bind((hostname,port))
sock.listen(32)
if SSLEnabled:
    SSLSock.bind((hostname,SSLPort))
    SSLSock.listen(32)
def checkIp(ip):
    if _clientRegister[ip][1]<=time.time():
        del _clientRegister[ip]
def garbage_collector_thread():
    while True:
        try:
            for i in _clientRegister:
                checkIp(i)
        except:
            pass
        time.sleep(30)#Garbage-Collection every half minute
def client_thread(cli,addr):
    ip=addr[0]
    if ip in banned_IPs:
        cli.close()
        return
    if ip in _clientRegister:
        _clientRegister[ip][0]+=1
        if _clientRegister[ip][0]>MaxIpConnections:
            cli.close()
            return
    else:
        _clientRegister[ip]=[0,time.time()+60]
    if cli.getsockname()[1]==SSLPort:
        cli=SSLContext.wrap(cli,True)
    header=b""
    blank=0
    try:
        while not b"\r\n\r\n" in header:
            block=cli.recv(1024)
            if block==b"":
                blank+=1
            else:
                blank=0
            if blank>=_max_blank_packets:
                cli.close()
                return
            if len(header)>MaxHeaderSize:
                cli.sendall(b"HTTP/1.1 431 Header Fields Too Large\r\nConnection: closed\r\n\r\n")
                cli.close()
                return
            header+=block
        header,body=header.split(b"\r\n\r\n",1)
        head={}
        status,*header=header.split(b"\r\n")
        for i in header:
            k,v=i.split(b": ",1)
            if k in header:
                head[k].append(v)
            else:
                head[k]=[v]
        method,route,proto=status.split(b" ",2)
        if b"Content-Length" in header:
            v=int(header[b"Content-Length"][0])
            if v>MaxBodySize:
                cli.sendall(b"HTTP/1.1 413 Payload too large\r\nConnection: close\r\n\r\n")
                cli.close()
                return
            size=len(body)
            returnfile=tempfile.mktemp()
            f=open(returnfile,"wb")
            f.write(returnfile)
            while size<v:
                block=cli.recv(1024)
                if block==b"":
                    blank+=1
                else:
                    blank=0
                if blank>=_max_blank_packets:
                    cli.close()
                    f.close()
                    os.remove(returnfile)
                    return
                size+=len(block)
                f.write(block)
            f.close()
        elif body!=b"":
            cli.sendall(b"HTTP/1.1 411 Length Required\r\nConnection: close\r\n\r\n")
            cli.close()
            return
        else:
            returnfile=None
        request=Request(method,route,proto,head,returnfile,addr,cli.getsockname()[1],cli)
        response=Response()
        response.socket=cli
    except ConnectionError:
        cli.close()
        return
    except:
        try:
            cli.sendall(b"HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n")
        except:
            pass
        cli.close()
        return
    try:
        IO(request,response)
    except:
        try:
            cli.sendall(b"HTTP/1.1 500 Internal Server Error\r\nConnection: close\r\n\r\n")
            cli.close()
            return
        except:
            cli.close()
            return
    try:
        if response.body!=None:
            response.headers["Content-Length"]=[str(os.path.getsize(response.body))]
        r=b" ".join([response.proto.encode("ascii"),str(response.status).encode("ascii"),response.statustext.encode("ascii")])
        r+=b"\r\n"
        for i in response.headers:
            k=i
            for v in response.headers[k]:
                r+=k.encode("ascii")+b": "+v.encode("ascii")+b"\r\n"
        r+=b"\r\n"
        cli.sendall(r)
        if response.body!=None:
            f=open(response.body,"rb")
            while True:
                block=f.read(1024)
                if block==b"":
                    break
                cli.sendall(block)
            f.close()
        cli.close()
        return
    except:
        try:
            cli.sendall(b"HTTP/1.1 500 Internal Server Error\r\nConnection: close\r\n\r\n")
            cli.close()
            return
        except:
            cli.close()
            return
def SSLAccept(sock):
    while True:
        cli,addr=sock.accept()
        threading.Thread(target=client_thread,args=(cli,addr)).start()
if SSLEnabled:
    threading.Thread(target=SSLAccept,args=(SSLSock,)).start()
threading.Thread(target=garbage_collector_thread).start()
while True:
    cli,addr=sock.accept()
    threading.Thread(target=client_thread,args=(cli,addr)).start()


问:
How to stop animation of Image-scaling to reset itself?
I have created a copy of the Button template and added an Image in there.
Then I created a mouseover state for *=> MouseOver to scale the image by 0.1.
It works. However despite leaving the mouse over the image, the animation resets itself back to initial state as if there was no mouseover still in place.

How can I make it stay there?

The second question is regarding the hardcoded path of Source within my Image. How can I inject it from the top into the style rather than having it hardcoded for one specific image? So that its more generic?

Many Thanks

```<code><Style x:Key="ButtonStyle1" TargetType="Button">
            <Setter Property="Background" Value="#FF1F3B53"/>
            <Setter Property="Foreground" Value="#FF000000"/>
            <Setter Property="Padding" Value="3"/>
            <Setter Property="BorderThickness" Value="1"/>
            <Setter Property="BorderBrush">
                <Setter.Value>
                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                        <GradientStop Color="#FFA3AEB9" Offset="0"/>
                        <GradientStop Color="#FF8399A9" Offset="0.375"/>
                        <GradientStop Color="#FF718597" Offset="0.375"/>
                        <GradientStop Color="#FF617584" Offset="1"/>
                    </LinearGradientBrush>
                </Setter.Value>
            </Setter>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Grid>
                            <VisualStateManager.VisualStateGroups>
                                <VisualStateGroup x:Name="CommonStates">
                                    <VisualStateGroup.Transitions>
                                        <VisualTransition GeneratedDuration="0" To="MouseOver">
                                            <Storyboard>
                                                <DoubleAnimation Duration="0:0:0.4" To="1.1" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.ScaleX)" Storyboard.TargetName="toolbarImage" d:IsOptimized="True"/>
                                                <DoubleAnimation Duration="0:0:0.4" To="1.1" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.ScaleY)" Storyboard.TargetName="toolbarImage" d:IsOptimized="True"/>
                                            </Storyboard>
                                        </VisualTransition>
                                    </VisualStateGroup.Transitions>
                                    <VisualState x:Name="Normal"/>
                                    <VisualState x:Name="MouseOver">
                                        <Storyboard>
                                            <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="BackgroundAnimation"/>
                                            <ColorAnimation Duration="0" To="#F2FFFFFF" Storyboard.TargetProperty="(Rectangle.Fill).(GradientBrush.GradientStops)[1].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient"/>
                                            <ColorAnimation Duration="0" To="#CCFFFFFF" Storyboard.TargetProperty="(Rectangle.Fill).(GradientBrush.GradientStops)[2].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient"/>
                                            <ColorAnimation Duration="0" To="#7FFFFFFF" Storyboard.TargetProperty="(Rectangle.Fill).(GradientBrush.GradientStops)[3].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient"/>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="Pressed">
                                        <Storyboard>
                                            <ColorAnimation Duration="0" To="#FF6DBDD1" Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)" Storyboard.TargetName="Background"/>
                                            <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="BackgroundAnimation"/>
                                            <ColorAnimation Duration="0" To="#D8FFFFFF" Storyboard.TargetProperty="(Rectangle.Fill).(GradientBrush.GradientStops)[0].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient"/>
                                            <ColorAnimation Duration="0" To="#C6FFFFFF" Storyboard.TargetProperty="(Rectangle.Fill).(GradientBrush.GradientStops)[1].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient"/>
                                            <ColorAnimation Duration="0" To="#8CFFFFFF" Storyboard.TargetProperty="(Rectangle.Fill).(GradientBrush.GradientStops)[2].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient"/>
                                            <ColorAnimation Duration="0" To="#3FFFFFFF" Storyboard.TargetProperty="(Rectangle.Fill).(GradientBrush.GradientStops)[3].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient"/>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="Disabled">
                                        <Storyboard>
                                            <DoubleAnimation Duration="0" To=".55" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="DisabledVisualElement"/>
                                        </Storyboard>
                                    </VisualState>
                                </VisualStateGroup>
                                <VisualStateGroup x:Name="FocusStates">
                                    <VisualState x:Name="Focused">
                                        <Storyboard>
                                            <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="FocusVisualElement"/>
                                        </Storyboard>
                                    </VisualState>
                                    <VisualState x:Name="Unfocused"/>
                                </VisualStateGroup>
                            </VisualStateManager.VisualStateGroups>
                            <VisualStateManager.CustomVisualStateManager>
                                <ei:ExtendedVisualStateManager/>
                            </VisualStateManager.CustomVisualStateManager>
                            <Border x:Name="Background" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="White" CornerRadius="3">
                                <Grid Background="{TemplateBinding Background}" Margin="1">
                                    <Border x:Name="BackgroundAnimation" Background="#FF448DCA" Opacity="0"/>
                                    <Rectangle x:Name="BackgroundGradient">
                                        <Rectangle.Fill>
                                            <LinearGradientBrush EndPoint=".7,1" StartPoint=".7,0">
                                                <GradientStop Color="#FFFFFFFF" Offset="0"/>
                                                <GradientStop Color="#F9FFFFFF" Offset="0.375"/>
                                                <GradientStop Color="#E5FFFFFF" Offset="0.625"/>
                                                <GradientStop Color="#C6FFFFFF" Offset="1"/>
                                            </LinearGradientBrush>
                                        </Rectangle.Fill>
                                    </Rectangle>
                                </Grid>
                            </Border>
                            <Image x:Name="toolbarImage" Source="./Images/New.png">
                                <Image.RenderTransform>
                                    <CompositeTransform CenterY="24" CenterX="24"/>
                                </Image.RenderTransform>
                            </Image>
                            <ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                            <Rectangle x:Name="DisabledVisualElement" Fill="#FFFFFFFF" IsHitTestVisible="false" Opacity="0" RadiusY="3" RadiusX="3"/>
                            <Rectangle x:Name="FocusVisualElement" IsHitTestVisible="false" Margin="1" Opacity="0" RadiusY="2" RadiusX="2" Stroke="#FF6DBDD1" StrokeThickness="1"/>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
</code>```

UPDATE:

Despite having set the autoreverse to false, I still havent sorted out the first issue.

```<code><VisualTransition From="Normal" GeneratedDuration="0" To="MouseOver">
                                            <Storyboard>
                                                <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="BackgroundAnimation"/>
                                                <ColorAnimation Duration="0" To="#F2FFFFFF" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[1].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient"/>
                                                <ColorAnimation Duration="0" To="#CCFFFFFF" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[2].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient"/>
                                                <ColorAnimation Duration="0" To="#7FFFFFFF" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[3].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient"/>
                                                <DoubleAnimation Duration="0:0:0.4" To="1.1" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.ScaleX)" Storyboard.TargetName="toolbarImage" AutoReverse="False"/>
                                                <DoubleAnimation Duration="0:0:0.4" To="1.1" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.ScaleY)" Storyboard.TargetName="toolbarImage" AutoReverse="False"/>
                                            </Storyboard>
                                        </VisualTransition>
</code>```

UPDATE 2:

I have uploaded a sample here to demo what I mean. Hover with mouse over the New button:
http://sl.venuscloud.com/

Am I missing something obvious?
Thanks

答:
Well your requirement does sound a bit impractical to me i.e. scaling images on mouseover and keeping them scaled forever then onwards??

Although if you insist

Being part of a Trigger, the scaling animation will anyways be removed (and scaled back to its original size) if you do not hover the mouse.

So for your requirement to fulfill, you can scale-animate the button in an attached behavior and not in Trigger that starts on main thread when mouseover is true (and make sure you write no reverse logic when its not a mouse over).

```<code>  <Button myNameSpace:MyAttachedBehavior.BeginScalingAnimation="{Binding IsMouseOver, RelativeSource={RelativeSource Self}}" />
</code>```

So in your attached behavior storyboard's AutoReverse property should be false and the scaling should persist after animation ends.

Now for next issue for image source...

You would have to create another Attached Property for Button which can be of ImageSource type. You can TemplateBind to that attached property in your Style.

e.g.

```<code>  <Button myNameSpace:MyAttachedBehavior.IconPath=".../xyz.png"/>
</code>```

and in Style's Template

```<code>  <Image Source="{TemplateBinding myNameSpace.MyAttachedBehavior:IconPath}" .../>
</code>```

in case if above TemplateBinding does not work try TemplatedParent as RelativeSource in normal Binding.

Let me know if this helps.

Body:
I have created a copy of the Button template and added an Image in there.
Then I created a mouseover state for *=> MouseOver to scale the image by 0.1.
It works. However despite leaving the mouse over the image, the animation resets itself back to initial state as if there was no mouseover still in place.

How can I make it stay there?

The second question is regarding the hardcoded path of Source within my Image. How can I inject it from the top into the style rather than having it hardcoded for one specific image? So that its more generic?

Many Thanks

UPDATE:

Despite having set the autoreverse to false, I still havent sorted out the first issue.

<VisualTransition From="Normal" GeneratedDuration="0" To="MouseOver">
                                            <Storyboard>
                                                <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="BackgroundAnimation"/>
                                                <ColorAnimation Duration="0" To="#F2FFFFFF" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[1].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient"/>
                                                <ColorAnimation Duration="0" To="#CCFFFFFF" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[2].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient"/>
                                                <ColorAnimation Duration="0" To="#7FFFFFFF" Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[3].(GradientStop.Color)" Storyboard.TargetName="BackgroundGradient"/>
                                                <DoubleAnimation Duration="0:0:0.4" To="1.1" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.ScaleX)" Storyboard.TargetName="toolbarImage" AutoReverse="False"/>
                                                <DoubleAnimation Duration="0:0:0.4" To="1.1" Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.ScaleY)" Storyboard.TargetName="toolbarImage" AutoReverse="False"/>
                                            </Storyboard>
                                        </VisualTransition>

UPDATE 2:

I have uploaded a sample here to demo what I mean. Hover with mouse over the New button:
http://sl.venuscloud.com/

Am I missing something obvious?
Thanks

Body:
Well your requirement does sound a bit impractical to me i.e. scaling images on mouseover and keeping them scaled forever then onwards??

Although if you insist

Being part of a Trigger, the scaling animation will anyways be removed (and scaled back to its original size) if you do not hover the mouse.

So for your requirement to fulfill, you can scale-animate the button in an attached behavior and not in Trigger that starts on main thread when mouseover is true (and make sure you write no reverse logic when its not a mouse over).

  <Button myNameSpace:MyAttachedBehavior.BeginScalingAnimation="{Binding IsMouseOver, RelativeSource={RelativeSource Self}}" />

So in your attached behavior storyboard's AutoReverse property should be false and the scaling should persist after animation ends.

Now for next issue for image source...

You would have to create another Attached Property for Button which can be of ImageSource type. You can TemplateBind to that attached property in your Style.

e.g.

  <Button myNameSpace:MyAttachedBehavior.IconPath=".../xyz.png"/>

and in Style's Template

  <Image Source="{TemplateBinding myNameSpace.MyAttachedBehavior:IconPath}" .../>

in case if above TemplateBinding does not work try TemplatedParent as RelativeSource in normal Binding.

Let me know if this helps.


问:
Slack: change browser to open links from desktop app
I use two browsers on my laptop - Brave for my personal stuff (Facebook, personal email, interesting things I want to read) and Firefox for my work browsing (work email, internal webpages, work communication). Normally I like having my default browser for the computer set to Brave (personal), since most of the time I use the laptop outside of work.

I now have the Slack desktop app to keep in better communication with folks at work. But when I click on links from there, it goes to Brave where I am not logged-in to anything work related.

Is there a way to change the browser that Slack opens without changin my system wide default browser?

I'm on a Mac, Mojave, if that helps.

答: If you using Ubuntu (Linux) you can just go to about:preferences and  click on "make default" button.


问:
SQL Server : select a record from a window with criteria
I have an audit table in SQL Server which stores data like this for a single case:

Example 1

```<code>ID        CREATED                 MESSAGE               MEMO         USER
------------------------------------------------------------------------------
A-123     08/02/2022 12:00:00     Generic Message 1     NULL         System
A-123     08/02/2022 12:05:30     Generic Message 2     NULL         System
A-123     08/02/2022 12:45:01     Reassigned to XYZ     NULL         System
A-123     08/02/2022 14:59:59     NULL                  Resolved     User XYZ
A-123     08/02/2022 18:05:05     Reassigned to XYZ     NULL         System
</code>```

Example 2

```<code>ID        CREATED                 MESSAGE               MEMO         USER
--------------------------------------------------------------------------------
A-987     07/02/2022 12:00:00     Generic Message 1     NULL         System
A-987     07/02/2022 12:05:30     Generic Message 2     NULL         System
A-987     07/02/2022 12:45:01     Generic Message 3     NULL         System
A-987     07/02/2022 14:59:59     NULL                  Resolved     User XYZ
A-987     07/02/2022 18:05:05     Reassigned to XYZ     NULL         System
</code>```

Using SQL I want to only select the ID value in these circumstances:

When there is a MESSAGE value of "Reassigned to XYZ" with a USER value of "System"

When point 1. occurs at an earlier time than the record that contains a MEMO value of "Resolved".

In the 2 examples above, example 1 would output ID A-123 because the 2 criteria have met, but example 2 wouldn't output anything because the "Reassigned to XYZ" MESSAGE value is after the timestamp of the "Resolved" MEMO entry.

I think I need to rank() and then do something but I can't work out what.

答:
I don't see a need for a window function here.  There are several ways to address this: here are but a few UNTESTED ways.

USING an Exists to limit data:  Get all XYZ, find any occurrence of a XYZ create date before a resolved data. and return that ID  multiple ID's would return if multiple "reassigned to XYZ' Id's exist.

```<code>SELECT ID
FROM TABLE
WHERE message = 'Reassigned to XYZ'
  AND exists (SELECT 1
                  FROM TABLE
                  WHERE memo = 'Resolved'
                    AND A.ID = B.ID
                    AND A.Created < B.Created)
</code>```

Using CTE's and an join.  Similar to exists;   show any XYZID whose created data is < the resolve'd created dat a for a same ID.  Could have multiple rows returned

```<code>WITH XYZ as (SELECT ID, Created FROM TABLE WHERE message = 'Reassigned to XYZ'),
     Resolved as (SELECT ID, Created FROM TABLE WHERE memo = 'Resolved')
SELECT XYZ.ID
FROM XYZ
INNER JOIN Resolved
   on XYZ.ID = Resolve.ID
  AND XYZ.Created < Resolved.Created
</code>```

You could use an aggregate as well I suppose and case expression

This assumes you could have multiple Reassigned to XYZ or resolved, and all it takes is for 1 XYZ to be before resolved for the ID to show up. only 1 ID would ever be returned if condition is met.

```<code>SELECT ID,
       MIN(CASE when Message = 'Reassigned to XYZ' then create end) as MinZYZ,
       MIN(Case when memo = 'Resolved' then create end) MinMemo
FROM Table
GROUP BY ID
HAVING MINXYZ < MinMemo
</code>```

I suppose we could do the min/case expression in the having to eliminate the values from the select if needed... simply substitute the expression for the aliased column name used

you could use cross apply cross apply is a table value function which allows the sub query to run once per record in the left table and operates like an inner join in that if no records are found the record is eliminated.  So only records which are XYZ and have a resolved created data greater than the XYZ record will be present.

```<code>SELECT Distinct XYZ.ID
FROM Table XYZ
CROSS APPLY (SELECT TOP 1 ID, Created FROM TABLE WHERE memo = 'Resolved' ORDER BY Created ASC) Resolved
   on XYZ.ID = Resolve.ID
  AND XYZ.Created < Resolved.Created
</code>```

NOTES:

Each has their own pro's/con's and assumptions.

Depending on data volume indexes etc performance can vary with each as well

Feel free to ask qustions about any or point out if they don't' work.  again UNTESTED so based entirely off of logical thinking and may not be with correct syntax or return correct results.

Body:
I have an audit table in SQL Server which stores data like this for a single case:

Example 1

ID        CREATED                 MESSAGE               MEMO         USER
------------------------------------------------------------------------------
A-123     08/02/2022 12:00:00     Generic Message 1     NULL         System
A-123     08/02/2022 12:05:30     Generic Message 2     NULL         System
A-123     08/02/2022 12:45:01     Reassigned to XYZ     NULL         System
A-123     08/02/2022 14:59:59     NULL                  Resolved     User XYZ
A-123     08/02/2022 18:05:05     Reassigned to XYZ     NULL         System

Example 2

ID        CREATED                 MESSAGE               MEMO         USER
--------------------------------------------------------------------------------
A-987     07/02/2022 12:00:00     Generic Message 1     NULL         System
A-987     07/02/2022 12:05:30     Generic Message 2     NULL         System
A-987     07/02/2022 12:45:01     Generic Message 3     NULL         System
A-987     07/02/2022 14:59:59     NULL                  Resolved     User XYZ
A-987     07/02/2022 18:05:05     Reassigned to XYZ     NULL         System

Using SQL I want to only select the ID value in these circumstances:

When there is a MESSAGE value of "Reassigned to XYZ" with a USER value of "System"

When point 1. occurs at an earlier time than the record that contains a MEMO value of "Resolved".

In the 2 examples above, example 1 would output ID A-123 because the 2 criteria have met, but example 2 wouldn't output anything because the "Reassigned to XYZ" MESSAGE value is after the timestamp of the "Resolved" MEMO entry.

I think I need to rank() and then do something but I can't work out what.

Body:
I don't see a need for a window function here.  There are several ways to address this: here are but a few UNTESTED ways.

USING an Exists to limit data:  Get all XYZ, find any occurrence of a XYZ create date before a resolved data. and return that ID  multiple ID's would return if multiple "reassigned to XYZ' Id's exist.

SELECT ID
FROM TABLE
WHERE message = 'Reassigned to XYZ'
  AND exists (SELECT 1
                  FROM TABLE
                  WHERE memo = 'Resolved'
                    AND A.ID = B.ID
                    AND A.Created < B.Created)

Using CTE's and an join.  Similar to exists;   show any XYZID whose created data is < the resolve'd created dat a for a same ID.  Could have multiple rows returned

WITH XYZ as (SELECT ID, Created FROM TABLE WHERE message = 'Reassigned to XYZ'),
     Resolved as (SELECT ID, Created FROM TABLE WHERE memo = 'Resolved')
SELECT XYZ.ID
FROM XYZ
INNER JOIN Resolved
   on XYZ.ID = Resolve.ID
  AND XYZ.Created < Resolved.Created

You could use an aggregate as well I suppose and case expression

This assumes you could have multiple Reassigned to XYZ or resolved, and all it takes is for 1 XYZ to be before resolved for the ID to show up. only 1 ID would ever be returned if condition is met.

SELECT ID,
       MIN(CASE when Message = 'Reassigned to XYZ' then create end) as MinZYZ,
       MIN(Case when memo = 'Resolved' then create end) MinMemo
FROM Table
GROUP BY ID
HAVING MINXYZ < MinMemo

I suppose we could do the min/case expression in the having to eliminate the values from the select if needed... simply substitute the expression for the aliased column name used

you could use cross apply cross apply is a table value function which allows the sub query to run once per record in the left table and operates like an inner join in that if no records are found the record is eliminated.  So only records which are XYZ and have a resolved created data greater than the XYZ record will be present.

SELECT Distinct XYZ.ID
FROM Table XYZ
CROSS APPLY (SELECT TOP 1 ID, Created FROM TABLE WHERE memo = 'Resolved' ORDER BY Created ASC) Resolved
   on XYZ.ID = Resolve.ID
  AND XYZ.Created < Resolved.Created

NOTES:

Each has their own pro's/con's and assumptions.

Depending on data volume indexes etc performance can vary with each as well

Feel free to ask qustions about any or point out if they don't' work.  again UNTESTED so based entirely off of logical thinking and may not be with correct syntax or return correct results.


问:
anchor tag question for Typecript Angular
click

I'm doing some accessibility work on some existing code. I have some anchor tags with click events bound to them. I noted there is no href attribute here either because the click event properly handles to route and clicking enter on the keyboard also triggers the even. I want this to be tabbable, but because there's is no href attribute it isn't tabbable, so I added a tabindex="0. This now made my a tag tabbable, but now clicking enter on the keyboard is not triggering my event. I've found that adding the following code to my a tag keys the click event working properly clicking it or pressing enter.

href="javascript:void(0)"

Is this acceptable code for accesibility standards?...or does someone recommend a better approach?

答:
You can use (keydown)="EnterSubmit($event, url.state) in tag.

And in .ts :

```<code>EnterSubmit(e,state){
     if (e.keyCode === 13) {
      alert("Submitted with enter.")
   }
}
</code>```

Addition to above

You also need to set focus on you anchor tag.
You can achieve that with viewChild or simple DOM way is :

```<code>document.getElementById("supportLink")?.focus();
</code>```

If you want this focus on page load, Write this in ngAfterViewInit().
Final HTML code :

```<code><a id="supportLink" (click)="navigate(url.state)" (keydown)="EnterSubmit($event, url.state)" tabindex="0">click</a>`
</code>```

Body:
You can use (keydown)="EnterSubmit($event, url.state) in tag.

And in .ts :

EnterSubmit(e,state){
     if (e.keyCode === 13) {
      alert("Submitted with enter.")
   }
}

Addition to above

You also need to set focus on you anchor tag.
You can achieve that with viewChild or simple DOM way is :

document.getElementById("supportLink")?.focus();

If you want this focus on page load, Write this in ngAfterViewInit().
Final HTML code :

<a id="supportLink" (click)="navigate(url.state)" (keydown)="EnterSubmit($event, url.state)" tabindex="0">click</a>`


问:
Pandas multi index partial selection using list of tuples
Consider the following dataframe

```<code>import pandas as pd
import numpy as np

arr = np.random.random((2, 4))
mdf = pd.DataFrame({'cid': ['c1', 'c2']})
pdf = pd.DataFrame({'doc_id': ['d1', 'd1', 'd2', 'd2'], 'passage_id': ['p1', 'p2', 'p1', 'p2']})
index = pd.MultiIndex.from_frame(mdf.join(pdf, how='cross'))
df = pd.DataFrame({'score': arr.flatten()}, index=index)
</code>```

df is

```<code>                             score
cid     doc_id  passage_id
c1      d1       p1          0.708722
                 p2          0.975350
        d2       p1          0.326029
                 p2          0.979832
c2      d1       p1          0.147153
                 p2          0.381807
        d2       p1          0.525054
                 p2          0.245478
</code>```

Now If i try to index using a list of tuples using only two levels

df.loc[[('c1', 'd1'), ('c2', 'd2')]]

I get the following error:

ValueError: operands could not be broadcast together with shapes (2,2) (3,) (2,2)

Why is this error happening ?

I expected the answer to be:

```<code>                             score
cid     doc_id  passage_id
c1      d1       p1          0.708722
                 p2          0.975350
c2      d2       p1          0.525054
                 p2          0.245478
</code>```

答:
You can use get_locs:

```<code>loc = df.index.get_locs
idx = np.union1d(loc(('c1', 'd1')), loc(('c2', 'd2')))
subdf = df.iloc[idx]
</code>```

Output:

```<code>>>> subdf
                          score
cid doc_id passage_id
c1  d1     p1          0.055452
           p2          0.758224
c2  d2     p1          0.773690
           p2          0.519005

>>> idx
array([0, 1, 6, 7])
</code>```

Body:
Consider the following dataframe

import pandas as pd
import numpy as np

arr = np.random.random((2, 4))
mdf = pd.DataFrame({'cid': ['c1', 'c2']})
pdf = pd.DataFrame({'doc_id': ['d1', 'd1', 'd2', 'd2'], 'passage_id': ['p1', 'p2', 'p1', 'p2']})
index = pd.MultiIndex.from_frame(mdf.join(pdf, how='cross'))
df = pd.DataFrame({'score': arr.flatten()}, index=index)

df is

                             score
cid     doc_id  passage_id
c1      d1       p1          0.708722
                 p2          0.975350
        d2       p1          0.326029
                 p2          0.979832
c2      d1       p1          0.147153
                 p2          0.381807
        d2       p1          0.525054
                 p2          0.245478

Now If i try to index using a list of tuples using only two levels

df.loc[[('c1', 'd1'), ('c2', 'd2')]]

I get the following error:

ValueError: operands could not be broadcast together with shapes (2,2) (3,) (2,2)

Why is this error happening ?

I expected the answer to be:

                             score
cid     doc_id  passage_id
c1      d1       p1          0.708722
                 p2          0.975350
c2      d2       p1          0.525054
                 p2          0.245478

Body:
You can use get_locs:

loc = df.index.get_locs
idx = np.union1d(loc(('c1', 'd1')), loc(('c2', 'd2')))
subdf = df.iloc[idx]

Output:

>>> subdf
                          score
cid doc_id passage_id
c1  d1     p1          0.055452
           p2          0.758224
c2  d2     p1          0.773690
           p2          0.519005

>>> idx
array([0, 1, 6, 7])


问:
How to handle shared column with jpa/hibernate?
I'm storing money/currency stored in the database which I want to map using JPA/Hibernate but one column is needed for two different mappings on the same entity.

DB Schema:

```<code>id: number
currency_code: string
total: number
sub_total: number
</code>```

POJOs:

```<code>public class MyEntity {
    private long id;
    private Money total;
    private Money subTotal;
}

public class Money {
    private  CurrencyCode currencyCode;
    private  BigInteger value;
}
</code>```

The problem I'm hitting with JPA/Hibernate is that the currency_code is needed to be mapped with both total and subTotal:

```<code>@Entity
@Table(name = "MyTable")
public class MyEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private long id;

    @Type(type = "customMoneyType")
    @Columns(columns = {
            @Column(name = "currency_code"),
            @Column(name = "total"),
    })
    private Money total;

    @Type(type = "customMoneyType")
    @Columns(columns = {
            @Column(name = "currency_code"),
            @Column(name = "sub_total"),
    })
    private Money subTotal;
}
</code>```

which leads to Caused by: org.hibernate.MappingException: Repeated column in mapping for entity

Both fields need to be updatable and nullable. The sharing of the column is legacy but not changeable in the near future.  With that said, I'm open to less than ideal solutions which could work until the DB schema can be changed.

答:
Just make MyEntity to align exactly to the table. Keep the currencyCode, total and subTotal fields as internal to the class and use OOP encapsulation technique to expose a methods for client work with them though the Money value object. Something like :

@Entity
@Table(name = "entity")
public class MyEntity {

    @Id
    @Column(name = "id")
    private long id;

    @Column(name = "currency_code")
    private CurrencyCode currenyCode;

    @Column(name = "total")
    private BigInteger total;

    @Column(name = "sub_total")
    private BigInteger subTotal;

    public Money getTotal(){
      return new Money(currenyCode, total);
    }

    public Money getSubTotal(){
      return new Money(currenyCode, subTotal);
    }

    public void updateTotal(Money m){
        this.currencyCode = m.getCurrenyCode();
        this.total = m.getValue();
    }

    public void updateSubTotal(Money m){
        this.currencyCode = m.getCurrenyCode();
        this.subTotal = m.getValue();
    }

}
```

Body:
I'm storing money/currency stored in the database which I want to map using JPA/Hibernate but one column is needed for two different mappings on the same entity.

DB Schema:

id: number
currency_code: string
total: number
sub_total: number

POJOs:

public class MyEntity {
    private long id;
    private Money total;
    private Money subTotal;
}

public class Money {
    private  CurrencyCode currencyCode;
    private  BigInteger value;
}

The problem I'm hitting with JPA/Hibernate is that the currency_code is needed to be mapped with both total and subTotal:

@Entity
@Table(name = "MyTable")
public class MyEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private long id;

    @Type(type = "customMoneyType")
    @Columns(columns = {
            @Column(name = "currency_code"),
            @Column(name = "total"),
    })
    private Money total;

    @Type(type = "customMoneyType")
    @Columns(columns = {
            @Column(name = "currency_code"),
            @Column(name = "sub_total"),
    })
    private Money subTotal;
}

which leads to Caused by: org.hibernate.MappingException: Repeated column in mapping for entity

Both fields need to be updatable and nullable. The sharing of the column is legacy but not changeable in the near future.  With that said, I'm open to less than ideal solutions which could work until the DB schema can be changed.


问:
Line Chart: Show all other countries as light grey
In the example below two countries are shown (via transform/filter).

How do I modify the code so that:

All the remaining countries also appear as lines coloured light grey

All the remaining countries are excluded from the legend

Thanks.

```<code>{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "description": "Multiple line chart",
  "width": "container",
  "title": {"text": "Average babies per woman, 1800-2018"},
  "data": {
    "url": "https://www.trafforddatalab.io/interactive_graphics_companion/data/gapminder_dtfr.csv"
  },
  "transform": [
    {"filter": {"field": "country", "oneOf": ["Iran", "United States"]}}
  ],
  "mark": "line",
  "encoding": {
    "x": {
      "field": "year",
      "type": "temporal",
      "timeUnit": "year",
      "axis": {"title": null, "grid": false}
    },
    "y": {
      "field": "fertilityRate",
      "type": "quantitative",
      "axis": {"title": null}
    },
    "color": {
      "field": "country",
      "type": "nominal",
      "legend": {"orient": "right", "direction": "vertical", "title": null}
    },
    "tooltip": [
      {
        "field": "year",
        "type": "temporal",
        "timeUnit": "year",
        "title": "Year"
      },
      {"field": "country", "type": "nominal", "title": "Country"},
      {
        "field": "fertilityRate",
        "type": "quantitative",
        "title": "Number of babies",
        "format": ".1f"
      }
    ]
  },
  "config": {"style": {"cell": {"stroke": "transparent"}}}
}
</code>```

答:
There are a few ways you could do this, but I would probably suggest using a layer chart to ensure that your selected lines will appear on top of all the others (view in editor):

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "description": "Multiple line chart",
  "width": "container",
  "title": {"text": "Average babies per woman, 1800-2018"},
  "data": {
    "url": "https://www.trafforddatalab.io/interactive_graphics_companion/data/gapminder_dtfr.csv"
  },
  "layer": [
    {
      "mark": {"type": "line", "color": "lightgray"},
      "encoding": {"detail": {"field": "country", "type": "nominal"}}
    },
    {
      "mark": "line",
      "transform": [
        {"filter": {"field": "country", "oneOf": ["Iran", "United States"]}}
      ],
      "encoding": {
        "color": {
          "field": "country",
          "type": "nominal",
          "legend": {"orient": "right", "direction": "vertical", "title": null}
        }
      }
    }
  ],
  "encoding": {
    "x": {
      "field": "year",
      "type": "temporal",
      "timeUnit": "year",
      "axis": {"title": null, "grid": false}
    },
    "y": {
      "field": "fertilityRate",
      "type": "quantitative",
      "axis": {"title": null}
    },
    "tooltip": [
      {
        "field": "year",
        "type": "temporal",
        "timeUnit": "year",
        "title": "Year"
      },
      {"field": "country", "type": "nominal", "title": "Country"},
      {
        "field": "fertilityRate",
        "type": "quantitative",
        "title": "Number of babies",
        "format": ".1f"
      }
    ]
  },
  "config": {"style": {"cell": {"stroke": "transparent"}}}
}
```

Body:
In the example below two countries are shown (via transform/filter).

How do I modify the code so that:

All the remaining countries also appear as lines coloured light grey

All the remaining countries are excluded from the legend

Thanks.

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "description": "Multiple line chart",
  "width": "container",
  "title": {"text": "Average babies per woman, 1800-2018"},
  "data": {
    "url": "https://www.trafforddatalab.io/interactive_graphics_companion/data/gapminder_dtfr.csv"
  },
  "transform": [
    {"filter": {"field": "country", "oneOf": ["Iran", "United States"]}}
  ],
  "mark": "line",
  "encoding": {
    "x": {
      "field": "year",
      "type": "temporal",
      "timeUnit": "year",
      "axis": {"title": null, "grid": false}
    },
    "y": {
      "field": "fertilityRate",
      "type": "quantitative",
      "axis": {"title": null}
    },
    "color": {
      "field": "country",
      "type": "nominal",
      "legend": {"orient": "right", "direction": "vertical", "title": null}
    },
    "tooltip": [
      {
        "field": "year",
        "type": "temporal",
        "timeUnit": "year",
        "title": "Year"
      },
      {"field": "country", "type": "nominal", "title": "Country"},
      {
        "field": "fertilityRate",
        "type": "quantitative",
        "title": "Number of babies",
        "format": ".1f"
      }
    ]
  },
  "config": {"style": {"cell": {"stroke": "transparent"}}}
}

Body:
There are a few ways you could do this, but I would probably suggest using a layer chart to ensure that your selected lines will appear on top of all the others (<a href="https://vega.github.io/editor/#/url/vega-lite/N4IgJAzgxgFgpgWwIYgFwhgF0wBwqgegIDc4BzJAOjIEtMYBXAI0poHsDp5kTykBaADZ04JACyUAVhDYA7EABoQAEzjQATjRyZ289AFkGgnTkFwABMNkXYSdZkUgA7jWX00IKHMxIa19Y46mGZooJhwAB4O6ACCpOpIZBZMSEw0auY4cOrmTmzIsgrmAIwAHAAM5fwATOVlIAC+SspIPqEgDOqCHli4+EROg5SYCQBmo2zqyi0+gqmsHH7hCVA6pAD6ZAk4MDRQEOteCDhIsroEM0gEFDgIfqrq626j6pT7xI1KcwCe2WgA2qBkOoANbtTDfLIeKxwRxeQSTaE0MhYLZIb6fEBwWReZR+MjtVQ+GjdVCgUbpQTKDxeBiyEYYpQQqHoWT5PxIboNbkKIF2MHoGGBBKyCATdQIAHkknLdoUuBUmlsOkMxxyOAAeVGAJAAEkRY4AKpncLKcwAZR84QgIAAutzbUpsbj8e14YiySB5Yr0LT6epGSBmbDWezZJzHGYkrJqZ7Jul6R5NCiHM0aOo4KtdB54jooBGmXQQqhZEZBNyHU6cWw8bICZ6InLKbGQL87IFISGg4gcJMC0GaAg4Ma6B42wElEgIjQbZ6gsXS4JBEotq40KNORA4DzW02FS3RtkdMIIQAlVqwpmdjwARwYpyCrRopEcU5n4KLIcX5aaQbYbGMLQpS9ZsxzgdsrxZbtjj7bpCyHEdolbcCJwHYIuwATRQz5pX3JUVQDDsoLZO5wzgtDixAABhZV-QxJpcJ9L0jxJOhvnPcIiK7O8HzoJ8X0LdCPAAOQYBAmGycw2FGcwUjSNRHHFZAkMoYptQae0lC8WQKXrUAIAhYtQCgBVSX0kY2BBLsRlOCATgzRMKwaIA" rel="nofollow noreferrer">view in editor):

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "description": "Multiple line chart",
  "width": "container",
  "title": {"text": "Average babies per woman, 1800-2018"},
  "data": {
    "url": "https://www.trafforddatalab.io/interactive_graphics_companion/data/gapminder_dtfr.csv"
  },
  "layer": [
    {
      "mark": {"type": "line", "color": "lightgray"},
      "encoding": {"detail": {"field": "country", "type": "nominal"}}
    },
    {
      "mark": "line",
      "transform": [
        {"filter": {"field": "country", "oneOf": ["Iran", "United States"]}}
      ],
      "encoding": {
        "color": {
          "field": "country",
          "type": "nominal",
          "legend": {"orient": "right", "direction": "vertical", "title": null}
        }
      }
    }
  ],
  "encoding": {
    "x": {
      "field": "year",
      "type": "temporal",
      "timeUnit": "year",
      "axis": {"title": null, "grid": false}
    },
    "y": {
      "field": "fertilityRate",
      "type": "quantitative",
      "axis": {"title": null}
    },
    "tooltip": [
      {
        "field": "year",
        "type": "temporal",
        "timeUnit": "year",
        "title": "Year"
      },
      {"field": "country", "type": "nominal", "title": "Country"},
      {
        "field": "fertilityRate",
        "type": "quantitative",
        "title": "Number of babies",
        "format": ".1f"
      }
    ]
  },
  "config": {"style": {"cell": {"stroke": "transparent"}}}
}


问:
Pydub - How to change frame rate without changing playback speed
I have a couple audio files that I open in Pydub with AudioSegment.

I want to decrease the audio quality from frame rate 22050 to 16000 Hz. (One channel files)

If I simply change the frame rate of AudioSegment, what I get is the exact same wave played in slower speed. Well, fair enough.

But how do I actually change the waves to fit a lower quality, same speed playback?

(Manual interpolation is the only thing I can think of, but I don't want to get into that trouble)

答:
Or you can do this instead also:

import librosa

y, sr = librosa.load(path, sr=16000)
```

and use it further as per your requirement.

Body:
Or you can do this instead also:

import librosa

y, sr = librosa.load(path, sr=16000)

and use it further as per your requirement.


问:
One method in many Tasks async/await
Hi I have a case where I need to call the same method in multiple Tasks. I want to have a possibility to call this method one by one (sync) not in parallel mode. It looks like that:

```<code>var isReadyToRefresh: Bool = true

func refresh(value: Int) async {
    try! await Task.sleep(nanoseconds: 100_000_000) // imitation API CALL
    isReadyToRefresh = false
    print("Try to refresh: \(value)")
}

func mockCallAPI(value: Int) async {
    if isReadyToRefresh {
        await refresh(value: value)
    }
}

Task {
     await mockCallAPI(value: 1)
}

Task {
     await mockCallAPI(value: 2)
}
</code>```

output:

Try to refresh: 1

Try to refresh: 2

my required output:

Try to refresh: 1 OR Try to refresh 2. Depends which task has been called as first one.

Any ideas?

答:
You said:

I want [the second attempt] to wait for the first refresh API finish

You can save a reference to your Task and, if found, await it. If not found, then start the task:

actor Refresh {
    var task: Task<Void, Never>?

    func refresh(value: Int) async {
        try! await Task.sleep(nanoseconds: 100_000_000) // imitation API CALL
        print("Try to refresh: \(value)")
    }

    func mockCallAPI(value: Int) async {
        if let task = self.task {
            _ = await task.result
            return
        }

        task = Task {
            await refresh(value: value)
            task = nil
        }
    }
}
```

Apple showed example of this pattern in the code provided the with WWDC 2021 video, Protect mutable state with Swift actors (but this code is not on the web site; only provided in the Developer app). See How to prevent actor reentrancy resulting in duplicative requests?

Their example is more complicated (a pattern to avoid duplicate network requests from being initiated by some image cache/downloader), but the kernel of the idea is the same: Save and await the Task.

Title: One method in many Tasks async/await

Body:
Hi I have a case where I need to call the same method in multiple Tasks. I want to have a possibility to call this method one by one (sync) not in parallel mode. It looks like that:

var isReadyToRefresh: Bool = true

func refresh(value: Int) async {
    try! await Task.sleep(nanoseconds: 100_000_000) // imitation API CALL
    isReadyToRefresh = false
    print("Try to refresh: \(value)")
}

func mockCallAPI(value: Int) async {
    if isReadyToRefresh {
        await refresh(value: value)
    }
}

Task {
     await mockCallAPI(value: 1)
}

Task {
     await mockCallAPI(value: 2)
}

output:

Try to refresh: 1

Try to refresh: 2

my required output:

Try to refresh: 1 OR Try to refresh 2. Depends which task has been called as first one.

Any ideas?

Body:
You said:

I want [the second attempt] to wait for the first refresh API finish

You can save a reference to your Task and, if found, await it. If not found, then start the task:

actor Refresh {
    var task: Task<Void, Never>?

    func refresh(value: Int) async {
        try! await Task.sleep(nanoseconds: 100_000_000) // imitation API CALL
        print("Try to refresh: \(value)")
    }

    func mockCallAPI(value: Int) async {
        if let task = self.task {
            _ = await task.result
            return
        }

        task = Task {
            await refresh(value: value)
            task = nil
        }
    }
}

Apple showed example of this pattern in the code provided the with WWDC 2021 video, Protect mutable state with Swift actors (but this code is not on the web site; only provided in the Developer app). See How to prevent actor reentrancy resulting in duplicative requests?

Their example is more complicated (a pattern to avoid duplicate network requests from being initiated by some image cache/downloader), but the kernel of the idea is the same: Save and await the Task.