问:
deno relative path issue
I wanted to some prefixes for my imports like you can see in the code below:

```<code>"paths": {
          "~/*": ["../../libs/*"],
          "@/*": ["./*"]
        }
</code>```

however I always get an relative import path "@/config.ts" not prefixed with / or ./ or ../ts(10001) when I try to import anything import User from "@/config.ts"

答:
You can alias import specifiers by using an import map. From the Deno manual:

You can use import maps with the --import-map=<FILE> CLI flag.

Example:

import_map.json

{
   "imports": {
      "fmt/": "https://deno.land/std@0.125.0/fmt/"
   }
}
```
<p><strong>color.ts</strong></p>
<pre class="lang-ts prettyprint-override"><code>import { red } from "fmt/colors.ts";

console.log(red("hello world"));
</code>```

Then:

```<code>$ deno run --import-map=import_map.json color.ts
</code>```

Title: deno relative path issue

Body:
I wanted to some prefixes for my imports like you can see in the code below:

"paths": {
          "~/*": ["../../libs/*"],
          "@/*": ["./*"]
        }

however I always get an relative import path "@/config.ts" not prefixed with / or ./ or ../ts(10001) when I try to import anything import User from "@/config.ts"

Body:
You can alias import specifiers by using an import map. From the Deno manual:

You can use import maps with the --import-map=<FILE> CLI flag.

Example:

import_map.json

{
   "imports": {
      "fmt/": "https://deno.land/std@0.125.0/fmt/"
   }
}

color.ts

import { red } from "fmt/colors.ts";

console.log(red("hello world"));

Then:

$ deno run --import-map=import_map.json color.ts


来源: stackexchange

问:
Unable to open Code-insiders undefined symbol SHA256
I am currently unable to open code-insiders (latest build) The interface loads and then immediately closes, however there are code-insider processes left behind still running in back ground that I have to kill directly.
The error in the log is:
/usr/share/code-insiders/code-insiders --unity-launch --enable-crashpad: symbol lookup error: /usr/share/code-insiders/resources/app/node_modules.asar.unpacked/vscode-encrypt/build/Release/vscode-encrypt-native.node: undefined symbol: SHA256_Init

 I have seen similar posts that point to the libcrypt and libssh libraries and I have tried re-installing both with no change. I have also purged code and reinstalled the latest build. This still occurs if I try and launch with extensions disabled.

Any suggestions on where to search next would be appreciated.

答:
SHA256_Init crash problem is due to the vscode-encrypt-native ELF is not linked against lcrypto so the symbols cannot be resolved properly.

You can do a quick fix:

$ find /usr/lib/ -type f -name "libcrypto.so.*"
/usr/lib/x86_64-linux-gnu/libcrypto.so.1.1

$ sudo apt instal patchelf

$ sudo patchelf --add-needed libcrypto.so.1.1 /usr/share/code-insiders/resources/app/node_modules.asar.unpacked/vscode-encrypt/build/Release/vscode-encrypt-native.node
```

Ref: https://github.com/microsoft/vscode/issues/142656#issuecomment-1034173634

ContentLicense: CC BY-SA 4.0

Body:
SHA256_Init crash problem is due to the vscode-encrypt-native ELF is not linked against lcrypto so the symbols cannot be resolved properly.

You can do a quick fix:

$ find /usr/lib/ -type f -name "libcrypto.so.*"
/usr/lib/x86_64-linux-gnu/libcrypto.so.1.1

$ sudo apt instal patchelf

$ sudo patchelf --add-needed libcrypto.so.1.1 /usr/share/code-insiders/resources/app/node_modules.asar.unpacked/vscode-encrypt/build/Release/vscode-encrypt-native.node

Ref: https://github.com/microsoft/vscode/issues/142656#issuecomment-1034173634


问:
Prestashop show tax rule name
I want to show the tax rule name (example: 21% Incl.) on the prestashop checkout page. Is there a way to do this?

I only found the following prefix:

```<code>{$display_tax_label|escape:'html':'UTF-8'}
</code>```

But this is only showing active or not.

Also found another thing which is listed in the invoice templates but I cannot use it somewhere else.

答:
Additional to @marsaldev's answer today i found to use the tax_name of the first product in cart - while being aware that this shop only uses one tax rule.

{$cart.products[0].tax_name}

thanks to @wolfack's hint

you should add what you found in invoice templates. So that we can
guide how to reuse it

i will post the results also to get a complete answer

ContentLicense: CC BY-SA 3.0

Title: Prestashop show tax rule name

Body:
I want to show the tax rule name (example: 21% Incl.) on the prestashop checkout page. Is there a way to do this?

I only found the following prefix:

{$display_tax_label|escape:'html':'UTF-8'}

But this is only showing active or not.

Also found another thing which is listed in the invoice templates but I cannot use it somewhere else.


问:
Java Attach API: VirtualMachine.list() returns empty list?
Any time I'm working with the Java Attach API, no valid VirtualMachines are ever returned. I've tried getting iterating through the list returned by VirtualMachine.list(), and any time I think I've obtained the process ID, I try using VirtualMachine.attach() and it gives me a NullPointerException because the attach() method itself never initializes the exception it tries to throw. I'm working on the project via Eclipse and the Windows process of the application itself when it runs is javaw.exe. What am I doing wrong?</p>

答:
The code that does the VM discovery is in tools.jar on Java 8. That is why running from the JDK is needed.

With modular Java you need the "jdk.attach" module, which you can add to your JRE with jlink.


问:
Some modulo hijinkery
I am solving a question on LeetCode:

You are given two positive integer arrays nums1 and nums2, both of length n.The absolute sum difference of arrays nums1 and nums2 is defined as the sum of |nums1[i] - nums2[i]| for each 0 <= i < n (0-indexed). You can replace at most one element of nums1 with any other element in nums1 to minimize the absolute sum difference.  Return the minimum absolute sum difference after replacing at most one element in the array nums1. Since the answer may be large, return it modulo (10^9 + 7). For Input: nums1 = [1,7,5], nums2 = [2,3,5], Output: 3.

The code that I came up with is as below:

class Solution {
public:
    int minAbsoluteSumDiff(vector<int>& nums1, vector<int>& nums2) {
        if(nums1==nums2) return 0;

        long long MOD=(int)1e9+7;

        set<long long> s(begin(nums1),end(nums1));

        long long diff=0ll, res=LLONG_MAX;
        for(int i=0; i<nums1.size(); i++)
            diff=(diff%MOD+(abs(nums1[i]-nums2[i]))%MOD)%MOD;

        for(int i=0; i<nums2.size(); i++) {
            long long curr=nums2[i];
            auto lb=s.lower_bound(curr);

            if(lb!=s.begin()) {
                auto p=prev(lb);
                long long prevElement=*p;
                long long currsum=diff;

                currsum=(currsum%MOD-(abs(nums1[i]-nums2[i]))%MOD)%MOD;
                currsum=(currsum%MOD+abs(curr-prevElement)%MOD)%MOD;

                res=min(res, currsum);
            }

            if(lb!=s.end()) {
                long long nextElement=*lb;
                long long currsum=diff;

                currsum=(currsum%MOD-(abs(nums1[i]-nums2[i]))%MOD)%MOD;
                currsum=(currsum%MOD+(abs(curr-nextElement))%MOD)%MOD;

                res=min(res, currsum);
            }
        }

        return res;
    }
};
```
<p>This works for <code>50/51</code> test cases, but on the last one with large values, some modulo hijinkery breaks it.  The reason I do:</p>
<pre class="lang-cpp prettyprint-override"><code>currsum=(currsum%MOD-(abs(nums1[i]-nums2[i]))%MOD)%MOD;
</code>```

is because of the distributive property of modulo: (a + b) % c = ((a % c) + (b % c)) % c.

What am I missing?

答:
The problem is a common mistake with modular arithmetic, and surprisingly, has nothing to do with integer overflow (as is usually the case) but is solely the result of order properties not mixing well with modulus.

You said the distributive property, (a + b) % c = ((a % c) + (b % c)) % c, should let you take moduli inside equations. This stops being true when results are being compared against each other. Let's look at a smaller example with a simpler problem:

```<code>Given two arrays A and B, find the array with the smallest sum,
 and return its sum modulo 9.

A = [2, 8]
B = [1, 1]
</code>```

Now, the answer should be array B, its sum is 2, which is less than 10. If you only perform modulo at the end, you get the right answer:

```<code>sum(A) = 10
sum(B) = 2

sum(B) < sum(A), so return (2 % 9) == 2
</code>```

but if you perform modulo in the middle:

```<code>sum(A) % 9 == 1
sum(B) % 9 == 2

sum(A) % 9 < sum(B) % 9, so you return (1 % 9) == 1
</code>```

Since the constraints here mean your sums can't overflow a long long int, your problem is fixed by only performing one modulo operation at the very end, inside the return statement.

In general, problems where you want the (minimum sum) modulo p rather than the minimum (sum modulo p) require you to not perform modular division on intermediate results: you have to use integer types large enough to compare the true value (or at least have a way of comparing true values).

Title: Some modulo hijinkery

Body:
I am solving a question on LeetCode:

You are given two positive integer arrays nums1 and nums2, both of length n.The absolute sum difference of arrays nums1 and nums2 is defined as the sum of |nums1[i] - nums2[i]| for each 0 <= i < n (0-indexed). You can replace at most one element of nums1 with any other element in nums1 to minimize the absolute sum difference.  Return the minimum absolute sum difference after replacing at most one element in the array nums1. Since the answer may be large, return it modulo (10^9 + 7). For Input: nums1 = [1,7,5], nums2 = [2,3,5], Output: 3.

The code that I came up with is as below:

class Solution {
public:
    int minAbsoluteSumDiff(vector<int>& nums1, vector<int>& nums2) {
        if(nums1==nums2) return 0;

        long long MOD=(int)1e9+7;

        set<long long> s(begin(nums1),end(nums1));

        long long diff=0ll, res=LLONG_MAX;
        for(int i=0; i<nums1.size(); i++)
            diff=(diff%MOD+(abs(nums1[i]-nums2[i]))%MOD)%MOD;

        for(int i=0; i<nums2.size(); i++) {
            long long curr=nums2[i];
            auto lb=s.lower_bound(curr);

            if(lb!=s.begin()) {
                auto p=prev(lb);
                long long prevElement=*p;
                long long currsum=diff;

                currsum=(currsum%MOD-(abs(nums1[i]-nums2[i]))%MOD)%MOD;
                currsum=(currsum%MOD+abs(curr-prevElement)%MOD)%MOD;

                res=min(res, currsum);
            }

            if(lb!=s.end()) {
                long long nextElement=*lb;
                long long currsum=diff;

                currsum=(currsum%MOD-(abs(nums1[i]-nums2[i]))%MOD)%MOD;
                currsum=(currsum%MOD+(abs(curr-nextElement))%MOD)%MOD;

                res=min(res, currsum);
            }
        }

        return res;
    }
};

This works for 50/51 test cases, but on the last one with large values, some modulo hijinkery breaks it.  The reason I do:

currsum=(currsum%MOD-(abs(nums1[i]-nums2[i]))%MOD)%MOD;

is because of the distributive property of modulo: (a + b) % c = ((a % c) + (b % c)) % c.

What am I missing?

Body:
The problem is a common mistake with modular arithmetic, and surprisingly, has nothing to do with integer overflow (as is usually the case) but is solely the result of order properties not mixing well with modulus.

You said the distributive property, (a + b) % c = ((a % c) + (b % c)) % c, should let you take moduli inside equations. This stops being true when results are being compared against each other. Let's look at a smaller example with a simpler problem:

Given two arrays A and B, find the array with the smallest sum,
 and return its sum modulo 9.

A = [2, 8]
B = [1, 1]

Now, the answer should be array B, its sum is 2, which is less than 10. If you only perform modulo at the end, you get the right answer:

sum(A) = 10
sum(B) = 2

sum(B) < sum(A), so return (2 % 9) == 2

but if you perform modulo in the middle:

sum(A) % 9 == 1
sum(B) % 9 == 2

sum(A) % 9 < sum(B) % 9, so you return (1 % 9) == 1

Since the constraints here mean your sums can't overflow a long long int, your problem is fixed by only performing one modulo operation at the very end, inside the return statement.

In general, problems where you want the (minimum sum) modulo p rather than the minimum (sum modulo p) require you to not perform modular division on intermediate results: you have to use integer types large enough to compare the true value (or at least have a way of comparing true values).


问:
How to generate Shake Gesture using Swift (XCTest)
I am writing UI Tests using Swift and XCTest for my application, i have to shake the device to get the notifications, can you please tell me how i can generate the shake gesture within code. </p>

答:
The solution is stupidly simple. All you need to do is to send "com.apple.UIKit.SimulatorShake" Darwin notification. See the example code below:

SimulatorShaker.h

```<code>#import <Foundation/Foundation.h>

