问:
Lazy loading images with accessibility and printer support
I am looking for a proper way to implement lazy loading of images without harming printability and accessibility, and without introducing layout shift (content jump), preferrably using native loading=lazy and a fallback for older browsers. Answers to the question How lazy loading images using JavaScript works?
 included various solutions none of which completely satisfy all of these requirements.

An elegant solution should be based on valid and complete html markup, i.e. using <img src, srcset, sizes, width, height, and loading attributes instead of putting the data into data- attributes, like the popular javascript libraries lazysizes and vanilla-lazyload do. There should be no need to use  elements either.

Due to a bug in chrome, the first browser to support native lazyloading, images that have not yet been loaded will be missing in the printed page.

Both javascript libraries mentioned above, require either invalid markup without any src attribute at all, or an empty or low quality placeholder (LQIP), while the src data is put into data-src instead, and srcset data put into data-srcset, all of which only works with javascript. Is this considered an acceptable or even best practice in 2020, and does this neither harm the site accessibility, cross-device compatibility, nor search engine optimization?

Update:

I tried a workaround for the printing bug using only HTML and CSS @media print background images in this codepen . Even if this worked as intended, there would be a necessary css directive for each and every image, which is neither elegant nor generic. Unfortunately there is no way to use media queries inside the <picture> element either.

There is another workaround by Houssein Djirdeh at at lazy-load-with-print-ctl1l4wu1.now.sh using javascript to change loading=lazy to loading=eager when a "print" button is clicked. The same function could also be used onbeforeprint.

I made a codepen using lazysizes.

I made another codepen using vanilla-lazyload .

I thought about forking a javascript solution to make it work using src and srcset, but this must probably have been tried before, the tradeoff would be that once the lazyloading script starts to act on the image elements, the browser might have already started downloading the source files.

答:
The proper solution for printable lazy loading in 2022 is using the native loading attribute.

```<code><img loading=lazy>
</code>```

The recommendation to use a custom print button has been obsoleted as chromium issue 875403 got fixed.

Prior recommendations included adding a custom print button (which did not fix the problem when using the native browser print functionality) or using JavaScript to load images onBeforePrint the latter not being considered a good solution, as loading=lazy, as a "DOM-only" solution, must not rely on JavaScript.

Beware that, even after the bug fix, some of your users might still visit your site with a buggy browser version.

Body:
The proper solution for printable lazy loading in 2022 is using the native loading attribute.

<img loading=lazy>

The recommendation to use a custom print button has been obsoleted as chromium issue 875403 got fixed.

Prior recommendations included adding a custom print button (which did not fix the problem when using the native browser print functionality) or using JavaScript to load images onBeforePrint the latter not being considered a good solution, as loading=lazy, as a "DOM-only" solution, must not rely on JavaScript.

Beware that, even after the bug fix, some of your users might still visit your site with a buggy browser version.


来源: stackexchange

问:
Subset groups in a data.table using conditions on two columns
I have a data.table with a high number of groups. I would like to subset whole groups (not just rows) based on the conditions on multiple columns. Consider the following data.table:

```<code>DT <- structure(list(id = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L),
                 group = c("A", "A", "A", "A", "B", "B", "B", "B", "C", "C", "C", "C"),
                 y = c(14, 19, 16, 10, 6, 8, 14, 19, 10, 9, 6, 8),
                 x = c(3, 3, 2, 3, 3, 3, 3, 2, 2, 3, 3, 3)),
            row.names = c(NA, -12L),
            class = c("data.table", "data.frame"))
>DT

    id group  y x
 1:  1     A 14 3
 2:  2     A 19 3
 3:  3     A 16 2
 4:  4     A 10 3
 5:  5     B  6 3
 6:  6     B  8 3
 7:  7     B 14 3
 8:  8     B 19 2
 9:  9     C 10 2
10: 10     C  9 3
11: 11     C  6 3
12: 12     C  8 3
</code>```

I would like to keep groups that have y=6 and x=3 in the same row. So that I would have only class B and C (preferably using data.table package in R):

```<code>    id group  y x
 1:  5     B  6 3
 2:  6     B  8 3
 3:  7     B 14 3
 4:  8     B 19 2
 5:  9     C 10 2
 6: 10     C  9 3
 7: 11     C  6 3
 8: 12     C  8 3
</code>```

All my attempts gave me only those rows containing y=6 and x=3, which I do not want:

```<code>    id group  y x
 1:  5     B  6 3
 2: 11     C  6 3
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a data.table with a high number of groups. I would like to subset whole groups (not just rows) based on the conditions on multiple columns. Consider the following data.table:

DT <- structure(list(id = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L),
                 group = c("A", "A", "A", "A", "B", "B", "B", "B", "C", "C", "C", "C"),
                 y = c(14, 19, 16, 10, 6, 8, 14, 19, 10, 9, 6, 8),
                 x = c(3, 3, 2, 3, 3, 3, 3, 2, 2, 3, 3, 3)),
            row.names = c(NA, -12L),
            class = c("data.table", "data.frame"))
>DT

    id group  y x
 1:  1     A 14 3
 2:  2     A 19 3
 3:  3     A 16 2
 4:  4     A 10 3
 5:  5     B  6 3
 6:  6     B  8 3
 7:  7     B 14 3
 8:  8     B 19 2
 9:  9     C 10 2
10: 10     C  9 3
11: 11     C  6 3
12: 12     C  8 3

I would like to keep groups that have y=6 and x=3 in the same row. So that I would have only class B and C (preferably using data.table package in R):

    id group  y x
 1:  5     B  6 3
 2:  6     B  8 3
 3:  7     B 14 3
 4:  8     B 19 2
 5:  9     C 10 2
 6: 10     C  9 3
 7: 11     C  6 3
 8: 12     C  8 3

All my attempts gave me only those rows containing y=6 and x=3, which I do not want:

    id group  y x
 1:  5     B  6 3
 2: 11     C  6 3

Body:
A data.table option

> DT[group %in% DT[.(3, 6), group, on = .(x, y)]]
   id group  y x
1:  5     B  6 3
2:  6     B  8 3
3:  7     B 14 3
4:  8     B 19 2
5:  9     C 10 2
6: 10     C  9 3
7: 11     C  6 3
8: 12     C  8 3


问:
extracting data from a string in PHP
I am a complete beginner in PHP.
I have several hundred product descriptions, for example here:

Superpremium cat food light chicken 1 kg

Superpremium cat food light chicken 10kg

Superpremium cat food beef 2x10 kg

Superpremium cat food beef 2 x 3,8 kg

Superpremium cat food beef 2 x 2kg

Superpremium cat food beef 42 x 85g

I would need to extract from the product name the name of flavor, quantity and weight like this:

For example:

From this: Superpremium cat food beef 42 x 85g

To this:

Flavor: beef

Number of pieces: 42

Weight: 85

KG/g: g

I tried to use an array, but it doesn't work for me at all.

There's a mess in the numbers. Sometimes 10kg is given, sometimes 10 kg with a gap as you can see in the examples above.

I have a list of name of the products (brands), list of flavors etc. so my idea was to use array and use if the string contains flavor then return "Flavor: beef" etc. I spent hours on looking how to use the functions but as a beginner have no idea how to make it work.

Thanks for help!

```<code><?php
function flavor($product) {

$arr = array('turkey', 'chicken', 'fish', 'salmon', 'rabbit', 'beef', 'cod');
foreach ($arr as $product) {
    return $product;

}
}

?>
</code>```

答:
This how the solution can look like:

```<code><?php

$description = <<<EOD
    Superpremium cat food light chicken 1 kg

    Superpremium cat food light chicken 10kg

    Superpremium cat food beef 2x10 kg

    Superpremium cat food beef 2 x 3,8 kg

    Superpremium cat food beef 2 x 2kg

    Superpremium cat food beef 42 x 85g
EOD;

preg_match_all("/.*food\s?([^\d]*)\s?([\d]+)\s*x?\s*([\d,]*)\s*([\w]*)/im", $description, $matches, PREG_SET_ORDER);

foreach ($matches as $match) {
    echo 'Flavor: ' . $match[1] . PHP_EOL;
    echo 'Number of pieces: ' . $match[2] . PHP_EOL;
    echo 'Weight: ' . ($match[3] ?: 1) . PHP_EOL;
    echo 'kg/g: ' . $match[4] . PHP_EOL . PHP_EOL;
}
</code>```

Explanations:

<<<EOD means heredoc syntax for strings in PHP, it allows to handle multiline text in a single variable

preg_match_all looks for pattern in the entire description text and save each piece in parentheses into $matches variable

im in the end of regex pattern means i - case-insensitive, m - multiline

PREG_SET_ORDER constant sets a needed order of found pieces in the $matches variable

PHP_EOL constant stands for end-of-line symbol "\n", allows to print text on a new line

($match[3] ?: 1) is a shortening for ($match[3] ? $match[3] : 1) which means that if we have a value in $match[3] array index then we use this value, if no then we use 1 (one piece if no value for it in the text)

Title: extracting data from a string in PHP

Body:
I am a complete beginner in PHP.
I have several hundred product descriptions, for example here:

Superpremium cat food light chicken 1 kg

Superpremium cat food light chicken 10kg

Superpremium cat food beef 2x10 kg

Superpremium cat food beef 2 x 3,8 kg

Superpremium cat food beef 2 x 2kg

Superpremium cat food beef 42 x 85g

I would need to extract from the product name the name of flavor, quantity and weight like this:

For example:

From this: Superpremium cat food beef 42 x 85g

To this:

Flavor: beef

Number of pieces: 42

Weight: 85

KG/g: g

I tried to use an array, but it doesn't work for me at all.

There's a mess in the numbers. Sometimes 10kg is given, sometimes 10 kg with a gap as you can see in the examples above.

I have a list of name of the products (brands), list of flavors etc. so my idea was to use array and use if the string contains flavor then return "Flavor: beef" etc. I spent hours on looking how to use the functions but as a beginner have no idea how to make it work.

Thanks for help!

<?php
function flavor($product) {

$arr = array('turkey', 'chicken', 'fish', 'salmon', 'rabbit', 'beef', 'cod');
foreach ($arr as $product) {
    return $product;

}
}

?>

Body:
This how the solution can look like:

<?php

$description = <<<EOD
    Superpremium cat food light chicken 1 kg

    Superpremium cat food light chicken 10kg

    Superpremium cat food beef 2x10 kg

    Superpremium cat food beef 2 x 3,8 kg

    Superpremium cat food beef 2 x 2kg

    Superpremium cat food beef 42 x 85g
EOD;

preg_match_all("/.*food\s?([^\d]*)\s?([\d]+)\s*x?\s*([\d,]*)\s*([\w]*)/im", $description, $matches, PREG_SET_ORDER);

foreach ($matches as $match) {
    echo 'Flavor: ' . $match[1] . PHP_EOL;
    echo 'Number of pieces: ' . $match[2] . PHP_EOL;
    echo 'Weight: ' . ($match[3] ?: 1) . PHP_EOL;
    echo 'kg/g: ' . $match[4] . PHP_EOL . PHP_EOL;
}

Explanations:

<<<EOD means heredoc syntax for strings in PHP, it allows to handle multiline text in a single variable

preg_match_all looks for pattern in the entire description text and save each piece in parentheses into $matches variable

im in the end of regex pattern means i - case-insensitive, m - multiline

PREG_SET_ORDER constant sets a needed order of found pieces in the $matches variable

PHP_EOL constant stands for end-of-line symbol "\n", allows to print text on a new line

($match[3] ?: 1) is a shortening for ($match[3] ? $match[3] : 1) which means that if we have a value in $match[3] array index then we use this value, if no then we use 1 (one piece if no value for it in the text)


问:
How to use external DLL (Dot Net) in Flutter?
I have develop Desktop project using c# which include Web API. Now we plan to start develop with Mobile platform using Flutter. So I already have build all functions which contains calculation and action to API into DLL. So Is it possible way that i can use this DLL in Flutter?

DLL project type " Class Library (Portable for IOS, Android and Windows)

答:
Yes, but is necessary to use native source for each platform.
Ex: For android, use http://en.wikipedia.org/wiki/Java_Native_Access for import functions from dll .net;
For windows its possible with c++...
I recommend you create a plugin for better organization.

For android, this link help you:
Setting up JNA in Android Studio

For communication Java/kotlin with flutter use:

```<code>import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
</code>```

Body:
Yes, but is necessary to use native source for each platform.
Ex: For android, use http://en.wikipedia.org/wiki/Java_Native_Access for import functions from dll .net;
For windows its possible with c++...
I recommend you create a plugin for better organization.

For android, this link help you:
Setting up JNA in Android Studio

For communication Java/kotlin with flutter use:

import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;


问:
How to get Page assembly from a Control?
I've create a method that gets the current page's assembly name and version so that I can display it in the page footer. It works just fine, but I'd like to move this logic into a control that I could drop into any web application project master page that references my control library. However, in the control library Assembly.GetExecutingAssembly() returns the control library assembly, not the web project assembly.

Here's the method:

```<code>    private string GetVersion()
    {
        const string cacheKey = "Web.Controls.ApplicationVersion";
        string version = (string) Page.Cache[cacheKey];
        if (version == null)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();

            // get the assembly version
            Version assemblyVersion = assembly.GetName().Version;

            // get the product name
            string productName;
            AssemblyProductAttribute productAttribute =
                assembly.GetCustomAttributes(typeof (AssemblyProductAttribute), false).Cast
                    <AssemblyProductAttribute>().FirstOrDefault();
            if (productAttribute != null)
            {
                productName = productAttribute.Product;
            }
            else
            {
                productName = String.Empty;
            }

            version = String.Format("{0} {1}", productName, assemblyVersion);

            Page.Cache[cacheKey] = version;
        }

        return version;
    }