@interface SimulatorShaker : NSObject

+ (void)performShake;

@end
</code>```

SimulatorShaker.m

```<code>#import "SimulatorShaker.h"
#import "notify.h"

@implementation SimulatorShaker

+ (void)performShake {
    notify_post("com.apple.UIKit.SimulatorShake");
}

@end
</code>```

If you work with the Swift project you'll have to add a bridging header. Usually Xcode suggests creating the bridging header automatically when you add some Objective-C files to the project. See how to set up the header manually in case you don't find the bridging header or experience any issues building a project

Note: the Darwin Notification API is private to 3rd party developers and Apple won't allow such code to be released to App Store. But you won't experience any bother if you use the SimulatorShaker for UI test purposes only.

Body:
The solution is stupidly simple. All you need to do is to send "com.apple.UIKit.SimulatorShake" Darwin notification. See the example code below:

SimulatorShaker.h

#import <Foundation/Foundation.h>

@interface SimulatorShaker : NSObject

+ (void)performShake;

@end

SimulatorShaker.m

#import "SimulatorShaker.h"
#import "notify.h"

@implementation SimulatorShaker

+ (void)performShake {
    notify_post("com.apple.UIKit.SimulatorShake");
}

@end

If you work with the Swift project you'll have to add a bridging header. Usually Xcode suggests creating the bridging header automatically when you add some Objective-C files to the project. See how to set up the header manually in case you don't find the bridging header or experience any issues building a project

Note: the Darwin Notification API is private to 3rd party developers and Apple won't allow such code to be released to App Store. But you won't experience any bother if you use the SimulatorShaker for UI test purposes only.


问:
I want to delete all the numbers that have 1, 4 or 5 in them, but it gives a index error
```<code>#list 000 to 999
numbers = []
for i in range(0, 1000):
    i = str(i).zfill(3)
    numbers.append(i)

num = "145"
for j in range(1000):
    for k in range(3):
        if numbers[j][k] in num:
            numbers.remove(numbers[j])
</code>```

I want to delete all the numbers that have 1, 4 or 5 in them

答:
```<code>numbers = []
for i in range(0, 10000):
    i = str(i).zfill(3)
    numbers.append(i)
print('1', numbers)
num_del = "145"
for num in numbers:
    for i in num_del:
        if i in num:
            numbers.remove(num)
print('2', numbers)
</code>```

Body:
#list 000 to 999
numbers = []
for i in range(0, 1000):
    i = str(i).zfill(3)
    numbers.append(i)

num = "145"
for j in range(1000):
    for k in range(3):
        if numbers[j][k] in num:
            numbers.remove(numbers[j])

I want to delete all the numbers that have 1, 4 or 5 in them


问:
If I change one button with CSS, the other is also changed
I'm having a problem editing buttons using css.

In particular, I notice that if I modify the "Cancel changes" button, the "Delete article parts" button present in a different div is also modified.

Can someone help me?

.button[type=submit],[type=button] {
    width: 30%;
    background-color: rgb(24, 73, 32);
    color: white;
    padding: 14px 20px;
    margin: 8px 0;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

button[type=submit]:hover {
    background-color: #45a049;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class = "button">
   <button type = "submit" class = "full"> Save changes </button>
   <input type = "button" value = "Cancel changes"
   onclick = "clearResult (document.getElementById ('id'). value)" />
</div>

<div class = "buttons">
   <form action = "creaFrammento.html">
       <input type = "submit" value = "Add article part" />
   </form>

   <input type = "button" value = "Delete article parts" onclick = "confirmation ()" />
</div></code>```

答:
That is because you are targeting any element with this property [type=button]. This targets both "Cancel changes" button and the "Delete article parts".

To target one specific element, you can give it an id and select the element with that id in your CSS. As you can see below, I've given the "Delete article parts" an id="delete-btn" so the CSS targeting #delete-btn will only apply to it.

.button[type=submit],[type=button] {
    width: 30%;
    background-color: rgb(24, 73, 32);
    color: white;
    padding: 14px 20px;
    margin: 8px 0;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

#delete-btn:hover {
    background-color: #45a049;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class = "button">
   <button type = "submit" class = "full"> Save changes </button>
   <input type = "button" value = "Cancel changes" id="delete-btn" onclick = "clearResult (document.getElementById ('id'). value)" />
</div>
<div class = "buttons">
   <form action = "creaFrammento.html">
       <input type = "submit" value = "Add article part" />
   </form>
   <input type = "button" value = "Delete article parts" onclick = "confirmation ()" />
</div></code>```

Body:
I'm having a problem editing buttons using css.

In particular, I notice that if I modify the "Cancel changes" button, the "Delete article parts" button present in a different div is also modified.

Can someone help me?

.button[type=submit],[type=button] {
    width: 30%;
    background-color: rgb(24, 73, 32);
    color: white;
    padding: 14px 20px;
    margin: 8px 0;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

button[type=submit]:hover {
    background-color: #45a049;
}

   <button type = "submit" class = "full"> Save changes </button>
   <input type = "button" value = "Cancel changes"
   onclick = "clearResult (document.getElementById ('id'). value)" />

   <form action = "creaFrammento.html">
       <input type = "submit" value = "Add article part" />
   </form>

   <input type = "button" value = "Delete article parts" onclick = "confirmation ()" />

Body:
That is because you are targeting any element with this property [type=button]. This targets both "Cancel changes" button and the "Delete article parts".

To target one specific element, you can give it an id and select the element with that id in your CSS. As you can see below, I've given the "Delete article parts" an id="delete-btn" so the CSS targeting #delete-btn will only apply to it.

.button[type=submit],[type=button] {
    width: 30%;
    background-color: rgb(24, 73, 32);
    color: white;
    padding: 14px 20px;
    margin: 8px 0;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

#delete-btn:hover {
    background-color: #45a049;
}

<div class = "button">
   <button type = "submit" class = "full"> Save changes </button>
   <input type = "button" value = "Cancel changes" id="delete-btn" onclick = "clearResult (document.getElementById ('id'). value)" />
</div>
<div class = "buttons">
   <form action = "creaFrammento.html">
       <input type = "submit" value = "Add article part" />
   </form>
   <input type = "button" value = "Delete article parts" onclick = "confirmation ()" />
</div>


问:
How to fix npm install and npm run dev error in Laravel
How can I fix an npm install and a npm run dev error in Laravel?

F:\new xampp\htdocs\img\hos-sps>npm install npm ERR! code
ERR_SOCKET_TIMEOUT npm ERR! errno ERR_SOCKET_TIMEOUT npm ERR! network
Invalid response body while trying to fetch
https://registry.npmjs.org/@babel%2fhelper-plugin-utils: Socket
timeout npm ERR! network This is a problem related to network
connectivity. npm ERR! network In most cases you are behind a proxy or
have bad network settings. npm ERR! network npm ERR! network If you
are behind a proxy, please make sure that the npm ERR! network 'proxy'
config is set properly.  See: 'npm help config'

npm ERR! A complete log of this run can be found in: npm ERR!

C:\Users\sammy
waweru\AppData\Local\npm-cache_logs\2022-02-10T17_32_47_296Z-debug-0.log

F:\new xampp\htdocs\img\hos-sps>npm help config

答:
Try to clean the cache and run your npm install and dev commands.

```<code>npm cache clean --force
</code>```

The above will delete all data out of the cache folder. Note that this is typically unnecessary, as npm's cache is self-healing and resistant to data corruption.

Body:
Try to clean the cache and run your npm install and dev commands.

npm cache clean --force

The above will delete all data out of the cache folder. Note that this is typically unnecessary, as npm's cache is self-healing and resistant to data corruption.


问:
AWS CLI JMESPath Query help using query option in cli
I have the following cli command

aws ecs list-services --cluster ecs-cluster-1
```
<p>Giving this JSON</p>
<pre class="lang-json prettyprint-override"><code>{
    "serviceArns": [
        "arn:aws:ecs:us-east-1:XXXXXXXXXXXXX:service/ecs-cluster-1/app4",
        "arn:aws:ecs:us-east-1:XXXXXXXXXXXXX:service/ecs-cluster-1/app3",
        "arn:aws:ecs:us-east-1:XXXXXXXXXXXXX:service/ecs-cluster-1/app1",
        "arn:aws:ecs:us-east-1:XXXXXXXXXXXXX:service/ecs-cluster-1/app4"
    ]
}
</code>```

How do I get app1 ARN back by matching name of the app (app1) using --query option?

Expected Output

```<code>arn:aws:ecs:us-east-1:XXXXXXXXXXXXX:service/ecs-cluster-1/app1
</code>```

Please note that this JSON array is not ordered.

答:
Assuming it is the first entry in the list, you can use:

```<code>--query servicesArns[0]
</code>```

Depending on your operating system, you might need to quote it:

```<code>--query 'servicesArns[0]'
</code>```

If you are looking for the entry that 'contains' app1, use:

```<code>--query serviceArns[?contains(@, 'app1') == `true`]|[0]
</code>```

Those back-ticks always cause me problems. You can play around and potentially use other tick-marks.

Good references for JMESPath:

JMESPath Tutorial

JMESPath Specification

Body:
I have the following cli command

aws ecs list-services --cluster ecs-cluster-1

Giving this JSON

{
    "serviceArns": [
        "arn:aws:ecs:us-east-1:XXXXXXXXXXXXX:service/ecs-cluster-1/app4",
        "arn:aws:ecs:us-east-1:XXXXXXXXXXXXX:service/ecs-cluster-1/app3",
        "arn:aws:ecs:us-east-1:XXXXXXXXXXXXX:service/ecs-cluster-1/app1",
        "arn:aws:ecs:us-east-1:XXXXXXXXXXXXX:service/ecs-cluster-1/app4"
    ]
}

How do I get app1 ARN back by matching name of the app (app1) using --query option?

Expected Output

arn:aws:ecs:us-east-1:XXXXXXXXXXXXX:service/ecs-cluster-1/app1

Please note that this JSON array is not ordered.

Body:
Assuming it is the first entry in the list, you can use:

--query servicesArns[0]

Depending on your operating system, you might need to quote it:

--query 'servicesArns[0]'

If you are looking for the entry that 'contains' app1, use:

--query serviceArns[?contains(@, 'app1') == `true`]|[0]

Those back-ticks always cause me problems. You can play around and potentially use other tick-marks.

Good references for JMESPath:

JMESPath Tutorial

JMESPath Specification


问:
Using structure map with MSTest
I have created myself a test project with a single test in it. Within the "TestInitialize" method I'm trying to call my StructureMap setup method where I set which concrete instances should be used for which interfaces.

However as soon as the test tries to run I get a {"Operation could destabilize the runtime."} exception. Without using structuremap it works fine (but obiviously I need it in there).

Can anyone point me in the right direction as to what might be causing this exception?

答: After a lot of messing around, I discovered that all I needed to do was to right-click on the StructureMap dll and click "Unblock" and the permissions were sorted.</p>

Title: Using structure map with MSTest


问:
Error in openshift standard_init_linux.go:219: exec user process caused: no such file or directory
I am running 90 microservices in openshift and few of the services are in CrashLoopBackOff and logs showing the following error message.

Error:

```<code> OC logs -f :
"standard_init_linux.go:219: exec user process caused: no such file or directory"
</code>```

OC Describe:
Is there an issue with the image because describe output shows:

```<code>"Container image "IMAGE_TAG" already present on machine"
</code>```

答:
Due to the fact that there is lack of information -

it is impossible to say exactly where the problem is.

I have found some similar errors.

Here is one of the best solutions that matches description of your problem:

Here the key to solve the problem was replacing the aronautica crate via rust-argon2 and modifying the Dockerfile:

FROM rust AS build
WORKDIR /usr/src
RUN apt-get update && apt-get upgrade -y && apt-get install -y build-essential git clang llvm-dev libclang-dev libssl-dev pkg-config libpq-dev brotli
RUN USER=root cargo new loxe-api WORKDIR /usr/src/loxe-api COPY
Cargo.toml Cargo.lock ./ COPY data ./data COPY migrations ./migrations
RUN cargo build --release
# Copy the source and build the application. COPY src ./src ENV PKG_CONFIG_ALLOW_CROSS=1 ENV
OPENSSL_INCLUDE_DIR="/usr/include/openssl" RUN cargo install --path .

FROM debian:buster-slim COPY --from=build
/usr/local/cargo/bin/loxe-api .
# standard env COPY .env ./.env COPY data ./data COPY migrations ./migrations RUN apt-get update && apt-get install -y libssl-dev
pkg-config libpq-dev brotli CMD ["/loxe-api"] ```
</code>```

See also this similar issues:

second one

third one

Body:
I am running 90 microservices in openshift and few of the services are in CrashLoopBackOff and logs showing the following error message.

Error:

 OC logs -f :
"standard_init_linux.go:219: exec user process caused: no such file or directory"

OC Describe:
Is there an issue with the image because describe output shows:

"Container image "IMAGE_TAG" already present on machine"

Body:
Due to the fact that there is lack of information -

it is impossible to say exactly where the problem is.

I have found some similar errors.

Here is one of the best solutions that matches description of your problem:

Here the key to solve the problem was replacing the aronautica crate via rust-argon2 and modifying the Dockerfile:

FROM rust AS build
WORKDIR /usr/src
RUN apt-get update && apt-get upgrade -y && apt-get install -y build-essential git clang llvm-dev libclang-dev libssl-dev pkg-config libpq-dev brotli
RUN USER=root cargo new loxe-api WORKDIR /usr/src/loxe-api COPY
Cargo.toml Cargo.lock ./ COPY data ./data COPY migrations ./migrations
RUN cargo build --release
# Copy the source and build the application. COPY src ./src ENV PKG_CONFIG_ALLOW_CROSS=1 ENV
OPENSSL_INCLUDE_DIR="/usr/include/openssl" RUN cargo install --path .

FROM debian:buster-slim COPY --from=build
/usr/local/cargo/bin/loxe-api .
# standard env COPY .env ./.env COPY data ./data COPY migrations ./migrations RUN apt-get update && apt-get install -y libssl-dev
pkg-config libpq-dev brotli CMD ["/loxe-api"] ```

See also this similar issues:

second one

third one


问:
Usage of Semaphores in Python
I am trying to use a Semaphore in Python to block the execution of a Thread, and release the Semaphore in another Thread depending on some conditions (in my case receiving some content over tcp).

But it is not working, my main Thread is not blocked like I though it would. My minimal example:

```<code>import time
from threading import Thread, Semaphore

class ServerManager():
  sem = Semaphore()

  def run(self):
    time.sleep(15)
    self.sem.release()

manager = ServerManager()
thread = Thread(target = manager.run)
thread.start()

manager.sem.acquire()
print("I am here immediately but should not")
</code>```

The message is printed immediately in the console but should only be printed after 15 seconds in my example. I'm sure I did something horribly wrong, but what?

答:
You need to read the documentation about threading.Semaphore.  A semaphore blocks when a thread tries to acquire and the counter is 0.  When you create a Semaphore, the default count is 1, so your acquire is able to succeed immediately.  I suspect you want

```<code>    sem = Semaphore(0)
</code>```

so the resource is immediately unavailable.

Title: Usage of Semaphores in Python

Body:
I am trying to use a Semaphore in Python to block the execution of a Thread, and release the Semaphore in another Thread depending on some conditions (in my case receiving some content over tcp).

But it is not working, my main Thread is not blocked like I though it would. My minimal example:

import time
from threading import Thread, Semaphore

class ServerManager():
  sem = Semaphore()

  def run(self):
    time.sleep(15)
    self.sem.release()

manager = ServerManager()
thread = Thread(target = manager.run)
thread.start()

manager.sem.acquire()
print("I am here immediately but should not")

The message is printed immediately in the console but should only be printed after 15 seconds in my example. I'm sure I did something horribly wrong, but what?

Body:
You need to read the documentation about threading.Semaphore.  A semaphore blocks when a thread tries to acquire and the counter is 0.  When you create a Semaphore, the default count is 1, so your acquire is able to succeed immediately.  I suspect you want

    sem = Semaphore(0)

so the resource is immediately unavailable.


问:
Vue.js: How can I make dynamically created HTML use scoped CSS?
Short version:

I'm generating a string with HTML in a component's method, and I can't figure out how to style that HTML with scoped CSS, because it's missing the data attribute for scoping.

Slightly longer version:

I have a function called highlight which takes a string and returns an HTML string with all occurrences of a search term highlighted, meaning surrounded by a . However, since I'm doing this manually in a string, that span doesn't get the special data attribute that the scoped CSS in my Vue component needs to work, so the only way for me to style those matches is to make my CSS not scoped, which I'd like to not have to do. Is there a more Vue-specific way for me to do this?
The function looks like this:

```<code>// Source: http://stackoverflow.com/a/280805/2874789
function highlight(data, search) {
    return data.replace(
      new RegExp("(" + preg_quote(search) + ")", 'gi'),
      "<span class=match>$1</span>"
    );
}
</code>```

(preg_quote is just a function that escapes things that need to be escaped)

Thanks!

答:
Good question! I had the same problem and solved it in an elegant way. Can't wait to share!

Suppose your template looks like this

```<code><template>
  <div class="match">
    <div v-html="<span>hello world</span>"></div>
  </div>
</template>
</code>```

Just change

```<code><style scoped>
.match span {
    color: yellow;
}
</style>

compiled output: `.match span[data-v-f3f3eg9] { color: yellow; }`
</code>```

to

```<code><style scoped>
.match >>> span {
    color: yellow;
}
</style>

compiled output: `.match[data-v-f3f3eg9] span { color: yellow; }`
</code>```

Look at the difference between the two outputs. You should know what I mean. See more on the Vue Loader Document.

Body:
Short version:

I'm generating a string with HTML in a component's method, and I can't figure out how to style that HTML with scoped CSS, because it's missing the data attribute for scoping.

Slightly longer version:

I have a function called highlight which takes a string and returns an HTML string with all occurrences of a search term highlighted, meaning surrounded by a . However, since I'm doing this manually in a string, that span doesn't get the special data attribute that the scoped CSS in my Vue component needs to work, so the only way for me to style those matches is to make my CSS not scoped, which I'd like to not have to do. Is there a more Vue-specific way for me to do this?
The function looks like this:

// Source: http://stackoverflow.com/a/280805/2874789
function highlight(data, search) {
    return data.replace(
      new RegExp("(" + preg_quote(search) + ")", 'gi'),
      "$1"
    );
}

(preg_quote is just a function that escapes things that need to be escaped)

Thanks!

Body:
Good question! I had the same problem and solved it in an elegant way. Can't wait to share!

Suppose your template looks like this

<template>
  <div class="match">
    <div v-html="<span>hello world</span>"></div>
  </div>
</template>

Just change

<style scoped>
.match span {
    color: yellow;
}
</style>

compiled output: `.match span[data-v-f3f3eg9] { color: yellow; }`

to

<style scoped>
.match >>> span {
    color: yellow;
}
</style>

compiled output: `.match[data-v-f3f3eg9] span { color: yellow; }`

Look at the difference between the two outputs. You should know what I mean. See more on the Vue Loader Document.


问:
Pandas numpy how to convert a complicated .apply function to a vectorized function
I have a dataframe and you can have it by run this code:

```<code>import numpy as np
import pandas as pd
from io import StringIO
# np.prod(PofMinTab1[LowerIntegralAge1[0]-1:(LowerIntegralAge1[0])])
dfs = """
    M0  M1  M2  M3 M4  M5 M6 M7 M8 M9 M10 M11 M12  age0  age4
1   1   2   3    4  5   6  1  2 3    4  5  6   1     3    5
2   7   5   4    5  8   3  1  2 3    4  5  6   1     4     8
3   4   8   9    3  5   2  1  2 3    4  5  6   1     6      9
"""
df = pd.read_csv(StringIO(dfs.strip()), sep='\s+', )
</code>```

And I have a .apply function:

```<code>def func(row):
    age0=row['age0']
    age4=row['age4']
    mt =[row['M0'],row['M1'],row['M2'],row['M3'], row['M4'],row['M5'],row['M6'],
         row['M7'],row['M8'],row['M9'],row['M10'],row['M11'],row['M12']]

    return np.prod(mt[age0:age4])

df['newcol']=df.apply(lambda row: func(row), axis=1)
</code>```

the output is:

```<code>M0  M1  M2  M3  M4  M5  M6  M7  M8  M9  M10 M11 M12   age0  age4    newcol
1   1   2   3   4   5   6   1   2   3   4   5   6   1   3   5       20
2   7   5   4   5   8   3   1   2   3   4   5   6   1   4   8       48
3   4   8   9   3   5   2   1   2   3   4   5   6   1   6   9       6
</code>```

Since in my real business,I have 100000 rows data,each time I use .apply function it is very slow, so I've converted most of my functions to vectorized function.

So my question,is there any way I can convert this one to numpy vectorized way,or any other way that can make it runs very fast?

Any friend can help?

答:
One idea I had was to mask the original data using a condition on column indices.</p>
```<code># Create indices for the columns you want to compute the product over
idx = np.arange(len(df.columns) - 2)
# Create a mask of bools which correspond to the values the product
# should be computed for
m = ((idx[None, :] >= df['age0'].to_numpy()[:,None])
      & (idx < df['age4'].to_numpy()[:,None]))
# Use `np.where` to apply the mask and `np.prod` to compute the row-wise product
df['result'] = np.prod(np.where(m, df.iloc[:, :-2], 1), axis=1)
</code>```

```<code>df

   M0  M1  M2  M3  M4  M5  M6  M7  M8  M9  M10  M11  M12  age0  age4  result
1   1   2   3   4   5   6   1   2   3   4    5    6    1     3     5      20
2   7   5   4   5   8   3   1   2   3   4    5    6    1     4     8      48
3   4   8   9   3   5   2   1   2   3   4    5    6    1     6     9       6
</code>```

Body:
I have a dataframe and you can have it by run this code:

import numpy as np
import pandas as pd
from io import StringIO
# np.prod(PofMinTab1[LowerIntegralAge1[0]-1:(LowerIntegralAge1[0])])
dfs = """
    M0  M1  M2  M3 M4  M5 M6 M7 M8 M9 M10 M11 M12  age0  age4
1   1   2   3    4  5   6  1  2 3    4  5  6   1     3    5
2   7   5   4    5  8   3  1  2 3    4  5  6   1     4     8
3   4   8   9    3  5   2  1  2 3    4  5  6   1     6      9
"""
df = pd.read_csv(StringIO(dfs.strip()), sep='\s+', )

And I have a .apply function:

def func(row):
    age0=row['age0']
    age4=row['age4']
    mt =[row['M0'],row['M1'],row['M2'],row['M3'], row['M4'],row['M5'],row['M6'],
         row['M7'],row['M8'],row['M9'],row['M10'],row['M11'],row['M12']]

    return np.prod(mt[age0:age4])

df['newcol']=df.apply(lambda row: func(row), axis=1)

the output is:

M0  M1  M2  M3  M4  M5  M6  M7  M8  M9  M10 M11 M12   age0  age4    newcol
1   1   2   3   4   5   6   1   2   3   4   5   6   1   3   5       20
2   7   5   4   5   8   3   1   2   3   4   5   6   1   4   8       48
3   4   8   9   3   5   2   1   2   3   4   5   6   1   6   9       6

Since in my real business,I have 100000 rows data,each time I use .apply function it is very slow, so I've converted most of my functions to vectorized function.

So my question,is there any way I can convert this one to numpy vectorized way,or any other way that can make it runs very fast?

Any friend can help?

Body:
One idea I had was to mask the original data using a condition on column indices.

# Create indices for the columns you want to compute the product over
idx = np.arange(len(df.columns) - 2)
# Create a mask of bools which correspond to the values the product
# should be computed for
m = ((idx[None, :] >= df['age0'].to_numpy()[:,None])
      & (idx < df['age4'].to_numpy()[:,None]))
# Use `np.where` to apply the mask and `np.prod` to compute the row-wise product
df['result'] = np.prod(np.where(m, df.iloc[:, :-2], 1), axis=1)

df

   M0  M1  M2  M3  M4  M5  M6  M7  M8  M9  M10  M11  M12  age0  age4  result
1   1   2   3   4   5   6   1   2   3   4    5    6    1     3     5      20
2   7   5   4   5   8   3   1   2   3   4    5    6    1     4     8      48
3   4   8   9   3   5   2   1   2   3   4    5    6    1     6     9       6


问:
How to embed an exe file into another exe file as a resource in C++?
I am trying to use a pre-build .exe file as a resource in my C++ project, after searching I done the following steps:

Step1
Create a new C++ project and place the following code in the Source.cpp file

```<code>#include<iostream>
#include<Windows.h>
#include<fstream>
#define IDB_EMBEDEXE 52
using namespace std;
int main() {

    int count = 2;

    HRSRC hResource = FindResource(NULL, MAKEINTRESOURCE(IDB_EMBEDEXE), __TEXT("BINARY"));
    HGLOBAL hGlobal = LoadResource(NULL, hResource);
    size_t exeSiz = SizeofResource(NULL, hResource);
    void* exeBuf = LockResource(hGlobal);

    ofstream outfile((char*)exeBuf, ios::out | ios::binary);
    if (!outfile)
        exit(9);
    outfile.write((char*)exeBuf, exeSiz);
    system((char*)exeBuf);

    return 0;
}
</code>```

Step2 Create a new resource file (.rc)

1- Project>Add new item

2- From Installed>Visual C++>Resource choose Resource File (.rc) let us name it Resource.rc

Step3 Edit the header file resource.h that has just created from Step2, add the following line to the header file:

#define IDB_EMBEDEXE 52

Step4 Edit the Resource.rc file by right click on it>Open with>Source Code (Text) Editor, add the following code just after the first #include statment (i.e. after #include "resource.h"

```<code>#define IDB_EMBEDEXE 52
IDB_EMBEDEXE    BINARY      "C:\\Users\\Almohandis\\source\\repos\\Project7\\sum2num.exe"
</code>```

After doing exactly these steps, I still get the following error in the cmd (not in the Visual Studio):

'MZ' is not recognized as an internal or external command,
operable program or batch file.

And the program ends with code 0

I think calling system() what causes the problem, especially the argument I passed.

Note that the binary representation of the sum2num.exe file starts with MZ....

答:
If your #define is already in resource.h, there is no need to duplicate it in your source code. Just use #include "resource.h" in your code instead.

In any case, you should be using the pre-defined RCDATA resource type, instead of creating a custom BINARY type.

That being said, your use of ofstream and system() are both wrong.  You are passing them the resource's raw binary data, but they are expecting a file path instead.  You are using a file path in your .rc file to specify the file whose binary data is copied into the resource.  The resource does not contain that file path, as you are clearly expecting.

Try this instead:

resource.h

```<code>...
#define IDB_EMBEDEXE 52
...
</code>```

Resource.rc

```<code>#include "resource.h"
...
IDB_EMBEDEXE    RCDATA      "C:\\Users\\Almohandis\\source\\repos\\Project7\\sum2num.exe"
...
</code>```

Source.cpp

```<code>#include <Windows.h>
#include <iostream>
#include <fstream>
#include <string>
#include <cstdio>
#include "resource.h"
using namespace std;

int main() {

    HRSRC hResource = FindResource(NULL, MAKEINTRESOURCE(IDB_EMBEDEXE), RT_RCDATA);
    if (!hResource)
        return 1;

    HGLOBAL hGlobal = LoadResource(NULL, hResource);
    if (!hGlobal)
        return 2;

    DWORD exeSiz = SizeofResource(NULL, hResource);
    if (!exeSiz)
        return 3;

    void* exeBuf = LockResource(hGlobal);
    if (!exeBuf)
        return 4;

    char tempPath[MAX_PATH] = {};
    if (!GetTempPathA(MAX_PATH, path))
        return 5;

    string fullPath = string(tempPath) + "sum2num.exe";

    ofstream outfile(fullPath.c_str(), ios::binary);
    if (!outfile.is_open())
        return 6;

    int res = (outfile.write((char*)exeBuf, exeSiz)) ? 0 : 7;
    outfile.close();

    if (res == 0) {
        system(fullPath.c_str());
    }

    remove(fullPath.c_str());

    return res;
}
</code>```

Body:
I am trying to use a pre-build .exe file as a resource in my C++ project, after searching I done the following steps:

Step1
Create a new C++ project and place the following code in the Source.cpp file

#include<iostream>
#include<Windows.h>
#include<fstream>
#define IDB_EMBEDEXE 52
using namespace std;
int main() {

    int count = 2;

    HRSRC hResource = FindResource(NULL, MAKEINTRESOURCE(IDB_EMBEDEXE), __TEXT("BINARY"));
    HGLOBAL hGlobal = LoadResource(NULL, hResource);
    size_t exeSiz = SizeofResource(NULL, hResource);
    void* exeBuf = LockResource(hGlobal);

    ofstream outfile((char*)exeBuf, ios::out | ios::binary);
    if (!outfile)
        exit(9);
    outfile.write((char*)exeBuf, exeSiz);
    system((char*)exeBuf);

    return 0;
}

Step2 Create a new resource file (.rc)

1- Project>Add new item

2- From Installed>Visual C++>Resource choose Resource File (.rc) let us name it Resource.rc

Step3 Edit the header file resource.h that has just created from Step2, add the following line to the header file:

#define IDB_EMBEDEXE 52

Step4 Edit the Resource.rc file by right click on it>Open with>Source Code (Text) Editor, add the following code just after the first #include statment (i.e. after #include "resource.h"

#define IDB_EMBEDEXE 52
IDB_EMBEDEXE    BINARY      "C:\\Users\\Almohandis\\source\\repos\\Project7\\sum2num.exe"

After doing exactly these steps, I still get the following error in the cmd (not in the Visual Studio):

'MZ' is not recognized as an internal or external command,
operable program or batch file.

And the program ends with code 0

I think calling system() what causes the problem, especially the argument I passed.

Note that the binary representation of the sum2num.exe file starts with MZ....

Body:
If your #define is already in resource.h, there is no need to duplicate it in your source code. Just use #include "resource.h" in your code instead.

In any case, you should be using the pre-defined RCDATA resource type, instead of creating a custom BINARY type.

That being said, your use of ofstream and system() are both wrong.  You are passing them the resource's raw binary data, but they are expecting a file path instead.  You are using a file path in your .rc file to specify the file whose binary data is copied into the resource.  The resource does not contain that file path, as you are clearly expecting.

Try this instead:

resource.h

...
#define IDB_EMBEDEXE 52
...

Resource.rc

#include "resource.h"
...
IDB_EMBEDEXE    RCDATA      "C:\\Users\\Almohandis\\source\\repos\\Project7\\sum2num.exe"
...

Source.cpp

#include <Windows.h>
#include <iostream>
#include <fstream>
#include <string>
#include <cstdio>
#include "resource.h"
using namespace std;

int main() {

    HRSRC hResource = FindResource(NULL, MAKEINTRESOURCE(IDB_EMBEDEXE), RT_RCDATA);
    if (!hResource)
        return 1;

    HGLOBAL hGlobal = LoadResource(NULL, hResource);
    if (!hGlobal)
        return 2;

    DWORD exeSiz = SizeofResource(NULL, hResource);
    if (!exeSiz)
        return 3;

    void* exeBuf = LockResource(hGlobal);
    if (!exeBuf)
        return 4;

    char tempPath[MAX_PATH] = {};
    if (!GetTempPathA(MAX_PATH, path))
        return 5;

    string fullPath = string(tempPath) + "sum2num.exe";

    ofstream outfile(fullPath.c_str(), ios::binary);
    if (!outfile.is_open())
        return 6;

    int res = (outfile.write((char*)exeBuf, exeSiz)) ? 0 : 7;
    outfile.close();

    if (res == 0) {
        system(fullPath.c_str());
    }

    remove(fullPath.c_str());

    return res;
}


问:
REMOTE_USER not always set in basic authentication when changing to running PHP as a CGI module
My host provider just moved me to PHP 7.4 (at my request) and in the process changed PHP from running as an Apache module (now 2.4.52) to as CGI -- good from what I know.  My website uses Basic Authentication, and my code relies HEAVILY on $_SERVER['REMOTE_USER'] to get the username in tons of places.

In some cases at least (so far from what I've seen), that variable is NOT set, but instead $_SERVER['REDIRECT_REMOTE_USER'] is.  In other places, there might be other $_SERVER vars that are set instead, tho I haven't seen them yet (I reverted to the old configuration for the time being, since this broke the site).   [BTW, a lot of this code is over 20 years old now.]

So my question: is there any way to force $_SERVER['REMOTE_USER'] to always be set with the username without having to modify all those places in my code?  Especially if there are some config settings that I could use?  I did see what looks to be a nice function to get the username in
PHP get username from Basic Authorization
but I'm hoping to find a way to avoid changing all that old code.  Or any other ideas?

答:
Try putting this in your .htaccess after RewriteEngine On

```<code>RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization}]
</code>```

That should set the REMOTE_USER environment variable when using CGI.

Body:
Try putting this in your .htaccess after RewriteEngine On

RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization}]