</code>```

I've also tried Assembly.GetEntryAssembly() which returns null, and Assembly.GetCallingAssembly() which returns the control assembly. Finally I tried Assembly.GetAssembly(Page.GetType()), which returns the page type generated at runtime (ASP.abc).

How can I get the web project assembly from within the context of a Control without asking for it explicitly by name?

答:
maybe it is not in time. But today I had run into the same issue. And first  what I had found was your questions without answer ( . Later I digged around this question.
The answer is: Assembly.GetAssembly(Page.GetType().BaseType)

The reason is generation page type at runtime as you mentioned above.
Good explanation I found in MSDN:

The type of the HTTP handler for a particular page depends on the URL.
  The first time the URL is invoked, a new class is composed and
  dynamically compiled to an assembly. The source code of the class is
  the outcome of a parsing process that examines the .aspx sources. The
  class is defined as part of the namespace ASP and is given a name that
  mimics the original URL. For example, if the URL endpoint is
  page.aspx, the name of the class is ASP.Page_aspx. The class name,
  though, can be programmatically controlled by setting the ClassName
  attribute in the @Page directive.

The base class for the HTTP handler is Page. This class defines the
  minimum set of methods and properties shared by all page handlers. The
  Page class implements the IHttpHandler interface.

Under a couple of circumstances, the base class for the actual handler
  is not Page but a different class. This happens, for example, if
  code-behind is used. Code-behind is a development technique that
  insulates the code necessary to a page into a separate C# or Microsoft
  Visual Basic® .NET class. The code of a page is the set of event
  handlers and helper methods that actually create the behavior of the
  page. This code can be defined inline using the
  tag or placed in an external class—the code-behind class. A
  code-behind class is a class that inherits from Page and specializes
  it with extra methods. When specified, the code-behind class is used
  as the base class for the HTTP handler.

So when you are using Page.GetType() you will get dynamic composed class. And this class is inherited from actual page class, and this one is into project assembly.
http://msdn.microsoft.com/en-us/library/aa479007.aspx -MSDN article refference.

ContentLicense: CC BY-SA 2.5

Body:
I've create a method that gets the current page's assembly name and version so that I can display it in the page footer. It works just fine, but I'd like to move this logic into a control that I could drop into any web application project master page that references my control library. However, in the control library Assembly.GetExecutingAssembly() returns the control library assembly, not the web project assembly.

Here's the method:

    private string GetVersion()
    {
        const string cacheKey = "Web.Controls.ApplicationVersion";
        string version = (string) Page.Cache[cacheKey];
        if (version == null)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();

            // get the assembly version
            Version assemblyVersion = assembly.GetName().Version;

            // get the product name
            string productName;
            AssemblyProductAttribute productAttribute =
                assembly.GetCustomAttributes(typeof (AssemblyProductAttribute), false).Cast
                    <AssemblyProductAttribute>().FirstOrDefault();
            if (productAttribute != null)
            {
                productName = productAttribute.Product;
            }
            else
            {
                productName = String.Empty;
            }

            version = String.Format("{0} {1}", productName, assemblyVersion);

            Page.Cache[cacheKey] = version;
        }

        return version;
    }

I've also tried Assembly.GetEntryAssembly() which returns null, and Assembly.GetCallingAssembly() which returns the control assembly. Finally I tried Assembly.GetAssembly(Page.GetType()), which returns the page type generated at runtime (ASP.abc).

How can I get the web project assembly from within the context of a Control without asking for it explicitly by name?

ContentLicense: CC BY-SA 3.0


问:
How to capitalize the second appearance of the same variable in WebStorm?
I have the following WebStorm Live Template:

[$VAR1$, set$VAR1$]

My goal is to capitalize the second occurrence of $VAR1$.

e.g. for the input: foo

the output should be: [foo, setFoo]

right now the output is: [foo, setfoo]

For Live Templates, there is a Dialog where I can define a function expression to capitalize a variable:

The problem here is that the definition is per variable, so both occurrences are capitalized then.

How can I capitalize only the second occurrence, or copy the value of one variable into another one which would be capitalized then?

答:
Just add another variable:

```<code>$VAR1$, set$VAR2$
</code>```

See https://blog.jetbrains.com/webstorm/2022/02/creating-and-using-code-snippets-with-placeholders/, you may find this blog post useful

Body:
Just add another variable:

$VAR1$, set$VAR2$

See https://blog.jetbrains.com/webstorm/2022/02/creating-and-using-code-snippets-with-placeholders/, you may find this blog post useful


问:
Laravel: how to cache config files properly
I'm using Laravel 8.0 in my application and I added a new .env variable:

```<code>APP_URL_FRONT=https://tmsv00008:6204
</code>```

And how I use it:

```<code>To access the project use the following link: <a href="{{ env('APP_URL_FRONT') }}/projects/{{ $project->id }}">LINK</a>
</code>```

When I deploy the application I cache the config files:

```<code>php artisan config:cache
</code>```

But the env files is not visible and the strange thing is that if I execute:

```<code>php artisan config:clear
</code>```

The variable is visible.
What I'm doing wrong? Because it doesn't make sense to me.

Also, in this article they suggest to execute the commands in this order:

```<code>php artisan config:cache
php artisan config:clear
</code>```

But this doesn't make sense to me. Shouldn't be the other way around? And I think the cache commands also clears the cache first.

答:
The env() function is strongly recommended to be used only in configuration file, since caching the configurations, will make the env function to return null

In other words, crate a configuration file, with that environment variable, or add it to an existing one

It's hidden in an old update guide this "note"

Body:
I'm using Laravel 8.0 in my application and I added a new .env variable:

APP_URL_FRONT=https://tmsv00008:6204

And how I use it:

To access the project use the following link: id }}">LINK

When I deploy the application I cache the config files:

php artisan config:cache

But the env files is not visible and the strange thing is that if I execute:

php artisan config:clear

The variable is visible.
What I'm doing wrong? Because it doesn't make sense to me.

Also, in this article they suggest to execute the commands in this order:

php artisan config:cache
php artisan config:clear

But this doesn't make sense to me. Shouldn't be the other way around? And I think the cache commands also clears the cache first.


问:
Get specific value from JSON array after comparison using PowerShell?
I want to get specific value once key is matched from JSON array object

Input:

```<code>[
    {
        "Id": "19A7A3C4",
        "displayName": "somename",
        "tags": [
            {
                "context": "CONTEXTLESS",
                "key": "apple",
                "value": "10"
            },
            {
                "context": "CONTEXTLESS",
                "key": "orange",
                "value": "20"
            },
            {
                "context": "CONTEXTLESS",
                "key": "grapes",
                "value": "30"
            }
        ]
    },
    {
        "Id": "111111",
        "displayName": "somename",
        "tags": [
            {
                "context": "CONTEXTLESS",
                "key": "cat",
                "value": "10"
            },
            {
                "context": "CONTEXTLESS",
                "key": "cat",
                "value": "20"
            }
        ]
    }
]
</code>```

I want to get the value of tag where key matches to cat and value matches to 10, I am using below query but getting whole object

```<code>$content = Get-Content -Raw -Path "data.json" | ConvertFrom-Json
$content | Where-Object{ $_.tags.key -eq "cat" -and $_.tags.value -eq "10"}
</code>```

Desired Output: 10

答:
Enumerate all tags, then use ForEach-Object to grab just the value property of any match:

```<code>$content.tags | Where-Object { $_.key -eq "cat" -and $_.value -eq "10"} |ForEach-Object -MemberName value
</code>```

Body:
I want to get specific value once key is matched from JSON array object

Input:

[
    {
        "Id": "19A7A3C4",
        "displayName": "somename",
        "tags": [
            {
                "context": "CONTEXTLESS",
                "key": "apple",
                "value": "10"
            },
            {
                "context": "CONTEXTLESS",
                "key": "orange",
                "value": "20"
            },
            {
                "context": "CONTEXTLESS",
                "key": "grapes",
                "value": "30"
            }
        ]
    },
    {
        "Id": "111111",
        "displayName": "somename",
        "tags": [
            {
                "context": "CONTEXTLESS",
                "key": "cat",
                "value": "10"
            },
            {
                "context": "CONTEXTLESS",
                "key": "cat",
                "value": "20"
            }
        ]
    }
]

I want to get the value of tag where key matches to cat and value matches to 10, I am using below query but getting whole object

$content = Get-Content -Raw -Path "data.json" | ConvertFrom-Json
$content | Where-Object{ $_.tags.key -eq "cat" -and $_.tags.value -eq "10"}

Desired Output: 10

Body:
Enumerate all tags, then use ForEach-Object to grab just the value property of any match:

$content.tags | Where-Object { $_.key -eq "cat" -and $_.value -eq "10"} |ForEach-Object -MemberName value


问:
append to pickle file [python opencv face recognition]
I would like to combine two pickle files into a new onethat both come from face recognition. I have a main actors.pkl file that one holds a lot of actors, now I would like to update this file but not using the imageset update methode. So I am creating a new picklefile actorupdate.pkl in this set are the registered faces not in actors.pkl

I am able to open / read both files and they both work perfect (recognition wise) so how would I be able to join both files into a new one (or append actorupdate.pkl to actors.pkl)

```<code>import pickle

data = pickle.loads(open("encodings/actors.pkl", "rb").read())
data2 = pickle.loads(open("encodings/actorupdate.pkl", "rb").read())