That should set the REMOTE_USER environment variable when using CGI.


问:
Permission issue while executing an ssh task in azure pipeline
What I am trying to do is to run a few lines of shell script in a remote machine via an azure pipeline. I used the ssh Deployment Task to accomplish this. I have used the script path argument to point the .sh file that contains the script that should be ran. The ssh task was able to connect to the remote host, but the following permission error pops up.
Can someone tell me what's going wrong here. The .sh file that i am using was created in the Linux box itself and has got the permission level set to 777 before moving to the repo.

There is an another  CopyFilesOverSSH@0 task in the pipeline in the same stage which works perfectly without any permission issues for the same user.

```<code>2021-12-31T12:41:42.1763039Z ##[section]Starting: SSH
2021-12-31T12:41:42.1894277Z ==============================================================================
2021-12-31T12:41:42.1894676Z Task         : SSH
2021-12-31T12:41:42.1895010Z Description  : Run shell commands or a script on a remote machine using SSH
2021-12-31T12:41:42.1895347Z Version      : 0.189.0
2021-12-31T12:41:42.1895637Z Author       : Microsoft Corporation
2021-12-31T12:41:42.1896023Z Help         : https://learn.microsoft.com/azure/devops/pipelines/tasks/deploy/ssh
2021-12-31T12:41:42.1896437Z ==============================================================================
2021-12-31T12:41:42.8200834Z Trying to establish an SSH connection to ***@80.xxx.xxx.xxx:22
2021-12-31T12:41:43.1333018Z Successfully connected.
2021-12-31T12:41:43.5698433Z ##[error]Failed to copy script to remote machine. Error: Error: put: Permission denied //checkFileAvailability.sh.
2021-12-31T12:41:43.6050230Z ##[section]Finishing: SSH
</code>```

答:
I had the same issue when run SSH script task under a user which was not a root. So for inline script to run under different user, that user should have:

Read/Write/Execute access to root folder, as TFS put all commands into generated bash script file and copy it to target machine root folder (below is another command, which is executed on already copied script file)

tr -d '\015' <./sshscript_099d4e8c-44ac-482d-b1bf-84a52c7ab810> ./sshscript_099d4e8c-44ac-482d-b1bf-84a52c7ab810._unix

User should have home directory as TFS switch to it

So to fix this issue I have granted rwx permissions to everyone for the root folder

```<code>chmod 777 /
ls -ld /
drwxrwxrwx 20 root root 4096 Feb 10 14:54 /
</code>```

And make sure that home folder for my user exists

Body:
What I am trying to do is to run a few lines of shell script in a remote machine via an azure pipeline. I used the ssh Deployment Task to accomplish this. I have used the script path argument to point the .sh file that contains the script that should be ran. The ssh task was able to connect to the remote host, but the following permission error pops up.
Can someone tell me what's going wrong here. The .sh file that i am using was created in the Linux box itself and has got the permission level set to 777 before moving to the repo.

There is an another  CopyFilesOverSSH@0 task in the pipeline in the same stage which works perfectly without any permission issues for the same user.

2021-12-31T12:41:42.1763039Z ##[section]Starting: SSH
2021-12-31T12:41:42.1894277Z ==============================================================================
2021-12-31T12:41:42.1894676Z Task         : SSH
2021-12-31T12:41:42.1895010Z Description  : Run shell commands or a script on a remote machine using SSH
2021-12-31T12:41:42.1895347Z Version      : 0.189.0
2021-12-31T12:41:42.1895637Z Author       : Microsoft Corporation
2021-12-31T12:41:42.1896023Z Help         : https://learn.microsoft.com/azure/devops/pipelines/tasks/deploy/ssh
2021-12-31T12:41:42.1896437Z ==============================================================================
2021-12-31T12:41:42.8200834Z Trying to establish an SSH connection to ***@80.xxx.xxx.xxx:22
2021-12-31T12:41:43.1333018Z Successfully connected.
2021-12-31T12:41:43.5698433Z ##[error]Failed to copy script to remote machine. Error: Error: put: Permission denied //checkFileAvailability.sh.
2021-12-31T12:41:43.6050230Z ##[section]Finishing: SSH

Body:
I had the same issue when run SSH script task under a user which was not a root. So for inline script to run under different user, that user should have:

Read/Write/Execute access to root folder, as TFS put all commands into generated bash script file and copy it to target machine root folder (below is another command, which is executed on already copied script file)

tr -d '\015' <./sshscript_099d4e8c-44ac-482d-b1bf-84a52c7ab810> ./sshscript_099d4e8c-44ac-482d-b1bf-84a52c7ab810._unix

User should have home directory as TFS switch to it

So to fix this issue I have granted rwx permissions to everyone for the root folder

chmod 777 /
ls -ld /
drwxrwxrwx 20 root root 4096 Feb 10 14:54 /

And make sure that home folder for my user exists


问:
Set legend width to be 100% plot width
How do I set the legend height or width to be 100% of the plot height/width regardless of the actual dimensions?

library(ggplot2)
ggplot(iris, aes(Petal.Width, Sepal.Width, color=Petal.Length))+
  geom_point()+
  theme(
    legend.title=element_blank(),
    legend.position="bottom",
    legend.key.width=unit(0.1,"npc"))
```
<p><img src="https://i.imgur.com/etPvIQL.png" alt="" /></p>
<p><sup>Created on 2022-02-11 by the reprex package (v2.0.1)</sup></p>

Session info

<pre class="lang-r prettyprint-override"><code>sessioninfo::session_info()
#> ─ Session info ───────────────────────────────────────────────────────────────
#>  setting  value
#>  version  R version 4.1.0 (2021-05-18)
#>  os       Ubuntu 20.04.3 LTS
#> ─ Packages ───────────────────────────────────────────────────────────────────
#>  ggplot2     * 3.3.5   2021-06-25 [1] CRAN (R 4.1.0)
#>
#> ──────────────────────────────────────────────────────────────────────────────
</code>```

答:
The only way I know of is to manually adjust the grid objects in the gtable of the plot. AFAIK, the guides are mostly defined in cm (rather than relative units), so getting them adapted to the panels is a bit of a pain. I'd also love to know a better way to do this.

library(ggplot2)

g <- ggplot(iris, aes(Petal.Width, Sepal.Width, color=Petal.Length))+
  geom_point()+
  theme(
    legend.title=element_blank(),
    legend.position="bottom",
    legend.key.width=unit(0.1,"npc"),
    legend.margin = margin(), # pre-emptively set zero margins
    legend.spacing.x = unit(0, "cm"))

gt <- ggplotGrob(g)

# Extract legend
is_legend <- which(gt$layout$name == "guide-box")
legend <- gt$grobs[is_legend][[1]]
legend <- legend$grobs[legend$layout$name == "guides"][[1]]

# Set widths in guide gtable
width <- as.numeric(legend$widths[4]) # save bar width (assumes 'cm' unit)
legend$widths[4] <- unit(1, "null") # replace bar width

# Set width/x of bar/labels/ticks. Assumes everything is 'cm' unit.
legend$grobs[[2]]$width <- unit(1, "npc")
legend$grobs[[3]]$children[[1]]$x <- unit(
  as.numeric(legend$grobs[[3]]$children[[1]]$x) / width, "npc"
)
legend$grobs[[5]]$x0 <- unit(as.numeric(legend$grobs[[5]]$x0) / width, "npc")
legend$grobs[[5]]$x1 <- unit(as.numeric(legend$grobs[[5]]$x1) / width, "npc")

# Replace legend
gt$grobs[[is_legend]] <- legend

# Draw new plot
grid::grid.newpage()
grid::grid.draw(gt)
```

Created on 2022-02-11 by the reprex package (v2.0.1)

Title: Set legend width to be 100% plot width

Body:
How do I set the legend height or width to be 100% of the plot height/width regardless of the actual dimensions?

library(ggplot2)
ggplot(iris, aes(Petal.Width, Sepal.Width, color=Petal.Length))+
  geom_point()+
  theme(
    legend.title=element_blank(),
    legend.position="bottom",
    legend.key.width=unit(0.1,"npc"))

Created on 2022-02-11 by the reprex package (v2.0.1)

Session info

sessioninfo::session_info()
#> ─ Session info ───────────────────────────────────────────────────────────────
#>  setting  value
#>  version  R version 4.1.0 (2021-05-18)
#>  os       Ubuntu 20.04.3 LTS
#> ─ Packages ───────────────────────────────────────────────────────────────────
#>  ggplot2     * 3.3.5   2021-06-25 [1] CRAN (R 4.1.0)
#>
#> ──────────────────────────────────────────────────────────────────────────────

Body:
The only way I know of is to manually adjust the grid objects in the gtable of the plot. AFAIK, the guides are mostly defined in cm (rather than relative units), so getting them adapted to the panels is a bit of a pain. I'd also love to know a better way to do this.

library(ggplot2)

g <- ggplot(iris, aes(Petal.Width, Sepal.Width, color=Petal.Length))+
  geom_point()+
  theme(
    legend.title=element_blank(),
    legend.position="bottom",
    legend.key.width=unit(0.1,"npc"),
    legend.margin = margin(), # pre-emptively set zero margins
    legend.spacing.x = unit(0, "cm"))

gt <- ggplotGrob(g)

# Extract legend
is_legend <- which(gt$layout$name == "guide-box")
legend <- gt$grobs[is_legend][[1]]
legend <- legend$grobs[legend$layout$name == "guides"][[1]]

# Set widths in guide gtable
width <- as.numeric(legend$widths[4]) # save bar width (assumes 'cm' unit)
legend$widths[4] <- unit(1, "null") # replace bar width

# Set width/x of bar/labels/ticks. Assumes everything is 'cm' unit.
legend$grobs[[2]]$width <- unit(1, "npc")
legend$grobs[[3]]$children[[1]]$x <- unit(
  as.numeric(legend$grobs[[3]]$children[[1]]$x) / width, "npc"
)
legend$grobs[[5]]$x0 <- unit(as.numeric(legend$grobs[[5]]$x0) / width, "npc")
legend$grobs[[5]]$x1 <- unit(as.numeric(legend$grobs[[5]]$x1) / width, "npc")

# Replace legend
gt$grobs[[is_legend]] <- legend

# Draw new plot
grid::grid.newpage()
grid::grid.draw(gt)

Created on 2022-02-11 by the reprex package (v2.0.1)


问:
Insert existing element an just created one
If I have: Some Code Here, can I create a new div element and move the span element inside just created div?

The new element must be in same place where span element was before

I'd like to use pure javascript code

答:
```<code>var wrapper = document.createElement('div');
var selected_span = document.getElementByTagName('span')[0]; //get the first available span element
span_clone = selected_span.cloneNode(true);
selected_span.parentNode.insertBefore(wrapper, selected_span);
selected_span.parentNode.removeChild(selected_span);
wrapper.appendChild(span_clone);
</code>```

What this does is create a new
, creates copy of the span, removes the original span and then inserts the copy inside the div

jsFiddle

this is the same example within a container

Body:
var wrapper = document.createElement('div');
var selected_span = document.getElementByTagName('span')[0]; //get the first available span element
span_clone = selected_span.cloneNode(true);
selected_span.parentNode.insertBefore(wrapper, selected_span);
selected_span.parentNode.removeChild(selected_span);
wrapper.appendChild(span_clone);

What this does is create a new <div>, creates copy of the span, removes the original span and then inserts the copy inside the div

jsFiddle

this is the same example within a container


问:
Cannot break Shrek loop in Rstudio
I have created a "while" loop that looks like this:

```<code>x <- 2
while (x < 8) {
    print("Shrek")
}
</code>```

Now, I have tried breaking the loop by inserting break in to the while loop, like this:

```<code>while (x < 8) {
    print("Shrek")
    break
}
</code>```

but this doesn't break the loop, the console just keeps printing "Shrek".
How can i make it stop? Have I put break in the wrong place?

Side question: Can there arise any problems from exiting Rstudio while it's in an on-going while() loop like this?

Thanks!

Edit:
Pressing escape stopped the loop. Is there any line of code in the console that also stops it?

答: Based on the code you have given I can't reproduce this. When I run everything, break works just fine. Have you potentially defined a variable called 'break' that would have overridden the default function? If not try resetting R and running this again.</p>

Title: Cannot break Shrek loop in Rstudio

Body:
I have created a "while" loop that looks like this:

x <- 2
while (x < 8) {
    print("Shrek")
}

Now, I have tried breaking the loop by inserting break in to the while loop, like this:

while (x < 8) {
    print("Shrek")
    break
}

but this doesn't break the loop, the console just keeps printing "Shrek".
How can i make it stop? Have I put break in the wrong place?

Side question: Can there arise any problems from exiting Rstudio while it's in an on-going while() loop like this?

Thanks!

Edit:
Pressing escape stopped the loop. Is there any line of code in the console that also stops it?


问:
SyntaxError: Unexpected token catch { ^
```<code>        node_modules\@angular-devkit\core\src\workspace\host.js:25
                    catch {
                          ^

    SyntaxError: Unexpected token {
            at createScript (vm.js:80:10)
            at Object.runInThisContext (vm.js:139:10)
            at Module._compile (module.js:616:28)
            at Object.Module._extensions..js (module.js:663:10)
            at Module.load (module.js:565:32)
            at tryModuleLoad (module.js:505:12)
            at Function.Module._load (module.js:497:3)
            at Module.require (module.js:596:17)
            at require (internal/module.js:11:18
</code>```
<p>"dependencies": {
"@angular/animations": "^4.0.2",
"@angular/common": "^4.0.0",
"@angular/compiler": "^4.0.0",
"@angular/core": "^4.0.0",
"@angular/forms": "^4.0.0",
"@angular/http": "^4.0.0",
"@angular/platform-browser": "^4.0.0",
"@angular/platform-browser-dynamic": "^4.0.0",
"@angular/router": "^4.0.0",
"@ng-idle/core": "^2.0.0-beta.15",
"@ng-idle/keepalive": "^2.0.0-beta.12",
"angular2-moment": "^1.9.0",
"blob-util": "^2.0.2",
"core-js": "^2.4.1",
"file-saver": "^2.0.5",
"font-awesome": "^4.7.0",
"mydatepicker": "^2.0.8",
"ng2-bootstrap-modal": "^1.0.1",
"ng2-order-pipe": "^0.1.5",
"ng2-select": "^2.0.0",
"ng2-tooltip-directive": "^1.3.7",
"primeng": "4.3.0",
"rxjs": "^5.1.0",
"tslint-language-service": "^0.9.9",
"xlsx": "^0.14.5",
"zone.js": "^0.8.4"
}</p>
```<code>"devDependencies": {
                "@angular/cli": "^12.1.0",
                "@angular/compiler-cli": "^4.0.0",
                "@types/jasmine": "2.5.38",
                "@types/node": "~6.0.60",
                "codelyzer": "~2.0.0",
                "jasmine-core": "~2.5.2",
                "jasmine-spec-reporter": "~3.2.0",
                "karma": "~1.4.1",
                "karma-chrome-launcher": "~2.1.1",
                "karma-cli": "~1.0.1",
                "karma-coverage-istanbul-reporter": "^0.2.0",
                "karma-jasmine": "~1.1.0",
                "karma-jasmine-html-reporter": "^0.2.2",
                "protractor": "~5.1.0",
                "ts-node": "~2.0.0",
                "tslint": "~4.5.0",
                "typescript": "^2.2.0"
              }

I tried uninstalling and installing typescript and @angular/cli and deleted node modules, couldn't solve it. Any help how can I get rid off TIA!
</code>```

答: I just had this issue after trying to update angular versions, and resolved it by using a newer version of node.</p>

Title: SyntaxError: Unexpected token catch { ^

Body:
        node_modules\@angular-devkit\core\src\workspace\host.js:25
                    catch {
                          ^

    SyntaxError: Unexpected token {
            at createScript (vm.js:80:10)
            at Object.runInThisContext (vm.js:139:10)
            at Module._compile (module.js:616:28)
            at Object.Module._extensions..js (module.js:663:10)
            at Module.load (module.js:565:32)
            at tryModuleLoad (module.js:505:12)
            at Function.Module._load (module.js:497:3)
            at Module.require (module.js:596:17)
            at require (internal/module.js:11:18

"dependencies": {
"@angular/animations": "^4.0.2",
"@angular/common": "^4.0.0",
"@angular/compiler": "^4.0.0",
"@angular/core": "^4.0.0",
"@angular/forms": "^4.0.0",
"@angular/http": "^4.0.0",
"@angular/platform-browser": "^4.0.0",
"@angular/platform-browser-dynamic": "^4.0.0",
"@angular/router": "^4.0.0",
"@ng-idle/core": "^2.0.0-beta.15",
"@ng-idle/keepalive": "^2.0.0-beta.12",
"angular2-moment": "^1.9.0",
"blob-util": "^2.0.2",
"core-js": "^2.4.1",
"file-saver": "^2.0.5",
"font-awesome": "^4.7.0",
"mydatepicker": "^2.0.8",
"ng2-bootstrap-modal": "^1.0.1",
"ng2-order-pipe": "^0.1.5",
"ng2-select": "^2.0.0",
"ng2-tooltip-directive": "^1.3.7",
"primeng": "4.3.0",
"rxjs": "^5.1.0",
"tslint-language-service": "^0.9.9",
"xlsx": "^0.14.5",
"zone.js": "^0.8.4"
}

"devDependencies": {
                "@angular/cli": "^12.1.0",
                "@angular/compiler-cli": "^4.0.0",
                "@types/jasmine": "2.5.38",
                "@types/node": "~6.0.60",
                "codelyzer": "~2.0.0",
                "jasmine-core": "~2.5.2",
                "jasmine-spec-reporter": "~3.2.0",
                "karma": "~1.4.1",
                "karma-chrome-launcher": "~2.1.1",
                "karma-cli": "~1.0.1",
                "karma-coverage-istanbul-reporter": "^0.2.0",
                "karma-jasmine": "~1.1.0",
                "karma-jasmine-html-reporter": "^0.2.2",
                "protractor": "~5.1.0",
                "ts-node": "~2.0.0",
                "tslint": "~4.5.0",
                "typescript": "^2.2.0"
              }

I tried uninstalling and installing typescript and @angular/cli and deleted node modules, couldn't solve it. Any help how can I get rid off TIA!


问:
Docker Compose merge arrays for YAML aliases and anchors
I have the following broken docker-compose file

version: '3.4'

x-vols1: &vols-1
    - /home/:/home/

x-vols2: &vols-2
    - /tmp/:/tmp/

services:
    app1:
        container_name: app1
        image: app1
        volumes:
            <<: *vols-1
    app2:
        container_name: app2
        image: app2
        volumes:
            <<: *vols-1
            <<: *vols-2
```

<p>This fails with the following error</p>

<pre class="lang-sh prettyprint-override"><code>$ docker-compose -f test.yaml config
ERROR: yaml.constructor.ConstructorError: while constructing a mapping
  in "./test.yaml", line 14, column 13
expected a mapping for merging, but found scalar
  in "./test.yaml", line 4, column 7
</code>```

Question 1: How can I merge arrays in docker-compose? The syntax that I am trying to use is the one for merging dicts

Question 2: If there is no way to merge arrays, is there a workaround?

Use case: I have multiple services, some of them map some volumes, others map other volumes, others map all volumes. I would like to not repeat myself.

Thank you!

答:
This is a slight variation on the currently accepted answer, which doesn't require you to change your docker-compose command line to include other files:

docker-compose.yml

version: '3.9'

services:
    app1:
        container_name: app1
        image: app1
        extends:
            file: common-volumes.yml
            service: app1
    app2:
        container_name: app2
        image: app2
        extends:
            file: common-volumes.yml
            service: app2
        volumes:
            - /tmp/:/tmp/
```
<h3>common-volumes.yml</h3>
<pre class="lang-yaml prettyprint-override"><code>x-vols1: &vols-1
    volumes:
        - /home/:/home/

services:
    app1:
        <<: *vols-1
    app2:
        <<: *vols-1
</code>```

To view the resulting config:

```<code>docker compose config
</code>```

Body:
I have the following broken docker-compose file

version: '3.4'

x-vols1: &vols-1
    - /home/:/home/

x-vols2: &vols-2
    - /tmp/:/tmp/

services:
    app1:
        container_name: app1
        image: app1
        volumes:
            <<: *vols-1
    app2:
        container_name: app2
        image: app2
        volumes:
            <<: *vols-1
            <<: *vols-2

This fails with the following error

$ docker-compose -f test.yaml config
ERROR: yaml.constructor.ConstructorError: while constructing a mapping
  in "./test.yaml", line 14, column 13
expected a mapping for merging, but found scalar
  in "./test.yaml", line 4, column 7

Question 1: How can I merge arrays in docker-compose? The syntax that I am trying to use is the one for merging dicts

Question 2: If there is no way to merge arrays, is there a workaround?

Use case: I have multiple services, some of them map some volumes, others map other volumes, others map all volumes. I would like to not repeat myself.

Thank you!

Body:
This is a slight variation on the currently accepted answer, which doesn't require you to change your docker-compose command line to include other files:

docker-compose.yml

version: '3.9'

services:
    app1:
        container_name: app1
        image: app1
        extends:
            file: common-volumes.yml
            service: app1
    app2:
        container_name: app2
        image: app2
        extends:
            file: common-volumes.yml
            service: app2
        volumes:
            - /tmp/:/tmp/

common-volumes.yml

x-vols1: &vols-1
    volumes:
        - /home/:/home/

services:
    app1:
        <<: *vols-1
    app2:
        <<: *vols-1

To view the resulting config:

docker compose config


问:
"No Column" error in google sheets when using query function
I am trying to query in order to ultimately, select between a date range to show only dates between YYYY-MM-DD and YYYY-MM-DD
Current code i am trying to use:

```<code>=QUERY({"Master!A:J"}, "select * where Col1 >= date '2022-01-01' AND Col1 <= date '2022-01-31'")
</code>```

I have also tried:

```<code>=QUERY({"Master!A:J"}, "select * where D >= date '2022-01-01' AND D <= date '2022-01-31'")
</code>```

the data from the master sheet is being received by an apps script if that makes a difference?

test sheet: https://docs.google.com/spreadsheets/d/e/2PACX-1vTjTlorc1KKmMjgR3-N4agrLK3RFme2dmYwe7hF6fWotDtPbZJg71O1S0jJv0tIqwtIGTi_l61LSIE7/pubhtml

答:
try:

```<code>=QUERY({Master!A:J},
 "where Col1 >= date '2022-01-01'
    and Col1 <= date '2022-01-31'")
</code>```

or:

```<code>=QUERY({Master!A:J},
 "where month(Col1)+1 = 1
    and year(Col1) = 2022")
</code>```

Body:
I am trying to query in order to ultimately, select between a date range to show only dates between YYYY-MM-DD and YYYY-MM-DD
Current code i am trying to use:

=QUERY({"Master!A:J"}, "select * where Col1 >= date '2022-01-01' AND Col1 <= date '2022-01-31'")

I have also tried:

=QUERY({"Master!A:J"}, "select * where D >= date '2022-01-01' AND D <= date '2022-01-31'")

the data from the master sheet is being received by an apps script if that makes a difference?

test sheet: https://docs.google.com/spreadsheets/d/e/2PACX-1vTjTlorc1KKmMjgR3-N4agrLK3RFme2dmYwe7hF6fWotDtPbZJg71O1S0jJv0tIqwtIGTi_l61LSIE7/pubhtml

Body:
try:

=QUERY({Master!A:J},
 "where Col1 >= date '2022-01-01'
    and Col1 <= date '2022-01-31'")

or:

=QUERY({Master!A:J},
 "where month(Col1)+1 = 1
    and year(Col1) = 2022")


问:
Problem with handling path length
I'm creating library which will be used for file manipulations, both on linux and windows. So I need to handle paths, the main requirements is that my functions will recieve strings in UTF8 format. But it causes some problems, one of them is I'm using MAX_PATH on windows and PATH_MAX in linux, to represent static path variables. In the case of ASCII characters there will be no problem, but when path contains unicode characters, the length of path will be twice shorter if unicode char requires 2 bytes per char, 3 times shorter if unicode char requires 3 bytes per char and so on. So is there good solution for this problem?

Thanks in advance!

p.s. sorry for my english.

答:
Doesn’t Microsoft use either UCS-2 or UTF-16 for its pathnames, and that so MAX_PATH   has a length that reflects 16-bit code units, not even proper characters?

I know that Apple uses UTF-16, and that each component in a pathname can be up to 256 UTF-16 code units not characters, and that it normalized to something approximating NFD from a long time ago.

I suspect you will have to first normalize if necessary, such as to NFD for Apple, then encode to your native filesystem’s internal format, and then check the length.

When you do that comparison, it is critical to remember that Unix uses 8-bit code units, Microsoft and Apple use 16-bit code units, and that no one seems to bother to actually use abstract characters. They could do that if they used UTF-32, but nobody wastes that much space in the filesystem.  Pity, that.

Title: Problem with handling path length


问:
Rails no route matches despite rails route output results
Route fails to match despite matching route found in rails routes

```<code>No route matches {:action=>"update", :controller=>"croppable_images", :name=>"cover_photo", :record_type=>"Stager"}, possible unmatched constraints: [:name] excluded from capture: No host specified, no public_key specified, no project_id specified

ActionController::UrlGenerationError (No route matches {:action=>"update", :controller=>"croppable_images", :name=>"cover_photo", :record_type=>"Stager"}, possible unmatched constraints: [:name]):

app/controllers/croppable_images_controller.rb:19:in `edit'
127.0.0.1 - - [04/Feb/2022:16:28:44 CST] "GET /stager/profile/cover_photo HTTP/1.1" 500 143893
http://localhost:3000/stager/profile -> /stager/profile/cover_photo
</code>```

The route call

```<code>@edit_image_url = stagers_stager_croppable_image_path('cover_photo')
</code>```
```<code><%=
  form_for(
    @croppable_image,
    url: @edit_image_url,
    method: :put
  ) do |f|
%>
</code>```

routes.rb section:

```<code>namespace :stagers, path: 'stager' do
    resource(
      :stager,
      path: 'profile',
      only: %i[edit update],
      path_names: {
        edit: ''
      }
    ) do
      %w[
        profile_photo
        cover_photo
      ].each do |croppable_image_name|
        resources(
          :croppable_image,
          controller: '/croppable_images',
          path: '',
          param: :name,
          only: %i[edit update],
          path_names: {
            edit: ''
          },
          defaults: {
            record_type: 'Stager'
          },
          constraints: {
            name: croppable_image_name
          }
        )
      end
    end
  end
</code>```

The route:

Helper
HTTP Verb
Path
Controller#Action

edit_stagers_stager_croppable_image_path
GET
/stager/profile/:name(.:format)
croppable_images#edit {:record_type=>"Stager", :name=>"profile_photo"}

stagers_stager_croppable_image_path
PATCH
/stager/profile/:name(.:format)
croppable_images#update {:record_type=>"Stager", :name=>"profile_photo"}

PUT
/stager/profile/:name(.:format)
croppable_images#update {:record_type=>"Stager", :name=>"profile_photo"}

GET
/stager/profile/:name(.:format)
croppable_images#edit {:record_type=>"Stager", :name=>"cover_photo"}

PATCH
/stager/profile/:name(.:format)
croppable_images#update {:record_type=>"Stager", :name=>"cover_photo"}

PUT
/stager/profile/:name(.:format)
croppable_images#update {:record_type=>"Stager", :name=>"cover_photo"}

答:
You are setting up that route with a constraint

```<code>%w[profile_photo cover_photo].each do |croppable_image_name|
  resrources
    ...
    constraints: { name: croppable_image_name }
  end
end
</code>```

So you need to add name: to your route, so this should work:

```<code>stagers_stager_croppable_image_path(name: 'profile_photo')
</code>```

However, since you are not using a specific route name on that each loop, calling it with name set to cover_photo will not work. I think you probably want to use a regex like

```<code>constraints: { name: /(cover|profile)_photo/ }
</code>```

Try declaring your routes like this (sorry I messed up your style)

```<code>Rails.application.routes.draw do
  namespace :stagers, path: 'stager' do
    resource(:stager, path: 'profile', only: %i[edit update], path_names: { edit: '' }) do
      resources(
        :croppable_image,
        controller: '/croppable_images',
        path: '',
        param: :name,
        only: %i[edit update],
        path_names: {
          edit: ''
        },
        defaults: {
          record_type: 'Stager'
        },
        constraints: {
          name: /(cover|profile)_photo/
        }
      )
    end
  end
end
</code>```

Body:
Route fails to match despite matching route found in rails routes

No route matches {:action=>"update", :controller=>"croppable_images", :name=>"cover_photo", :record_type=>"Stager"}, possible unmatched constraints: [:name] excluded from capture: No host specified, no public_key specified, no project_id specified

ActionController::UrlGenerationError (No route matches {:action=>"update", :controller=>"croppable_images", :name=>"cover_photo", :record_type=>"Stager"}, possible unmatched constraints: [:name]):

app/controllers/croppable_images_controller.rb:19:in `edit'
127.0.0.1 - - [04/Feb/2022:16:28:44 CST] "GET /stager/profile/cover_photo HTTP/1.1" 500 143893
http://localhost:3000/stager/profile -> /stager/profile/cover_photo

The route call

@edit_image_url = stagers_stager_croppable_image_path('cover_photo')

<%=
  form_for(
    @croppable_image,
    url: @edit_image_url,
    method: :put
  ) do |f|
%>

routes.rb section:

namespace :stagers, path: 'stager' do
    resource(
      :stager,
      path: 'profile',
      only: %i[edit update],
      path_names: {
        edit: ''
      }
    ) do
      %w[
        profile_photo
        cover_photo
      ].each do |croppable_image_name|
        resources(
          :croppable_image,
          controller: '/croppable_images',
          path: '',
          param: :name,
          only: %i[edit update],
          path_names: {
            edit: ''
          },
          defaults: {
            record_type: 'Stager'
          },
          constraints: {
            name: croppable_image_name
          }
        )
      end
    end
  end

The route:

Helper
HTTP Verb
Path
Controller#Action

edit_stagers_stager_croppable_image_path
GET
/stager/profile/:name(.:format)
croppable_images#edit {:record_type=>"Stager", :name=>"profile_photo"}

stagers_stager_croppable_image_path
PATCH
/stager/profile/:name(.:format)
croppable_images#update {:record_type=>"Stager", :name=>"profile_photo"}

PUT
/stager/profile/:name(.:format)
croppable_images#update {:record_type=>"Stager", :name=>"profile_photo"}

GET
/stager/profile/:name(.:format)
croppable_images#edit {:record_type=>"Stager", :name=>"cover_photo"}

PATCH
/stager/profile/:name(.:format)
croppable_images#update {:record_type=>"Stager", :name=>"cover_photo"}

PUT
/stager/profile/:name(.:format)
croppable_images#update {:record_type=>"Stager", :name=>"cover_photo"}

Body:
You are setting up that route with a constraint

%w[profile_photo cover_photo].each do |croppable_image_name|
  resrources
    ...
    constraints: { name: croppable_image_name }
  end
end

So you need to add name: to your route, so this should work:

stagers_stager_croppable_image_path(name: 'profile_photo')

However, since you are not using a specific route name on that each loop, calling it with name set to cover_photo will not work. I think you probably want to use a regex like

constraints: { name: /(cover|profile)_photo/ }

Try declaring your routes like this (sorry I messed up your style)

Rails.application.routes.draw do
  namespace :stagers, path: 'stager' do
    resource(:stager, path: 'profile', only: %i[edit update], path_names: { edit: '' }) do
      resources(
        :croppable_image,
        controller: '/croppable_images',
        path: '',
        param: :name,
        only: %i[edit update],
        path_names: {
          edit: ''
        },
        defaults: {
          record_type: 'Stager'
        },
        constraints: {
          name: /(cover|profile)_photo/
        }
      )
    end
  end
end


问:
cc1.exe System Error - libwinpthread-1.dll missing - But it isn't
I recently downloaded MinGW-w64 from Sourceforge onto my external hard drive, where all the files reside in:

E:\mingw-w64\x86_64-4.9.2-posix-seh-rt_v3-rev1\mingw64\bin

When I try compiling my first "Hello World" program using gcc on Windows 8.1, I get a cc1.exe System Error, that tells me

The program can't start because libwinpthread-1.dll is missing.
  Try reinstalling the program to fix the problem.

And yet, libwinpthread-1.dll (all 54,784 bytes of it) is sitting right there in the very same directory as gcc.exe. Do I really need to reinstall everything, or is something else going wrong here?

答: the dll files are already in the application file but what you need to do is copy the dll files and paste it in windows system32</p>


问:
How to add event handlers to button elements rendered in an OL using Javascript and get the index position?
I'm trying to build a simple to do list application. I've linked my input field to an array which gets rendered out as an ordered list, and there are two buttons added to each item, one to state "completed" and one for "remove".

I've having difficulty with two parts: 1) adding event handlers to the buttons rendered out in the OL (I've managed to in the code below but I'm not sure if it's the right way. Part 2) identifying the index of the item so that I can modify it with the completed and remove buttons.

I've tried to use event delegation to tackle part 1 but I'm not sure if this is correct, and I don't know how to relate it to part 2.

```<code>document.getElementById("parent-list").addEventListener("click", function(e) {
    if(e.target && e.target.nodeName == "BUTTON") {
        console.log(e.target);
    }
});
</code>```

答:
One way would be to add the index as an attribute of the LI element within your ordered list. Then you could access it like so:

document.getElementById("parent-list").addEventListener("click", function(e) {
  if (e.target && e.target.nodeName == "BUTTON") {
    const list = e.target.closest('li[data-idx]');
    const idx = list.dataset.idx;
    console.log(e.target, list, idx);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol id='parent-list'>
  <li data-idx='1'><button class='action'>click me</button></li>
  <li data-idx='2'><button class='action'>click me</button></li>
</ol></code>```

Of course this is just a proof of concept, you'd need to add error handling and such.

Body:
I'm trying to build a simple to do list application. I've linked my input field to an array which gets rendered out as an ordered list, and there are two buttons added to each item, one to state "completed" and one for "remove".

I've having difficulty with two parts: 1) adding event handlers to the buttons rendered out in the OL (I've managed to in the code below but I'm not sure if it's the right way. Part 2) identifying the index of the item so that I can modify it with the completed and remove buttons.

I've tried to use event delegation to tackle part 1 but I'm not sure if this is correct, and I don't know how to relate it to part 2.

document.getElementById("parent-list").addEventListener("click", function(e) {
    if(e.target && e.target.nodeName == "BUTTON") {
        console.log(e.target);
    }
});

Body:
One way would be to add the index as an attribute of the LI element within your ordered list. Then you could access it like so:

document.getElementById("parent-list").addEventListener("click", function(e) {
  if (e.target && e.target.nodeName == "BUTTON") {
    const list = e.target.closest('li[data-idx]');
    const idx = list.dataset.idx;
    console.log(e.target, list, idx);
  }
});

<ol id='parent-list'>
  <li data-idx='1'><button class='action'>click me</button></li>
  <li data-idx='2'><button class='action'>click me</button></li>
</ol>

Of course this is just a proof of concept, you'd need to add error handling and such.


问:
Panda dataframe: Select rows that are in a string
I have a dataframe as my dictionary contains a few tens of thousands of rows and 2 columns.

first column is id and the second one is an string.
input of my code is another string (usually a few thousand of words) and need to select rows if the input string contains that rows.
dataframe:

```<code>id  vals
1   apple
2   book
3   an apple
4   apple one
</code>```

input string: this is an apple from apple one.

output must be something like this: 1,3,4
which are ids of included in input string.

I know how to do it by lists simply like this:

```<code>[key.id for key in keys if " "+(key.vals.lower())+" " in inputstring]
</code>```

but we changed the dataflow and using dataframe instead. I need to do the same using indexing to make is as fast as possible

答:
You could try this:

```<code>input_string = "this is an apple from apple one"
list(df[[s in input_string for s in df['vals']]]['id'])
</code>```

Output:

```<code>[1, 3, 4]
</code>```

Body:
I have a dataframe as my dictionary contains a few tens of thousands of rows and 2 columns.

first column is id and the second one is an string.
input of my code is another string (usually a few thousand of words) and need to select rows if the input string contains that rows.
dataframe:

id  vals
1   apple
2   book
3   an apple
4   apple one

input string: this is an apple from apple one.

output must be something like this: 1,3,4
which are ids of included in input string.

I know how to do it by lists simply like this:

[key.id for key in keys if " "+(key.vals.lower())+" " in inputstring]

but we changed the dataflow and using dataframe instead. I need to do the same using indexing to make is as fast as possible

Body:
You could try this:

input_string = "this is an apple from apple one"
list(df[[s in input_string for s in df['vals']]]['id'])

Output:

[1, 3, 4]


问:
Is root certificate in the trust store enough to establish a connection?
Is having the root certificate in truststore enough for establishing the connection with a website? If so, just to test, I've imported the root certificate of google to new trust store which I have created and pointed to that trust store. Even then I am getting the following exception.
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

But if I try to connect to google using default java trust store then it's working fine. Can someone please help me with this? TIA.

答:
sorry bit TLDR for Saptarshi Basu answer. here in my laymen terms

if you trust store only has the root cert the server must send the chain

if your trust store has the chain (so including the intermediate cert) the server can
only send it's issued cert

Troubleshoot with
https://gist.github.com/4ndrej/4547029#file-sslpoke-java
and openssl (it uses the OS cert store)

openssl version -d
openssl s_client -connect google.com:443 -showcerts
```


问:
setProduct hook isnt a function?
I keep getting an error saying that the setProduct value isn't a function in my react code. Here is a codesandbox example of what I've been working on.

https://codesandbox.io/s/determined-jang-0ro1v

答: I can't recommend typescript enough. The return value of useState is  an array type. You need to unpack it using array syntax: const [product, setProduct] = useState()

Title: setProduct hook isnt a function?


问:
SQL (Redshift) - Rolling average with all preceding values
I have a table like so:

Day
Value

1
3

1
5

1
1

2
4

2
7

3
1

3
1

3
2

3
5

How do I create a rolling average that takes into account all previous days to produce a table like so:

Day
Rolling_avg

1
3

2
4

3
3.22

Day1 = avg(day 1 values)

Day2 = avg(day1 + day2 values)

Day3 = avg(day1 + day2 + day3 values)

so on so forth..thank you!

答:
First aggregate by day to get the sum of values and counts for each day.  Then use analytic functions to find the rolling averages.

WITH cte AS (
    SELECT Day, SUM(Value) ValueSum, COUNT(*) AS Count
    FROM yourTable
    GROUP BY Day
)

SELECT Day, SUM(ValueSum) OVER (ORDER BY Day) /
                SUM(Count) OVER (ORDER BY Day) AS Rolling_avg
FROM cte
ORDER BY Day;
```

Demo

Body:
First aggregate by day to get the sum of values and counts for each day.  Then use analytic functions to find the rolling averages.

WITH cte AS (
    SELECT Day, SUM(Value) ValueSum, COUNT(*) AS Count
    FROM yourTable
    GROUP BY Day
)

SELECT Day, SUM(ValueSum) OVER (ORDER BY Day) /
                SUM(Count) OVER (ORDER BY Day) AS Rolling_avg
FROM cte
ORDER BY Day;

Demo


问:
Proper CPython String Concatenation
Last night I was at a Boston Python Meetup that described various Python implementations. Part of the discussion included string concatenation.

Apparently for CPython there is less heap fragmentation if strings are concatenated starting with an empty string and then using join.

Is this an OK way to construct a string

```<code>sql_statement = "select count(*) " + \
    "from ept_inv e " + \
    "where e.ept_type =  " + str(in_row[cs.DeviceType]) + " " + \
    "and e.inv_id = " + str(in_row[cs.EndpointID]) + " ; "
</code>```

or should I have set sql_statement to "" and then joined each piece?
Thanks.

答:
You could use a multi-line string literal with .format:

```<code>sql_statement_format = """
    select count(*)
    from ept_inv e
    where e.ept_type = {device_type}
    and e.inv_id = {endpoint_id};
"""
sql_statement = sql_statement_format.format(
    device_type=in_row[cs.DeviceType],
    endpoint_id=in_row[cs.EndpointId])
</code>```

You need to properly sanitize your SQL queries, or bad things can happen.  Is there any reason you're not using the Python database API?

Title: Proper CPython String Concatenation

Body:
Last night I was at a Boston Python Meetup that described various Python implementations. Part of the discussion included string concatenation.

Apparently for CPython there is less heap fragmentation if strings are concatenated starting with an empty string and then using join.

Is this an OK way to construct a string

sql_statement = "select count(*) " + \
    "from ept_inv e " + \
    "where e.ept_type =  " + str(in_row[cs.DeviceType]) + " " + \
    "and e.inv_id = " + str(in_row[cs.EndpointID]) + " ; "

or should I have set sql_statement to "" and then joined each piece?
Thanks.

Body:
You could use a multi-line string literal with .format:

sql_statement_format = """
    select count(*)
    from ept_inv e
    where e.ept_type = {device_type}
    and e.inv_id = {endpoint_id};
"""
sql_statement = sql_statement_format.format(
    device_type=in_row[cs.DeviceType],
    endpoint_id=in_row[cs.EndpointId])

You need to properly sanitize your SQL queries, or bad things can happen.  Is there any reason you're not using the Python database API?


问:
How can I print the empty spaces with " | | " until the line ends
I am working with vectors and I wanna know how I can print the empty spaces in between until the line ends.

void print_vector(const std::vector < int > & v, int print_cols, int col_width) {
  //dash
  cout << string(print_cols * (col_width + 2) + 1, '-');
  cout << endl;
  //printing the vector in formated output
  cout << "|";
  for (size_t x = 0; x < v.size(); x++) {

    cout << right << setw(col_width) << v[x] << " |";
    //prints new line if it reaches limit of numbers per line
    if ((x + 1) % print_cols == 0) cout << endl << "|";

  }

  //dash
  cout << endl << string(print_cols * (col_width + 2) + 1, '-');
  cout << endl;
}
```

this is my current output: my output so far and sorry I can't embed images yet it wont let me.
But this is the output that I want output needed

答:
You can add an extra loop after the one you have and before the bottom row of dashes:

The loop would print a given number of blank columns.

The number of blank columns can be computed as print_cols - v.size() % print_cols.

The loop should not be executed if the number of blank columns is equal to the total number of columns. That would print a full row of empty columns. That case happens when the vector you want to print has a number of elements that is an exact multiple of the number of columns.

Every iteration of the loop should print col_width + 1 blanks and a '|' (or if you prefer it, to make it more consistent with your other code, col_width blanks plus a " |").

Yet you should fix another issue with your code:

The check for reaching the end of the row (enabling the print of a new line and a '|') should be instead a check for starting a row.

If you do it at the end, for the case when the last element of the vector goes in the last column, you will unnecessarily add a new row.

Doing it at the beginning, since you know you have at least one more number to show, you can print "\n|" and then the number.

The check x % print_cols == 0 will tell you if x is the index of the first element of a row.

[Demo]

#include <iomanip>  // setw
#include <iostream>  // cout
#include <numeric>  // iota
#include <string>
#include <vector>

void print_vector(const std::vector<int>& v, int print_cols, int col_width) {
    // dash
    std::cout << std::string(print_cols * (col_width + 2) + 1, '-');

    // printing the vector in formated output
    for (size_t x = 0; x < v.size(); x++) {
        // prints new line if it is the first element of the line
        if (x % print_cols == 0) {
            std::cout << "\n|";
        }
        std::cout << std::right << std::setw(col_width) << v[x] << " |";
    }
    // prints last empty columns
    if (int number_of_blank_columns = print_cols - v.size() % print_cols;
        number_of_blank_columns != print_cols) {

        for (int x = 0; x < number_of_blank_columns; x++) {
            std::cout << std::string(col_width + 1, ' ') << "|";
        }
    }

    // dash
    std::cout << "\n" << std::string(print_cols * (col_width + 2) + 1, '-') << "\n";
}

int main() {
    {
        std::vector<int> v(8);
        std::iota(std::begin(v), std::end(v), 100);
        print_vector(v, 5, 4);
    }
    std::cout << "\n";
    {
        std::vector<int> v(10);
        std::iota(std::begin(v), std::end(v), 100);
        print_vector(v, 5, 4);
    }
}

// Outputs:
//
//   -------------------------------
//   | 100 | 101 | 102 | 103 | 104 |
//   | 105 | 106 | 107 |     |     |
//   -------------------------------
//
//   -------------------------------
//   | 100 | 101 | 102 | 103 | 104 |
//   | 105 | 106 | 107 | 108 | 109 |
//   -------------------------------
```

Body:
I am working with vectors and I wanna know how I can print the empty spaces in between until the line ends.

void print_vector(const std::vector < int > & v, int print_cols, int col_width) {
  //dash
  cout << string(print_cols * (col_width + 2) + 1, '-');
  cout << endl;
  //printing the vector in formated output
  cout << "|";
  for (size_t x = 0; x < v.size(); x++) {

    cout << right << setw(col_width) << v[x] << " |";
    //prints new line if it reaches limit of numbers per line
    if ((x + 1) % print_cols == 0) cout << endl << "|";

  }

  //dash
  cout << endl << string(print_cols * (col_width + 2) + 1, '-');
  cout << endl;
}

this is my current output: my output so far and sorry I can't embed images yet it wont let me.
But this is the output that I want output needed


问:
Android Gradle plugin requires Java 11 to run. Changing it to 11 or above has no effect
This question is fairly old on Stackoverflow but none of the provided solutions worked for me.
So I try to generate an Android App Bundle with Android Studio and first receive the message

Generate Signed Bundle: Errors while building Bundle file. You can find the errors in the 'Messages' view.

which results in

Cause: argument type mismatch

Then in the terminal I run

./gradlew build --warning-mode all

which gives me:

So I tried various things:

Android Studio (Arctic Fox) => Preferences => Build/Execution/Deployment => Buidl Tools => Gradle => set Version to 11.0.10

I also tried Version 17. No success. Still the same error on building

I reset Android Studio to default settings. After restart there was a popup asking me to change SDK from 1.8 - I clicked there and did the change. No success. Still the same error.

I run ./gradlew --version  in Terminal and receive this

So basically everything I do regarding changing the SDK has no effect. Honestly I am out of options now and don't know what to do next.

答:
On MAC, this worked for me</p>
```<code>export JAVA_HOME=/Applications/Android\ Studio.app/Contents/jre/Contents/Home
</code>```

Body:
On MAC, this worked for me

export JAVA_HOME=/Applications/Android\ Studio.app/Contents/jre/Contents/Home


问:
Sharing data across processes on linux
In my application, I have a process which forks off a child, say child1, and this child process writes a huge binary file on the disk and exits. The parent process then forks off another child process, child2, which reads in this huge file to do further processing.

The file dumping and re-loading is making my application slow and I'm thinking of possible
ways of avoiding disk I/O completely. Possible ways I have identified are ram-disk or tmpfs.
Can I somehow implement ram-disk or tmpfs from within my application? Or is there any other
way by which I can avoid disk I/O completely and send data across processes reliably.

答: You can use pipes, sockets, and take advantage of sendfile() or splice() features of Linux kernel (they can avoid data copying).

Title: Sharing data across processes on linux


问:
Error loading shared libraries on Windows
I am on Windows 10 using msys.

Whenever I try to run protoc.exe for protobufs I get the following error.

error while loading shared libraries: ?: cannot open shared object file: No such file or directory

I have checked with ldd

```<code>        ntdll.dll => /c/Windows/SYSTEM32/ntdll.dll (0x7ffe998b0000)
        KERNEL32.DLL => /c/Windows/System32/KERNEL32.DLL (0x7ffe97c10000)
        KERNELBASE.dll => /c/Windows/System32/KERNELBASE.dll (0x7ffe972a0000)
        msvcrt.dll => /c/Windows/System32/msvcrt.dll (0x7ffe98900000)

</code>```

All of these files exist and PATH is set to /c/Windows/SYSTEM32.

I am not sure what is going on here.

You can trigger this in bazel by trying to build any protobuf

bazel build --compiler=mingw-gcc some_proto

only in msys though.

答:
Okay there are two ways to fix this.

build through command prompt and change PATH
to include

C:\Windows\SYSTEM32
C:\msys64\usr\bin

Through msys move the following files to C:\msys64\mingw64\bin

ntdll.dll

KERNEL32.DLL

KERNELBASE.dll

msvcrt.dll

Body:
I am on Windows 10 using msys.

Whenever I try to run protoc.exe for protobufs I get the following error.

error while loading shared libraries: ?: cannot open shared object file: No such file or directory

I have checked with ldd

        ntdll.dll => /c/Windows/SYSTEM32/ntdll.dll (0x7ffe998b0000)
        KERNEL32.DLL => /c/Windows/System32/KERNEL32.DLL (0x7ffe97c10000)
        KERNELBASE.dll => /c/Windows/System32/KERNELBASE.dll (0x7ffe972a0000)
        msvcrt.dll => /c/Windows/System32/msvcrt.dll (0x7ffe98900000)

All of these files exist and PATH is set to /c/Windows/SYSTEM32.

I am not sure what is going on here.

You can trigger this in bazel by trying to build any protobuf

bazel build --compiler=mingw-gcc some_proto

only in msys though.