verify dataset (names):
data['names'] = ['ben_afflek', 'ben_afflek', 'ben_afflek', 'ben_afflek', 'ben_afflek', 'ben_afflek', 'ben_afflek', 'ben_afflek', ........
data2['names'] = ['Gal_Gadot', 'Gal_Gadot', 'Gal_Gadot', 'Gal_Gadot', 'Gal_Gadot', 'Gal_Gadot']
</code>```

trying to use this methode:

```<code>filename="picklefile"
with open(filename, 'wb') as fp:
   pickle.dump(data ,fp)
   pickle.dump(data2 ,fp)
</code>```

but in that case it writes a new file to my disk but the information from data2 is not there, it became just a copy of data and I would like to use the file directly not create a new pickle file on my disk.

答: You can simply append second list into first one and then just dumps it</p>

Body:
I would like to combine two pickle files into a new onethat both come from face recognition. I have a main actors.pkl file that one holds a lot of actors, now I would like to update this file but not using the imageset update methode. So I am creating a new picklefile actorupdate.pkl in this set are the registered faces not in actors.pkl

I am able to open / read both files and they both work perfect (recognition wise) so how would I be able to join both files into a new one (or append actorupdate.pkl to actors.pkl)

import pickle

data = pickle.loads(open("encodings/actors.pkl", "rb").read())
data2 = pickle.loads(open("encodings/actorupdate.pkl", "rb").read())

verify dataset (names):
data['names'] = ['ben_afflek', 'ben_afflek', 'ben_afflek', 'ben_afflek', 'ben_afflek', 'ben_afflek', 'ben_afflek', 'ben_afflek', ........
data2['names'] = ['Gal_Gadot', 'Gal_Gadot', 'Gal_Gadot', 'Gal_Gadot', 'Gal_Gadot', 'Gal_Gadot']

trying to use this methode:

filename="picklefile"
with open(filename, 'wb') as fp:
   pickle.dump(data ,fp)
   pickle.dump(data2 ,fp)

but in that case it writes a new file to my disk but the information from data2 is not there, it became just a copy of data and I would like to use the file directly not create a new pickle file on my disk.


问:
How to configure Angular/nginx routing with proper status codes
I'm struggling to find any good documentation or guides on how to setup the routing in Angular and Nginx to support the following logic:

```<code>Route                            File       Status

example.com                   -> index.html 200 OK
example.com/path              -> index.html 200 OK
example.com/not-found         -> index.html 404 NOT FOUND
example.com/another-not-found -> index.html 404 NOT FOUND
</code>```

Important points:

Refreshing the page should give the same result

Going to a path that doesn't exist should not redirect, it should give a 404 status code and show the 404 page.

Is there a way to do this? Any help would be much appreciated.

答:
It seems it's not possible to make Angular work this way. Using the Angular docs as an example, they don't do it either.

Even though Google themselves says this is a bad practice: https://developers.google.com/search/docs/advanced/crawling/soft-404-errors

Fortunately it's not a massive issue as Google does try to recognize pages with a 200 status as a 404 as long as the content on the page makes it clear enough that it's actually a 404.

One SEO improvment can be seen in the Angular docs source code:

// Dynamically, pre-emptively, add `noindex`, which will be removed when the doc is ready and valid
const tag = document.createElement('meta');
tag.name = 'robots';
tag.content = 'noindex';
document.head.appendChild(tag);
```

This will add <meta name="robots" content="noindex"> to all pages. They then remove this tag once they know the page is valid (ie. not 404).

Body:
I'm struggling to find any good documentation or guides on how to setup the routing in Angular and Nginx to support the following logic:

Route                            File       Status

example.com                   -> index.html 200 OK
example.com/path              -> index.html 200 OK
example.com/not-found         -> index.html 404 NOT FOUND
example.com/another-not-found -> index.html 404 NOT FOUND

Important points:

Refreshing the page should give the same result

Going to a path that doesn't exist should not redirect, it should give a 404 status code and show the 404 page.

Is there a way to do this? Any help would be much appreciated.

Body:
It seems it's not possible to make Angular work this way. Using the Angular docs as an example, they don't do it either.

Even though Google themselves says this is a bad practice: https://developers.google.com/search/docs/advanced/crawling/soft-404-errors

Fortunately it's not a massive issue as Google does try to recognize pages with a 200 status as a 404 as long as the content on the page makes it clear enough that it's actually a 404.

One SEO improvment can be seen in the Angular docs source code:

// Dynamically, pre-emptively, add `noindex`, which will be removed when the doc is ready and valid
const tag = document.createElement('meta');
tag.name = 'robots';
tag.content = 'noindex';
document.head.appendChild(tag);

This will add <meta name="robots" content="noindex"> to all pages. They then remove this tag once they know the page is valid (ie. not 404).


问:
asmx asp.net webservice return multiple classes wsdl
We are developing a webservice for a client.  We are not supose to throw SoapExceptions, so instead, we catch every exception server side, and return a custom Exception class.

```<code>Public Class Order
...
End Class

Public Class MyException
...
End Class
</code>```

And then in my webservice a function (webmethod):

```<code>Public Function GetOrder(ByVal id As Integer) As Object

    Try
        ...
        Return New Order()
    Catch ex As Exception
        Return New MyException(ex.Message)
    End Try

End Function
</code>```

The problem now is, that since my webmethod is returning the type [Object]. The wdsl that is generated does not contain the order, or the exception.

I can change the [Object] to [Order] Or [MyException], but only one of them is generated in the wsdl.

So does anybody have an idea of how i should handle this? I want both the MyException type and the Order type in my wsdl, but i just cant get it working.

Thank you all.

答:
If your definition of MyException

```<code>Public Class MyException
        inherits System.Exception
    ...
    End Class
</code>```

then you shouldn't need to return the Custom Exception just throw it.

then you can define

```<code>Public Function GetOrder(ByVal id As Integer) As Order

    Try
        ...
        Return New Order()
    Catch ex As Exception
        Throw New MyException(ex.Message)
    End Try

End Function
</code>```

As I recall (and it's been a while) trying to return multiple objects from a web method can prove to be extremely troublesome

Body:
We are developing a webservice for a client.  We are not supose to throw SoapExceptions, so instead, we catch every exception server side, and return a custom Exception class.

Public Class Order
...
End Class

Public Class MyException
...
End Class

And then in my webservice a function (webmethod):

Public Function GetOrder(ByVal id As Integer) As Object

    Try
        ...
        Return New Order()
    Catch ex As Exception
        Return New MyException(ex.Message)
    End Try

End Function

The problem now is, that since my webmethod is returning the type [Object]. The wdsl that is generated does not contain the order, or the exception.

I can change the [Object] to [Order] Or [MyException], but only one of them is generated in the wsdl.

So does anybody have an idea of how i should handle this? I want both the MyException type and the Order type in my wsdl, but i just cant get it working.

Thank you all.

Body:
If your definition of MyException

Public Class MyException
        inherits System.Exception
    ...
    End Class

then you shouldn't need to return the Custom Exception just throw it.

then you can define

Public Function GetOrder(ByVal id As Integer) As Order

    Try
        ...
        Return New Order()
    Catch ex As Exception
        Throw New MyException(ex.Message)
    End Try

End Function

As I recall (and it's been a while) trying to return multiple objects from a web method can prove to be extremely troublesome


问:
GNU ARM assembler giving a seemingly irrelevant register in error message

Goal

I'm building a mutex primitive using gcc inline assembly for a CortexM7 target using the LDREX and STREX instructions, following the Barrier Litmus Tests and Cookbook document from ARM.

Code

```<code>static inline void testAcquireLock(unsigned int *lock) {
  unsigned int tempStore1 = 0;
  unsigned int tempStore2 = 0;

  __asm__ volatile(
      "Loop%=:                         \n\t" // "%=" generates unique #
      "LDREX %[ts1], %[lock]           \n\t" // exclusive read lock
      "CMP %[ts1], #0                  \n\t" // check if 0
      "ITT EQ                          \n\t" // block for below conds.
      "STREXEQ %[ts1], %[ts2], %[lock] \n\t" // attempt to ex. store new value
      "CMPEQ %[ts1], #0                \n\t" // test if store suceeded
      "BNE Loop%=                      \n\t" // retry if not
      "DMB                             \n\t" // mem barrier for subsequent reads
      : [lock] "+l"(*lock), [ts1] "=l"(tempStore1), [ts2] "=l"(tempStore2)
      : // inputs
      : "memory");
}
</code>```

Error Message

The only error shown is below. The assembler is referencing R15, which doesn't seem to be used in the generated assembly? Line 191 in the error message corresponds to the first LDREX instruction seen above.

```<code>[build] /tmp/ccEU4dXd.s: Assembler messages:
[build] /tmp/ccEU4dXd.s:191: Error: r15 not allowed here -- `ldrex r1,r3'
[build] /tmp/ccEU4dXd.s:194: Error: r15 not allowed here -- `strexeq r1,r2,r3'
</code>```

Build/Compiler Options

The project is configured with CMake using the following compiler settings:

```<code>target_compile_options(testing
PRIVATE
    -mcpu=cortex-m7
    -mfpu=fpv5-d16
    -mfloat-abi=hard
    -mthumb
    -Wall
    -fdata-sections
    -ffunction-sections
)
</code>```

Compile command that caused the error:

```<code>[build] /usr/bin/arm-none-eabi-gcc -DSTM32F777xx -DUSE_HAL_DRIVER -I<removed>  -g   -mcpu=cortex-m7 -mfpu=fpv5-d16 -mfloat-abi=hard -mthumb -Wall -fdata-sections -ffunction-sections -std=gnu11 -o <removed>.c.obj   -c <removed>.c
</code>```

Research / What I've Tried

After reading I realize there's two (instruction sets? syntax parsers?) for armv7, and the processor can be in one of two modes for these (ARM and THUMB). But I don't fully understand this, and how it affects the parsing of handwritten assembly.

I suspected, because the processor is in thumb mode (-mthumb), it has something to do with my inline alias constraints? Per documentation I tried switching between "+l", "+r", "+h" but it doesn't seem to change anything.

I tried using hardcoded registers "r3, r4, r5" instead of the inline aliases but that gave the same error.

答:
Per @jester's help, I realized I had the wrong constraint on the GCC-inline variable alias for the lock. It should have been "+m", specifying a memory address instead of a register.

<s>I was also de-referencing the address of the lock when I should have been leaving it as a pointer.

I changed [lock] "+l"(*lock) to [lock] "+m"(lock) and it now builds.</s>

Body:
Goal

I'm building a mutex primitive using gcc inline assembly for a CortexM7 target using the LDREX and STREX instructions, following the Barrier Litmus Tests and Cookbook document from ARM.

Code

static inline void testAcquireLock(unsigned int *lock) {
  unsigned int tempStore1 = 0;
  unsigned int tempStore2 = 0;

  __asm__ volatile(
      "Loop%=:                         \n\t" // "%=" generates unique #
      "LDREX %[ts1], %[lock]           \n\t" // exclusive read lock
      "CMP %[ts1], #0                  \n\t" // check if 0
      "ITT EQ                          \n\t" // block for below conds.
      "STREXEQ %[ts1], %[ts2], %[lock] \n\t" // attempt to ex. store new value
      "CMPEQ %[ts1], #0                \n\t" // test if store suceeded
      "BNE Loop%=                      \n\t" // retry if not
      "DMB                             \n\t" // mem barrier for subsequent reads
      : [lock] "+l"(*lock), [ts1] "=l"(tempStore1), [ts2] "=l"(tempStore2)
      : // inputs
      : "memory");
}

Error Message

The only error shown is below. The assembler is referencing R15, which doesn't seem to be used in the generated assembly? Line 191 in the error message corresponds to the first LDREX instruction seen above.

[build] /tmp/ccEU4dXd.s: Assembler messages:
[build] /tmp/ccEU4dXd.s:191: Error: r15 not allowed here -- `ldrex r1,r3'
[build] /tmp/ccEU4dXd.s:194: Error: r15 not allowed here -- `strexeq r1,r2,r3'

Build/Compiler Options

The project is configured with CMake using the following compiler settings:

target_compile_options(testing
PRIVATE
    -mcpu=cortex-m7
    -mfpu=fpv5-d16
    -mfloat-abi=hard
    -mthumb
    -Wall
    -fdata-sections
    -ffunction-sections
)

Compile command that caused the error:

[build] /usr/bin/arm-none-eabi-gcc -DSTM32F777xx -DUSE_HAL_DRIVER -I<removed>  -g   -mcpu=cortex-m7 -mfpu=fpv5-d16 -mfloat-abi=hard -mthumb -Wall -fdata-sections -ffunction-sections -std=gnu11 -o <removed>.c.obj   -c <removed>.c

Research / What I've Tried

After reading I realize there's two (instruction sets? syntax parsers?) for armv7, and the processor can be in one of two modes for these (ARM and THUMB). But I don't fully understand this, and how it affects the parsing of handwritten assembly.

I suspected, because the processor is in thumb mode (-mthumb), it has something to do with my inline alias constraints? Per documentation I tried switching between "+l", "+r", "+h" but it doesn't seem to change anything.

I tried using hardcoded registers "r3, r4, r5" instead of the inline aliases but that gave the same error.


问:
How do I select groups of customer references that don't use a particular service?
Using the following table (customer_table):

customer_ref
product
service

PI-003
cube
streaming

PI-722
cube
streaming

PI-723
cube
streaming

PI-724
cube
streaming

PI-724
pyramid
download

PI-725
cube
streaming

PI-727
cube
streaming

PI-728
cube
streaming

PI-729
cube
streaming

PI-729
pyramid
download

PI-730
cube
streaming

PI-730
sphere
radio

How do I select groups of customer references that don't use a download as a service?

If I do:
SELECT customer_ref FROM customer_table WHERE service <> download

It will return customer_ref PI-724 and PI-729 which do have a service that isn't download but I don't want to return them because under the same customer_ref they do have a service that is download - if that makes sense.

Under my parameters I want to return the following customer_ref:

customer_ref

PI-003

PI-722

PI-723

PI-725

PI-727

PI-728

PI-730

答:
Jointure way</p>
```<code>SELECT c1.customer_ref
FROM customer_table  c1
LEFT JOIN customer_table  c2 ON c1.customer_ref=c2.customer_ref AND c2.service='download'
WHERE c2.customer_ref IS NULL
</code>```

Body:
Jointure way

SELECT c1.customer_ref
FROM customer_table  c1
LEFT JOIN customer_table  c2 ON c1.customer_ref=c2.customer_ref AND c2.service='download'
WHERE c2.customer_ref IS NULL


问:
How to see docker image contents
I did a docker pull and can list the image that's downloaded. I want to see the contents of this image. Did a search on the net but no straight answer.</p>

答:
Perhaps this is nota  very straight forward approach but this one worked for me.
I had an ECR Repo (Amazon Container Service Repository) whose code i wanted to see.

First we need to save the repo you want to access as a tar file. In my case the command went like - docker save .dkr.ecr.us-east-1.amazonaws.com/<name_of_repo>:image-tag > saved-repo.tar

UNTAR the file using the command - tar -xvf saved-repo.tar. You could see many folders and files

Now try to find the file which contain the code you are looking for (if you know some part of the code)
Command for searching the file - grep -iRl "string you want to search" ./

This will make you reach the file. It can happen that even that file is tarred, so untar it using the command mentioned in step 2.

If you dont know the code you are searching for, you will need to go through all the files that you got after step 2 and this can be bit tiring.

All the Best !

Title: How to see docker image contents


问:
Calculating the number of active employees as at previous months with DAX
I am wondering if there's a way to calculate the number of active employees with the use of start date/ termination date without having to create a daily snapshot table.

the employee table is like this:

```<code>Emp_ID.   Start Date        Termination Date      other columns
</code>```

and obviously Dim_date is as usual:

```<code>Date_key      Date            Year.    Month.    Etc...
</code>```

Employee table is connected to Dim_Date via Start Date field, so if we use a DAX formula like :

```<code>ActiveEmps =
CALCULATE (
COUNTX (
    FILTER (
        employee,
        [start date] < MIN ( Dim_Date[Date] )
            && [Termination Date] > MAX ( Dim_Date[Date] )
    ),
    Emp_ID
)
,other filters within calculate context)
</code>```

It won't work and the reason is it's only counting active employees in which their start date falls within the selected time period. (because of the relationship)

答:
I would have done it this way:</p>
```<code>ActiveEmps :=
VAR ThisDate =
    MIN( Dim_Date[Date] )
RETURN
    CALCULATE(
        COUNTROWS( employee ),
        FILTER(
            ALL( employee ),
            employee[Start Date] < ThisDate
                && employee[Termination Date] > ThisDate
        )
    )
</code>```

Body:
I am wondering if there's a way to calculate the number of active employees with the use of start date/ termination date without having to create a daily snapshot table.

the employee table is like this:

Emp_ID.   Start Date        Termination Date      other columns

and obviously Dim_date is as usual:

Date_key      Date            Year.    Month.    Etc...

Employee table is connected to Dim_Date via Start Date field, so if we use a DAX formula like :

ActiveEmps =
CALCULATE (
COUNTX (
    FILTER (
        employee,
        [start date] < MIN ( Dim_Date[Date] )
            && [Termination Date] > MAX ( Dim_Date[Date] )
    ),
    Emp_ID
)
,other filters within calculate context)

It won't work and the reason is it's only counting active employees in which their start date falls within the selected time period. (because of the relationship)

Body:
I would have done it this way:

ActiveEmps :=
VAR ThisDate =
    MIN( Dim_Date[Date] )
RETURN
    CALCULATE(
        COUNTROWS( employee ),
        FILTER(
            ALL( employee ),
            employee[Start Date] < ThisDate
                && employee[Termination Date] > ThisDate
        )
    )


问:
Replace/Rearrange/Swap words in string based on first number in SQL
I have a table containing a column "Description"

This column has multiple rows like this:

```<code>Heartxxx 03-0 ww wwwq
Heart Child 75-0 qweq
Legxxxxxxww 08-0 qaew
</code>```

What I need is the "word" chars consisting of 4 chars starting from the first number to be in the beginning of the string. So expected results:

```<code>03-0 Heartxxx ww wwwq
75-0 Heart Child qweq
08-0 Legxxxxxxww qaew
</code>```

Is this possible and how?

Thanks.

答:
If you are using Postgres you can use a combination of substring() and regexp_replace()

```<code>select substring(the_column from '[0-9-]{4}') || ' '|| regexp_replace(the_column, '[0-9-]{4}\s', '')
from the_table;
</code>```

This:

```<code>with the_table (the_column) as (
  VALUES
    ('Heartxxx 03-0 ww wwwq'),
    ('Heart Child 75-0 qweq'),
    ('Legxxxxxxww 08-0 qaew')
)
select the_column,
       substring(the_column from '[0-9-]{4}') || ' '|| regexp_replace(the_column, '[0-9-]{4}\s', '') as new_word
from the_table;
</code>```

Returns:

the_column            | new_word
----------------------+----------------------
Heartxxx 03-0 ww wwwq | 03-0 Heartxxx ww wwwq
Heart Child 75-0 qweq | 75-0 Heart Child qweq
Legxxxxxxww 08-0 qaew | 08-0 Legxxxxxxww qaew
```

Body:
I have a table containing a column "Description"

This column has multiple rows like this:

Heartxxx 03-0 ww wwwq
Heart Child 75-0 qweq
Legxxxxxxww 08-0 qaew

What I need is the "word" chars consisting of 4 chars starting from the first number to be in the beginning of the string. So expected results:

03-0 Heartxxx ww wwwq
75-0 Heart Child qweq
08-0 Legxxxxxxww qaew

Is this possible and how?

Thanks.

Body:
If you are using Postgres you can use a combination of substring() and regexp_replace()

select substring(the_column from '[0-9-]{4}') || ' '|| regexp_replace(the_column, '[0-9-]{4}\s', '')
from the_table;

This:

with the_table (the_column) as (
  VALUES
    ('Heartxxx 03-0 ww wwwq'),
    ('Heart Child 75-0 qweq'),
    ('Legxxxxxxww 08-0 qaew')
)
select the_column,
       substring(the_column from '[0-9-]{4}') || ' '|| regexp_replace(the_column, '[0-9-]{4}\s', '') as new_word
from the_table;

Returns:

the_column            | new_word
----------------------+----------------------
Heartxxx 03-0 ww wwwq | 03-0 Heartxxx ww wwwq
Heart Child 75-0 qweq | 75-0 Heart Child qweq
Legxxxxxxww 08-0 qaew | 08-0 Legxxxxxxww qaew


问:
Conversion of Infix expression to Postfix
Below is the program i have written to convert a infix expression to postfix. It does give an output but its not always the right one. For example if we input the expression A+B*C-D/F+G , the expected output is ABC*+DF/G+- but rather the program outputs AB+C*D-F/G+. What is the problem in the program.

```<code>#include<iostream>
#include<stack>
#include<string.h>
using namespace std;

int prec(char oper){
    if(oper == '^')
      return 3;
    else if(oper == '*' || '/')
      return 2;
    else if(oper == '+' || '-')
      return 1;
    else
      return -1;
}

string itp(string s){
  stack<char> stack;
  string output = "";
  int num = s.length();

  for(int i = 0 ; i < num ; i++){
    char ch = s[i];

    if((ch>='a' && ch<='z')||(ch>='A' && ch<='Z')||(ch>='0' && ch<='9'))
      output = output + ch;

    else if(ch == '(')
      stack.push('(');

    else if(ch == ')'){
      while(stack.top()!='('){
        output = output + stack.top();
        stack.pop();
      }
      stack.pop();
    }

    else{
      while(!stack.empty() && prec(s[i]) <= prec(stack.top())){
        output = output + stack.top();
        stack.pop();
      }
      stack.push(ch);
    }
    }
  while (!stack.empty()) {
  output = output + stack.top();
  stack.pop();
  }

  return output;
}

int main(){
  string question;
  cout<<"Enter the infix expression : ";
    cin >> question;
    cout<<endl<<"Postfix expression : "<<itp(question);
    return 0;
}
</code>```

答:
Here:

```<code>else if(oper == '*' || '/')
</code>```

you are using || wrongly. If you consider operator precedence (https://en.cppreference.com/w/cpp/language/operator_precedence) you will see that == has higher rank than ||, hence it is parsed as

```<code>else if( (oper == '*') || '\')
</code>```

The first part will evaluate to true or false but as \ is not equal to 0, it will be true always, hence in total the condition is true always.

What you want is

```<code> else if( oper=='*' || oper=='\')
</code>```

Body:
Below is the program i have written to convert a infix expression to postfix. It does give an output but its not always the right one. For example if we input the expression A+B*C-D/F+G , the expected output is ABC*+DF/G+- but rather the program outputs AB+C*D-F/G+. What is the problem in the program.

#include<iostream>
#include<stack>
#include<string.h>
using namespace std;

int prec(char oper){
    if(oper == '^')
      return 3;
    else if(oper == '*' || '/')
      return 2;
    else if(oper == '+' || '-')
      return 1;
    else
      return -1;
}

string itp(string s){
  stack<char> stack;
  string output = "";
  int num = s.length();

  for(int i = 0 ; i < num ; i++){
    char ch = s[i];

    if((ch>='a' && ch<='z')||(ch>='A' && ch<='Z')||(ch>='0' && ch<='9'))
      output = output + ch;

    else if(ch == '(')
      stack.push('(');

    else if(ch == ')'){
      while(stack.top()!='('){
        output = output + stack.top();
        stack.pop();
      }
      stack.pop();
    }

    else{
      while(!stack.empty() && prec(s[i]) <= prec(stack.top())){
        output = output + stack.top();
        stack.pop();
      }
      stack.push(ch);
    }
    }
  while (!stack.empty()) {
  output = output + stack.top();
  stack.pop();
  }

  return output;
}

int main(){
  string question;
  cout<<"Enter the infix expression : ";
    cin >> question;
    cout<<endl<<"Postfix expression : "<<itp(question);
    return 0;
}

Body:
Here:

else if(oper == '*' || '/')

you are using || wrongly. If you consider operator precedence (https://en.cppreference.com/w/cpp/language/operator_precedence) you will see that == has higher rank than ||, hence it is parsed as

else if( (oper == '*') || '\')

The first part will evaluate to true or false but as \ is not equal to 0, it will be true always, hence in total the condition is true always.

What you want is

 else if( oper=='*' || oper=='\')


问:
How to update/upgrade a package using pip?
What is the way to update a package using pip?
those do not work:

```<code>pip update
pip upgrade
</code>```

I know this is a simple question but it is needed as it is not so easy to find (pip documentation doesn't pop up and other questions from stack overflow are relevant but are not exactly about that)

答:
Execute the below command in your command prompt,

```<code>C:\Users\Owner\AppData\Local\Programs\Python\Python310>python -m pip install --upgrade pip
</code>```

Output will be like below,

```<code>Requirement already satisfied: pip in c:\users\owner\appdata\local\programs\python\python310\lib\site-packages (21.2.4)
Collecting pip
  Downloading pip-22.0.3-py3-none-any.whl (2.1 MB)
     |████████████████████████████████| 2.1 MB 3.3 MB/s
Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 21.2.4
    Uninstalling pip-21.2.4:
      Successfully uninstalled pip-21.2.4
Successfully installed pip-22.0.3
</code>```

Body:
What is the way to update a package using pip?
those do not work:

pip update
pip upgrade

I know this is a simple question but it is needed as it is not so easy to find (pip documentation doesn't pop up and other questions from stack overflow are relevant but are not exactly about that)

Body:
Execute the below command in your command prompt,

C:\Users\Owner\AppData\Local\Programs\Python\Python310>python -m pip install --upgrade pip

Output will be like below,

Requirement already satisfied: pip in c:\users\owner\appdata\local\programs\python\python310\lib\site-packages (21.2.4)
Collecting pip
  Downloading pip-22.0.3-py3-none-any.whl (2.1 MB)
     |████████████████████████████████| 2.1 MB 3.3 MB/s
Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 21.2.4
    Uninstalling pip-21.2.4:
      Successfully uninstalled pip-21.2.4
Successfully installed pip-22.0.3


问:
If ID number matches it will return a yes, or will return a "NO" if NO ID number was found to match
I have an excel workbook with 2 sheets. One sheet is called Roster and sheet 2 is called Safety Meeting. On sheet 2(Safety Meeting) is a column with [Id#-name] for those who attended. How do I get “Yes” or “No” return on sheet 1(Roster) on  Column C, for those who attended on sheet 2(Safety Meeting). Also, Roster sheet only has ID# and on Safety Meeting sheet it has ID#andName, but I only need to match the ID number. And if ID# is not there it returns a "NO" because there is no match or its missing.
Note: Im only trying to match ID#s, so Column A on Roster Sheet and Column B on Safety Meeting sheet. Sometimes on Column B of Safety Sheet it will only show "ID#- "(ex. 900003- ). Thats why the ID#s only matters not name
I was trying IF and MATCH functions, but having a column with ID numbers and name is throwing me off.

Roster Sheet
Safety Meeting attendees

答:
Well, you may try using in this was as well,

Formula used in cell C2

```<code>=IF(ISNA(MATCH(A2,--LEFT($G$2:$G$7,FIND("-",$G$2:$G$7)-1),0)),"No","Yes")
</code>```

And Fill Down!

With respect to your workbook the formula should be like this in cell C2 - ROSTER SHEET

```<code>=IF(ISNA(MATCH(A2,--LEFT('Safety Meeting'!$B$2:$B$7,FIND("-",'Safety Meeting'!$B$2:$B$7)-1),0)),"No","Yes")
</code>```

Please adjust the ranges accordingly as per your data, !

Body:
Well, you may try using in this was as well,

Formula used in cell C2

=IF(ISNA(MATCH(A2,--LEFT($G$2:$G$7,FIND("-",$G$2:$G$7)-1),0)),"No","Yes")

And Fill Down!

With respect to your workbook the formula should be like this in cell C2 - ROSTER SHEET

=IF(ISNA(MATCH(A2,--LEFT('Safety Meeting'!$B$2:$B$7,FIND("-",'Safety Meeting'!$B$2:$B$7)-1),0)),"No","Yes")

Please adjust the ranges accordingly as per your data, !


问:
AdWords to GoogleAds v9: UserList selectors and building a list of UserList's (UserListPage in Adwords)
I can't figure out what is used to mimic the UserListPage and Selector behavior from Adwords in Google Ads. If anyone knows the proper classes to use I'd appreciate it. I am trying to retrieve a list of user lists with specific conditions, to then feed the userlist id,name and eligible into an Audience list.</p>

答:
I belive you're looking for UserListService.
Here's an example provided for creating and managing a list https://github.com/googleads/google-ads-python/blob/main/examples/remarketing/add_customer_match_user_list.py

You might also make a search query to retrieve a specific user list like

```<code>SELECT user_list.id, user_list.type, user_list.name FROM user_list
</code>```

Body:
I belive you're looking for UserListService.
Here's an example provided for creating and managing a list https://github.com/googleads/google-ads-python/blob/main/examples/remarketing/add_customer_match_user_list.py

You might also make a search query to retrieve a specific user list like

SELECT user_list.id, user_list.type, user_list.name FROM user_list


问:
Using Avro Schemas that refer other Avro Schema to generate specific record class in Java
I have 2 schemas i.e. LogLine and User schemas

```<code>{
  "namespace": "com.sample.log",
  "type": "record",
  "name": "User",
  "fields": [
    {"name": "username", "type": "string"},
    {"name": "user_type", "type": "string"},
  ]
}
</code>```
```<code>
{
  "namespace": "com.sample.log",
  "type": "record",
  "name": "LogLine",
  "fields": [
    {"name": "ip", "type": "string"},
    {"name": "timestamp",  "type": "long"},
    {"name": "url",  "type": "string"},
    {"name": "referrer",  "type": "string"},
    {"name": "useragent",  "type": "string"},
    {"name": "sessionid",  "type": ["null","int"], "default": null}
    {"name": "user",  "type": ["null","user"], "default": null}
  ]
}
</code>```

I have defined the Logline schema such that I need to refer to another schema "user" schema. I need to generate the specific record class by using the Avro Maven plugin.

When I try to do the same getting error

Failed to execute goal org.apache.avro:avro-maven-plugin:1.8.2:schema (default) on project Logging: Execution default of goal org.apache.avro:avro-maven-plugin:1.8.2:schema failed Undefined Name "User"

答:
Since I was using Avro Maven plugin I need to import the User schema first which is a dependency for Logline schema. Below I have added the import unser the imports section and it worked for me.

```<code>         <plugin>
            <groupId>org.apache.avro</groupId>
            <artifactId>avro-maven-plugin</artifactId>
            <version>${avro.version}</version>
            <executions>
                <execution>
                    <phase>generate-sources</phase>
                    <goals>
                        <goal>schema</goal>
                    </goals>
                    <configuration>
                        <sourceDirectory>${project.basedir}/src/main/resources/typedmessages/</sourceDirectory>
                        <imports>
                            <import>${project.basedir}/src/main/resources/typedmessages/user.avsc</import>
                        </imports>
                        <includes>
                            <include>*.avsc</include>
                        </includes>
                        <outputDirectory>${project.build.directory}/generated-sources</outputDirectory>
                    </configuration>
                </execution>
            </executions>
        </plugin>
</code>```

More details can be found in the blog:
https://feitam.es/use-of-avro-maven-plugin-with-complex-schemas-defined-in-several-files-to-be-reused-in-different-typed-messages/

Body:
I have 2 schemas i.e. LogLine and User schemas

{
  "namespace": "com.sample.log",
  "type": "record",
  "name": "User",
  "fields": [
    {"name": "username", "type": "string"},
    {"name": "user_type", "type": "string"},
  ]
}

{
  "namespace": "com.sample.log",
  "type": "record",
  "name": "LogLine",
  "fields": [
    {"name": "ip", "type": "string"},
    {"name": "timestamp",  "type": "long"},
    {"name": "url",  "type": "string"},
    {"name": "referrer",  "type": "string"},
    {"name": "useragent",  "type": "string"},
    {"name": "sessionid",  "type": ["null","int"], "default": null}
    {"name": "user",  "type": ["null","user"], "default": null}
  ]
}

I have defined the Logline schema such that I need to refer to another schema "user" schema. I need to generate the specific record class by using the Avro Maven plugin.

When I try to do the same getting error

Failed to execute goal org.apache.avro:avro-maven-plugin:1.8.2:schema (default) on project Logging: Execution default of goal org.apache.avro:avro-maven-plugin:1.8.2:schema failed Undefined Name "User"

Body:
Since I was using Avro Maven plugin I need to import the User schema first which is a dependency for Logline schema. Below I have added the import unser the imports section and it worked for me.

         <plugin>
            <groupId>org.apache.avro</groupId>
            <artifactId>avro-maven-plugin</artifactId>
            <version>${avro.version}</version>
            <executions>
                <execution>
                    <phase>generate-sources</phase>
                    <goals>
                        <goal>schema</goal>
                    </goals>
                    <configuration>
                        <sourceDirectory>${project.basedir}/src/main/resources/typedmessages/</sourceDirectory>
                        <imports>
                            <import>${project.basedir}/src/main/resources/typedmessages/user.avsc</import>
                        </imports>
                        <includes>
                            <include>*.avsc</include>
                        </includes>
                        <outputDirectory>${project.build.directory}/generated-sources</outputDirectory>
                    </configuration>
                </execution>
            </executions>
        </plugin>

More details can be found in the blog:
https://feitam.es/use-of-avro-maven-plugin-with-complex-schemas-defined-in-several-files-to-be-reused-in-different-typed-messages/


问:
Unique record in Asp.Net SQL
I asked this question previously but the answers weren't what I was looking for.

I created a table in Asp.net without using code. It contains two columns.

YourUserId and FriendUserId

This is a many to many relationship.

Heres what I want:

There can be multiple records with your name as the UserId, there can also be multiple records with FriendUserId being the same...but there cannot be multiple records with both being the same. For example:

Dave : Greg

Dave : Chris

Greg : Chris

Chris : Greg

is good

Dave : Greg

Dave : Greg

is not good.

I right clicked on the table and chose Indexes/Keys. I then put both columns in the columns section and chose to make the unique. I thought this would make them unique as a whole but individually not unique.

If you go to the Dataset, it show keys next to both columns and says that there is a constraint with both columns being checked.

Is there a way of just making sure that you are not inserting a duplicate copy of a record into the table without individual columns being unique?

I tried controling it with my sql insert statement but that did not work. This is what I tried.

INSERT INTO [FriendRequests] ([UserId], [FriendUserId]) VALUES ('"+UserId+"', '"+PossibleFriend+"') WHERE NOT EXIST (SELECT [UserId], [FriendUserId] FROM [FriendRequests])

That didn't work for some reason.
Thank you for your help!

答:
You should create a compound primary key to prevent duplicate rows.

```<code>ALTER TABLE FriendRequests
ADD CONSTRAINT pk_FriendRequests PRIMARY KEY (UserID, FriendUserID)
</code>```

Or select both columns in table designer and right click to set it as a key.

To prevent self-friendship, you'd create a CHECK constraint:

```<code>ALTER TABLE FriendRequests
ADD CONSTRAINT ck_FriendRequests_NoSelfFriends CHECK (UserID <> FriendUserID)
</code>```

You can add the check constraint in the designer by right clicking anywhere in the table designer, clicking "Check constraints", clicking "add", and setting expression to UserID <> FriendUserID

You might want to look at this question

Title: Unique record in Asp.Net SQL

Body:
You should create a compound primary key to prevent duplicate rows.

ALTER TABLE FriendRequests
ADD CONSTRAINT pk_FriendRequests PRIMARY KEY (UserID, FriendUserID)

Or select both columns in table designer and right click to set it as a key.

To prevent self-friendship, you'd create a CHECK constraint:

ALTER TABLE FriendRequests
ADD CONSTRAINT ck_FriendRequests_NoSelfFriends CHECK (UserID <> FriendUserID)

You can add the check constraint in the designer by right clicking anywhere in the table designer, clicking "Check constraints", clicking "add", and setting expression to UserID <> FriendUserID

You might want to look at this question

OwnerDisplayName: Mehrdad

LastEditorDisplayName: Mehrdad


问:
Extjs: Creating a date object from a AJAX (M$) formatted string?
I have an ExtJS listview with a JsonStore connected to a .NET webservice. One of my columns has the type Date which I want to populate from a .NET DateTime object.

```<code>{
    header: 'Date',
    dateFormat: 'M$',
    type: 'date',
    tpl: '{myTime:date("j. M Y, G:i")}',
    dataIndex: 'myTime'
}
</code>```

My result from the webservice is

/Date(1313669548625)/

I am getting an Invalid date error and a quick test concurs:

```<code>var myTime = '/Date(1313669548625)/';
var dt = new Date(myTime);
</code>```

How can I serve/parse the DateTime object so that my listview can handle the result?

I have interpreted the ExtJS documentation as ExtJS has extended the builtin Date object with parsing of MS Ajax formatted DateTime objects (M$).

答: I checked and the way to use it  is var dt = new Date(Date(1313669548625)) without the slashes and quotes</p>

Body:
I have an ExtJS listview with a JsonStore connected to a .NET webservice. One of my columns has the type Date which I want to populate from a .NET DateTime object.

{
    header: 'Date',
    dateFormat: 'M$',
    type: 'date',
    tpl: '{myTime:date("j. M Y, G:i")}',
    dataIndex: 'myTime'
}

My result from the webservice is

/Date(1313669548625)/

I am getting an Invalid date error and a quick test concurs:

var myTime = '/Date(1313669548625)/';
var dt = new Date(myTime);

How can I serve/parse the DateTime object so that my listview can handle the result?

I have interpreted the ExtJS documentation as ExtJS has extended the builtin Date object with parsing of MS Ajax formatted DateTime objects (M$).


问:
AWS fargate running 24*7
we have an application which runs for 15 mins * 3 times a day. We dont want container to be running always (24*7). Once applicaiton finish, container should stop.
i dont think we can achieve this in AWS Fargate

Will you please recommend any such container services in AWS?

答:
What you want is completely achievable, a task will stop once it's finished, only a service will always stay up and running.

Another solution would be to use an AWS Lambda, as an AWS lambda can run up to 15 minutes. You can also specify a docker image to run your AWS lambda in.

Title: AWS fargate running 24*7


问:
Substract the SUM of orders with the SUM of sales GROUP BY products
I need that the sum of the products sold be subtracted from the sum of the products ordered
I've three tables:

Result = (SUM of or_quantity GROUP BY pr_code) - (SUM of sl_quantity GROUP BY pr_code)

How can I do the syntax?

```<code>
**products**
-------------
id    pr_code
-------------
1     LEGNO1
2     PROD2
3     WOOD

**orders**
---------------------------------------
id    pr_code   or_quantity
---------------------------------------
1     LEGNO1    20
2     LEGNO1    2
3     PROD2 5
4     WOOD  8

**sales**
---------------------------------------
id    pr_code   sl_quantity
---------------------------------------
1     LEGNO1    8
2     LEGNO1    1
3     LEGNO1    1
4     WOOD  3

**Result**
---------------------------------------
id    pr_code   re_quantity
---------------------------------------
1     LEGNO1    12
2     PROD2 5
3     WOOD  5
</code>```

答:
First you have to use UNION ALL between orders & sales and then INNER JOIN with products table.</p>
```<code>SELECT      products.id,MIS.pr_code,
            SUM(MIS.or_quantity-MIS.sl_quantity) AS re_quantity
FROM
(
SELECT      pr_code,or_quantity,0 AS sl_quantity
FROM        orders
UNTON ALL
SELECT      pr_code,0 AS or_quantity,sl_quantity
FROM        sales
)           MIS INNER JOIN products ON
            MIS.pr_code=products.pr_code
GROUP BY    products.id,pr_code
ORDER BY    products.id,pr_code;
</code>```

Body:
I need that the sum of the products sold be subtracted from the sum of the products ordered
I've three tables:

Result = (SUM of or_quantity GROUP BY pr_code) - (SUM of sl_quantity GROUP BY pr_code)

How can I do the syntax?

**products**
-------------
id    pr_code
-------------
1     LEGNO1
2     PROD2
3     WOOD

**orders**
---------------------------------------
id    pr_code   or_quantity
---------------------------------------
1     LEGNO1    20
2     LEGNO1    2
3     PROD2 5
4     WOOD  8

**sales**
---------------------------------------
id    pr_code   sl_quantity
---------------------------------------
1     LEGNO1    8
2     LEGNO1    1
3     LEGNO1    1
4     WOOD  3

**Result**
---------------------------------------
id    pr_code   re_quantity
---------------------------------------
1     LEGNO1    12
2     PROD2 5
3     WOOD  5

Body:
First you have to use UNION ALL between orders & sales and then INNER JOIN with products table.

SELECT      products.id,MIS.pr_code,
            SUM(MIS.or_quantity-MIS.sl_quantity) AS re_quantity
FROM
(
SELECT      pr_code,or_quantity,0 AS sl_quantity
FROM        orders
UNTON ALL
SELECT      pr_code,0 AS or_quantity,sl_quantity
FROM        sales
)           MIS INNER JOIN products ON
            MIS.pr_code=products.pr_code
GROUP BY    products.id,pr_code
ORDER BY    products.id,pr_code;


问:
Attribute Error When Using API to Access Google Calendar
I wrote some basic code to test the Google Calendar API using delegated credentials:

```<code>credentials = service_account.Credentials.from_service_account_file(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)
credentials = credentials.with_subject(SUBJECT_EMAIL)
calendar_service = googleapiclient.discovery.build('calendar', 'v3', credentials)
events = calendar_service.events().list(calendarId='primary').execute()
</code>```

I get an error AttributeError: 'Credentials' object has no attribute 'request' which is triggered on the last line.

I've run similar code many times in the past and haven't ever come across this issue. Any help would be appreciated.

Here is the traceback:

```<code>Traceback (most recent call last):
  File "/Users/jd/PycharmProjects/TorOooCalendarIntegration/main.py", line 14, in <module>
    events = calendar_service.events().list(calendarId='primary').execute()
  File "/Users/jd/PycharmProjects/TorOooCalendarIntegration/venv/lib/python3.10/site-packages/googleapiclient/_helpers.py", line 134, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/Users/jd/PycharmProjects/TorOooCalendarIntegration/venv/lib/python3.10/site-packages/googleapiclient/http.py", line 920, in execute
    resp, content = _retry_request(
  File "/Users/jd/PycharmProjects/TorOooCalendarIntegration/venv/lib/python3.10/site-packages/googleapiclient/http.py", line 191, in _retry_request
    resp, content = http.request(uri, method, *args, **kwargs)
AttributeError: 'Credentials' object has no attribute 'request'
</code>```

答:
Try this is insead.

```<code>import httplib2
import pprint
import sys

from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

def main(argv):
  # Load the json format key that you downloaded from the Google API
  credentials = ServiceAccountCredentials.from_json_keyfile_name(
      SERVICE_ACCOUNT_FILE,
      scopes=SCOPES)
  credentials = credentials.with_subject(SUBJECT_EMAIL)

  # Create an httplib2.Http object to handle our HTTP requests and authorize
  # it with the Credentials.
  http = httplib2.Http()
  http = credentials.authorize(http)

  service = build("calendar", "v3", http=http)

  # List all the tasklists for the account.
  events = service.events().list(calendarId='primary').execute(http=http)
  pprint.pprint(events)

if __name__ == '__main__':
  main(sys.argv)
</code>```

Shamelessly copied and altered from tasks.py

Body:
I wrote some basic code to test the Google Calendar API using delegated credentials:

credentials = service_account.Credentials.from_service_account_file(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)
credentials = credentials.with_subject(SUBJECT_EMAIL)
calendar_service = googleapiclient.discovery.build('calendar', 'v3', credentials)
events = calendar_service.events().list(calendarId='primary').execute()

I get an error AttributeError: 'Credentials' object has no attribute 'request' which is triggered on the last line.

I've run similar code many times in the past and haven't ever come across this issue. Any help would be appreciated.

Here is the traceback:

Traceback (most recent call last):
  File "/Users/jd/PycharmProjects/TorOooCalendarIntegration/main.py", line 14, in <module>
    events = calendar_service.events().list(calendarId='primary').execute()
  File "/Users/jd/PycharmProjects/TorOooCalendarIntegration/venv/lib/python3.10/site-packages/googleapiclient/_helpers.py", line 134, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/Users/jd/PycharmProjects/TorOooCalendarIntegration/venv/lib/python3.10/site-packages/googleapiclient/http.py", line 920, in execute
    resp, content = _retry_request(
  File "/Users/jd/PycharmProjects/TorOooCalendarIntegration/venv/lib/python3.10/site-packages/googleapiclient/http.py", line 191, in _retry_request
    resp, content = http.request(uri, method, *args, **kwargs)
AttributeError: 'Credentials' object has no attribute 'request'

Body:
Try this is insead.

import httplib2
import pprint
import sys

from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

def main(argv):
  # Load the json format key that you downloaded from the Google API
  credentials = ServiceAccountCredentials.from_json_keyfile_name(
      SERVICE_ACCOUNT_FILE,
      scopes=SCOPES)
  credentials = credentials.with_subject(SUBJECT_EMAIL)

  # Create an httplib2.Http object to handle our HTTP requests and authorize
  # it with the Credentials.
  http = httplib2.Http()
  http = credentials.authorize(http)

  service = build("calendar", "v3", http=http)

  # List all the tasklists for the account.
  events = service.events().list(calendarId='primary').execute(http=http)
  pprint.pprint(events)

if __name__ == '__main__':
  main(sys.argv)

Shamelessly copied and altered from tasks.py


问:
How to filter an associative arrays using array of keys in PHP?
I have an associative arrays and an array of keys.

```<code>$A = array('a'=>'book', 'b'=>'pencil', 'c'=>'pen');
$B = array('a', 'b');
</code>```

How I build an associative array from all element of $A where the key is in $B?
For the example above, the answer should be

```<code>$C = array('a'=>'book', 'b'=>'pencil');
</code>```

答:
Here's a simple solution which checks that the key exists in $A before appending it to $C

```<code>$A = array('a'=>'book', 'b'=>'pencil', 'c'=>'pen');
$B = array('a', 'b');

$C = array();
foreach ($B as $bval) {
  // If the $B key exists in $A, add it to $C
  if (isset($A[$bval])) $C[$bval] = $A[$bval];
}

var_dump($C);

// Prints:
array(2) {
  ["a"]=>
  string(4) "book"
  ["b"]=>
  string(6) "pencil"
}
</code>```

Body:
I have an associative arrays and an array of keys.

$A = array('a'=>'book', 'b'=>'pencil', 'c'=>'pen');
$B = array('a', 'b');

How I build an associative array from all element of $A where the key is in $B?
For the example above, the answer should be

$C = array('a'=>'book', 'b'=>'pencil');

Body:
Here's a simple solution which checks that the key exists in $A before appending it to $C

$A = array('a'=>'book', 'b'=>'pencil', 'c'=>'pen');
$B = array('a', 'b');

$C = array();
foreach ($B as $bval) {
  // If the $B key exists in $A, add it to $C
  if (isset($A[$bval])) $C[$bval] = $A[$bval];
}

var_dump($C);

// Prints:
array(2) {
  ["a"]=>
  string(4) "book"
  ["b"]=>
  string(6) "pencil"
}


问:
Python function overload with mypy
I have recently started adding type definitions to my Python code and I am stuck at this problem.

Given a foo.py file:

from typing import overload

@overload
def foo(a: int) -> int: ...

@overload
def foo(b: float) -> int: ...

def foo(a: int = 0, b: float = 0) -> int:
    # implementation not relevant
    return 42
```
<p>When I run <code>mypy</code> I get the following error:</p>
<pre class="lang-sh prettyprint-override"><code>$ mypy foo.py
foo.py:10: error: Overloaded function implementation does not accept all possible arguments of signature 2  [misc]
</code>```

I cannot understand where the error is.

In Java I can do that:

interface IFoo {
        int foo(int a);
        int foo(float b);
}

public class Foo implements IFoo {
        public int foo(int a) {
                return this.foo(a, 0f);
        }

        public int foo(float b) {
                return this.foo(0, b);
        }

        private int foo(int a, float b) {
                // implementation not relevant
                return 42;
        }

        public static void main (String[] args) {
                Foo obj = new Foo();
                System.out.println(obj.foo(1));
                System.out.println(obj.foo(1f));
                System.out.println(obj.foo(1, 1f));
        }
}
```

Can anybody explain me what I am doing wrong in the Python code?

答:
One problem with your code is that when one call your function with an argument:

```<code>foo(x)
</code>```

that x is always for the a argument, thank to this signature:

```<code>def foo(a: int) -> int: ...
</code>```

and your:

```<code>def foo(b: float) -> int: ...
</code>```

is never matched.

Title: Python function overload with mypy

Body:
I have recently started adding type definitions to my Python code and I am stuck at this problem.

Given a foo.py file:

from typing import overload

@overload
def foo(a: int) -> int: ...

@overload
def foo(b: float) -> int: ...

def foo(a: int = 0, b: float = 0) -> int:
    # implementation not relevant
    return 42

When I run mypy I get the following error:

$ mypy foo.py
foo.py:10: error: Overloaded function implementation does not accept all possible arguments of signature 2  [misc]

I cannot understand where the error is.

In Java I can do that:

interface IFoo {
        int foo(int a);
        int foo(float b);
}

public class Foo implements IFoo {
        public int foo(int a) {
                return this.foo(a, 0f);
        }

        public int foo(float b) {
                return this.foo(0, b);
        }

        private int foo(int a, float b) {
                // implementation not relevant
                return 42;
        }

        public static void main (String[] args) {
                Foo obj = new Foo();
                System.out.println(obj.foo(1));
                System.out.println(obj.foo(1f));
                System.out.println(obj.foo(1, 1f));
        }
}

Can anybody explain me what I am doing wrong in the Python code?

Body:
One problem with your code is that when one call your function with an argument:

foo(x)

that x is always for the a argument, thank to this signature:

def foo(a: int) -> int: ...

and your:

def foo(b: float) -> int: ...

is never matched.


问:
How do I remove parentheses and single quotation marks from my output?
How do I remove parentheses and single quotation marks from my output? There is no requirement in my code to show brackets and single quotation marks.

person = "    xx   "
what_he_said = "    abc！"
print(f"{person.split()}曾经说过，“{what_he_said.split()}”")
```
<p>This is the actual output:</p>
```['xx']曾经说过，“['abc！']”
```

I don't want to output the middle brackets and quotation marks.
I'm using Python 3.10, the IDE is pycharm.

答:
The result of split is a list. If you want the str without surrounding space, you should use strip

person = "    xx   "
what_he_said = "    abc！"
print(f"{person.strip()}曾经说过，“{what_he_said.strip()}”")
```

Body:
How do I remove parentheses and single quotation marks from my output? There is no requirement in my code to show brackets and single quotation marks.

person = "    xx   "
what_he_said = "    abc！"
print(f"{person.split()}曾经说过，“{what_he_said.split()}”")

This is the actual output:

['xx']曾经说过，“['abc！']”

I don't want to output the middle brackets and quotation marks.
I'm using Python 3.10, the IDE is pycharm.


问:
Moq: How to Setup ToDictionary
I want to mock a Linq expression that returns a Dictionary<string, string>

```<code>Dictionary<string, string> properties = new Dictionary<string, string>()
{
    { "Service", "serviceTest" }
}
</code>```
```<code>equipment.SetProperties(dmsElement.Properties.ToDictionary(x => x.Definition.Name, x => x.Value));
</code>```

Here is the unit test

```<code>fakeEquipment.Setup(e => e.Properties.ToDictionary(It.IsAny<Func<IDmsElementProperty, string>>(), It.IsAny<Func<IDmsElementProperty, string>>())).Returns(properties);

</code>```

I am getting the following error:

System.NotSupportedException: 'Unsupported expression: ... => ....ToDictionary<IDmsElementProperty, string, string>(It.IsAny<Func<IDmsElementProperty, string>>(), It.IsAny<Func<IDmsElementProperty, string>>())

How can I setup the ToDictionary method to retrieve the expected values?

答:
You cannot mock the ToDictionary method because it is an extension method found in the System.Enumerable type. That method is going to enumerate your .Properties property no matter what.
You can and should, however, mock directly e.Properties.

You can return an implementation of the IPropertyCollection interface, or if it's not that much of a problem write a very simple adapter exposing an underlying collection (be it a dictionary or a list).
If you have access to an existing class (say, ListPropertyCollection<T>), you could just instantiate it.

Title: Moq: How to Setup ToDictionary

Body:
I want to mock a Linq expression that returns a Dictionary<string, string>

Dictionary<string, string> properties = new Dictionary<string, string>()
{
    { "Service", "serviceTest" }
}

equipment.SetProperties(dmsElement.Properties.ToDictionary(x => x.Definition.Name, x => x.Value));

Here is the unit test

fakeEquipment.Setup(e => e.Properties.ToDictionary(It.IsAny<Func<IDmsElementProperty, string>>(), It.IsAny<Func<IDmsElementProperty, string>>())).Returns(properties);

I am getting the following error:

System.NotSupportedException: 'Unsupported expression: ... => ....ToDictionary<IDmsElementProperty, string, string>(It.IsAny<Func<IDmsElementProperty, string>>(), It.IsAny<Func<IDmsElementProperty, string>>())

How can I setup the ToDictionary method to retrieve the expected values?


问:
how to get the provider access token in next-auth
Hi I am new to nextjs and for authentication I am using next-auth. The users can log in using Google and when they are logged in and authenticated I want to get the access_token given by provider in this case Google.
Although I can get that inside signIn callback function but is there a way to globally access that?</p>

答:
for Credentials login

use callbacks like this

```<code>callbacks: {
    jwt: async ({ token, user }) => {
        user && (token.user = user)
        return token
    },
    session: async ({ session, token }) => {
        session.user = token.user
        return session
    }
}
</code>```

then in page import

```<code>import { getSession ,useSession, signIn, signOut } from "next-auth/react";
</code>```

and use this for get token

```<code>const { data: token, status } = useSession()
console.log(token)
</code>```

for get sessin use this

```<code>const { data: session, status } = useSession()
console.log(session)
</code>```

Body:
for Credentials login

use callbacks like this

callbacks: {
    jwt: async ({ token, user }) => {
        user && (token.user = user)
        return token
    },
    session: async ({ session, token }) => {
        session.user = token.user
        return session
    }
}

then in page import

import { getSession ,useSession, signIn, signOut } from "next-auth/react";

and use this for get token

const { data: token, status } = useSession()
console.log(token)

for get sessin use this

const { data: session, status } = useSession()
console.log(session)


问:
Where the images get stored in Azure Kubernetes Cluster after pulling from Azure Container Registry?
I am using Kubernetes to deploy all my microservices provided by Azure Kubernetes Services.

Whenever I release an update of my microservice which is getting frequently from last one month, it pulls the new image from the Azure Container Registry.

I was trying to figure out where do these images reside in the cluster?

Just like Docker stores, the pulled images in /var/lib/docker & since the Kubernetes uses Docker under the hood may be it stores the images somewhere too.

But if this is the case, how can I delete the old images from the cluster that are not in use anymore?

答:
Clusters with Linux node pools created on Kubernetes v1.19 or greater default to containerd for its container runtime (Container runtime configuration).

To manually remove unused images on a node running containerd:

Identity node names:

kubectl get nodes
```
<p>Start an interactive debugging container on a node (Connect with SSH to Azure Kubernetes Service):</p>
<pre class="lang-sh prettyprint-override"><code>kubectl debug node/aks-agentpool-11045208-vmss000003 -it --image=mcr.microsoft.com/aks/fundamental/base-ubuntu:v0.0.11
</code>```

Setup crictl on the debugging container (check for newer releases of crictl):

The host node's filesystem is available at /host, so configure crictl to use the host node's containerd.sock.

curl -sL https://github.com/kubernetes-sigs/cri-tools/releases/download/v1.23.0/crictl-v1.23.0-linux-amd64.tar.gz | tar xzf - -C /usr/local/bin \
    && export CONTAINER_RUNTIME_ENDPOINT=unix:///host/run/containerd/containerd.sock IMAGE_SERVICE_ENDPOINT=unix:///host/run/containerd/containerd.sock
```
<p>Remove unused images on the node:</p>
<pre class="lang-sh prettyprint-override"><code>crictl rmi --prune
</code>```

Body:
Clusters with Linux node pools created on Kubernetes v1.19 or greater default to containerd for its container runtime (Container runtime configuration).

To manually remove unused images on a node running containerd:

Identity node names:

kubectl get nodes

Start an interactive debugging container on a node (Connect with SSH to Azure Kubernetes Service):

kubectl debug node/aks-agentpool-11045208-vmss000003 -it --image=mcr.microsoft.com/aks/fundamental/base-ubuntu:v0.0.11

Setup crictl on the debugging container (check for newer releases of crictl):

The host node's filesystem is available at /host, so configure crictl to use the host node's containerd.sock.

curl -sL https://github.com/kubernetes-sigs/cri-tools/releases/download/v1.23.0/crictl-v1.23.0-linux-amd64.tar.gz | tar xzf - -C /usr/local/bin \
    && export CONTAINER_RUNTIME_ENDPOINT=unix:///host/run/containerd/containerd.sock IMAGE_SERVICE_ENDPOINT=unix:///host/run/containerd/containerd.sock

Remove unused images on the node:

crictl rmi --prune


问:
*ngFor is not working angular for calling data from api
I am trying to get data from api and show it on frontend but *ngFor is not working I checked all variables are working correctly and the data is showing in console.log but not showing on frontend, below I have shared you screenshot for the same

Thank you in advance,

答: you declear the projects property in any but this is array.so  projects property declear projects:any=[]; like this</p>


问:
Android Studio - how to find nearest array location of my current location
the schema is I have 3 locations and I need to find where is the nearest location depending on my current location.

how to achieve that ?

and is it possible to use FusedLocation instead of LocationManager ?

答:
you can use

```<code>double distance = SphericalUtil.computeDistanceBetween(place1.getPosition(), place2.getPosition());
        distance = (int)Math.round(distance);
</code>```

place1 its current location

```<code>LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

               place1 = new MarkerOptions().position(latLng);
</code>```

place2 its one of our location

```<code>place2 = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Position 1");
</code>```

I use this function to switch to another activity if the distance is less than 5 meters

```<code>if (distance <= 5) {
            Intent intent = new Intent();
            intent.setClass(activity1.this, activity2.class);
            startActivity(intent);
        }
</code>```

Body:
you can use

double distance = SphericalUtil.computeDistanceBetween(place1.getPosition(), place2.getPosition());
        distance = (int)Math.round(distance);

place1 its current location

LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

               place1 = new MarkerOptions().position(latLng);

place2 its one of our location

place2 = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Position 1");

I use this function to switch to another activity if the distance is less than 5 meters

if (distance <= 5) {
            Intent intent = new Intent();
            intent.setClass(activity1.this, activity2.class);
            startActivity(intent);
        }


问:
loop (for) in R to read separately many files (from list of files)
I have a list of Excel files that I want to read.
As they have sometimes different columns I want to read them separately, giving them their location as name.

I'm new in loops, and I cannot get to name them differently. This is what I tried, but reads only one (of 40) file.

```<code>myfiles = list.files(path="Invoices/GLS/",
                     pattern = "0_*", full.names = TRUE, recursive = T)
myfiles

for(val in myfiles) {
   val <- read_excel(val)
}
</code>```

答:
Read them in a list using sapply -

```<code>myfiles = list.files(path="Invoices/GLS/", pattern = "0_*",
                     full.names = TRUE, recursive = TRUE)

val <- sapply(myfiles, readxl::read_excel, simplify = FALSE)
</code>```

names(val) should return path of the files.

Body:
I have a list of Excel files that I want to read.
As they have sometimes different columns I want to read them separately, giving them their location as name.

I'm new in loops, and I cannot get to name them differently. This is what I tried, but reads only one (of 40) file.

myfiles = list.files(path="Invoices/GLS/",
                     pattern = "0_*", full.names = TRUE, recursive = T)
myfiles

for(val in myfiles) {
   val <- read_excel(val)
}

Body:
Read them in a list using sapply -

myfiles = list.files(path="Invoices/GLS/", pattern = "0_*",
                     full.names = TRUE, recursive = TRUE)

val <- sapply(myfiles, readxl::read_excel, simplify = FALSE)

names(val) should return path of the files.


问:
How could I bind docker container to specific external interface
I have two network interfaces, eth0 and eth1,

How could I bind all docker container to eth1, and let all network traffic go out and in via the eth1

Thanks~

update

I tried to bind to the eth1 with 133.130.60.36.

But i still got no luck, i still get the eth0 IP as the public IP in the container. the network flow is not go out via eth1

```<code>➜  ~  docker run -d --name Peach_1 -p 133.130.60.36::9998 -ti sample/ubuntu-vnc-selenium-firefox

➜  ~  docker ps
CONTAINER ID        IMAGE                                 COMMAND                CREATED             STATUS              PORTS                                     NAMES
eb28f0d1c337        sample/ubuntu-vnc-selenium-firefox   "/opt/bin/run_sele_s   4 minutes ago       Up 4 minutes        5901/tcp, 133.130.60.36:32768->9998/tcp   Peach_1

➜  ~  docker exec -ti Peach_1 zsh

➜  /  curl ipecho.net/plain ; echo
133.130.101.114
</code>```

答:
Putting IP in -p only works for traffic that comes to server, for traffic that leaving server you can assign static local IP to each container, Then change source IP in iptables or snat. Here is a sample iptables rule:

```<code>iptables -t nat -I POSTROUTING -p all -s 172.20.128.2 ! -d 172.20.128.2 -j SNAT --to-source YourInterfaceIP
</code>```

Body:
I have two network interfaces, eth0 and eth1,

How could I bind all docker container to eth1, and let all network traffic go out and in via the eth1

Thanks~

update

I tried to bind to the eth1 with 133.130.60.36.

But i still got no luck, i still get the eth0 IP as the public IP in the container. the network flow is not go out via eth1

➜  ~  docker run -d --name Peach_1 -p 133.130.60.36::9998 -ti sample/ubuntu-vnc-selenium-firefox

➜  ~  docker ps
CONTAINER ID        IMAGE                                 COMMAND                CREATED             STATUS              PORTS                                     NAMES
eb28f0d1c337        sample/ubuntu-vnc-selenium-firefox   "/opt/bin/run_sele_s   4 minutes ago       Up 4 minutes        5901/tcp, 133.130.60.36:32768->9998/tcp   Peach_1

➜  ~  docker exec -ti Peach_1 zsh

➜  /  curl ipecho.net/plain ; echo
133.130.101.114

Body:
Putting IP in -p only works for traffic that comes to server, for traffic that leaving server you can assign static local IP to each container, Then change source IP in iptables or snat. Here is a sample iptables rule:

iptables -t nat -I POSTROUTING -p all -s 172.20.128.2 ! -d 172.20.128.2 -j SNAT --to-source YourInterfaceIP


问:
Why should we use sp for font sizes in Android?

Possible Duplicate:

  Difference of px, dp, dip and sp in android

I am new to Android and I was trying out this tutorial

In that tutorial, they used the unit "sp" for textSize attribute and "dp" for other attributes.

Please tell me how sp differs from dp?

答:
The dp has constant ratio transition to px: dp = px * ratio. Where ratio will never change on any particular device.

While sp (s for scaled) has scalable ratio: sp = px * ratio * scale. Where ratio never changes, but scale is user configurable. This scale can be used by people who need larger font sizes, for example, to use device more comfortably.


问:
No module named 'google' when using protobuf in python
I am trying to write a simple program using protobuf in python on MAC. But I am getting "no module named 'google'" error. I installed protobuf using 'brew install protobuf'.

Below are the files.

addressbook.proto:

```<code>syntax = "proto3";

package tutorial;

message Person {
  optional string name = 1;
  optional int32 id = 2;
  optional string email = 3;

  enum PhoneType {
    MOBILE = 0;
    HOME = 1;
    WORK = 2;
  }

  message PhoneNumber {
    optional string number = 1;
    optional PhoneType type = 2;
  }

  repeated PhoneNumber phones = 4;
}

message AddressBook {
  repeated Person people = 1;
}
</code>```

I used protoc command as below to generate addressbook_pb2.py

```<code>protoc -I=. --python_out=. ./addressbook.proto --experimental_allow_proto3_optional
</code>```

test.py:

```<code>import addressbook_pb2
import sys

def writeData():
    return

if __name__ == "__main__":
    writeData()
</code>```

I am getting below error.

```<code>Traceback (most recent call last):
  File "/Users/ka/Desktop/proto_python/test.py", line 1, in <module>
    import addressbook_pb2
  File "/Users/ka/Desktop/proto_python/addressbook_pb2.py", line 5, in <module>
    from google.protobuf import descriptor as _descriptor
ModuleNotFoundError: No module named 'google'
</code>```

Can some one please help me how to resolve this issue.

答:
try with

```<code>pip install protobuf (or pip3 install...)
</code>```

And if you don't even had pip installed then

```<code>sudo apt-get install python-pip  (or python3-pip)
</code>```

Body:
I am trying to write a simple program using protobuf in python on MAC. But I am getting "no module named 'google'" error. I installed protobuf using 'brew install protobuf'.

Below are the files.

addressbook.proto:

syntax = "proto3";

package tutorial;

message Person {
  optional string name = 1;
  optional int32 id = 2;
  optional string email = 3;

  enum PhoneType {
    MOBILE = 0;
    HOME = 1;
    WORK = 2;
  }

  message PhoneNumber {
    optional string number = 1;
    optional PhoneType type = 2;
  }

  repeated PhoneNumber phones = 4;
}

message AddressBook {
  repeated Person people = 1;
}

I used protoc command as below to generate addressbook_pb2.py

protoc -I=. --python_out=. ./addressbook.proto --experimental_allow_proto3_optional

test.py:

import addressbook_pb2
import sys

def writeData():
    return

if __name__ == "__main__":
    writeData()

I am getting below error.

Traceback (most recent call last):
  File "/Users/ka/Desktop/proto_python/test.py", line 1, in <module>
    import addressbook_pb2
  File "/Users/ka/Desktop/proto_python/addressbook_pb2.py", line 5, in <module>
    from google.protobuf import descriptor as _descriptor
ModuleNotFoundError: No module named 'google'

Can some one please help me how to resolve this issue.

Body:
try with

pip install protobuf (or pip3 install...)

And if you don't even had pip installed then

sudo apt-get install python-pip  (or python3-pip)


问:
Getting Tokyo stock price data to appear on Google spreadsheet
I have no problem retrieving price data of US stocks. For example, to retrieve Apple price data, this formula =GOOGLEFINANCE("AAPL","changepct")/100 works fine. When I tried to retrieve Tokyo stocks price data, this formula GOOGLEFINANCE("TYO:1969","changepct")/100 cannot work. Both formulas look similar. I cannot figure out why. Is it because Tokyo stocks are not supported by Google Finance?

答: A simple solution is to use the German stock exchanges and convert the euro rates to dollars or yen with googlefinance. So for example: DIP for KDDI</p>


答:
If i'm correct that what you want is to get sum of product orders and sum of product sales right?</p>
```<code>SELECT products.pr_code,
    (SELECT IFNULL(SUM(orders.or_quantity),0) FROM orders WHERE orders.pr_code = products.pr_code) AS sum_orders,
    (SELECT IFNULL(SUM(sales.sl_quantity),0) FROM sales WHERE sales.pr_code = products.pr_code) AS sum_sales,
    (SELECT IFNULL(SUM(orders.or_quantity),0) FROM orders WHERE orders.pr_code = products.pr_code) - (SELECT IFNULL(SUM(sales.sl_quantity),0) FROM sales WHERE sales.pr_code = products.pr_code) as re_quality
FROM products LEFT JOIN sales
ON (products.pr_code = sales.pr_code) GROUP BY products.pr_code
</code>```

Title: Substract the SUM of orders with the SUM of sales GROUP BY products

Body:
I need that the sum of the products sold be subtracted from the sum of the products ordered
I've three tables:

Result = (SUM of or_quantity GROUP BY pr_code) - (SUM of sl_quantity GROUP BY pr_code)

How can I do the syntax?

**products**
-------------
id    pr_code
-------------
1     LEGNO1
2     PROD2
3     WOOD

**orders**
---------------------------------------
id    pr_code   or_quantity
---------------------------------------
1     LEGNO1    20
2     LEGNO1    2
3     PROD2 5
4     WOOD  8

**sales**
---------------------------------------
id    pr_code   sl_quantity
---------------------------------------
1     LEGNO1    8
2     LEGNO1    1
3     LEGNO1    1
4     WOOD  3

**Result**
---------------------------------------
id    pr_code   re_quantity
---------------------------------------
1     LEGNO1    12
2     PROD2 5
3     WOOD  5

Body:
If i'm correct that what you want is to get sum of product orders and sum of product sales right?

SELECT products.pr_code,
    (SELECT IFNULL(SUM(orders.or_quantity),0) FROM orders WHERE orders.pr_code = products.pr_code) AS sum_orders,
    (SELECT IFNULL(SUM(sales.sl_quantity),0) FROM sales WHERE sales.pr_code = products.pr_code) AS sum_sales,
    (SELECT IFNULL(SUM(orders.or_quantity),0) FROM orders WHERE orders.pr_code = products.pr_code) - (SELECT IFNULL(SUM(sales.sl_quantity),0) FROM sales WHERE sales.pr_code = products.pr_code) as re_quality
FROM products LEFT JOIN sales
ON (products.pr_code = sales.pr_code) GROUP BY products.pr_code