问:
npm Install error- node modules but no package-lock.json
I'm getting an error with my npm install and would love some help/advice.

```<code>ELIFECYCLE
ENOENT
spawn bash
yorkie@2.0.0 install `node bin/install.js`
spawn bash ENOENT
Failed at the yorkie@2.0.0 install script
This is probably not a problem with npm. There is likely additional logging output above.
</code>```

My node path is set in my environmental variables. My node version is 10.24.1 and npm version is 6.4.1
I am using nvm for windows to manage versions.
Whenever I run npm install I get this error, and node modules is created, but package-lock is not.
I have deleted node modules and ran npm cache clear with no success.

Any tips appreciated!

答:
This solved it for me!

```<code>npm config delete script-shell
</code>```

Source: https://stackoverflow.com/a/46006249/15787997

Body:
I'm getting an error with my npm install and would love some help/advice.

ELIFECYCLE
ENOENT
spawn bash
yorkie@2.0.0 install `node bin/install.js`
spawn bash ENOENT
Failed at the yorkie@2.0.0 install script
This is probably not a problem with npm. There is likely additional logging output above.

My node path is set in my environmental variables. My node version is 10.24.1 and npm version is 6.4.1
I am using nvm for windows to manage versions.
Whenever I run npm install I get this error, and node modules is created, but package-lock is not.
I have deleted node modules and ran npm cache clear with no success.

Any tips appreciated!

Body:
This solved it for me!

npm config delete script-shell

Source: https://stackoverflow.com/a/46006249/15787997


来源: stackexchange

问:
How to use asyncio to download files on s3 bucket
I'm using the following code to download all my files in a s3 bucket:

```<code>def main(bucket_name, destination_dir):
    bucket = boto3.resource('s3').Bucket(bucket_name)
    for obj in bucket.objects.all():
        if obj.key.endswith('/'):
            continue
        destination = '%s/%s' % (bucket_name, obj.key)
        if not os.path.exists(destination):
            os.makedirs(os.path.dirname(destination), exist_ok=True)
        bucket.download_file(obj.key, destination)
</code>```

I would like to know how to make this asynchronous, if possible.

Thank u in advance.

答:
You can use the generate_presigned_url method of the s3 client to get the URL with AWS credentials (see docs), and then send a request to download a file through the async HTTP client (aiohttp for example)

aiohttp applies URL canonicalization which can cause issues if the Key includes spaces or non-ASCII characters. Using URL(..., encoded=True) will fix this issue.

```<code>import boto3
import asyncio
from aiohttp import client
from yarl import URL

bucket = 'some-bucket-name'

s3_client = boto3.client('s3')
s3_objs = s3_client.list_objects(Bucket=bucket)['Contents']

async def download_s3_obj(key: str, aiohttp_session: client.ClientSession):
    request_url = s3_client.generate_presigned_url('get_object', {
        'Bucket': bucket,
        'Key': key
    })

    async with aiohttp_session.get(URL(request_url, encoded=True)) as response:
        file_path = 'some-local-folder-name/' + key.split('/')[-1]

        with open(file_path, 'wb') as file:
            file.write(await response.read())

async def get_tasks():
    session = client.ClientSession()

    return [download_s3_obj(f['Key'], session) for f in s3_objs], session

loop = asyncio.get_event_loop()
tasks, session = loop.run_until_complete(get_tasks())
loop.run_until_complete(asyncio.gather(*tasks))

loop.run_until_complete(session.close())
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using the following code to download all my files in a s3 bucket:

def main(bucket_name, destination_dir):
    bucket = boto3.resource('s3').Bucket(bucket_name)
    for obj in bucket.objects.all():
        if obj.key.endswith('/'):
            continue
        destination = '%s/%s' % (bucket_name, obj.key)
        if not os.path.exists(destination):
            os.makedirs(os.path.dirname(destination), exist_ok=True)
        bucket.download_file(obj.key, destination)

I would like to know how to make this asynchronous, if possible.

Thank u in advance.

Body:
You can use the generate_presigned_url method of the s3 client to get the URL with AWS credentials (see docs), and then send a request to download a file through the async HTTP client (aiohttp for example)

aiohttp applies URL canonicalization which can cause issues if the Key includes spaces or non-ASCII characters. Using URL(..., encoded=True) will fix this issue.

import boto3
import asyncio
from aiohttp import client
from yarl import URL

bucket = 'some-bucket-name'

s3_client = boto3.client('s3')
s3_objs = s3_client.list_objects(Bucket=bucket)['Contents']

async def download_s3_obj(key: str, aiohttp_session: client.ClientSession):
    request_url = s3_client.generate_presigned_url('get_object', {
        'Bucket': bucket,
        'Key': key
    })

    async with aiohttp_session.get(URL(request_url, encoded=True)) as response:
        file_path = 'some-local-folder-name/' + key.split('/')[-1]

        with open(file_path, 'wb') as file:
            file.write(await response.read())

async def get_tasks():
    session = client.ClientSession()

    return [download_s3_obj(f['Key'], session) for f in s3_objs], session

loop = asyncio.get_event_loop()
tasks, session = loop.run_until_complete(get_tasks())
loop.run_until_complete(asyncio.gather(*tasks))

loop.run_until_complete(session.close())

ContentLicense: CC BY-SA 4.0


问:
JavaScript isset() equivalent
In PHP you can do if(isset($array['foo'])) { ... }. In JavaScript you often use if(array.foo) { ... } to do the same, but this is not exactly the same statement. The condition will also evaluate to false if array.foo does exists but is false or 0 (and probably other values as well).

What is the perfect equivalent of PHP's isset in JavaScript?

In a broader sense, a general, complete guide on JavaScript's handling of variables that don't exist, variables without a value, etc. would be convenient.

Update: 11 years and 11 months ago I posted this question, and wow, it still gets a lot of activity. Now, I'm pretty sure that when I wrote this, I only wanted to know how to check for the presence of a property in an associative array (a.k.a. dictionary), and as such the correct (for me) answers involve hasOwnProperty or the in operator. I wasn't interested in checking local or global variables.

But while I remember that well, that intent is not quite clear in the question as written, or even directly contradicted by it! I never mentioned the associative array, and PHP's isset does also do those other things. Let this be a lesson to all of us about how important it is to properly state your requirements in a question, and also how global variables, local variables, object properties, dictionary keys and what-have-you aren't Huey, Dewey, and Louie.

In the meantime (heh), many many people have provided answers to that effect as well, so for those of you who found this question through Google, well, I'm glad my vagueness helped in a way I guess. Anyway, just wanted to clarify that.

答:
This is the most concise equivalent of Php's isset() :

```<code>if(var == undefined)
</code>```

true  this is var !isset

false this is var isset

Title: JavaScript isset() equivalent

Body:
This is the most concise equivalent of Php's isset() :

if(var == undefined)

true  this is var !isset

false this is var isset


问:
Unable to create Azure BlobContainerClient as I am getting a java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/TSFBuilder
I am facing an error while trying to create a Azure blobConatinerClient using the credentials I have.

credentials is instanceOf StorageSharedKeyCredential
and
endpoint is instanceOf String

This is the code

```<code> public BlobContainerClient initBlobClient() {
    BlobContainerClient blobContainerClient;

    StorageSharedKeyCredential credential = new StorageSharedKeyCredential(ACCOUNT_NAME, ACCOUNT_KEY);

    String endpoint = String.format(Locale.ROOT, "https://test.blob.core.windows.net");

// Getting the ClassDefError here
    BlobServiceClient storageClient = new BlobServiceClientBuilder().endpoint(endpoint).credential(credential).buildClient();

    blobContainerClient = storageClient.getBlobContainerClient(CONTAINTER_NAME);

    return blobContainerClient;
  }
</code>```

and this is the stacktrace this triggers

```<code>    at com.fasterxml.jackson.dataformat.xml.XmlMapper.<init>(XmlMapper.java:122)
    at com.azure.core.util.serializer.JacksonAdapter.<init>(JacksonAdapter.java:76)
    at com.azure.core.util.serializer.JacksonAdapter.createDefaultSerializerAdapter(JacksonAdapter.java:109)
    at com.azure.core.http.rest.RestProxy.createDefaultSerializer(RestProxy.java:615)
    at com.azure.core.http.rest.RestProxy.create(RestProxy.java:667)
    at com.azure.storage.blob.implementation.ServicesImpl.<init>(ServicesImpl.java:58)
    at com.azure.storage.blob.implementation.AzureBlobStorageImpl.<init>(AzureBlobStorageImpl.java:216)
    at com.azure.storage.blob.implementation.AzureBlobStorageBuilder.build(AzureBlobStorageBuilder.java:93)
    at com.azure.storage.blob.BlobServiceAsyncClient.<init>(BlobServiceAsyncClient.java:108)
    at com.azure.storage.blob.BlobServiceClientBuilder.buildAsyncClient(BlobServiceClientBuilder.java:109)
    at com.azure.storage.blob.BlobServiceClientBuilder.buildClient(BlobServiceClientBuilder.java:82)
</code>```

And these are azure dependencies I have. I also added Jackson, since one of the StackOverflow comments said that would solve the issue but it didn't.

```<code>    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.12.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.azure/azure-storage-blob -->
    <dependency>
      <groupId>com.azure</groupId>
      <artifactId>azure-storage-blob</artifactId>
      <version>12.9.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.azure/azure-core -->
    <dependency>
      <groupId>com.azure</groupId>
      <artifactId>azure-core</artifactId>
      <version>1.3.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/io.projectreactor/reactor-core -->
    <dependency>
      <groupId>io.projectreactor</groupId>
      <artifactId>reactor-core</artifactId>
      <version>3.3.4.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>com.microsoft.azure</groupId>
      <artifactId>azure-storage</artifactId>
      <version>8.6.3</version>
    </dependency>

    <dependency>
      <groupId>com.microsoft.azure</groupId>
      <artifactId>azure</artifactId>
      <version>1.33.0</version>
    </dependency>
</code>```

Can someone please point out if something is missing, Or if I have to change anything here?

答:
I encountered same problem on clojure which also uses Azure's java library. In my case there was some other libraries that we were using which had jackson fasterxml dependency. azure-storage-blob also uses same dependency with a different version.

For us among those adding higher version of jason fasterxml dependency to dependencies solved our issue.

First you can find all the dependency tree, then analyzing the tree you can find most update version of jason fasterxml.

Below dependencies worked for us

```<code>                 [com.azure/azure-storage-blob "12.14.3"]
                 [com.fasterxml.jackson.core/jackson-databind "2.13.1"]
                 [com.fasterxml.jackson.core/jackson-core "2.13.1"]]

</code>```

You can find more details here

Body:
I am facing an error while trying to create a Azure blobConatinerClient using the credentials I have.

credentials is instanceOf StorageSharedKeyCredential
and
endpoint is instanceOf String

This is the code

 public BlobContainerClient initBlobClient() {
    BlobContainerClient blobContainerClient;

    StorageSharedKeyCredential credential = new StorageSharedKeyCredential(ACCOUNT_NAME, ACCOUNT_KEY);

    String endpoint = String.format(Locale.ROOT, "https://test.blob.core.windows.net");

// Getting the ClassDefError here
    BlobServiceClient storageClient = new BlobServiceClientBuilder().endpoint(endpoint).credential(credential).buildClient();

    blobContainerClient = storageClient.getBlobContainerClient(CONTAINTER_NAME);

    return blobContainerClient;
  }

and this is the stacktrace this triggers

    at com.fasterxml.jackson.dataformat.xml.XmlMapper.<init>(XmlMapper.java:122)
    at com.azure.core.util.serializer.JacksonAdapter.<init>(JacksonAdapter.java:76)
    at com.azure.core.util.serializer.JacksonAdapter.createDefaultSerializerAdapter(JacksonAdapter.java:109)
    at com.azure.core.http.rest.RestProxy.createDefaultSerializer(RestProxy.java:615)
    at com.azure.core.http.rest.RestProxy.create(RestProxy.java:667)
    at com.azure.storage.blob.implementation.ServicesImpl.<init>(ServicesImpl.java:58)
    at com.azure.storage.blob.implementation.AzureBlobStorageImpl.<init>(AzureBlobStorageImpl.java:216)
    at com.azure.storage.blob.implementation.AzureBlobStorageBuilder.build(AzureBlobStorageBuilder.java:93)
    at com.azure.storage.blob.BlobServiceAsyncClient.<init>(BlobServiceAsyncClient.java:108)
    at com.azure.storage.blob.BlobServiceClientBuilder.buildAsyncClient(BlobServiceClientBuilder.java:109)
    at com.azure.storage.blob.BlobServiceClientBuilder.buildClient(BlobServiceClientBuilder.java:82)

And these are azure dependencies I have. I also added Jackson, since one of the StackOverflow comments said that would solve the issue but it didn't.

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.12.0</version>
    </dependency>

    <dependency>
      <groupId>com.azure</groupId>
      <artifactId>azure-storage-blob</artifactId>
      <version>12.9.0</version>
    </dependency>

    <dependency>
      <groupId>com.azure</groupId>
      <artifactId>azure-core</artifactId>
      <version>1.3.0</version>
    </dependency>

    <dependency>
      <groupId>io.projectreactor</groupId>
      <artifactId>reactor-core</artifactId>
      <version>3.3.4.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>com.microsoft.azure</groupId>
      <artifactId>azure-storage</artifactId>
      <version>8.6.3</version>
    </dependency>

    <dependency>
      <groupId>com.microsoft.azure</groupId>
      <artifactId>azure</artifactId>
      <version>1.33.0</version>
    </dependency>

Can someone please point out if something is missing, Or if I have to change anything here?

Body:
I encountered same problem on clojure which also uses Azure's java library. In my case there was some other libraries that we were using which had jackson fasterxml dependency. azure-storage-blob also uses same dependency with a different version.

For us among those adding higher version of jason fasterxml dependency to dependencies solved our issue.

First you can find all the dependency tree, then analyzing the tree you can find most update version of jason fasterxml.

Below dependencies worked for us

                 [com.azure/azure-storage-blob "12.14.3"]
                 [com.fasterxml.jackson.core/jackson-databind "2.13.1"]
                 [com.fasterxml.jackson.core/jackson-core "2.13.1"]]

You can find more details here


问:
MoviePy: How to convert horizontal video to vertical
I have the following 1920x1080 video:

I need to convert it to 1080x1920, and zoom in in the center so that it looks like this:

by using moviepy. I can't seem to figure out how to make this work.

Body:
this works fine (from 1920x1080 to 1080x1920):

video = video.resize(height=1920)
video = video.crop(x1=1166.6,y1=0,x2=2246.6,y2=1920)


问:
Is functions in redux reducers ok?
I am writing some reducers with Redux-Sagas, Im quite new to this and all reducers we have now dont have any thing like I am about to do. Started to question myself if its the right thing to do.

In this case I have an INITIAL_STATE thats contains a dataProp, this data has an prop that is an array of users. Now I create a editUser form, when the user is updated I get the updated user back. to update that user in the ReactView I do like this:

```<code>const updateUser = (users, user) => {
                //Update user and return array
               };

   [actions.updateUserSuccess]: (state, payload) => ({
            ...state,
            viewData: {
                ...state.viewData,
                users: updateUser(...state.viewData.Users, payload)
            },
            loadingUser: false,
        }),
</code>```

And the question, is it ok to put a method to handle a thing like this on top of the reducer file?

答:
Sure, that's totally fine, and in fact we have a docs page on "SplittingReducer Logic" that even talks about that.

That said, you really should be using our official Redux Toolkit package to write your Redux logic.  It will greatly simplify all your Redux code.  In particular, it uses Immer to let you write "mutating" syntax in your reducers, and turns that into safe and correct immutable updates.  No more object spreads!

Title: Is functions in redux reducers ok?

Body:
I am writing some reducers with Redux-Sagas, Im quite new to this and all reducers we have now dont have any thing like I am about to do. Started to question myself if its the right thing to do.

In this case I have an INITIAL_STATE thats contains a dataProp, this data has an prop that is an array of users. Now I create a editUser form, when the user is updated I get the updated user back. to update that user in the ReactView I do like this:

const updateUser = (users, user) => {
                //Update user and return array
               };

   [actions.updateUserSuccess]: (state, payload) => ({
            ...state,
            viewData: {
                ...state.viewData,
                users: updateUser(...state.viewData.Users, payload)
            },
            loadingUser: false,
        }),

And the question, is it ok to put a method to handle a thing like this on top of the reducer file?


问:
Can Standard .NET CMS systems be made to work with ASP.NET MVC
Has anyone successfully used a CMS developed for standard ASP.NET with ASP.NET MVC?

I currently use Immediacy CMS and it seems to be quite tightly coupled with standard ASP.NET, but I'd really like to start using ASP.NET MVC.

Are there any CMS systems out there directed at MVC?

How could I persuade my employer to move to ASP.NET MVC?

答:
N2 CMS has an example site in ASP.NET MVC that I've been playing around with that works quite nicely - note that the code is now hosted on Google Code.

The problem you've got is that many CMS' already do a lot of "routing" in that the pages you are requesting/editing don't actually exist on disk, but are all in a data store of some kind, and there's an HttpHandler or ISAPI Filter sitting in front of ASP.NET to intercept the requests and work out what should be happening.

OwnerDisplayName: mdresser

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Zhaph - Ben Duguid


问:
Method Overloading in Excel COM Interop
I am having a lot of troubles with method overloading here and have no idea why only one method gets called each time regardless the number of parameters I pass into. Below is the sample code.

```<code>[ClassInterface(ClassInterfaceType.AutoDual), ComVisible(true)]
public class myClass
{
    //constructor
    public myClass() {}

    //base method
    public string myfunction(string id, string pk) {return results;}

    //overloading method 1
    public string myfunction(string id, string pk, string param1) { return results;}

    //overloading method 2
    public string myfunction(string id, string pk, string param1, string param2) {return results;}

    [ComRegisterFunctionAttribute]
        public static void RegisterFunction(Type type)
        {

            Registry.ClassesRoot.CreateSubKey(
              GetSubKeyName(type, "Programmable"));
            RegistryKey key = Registry.ClassesRoot.OpenSubKey(
              GetSubKeyName(type, "InprocServer32"), true);
            key.SetValue("",
              System.Environment.SystemDirectory + @"\mscoree.dll",
              RegistryValueKind.String);
        }
        [ComUnregisterFunctionAttribute]
        public static void UnregisterFunction(Type type)
        {

            Registry.ClassesRoot.DeleteSubKey(
              GetSubKeyName(type, "Programmable"), false);
        }
        private static string GetSubKeyName(Type type,
          string subKeyName)
        {
            System.Text.StringBuilder s =
              new System.Text.StringBuilder();
            s.Append(@"CLSID\{");
            s.Append(type.GUID.ToString().ToUpper());
            s.Append(@"}\");
            s.Append(subKeyName);
            return s.ToString();
        }

}
</code>```

So when I tested it in Excel, the base method worked fine and I could get the expected value. However, it would fail if I tried the rest two functions using method overloading. They simply didn't get called for some reason. Am I missing something in the code? Can anyone help me please?  Thanks very much.

Edit:

Through some experiments, it occurs to me that there only 1 method can be recognized, which normally is the first method. So if I swap the order between base method and overloading method 1, the overloading method 1 will be called instead of the base method. Looks like the whole class just gets stuck in the first method and wouldn't go on.

答:
COM Interop does not support overloading: see the "Overloading" section in this MSDN article.

The Type Library Exporter will rename overloaded members by appending a prefix (e.g. _2).

Title: Method Overloading in Excel COM Interop

Body:
I am having a lot of troubles with method overloading here and have no idea why only one method gets called each time regardless the number of parameters I pass into. Below is the sample code.

[ClassInterface(ClassInterfaceType.AutoDual), ComVisible(true)]
public class myClass
{
    //constructor
    public myClass() {}

    //base method
    public string myfunction(string id, string pk) {return results;}

    //overloading method 1
    public string myfunction(string id, string pk, string param1) { return results;}

    //overloading method 2
    public string myfunction(string id, string pk, string param1, string param2) {return results;}

    [ComRegisterFunctionAttribute]
        public static void RegisterFunction(Type type)
        {

            Registry.ClassesRoot.CreateSubKey(
              GetSubKeyName(type, "Programmable"));
            RegistryKey key = Registry.ClassesRoot.OpenSubKey(
              GetSubKeyName(type, "InprocServer32"), true);
            key.SetValue("",
              System.Environment.SystemDirectory + @"\mscoree.dll",
              RegistryValueKind.String);
        }
        [ComUnregisterFunctionAttribute]
        public static void UnregisterFunction(Type type)
        {

            Registry.ClassesRoot.DeleteSubKey(
              GetSubKeyName(type, "Programmable"), false);
        }
        private static string GetSubKeyName(Type type,
          string subKeyName)
        {
            System.Text.StringBuilder s =
              new System.Text.StringBuilder();
            s.Append(@"CLSID\{");
            s.Append(type.GUID.ToString().ToUpper());
            s.Append(@"}\");
            s.Append(subKeyName);
            return s.ToString();
        }

}

So when I tested it in Excel, the base method worked fine and I could get the expected value. However, it would fail if I tried the rest two functions using method overloading. They simply didn't get called for some reason. Am I missing something in the code? Can anyone help me please?  Thanks very much.

Edit:

Through some experiments, it occurs to me that there only 1 method can be recognized, which normally is the first method. So if I swap the order between base method and overloading method 1, the overloading method 1 will be called instead of the base method. Looks like the whole class just gets stuck in the first method and wouldn't go on.


问:
How to set up a google calendar web hook in Nodejs?
I looked at the google calendar node js api and this wasn’t clear.

How do I set up a web hook using the Nodejs google calendar library?

I want to tell google to ping a server when my clients has either added or changed an appointment on his google calendar?

How can I use Nodejs to set up the watch?

答:
The Google Calendar API provides push notifications that let you watch for changes to resources (Webhooks).

Google Calendar Push notification
View in Fusebit

const calendar = googleClient.calendar('v3');
const watchResponse = await calendar.events.watch({
  resource: {
      id: uuidv4(),
      type: 'web_hook',
      address: 'Your webhook address here'
    },
    calendarId: 'primary'
  });

const { data } = watchResponse;
console.log('Calendar Webhook created', data);

```


问:
New-SelfSignedCertificate to create certificate gives Access Denied
I'm trying to use New-SelfSignedCertificate in PowerShell to create a certificate on Windows 10, but the command gives me a permissions error. I'm using an Administrator account.

Command:

```<code>New-SelfSignedCertificate -Type Custom -Subject "CN=Contoso Software, O=Contoso Corporation, C=US" -KeyUsage DigitalSignature -FriendlyName MyCert -CertStoreLocation "Cert:\LocalMachine\My"
</code>```

Output:

```<code>New-SelfSignedCertificate : CertEnroll::CX509Enrollment::_CreateRequest: Access denied. 0x80090010 (-2146893808 NTE_PERM)
At line:1 char:1
+ New-SelfSignedCertificate -Type Custom -Subject "CN=Contoso Software, ..."
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [New-SelfSignedCertificate], Exception
    + FullyQualifiedErrorId : System.Exception,Microsoft.CertificateServices.Commands.NewSelfSignedCertificateCommand
</code>```

答: Not the right answer.  Run-as Privileges are the problem.</p>

Body:
I'm trying to use New-SelfSignedCertificate in PowerShell to create a certificate on Windows 10, but the command gives me a permissions error. I'm using an Administrator account.

Command:

New-SelfSignedCertificate -Type Custom -Subject "CN=Contoso Software, O=Contoso Corporation, C=US" -KeyUsage DigitalSignature -FriendlyName MyCert -CertStoreLocation "Cert:\LocalMachine\My"

Output:

New-SelfSignedCertificate : CertEnroll::CX509Enrollment::_CreateRequest: Access denied. 0x80090010 (-2146893808 NTE_PERM)
At line:1 char:1
+ New-SelfSignedCertificate -Type Custom -Subject "CN=Contoso Software, ..."
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [New-SelfSignedCertificate], Exception
    + FullyQualifiedErrorId : System.Exception,Microsoft.CertificateServices.Commands.NewSelfSignedCertificateCommand


问:
Xcode: Keep order of plist
I have a question depending plists in Xcode.
I'm loading images from a plist into a NSDictionary (the paths of the images) and then display the images from that dictionary but they are not shown in the same order like in the plist.

How can I manage that the images are shown in the same order?

答: You can add "order" parameter in plist so when you take this you will take according to "order" parameter... But actually if you are not use threading or nsoperation it must be work can you share the code snippet? </p>

Title: Xcode: Keep order of plist


问:
Group by month and week
I would like to know what is the best way to group my hash of
{date->value} in month and week.

```<code>{Sat, 23 Apr 2016=>6.0, Mon, 06 Mar 2017=>9.0, Tue, 04 Apr 2017=>13.0, Tue, 11 Apr 2017=>25.0}
</code>```

I would like a result like:

```<code>{Apr 2016=>6, Mar 2017=>9, Apr 2017=>38}
</code>```

I tried with Groupdate/Chartkick but I am not getting a good result.

Thanks

答: Even easier: data.transform_keys! { |k| k.strftime("%B %Y") }

Title: Group by month and week

Body:
I would like to know what is the best way to group my hash of
{date->value} in month and week.

{Sat, 23 Apr 2016=>6.0, Mon, 06 Mar 2017=>9.0, Tue, 04 Apr 2017=>13.0, Tue, 11 Apr 2017=>25.0}

I would like a result like:

{Apr 2016=>6, Mar 2017=>9, Apr 2017=>38}

I tried with Groupdate/Chartkick but I am not getting a good result.

Thanks


问:
What is the best way to have a div overlap multiple table cells
I am building a calendar web page using jQuery and asp.net-mvc similar to this and I can't figure out how this example is supporting events that span multiple days  (it shows the event as a single item across multiple days in the view).

Using firebug, I see that the calendar is simply a table:

but I can't figure out how they have the event  div that crosses multiple cells of a table like the "Long Event" in the image below?

答:
You can have the " overlap" effect with some css.

HTML for a table cell (a day of your calendar)

```<code><td>
  <div>
    <div class="a occupied"> occupied [AV]  [1]  </div>
    <div class="spacer occupied "> </div>
    <div class="b occupied"> occupied [AV]  [1]</div>
  </div>
</td>
</code>```

CSS for inner divs

```<code> table.vertical-table tr > td > div > .checkin,
 table.vertical-table tr > td > div > .checkout,
 table.vertical-table tr > td > div > .occupied {
    background: #139ff7;
    color: white;
    font-weight: bold;
 }
</code>```

CSS for a specific events ending(top) or beginning(bottom) in the during daytime

```<code>table.vertical-table tr > td > div > div.a,
table.vertical-table tr > td > div > div.b {
  height: 45%;
}
</code>```

More customisation needed of course for every personal case, but I guess the code above is giving you the idea.

Body:
You can have the " overlap" effect with some css.

HTML for a table cell (a day of your calendar)

<td>
  <div>
    <div class="a occupied"> occupied [AV]  [1]  </div>
    <div class="spacer occupied "> </div>
    <div class="b occupied"> occupied [AV]  [1]</div>
  </div>
</td>

CSS for inner divs

 table.vertical-table tr > td > div > .checkin,
 table.vertical-table tr > td > div > .checkout,
 table.vertical-table tr > td > div > .occupied {
    background: #139ff7;
    color: white;
    font-weight: bold;
 }

CSS for a specific events ending(top) or beginning(bottom) in the during daytime

table.vertical-table tr > td > div > div.a,
table.vertical-table tr > td > div > div.b {
  height: 45%;
}

More customisation needed of course for every personal case, but I guess the code above is giving you the idea.


问:
Data changes only after closing the app in the background in SwiftUI
I´m using core data to safe date in my iOS app. On button click I safe data to core data. In a separate tab the data is used in computed properties to get averages out of the added values and display them to the view. This works but the data only updates after the app is closed in the background. I've tried to pass the data into a viewModel and pass the data with an Environment Object but that didn't work (Sorry if this isn't very precise, that's my first post).</p>
```<code>import SwiftUI

struct HabitStatistics: View {

    @Environment(\.managedObjectContext) private var viewContext

    @FetchRequest(sortDescriptors: []) var habits: FetchedResults<Habit>

        // MARK: Computing EarlyBird Property
        var filteredEarlyBird: Int {
            var earlyBird = 0
            var counter = 0
            for h in habits {
                let component = Calendar.current.dateComponents([.hour, .minute], from: h.getUpTime ?? Date())
                let hour = component.hour ?? 0
                let minute = component.minute ?? 0
                let difference = (hour * 60 + minute) - 270
                earlyBird += difference
                counter += 1
            }
            if counter != 0 {
                earlyBird /= counter
                return earlyBird
            } else {
                return 0
            }
        }

            // MARK: Computing ateMeat Property
        var filteredMeat: Int {
            var total: Int {
                if habits.count == 0 {
                    return 1
                } else {
                    return habits.count
                }
            }
            var count = 0
            var perc = 0
            for h in habits {
                if h.ateMeat == 0 {
                    count += 1
                }
            }
            perc = count * 100 / total
            return perc
        }

            // MARK: Computing ateSuger Property
        var filteredSugar: Int {
            var total: Int {
                if habits.count == 0 {
                    return 1
                } else {
                    return habits.count
                }
            }
            var count = 0
            var perc = 0
            for h in habits {
                if h.ateSugar == 0 {
                    count += 1
                }
            }
            perc = count * 100 / total
            return perc
        }

            // MARK: Computing didSports Property
        var filteredSport: Int {
            var total: Int {
                if habits.count == 0 {
                    return 1
                } else {
                    return habits.count
                }
            }
            var count = 0
            var perc = 0
            for h in habits {
                if h.didSports == 1 {
                    count += 1
                }
            }
            perc = count * 100 / total
            return perc
        }

    var body: some View {

        VStack(alignment: .leading, spacing: 0) {
                // Headline
            Text("This Week")
                .bold()
            VStack {
                RectangleCard(textLeft: "Meatfree", textRight: "\(filteredMeat) %")
                RectangleCard(textLeft: "Sugarfree", textRight: "\(filteredSugar) %")
                RectangleCard(textLeft: "Sportsrate", textRight: "\(filteredSport)%")
                RectangleCard(textLeft: "Average Time Loss", textRight: "\(filteredEarlyBird) Min lost")

            }
        }

    }
}

import SwiftUI
struct DailyForm: View {

    @Environment(\.managedObjectContext) private var viewContext
    @EnvironmentObject var model: HabitModel

    @State var getUpTime = Date()
    @State var ateMeat = InputOptions.nein
    @State var ateSugar = InputOptions.nein
    @State var didSports = InputOptions.nein

    var body: some View {

        VStack {
            HStack {
                Button("Clear") {
                    clear()
                }
                Spacer()
                Button("Add") {
                    addHabit()
                    clear()
                }

            }
            .padding()

            ScrollView (showsIndicators: false) {

                VStack (alignment: .leading) {
                    AddPickerValues(getUpTime: $getUpTime,
                                    ateMeat: $ateMeat,
                                    ateSugar: $ateSugar,
                                    didSports: $didSports)
                }
                .padding(.horizontal)
            }

        }
    }

    func clear() {
        getUpTime = Date()
        ateMeat = InputOptions.nein
        ateSugar = InputOptions.nein
        didSports = InputOptions.nein
    }

    func addHabit() {
        let habit = Habit(context: viewContext)
        habit.id = UUID()
        habit.getUpTime = getUpTime
        habit.ateMeat = convertValue(habit: ateMeat)
        habit.ateSugar = convertValue(habit: ateSugar)
        habit.didSports = convertValue(habit: didSports)

        do {
            try viewContext.save()
        }
        catch {
                // Couldn't save the recipe
        }
    }

    func convertValue (habit: InputOptions) -> Int {
        if habit == InputOptions.nein {
            return 0
        } else {
            return 1
        }
    }
}
</code>```

答:
This is working:

Main:

```<code>@main
struct coretatatestApp: App {
    let persistenceController = PersistenceController.shared

    var body: some Scene {
        WindowGroup {
            TabView {
                DailyForm()
                    .tabItem {
                        Label("Daily Form", systemImage: "calendar" )
                    }
                HabitStatistics()
                    .tabItem {
                        Label("Statistics", systemImage: "chart.bar.fill" )
                    }
            }
            .environment(\.managedObjectContext, persistenceController.container.viewContext)
        }
    }
}
</code>```

Statistics:

```<code>struct HabitStatistics: View {

    @Environment(\.managedObjectContext) private var viewContext

    @FetchRequest(sortDescriptors: []) var habits: FetchedResults<Habit>

    // MARK: Computing EarlyBird Property
    var filteredEarlyBird: Int {
        var earlyBird = 0
        var counter = 0
        for h in habits {
            let component = Calendar.current.dateComponents([.hour, .minute], from: h.getUpTime ?? Date())
            let hour = component.hour ?? 0
            let minute = component.minute ?? 0
            let difference = (hour * 60 + minute) - 270
            earlyBird += difference
            counter += 1
        }
        if counter != 0 {
            earlyBird /= counter
            return earlyBird
        } else {
            return 0
        }
    }

    // MARK: Computing ateMeat Property
    var filteredMeat: Int {
        var total: Int {
            if habits.count == 0 {
                return 1
            } else {
                return habits.count
            }
        }
        var count = 0
        var perc = 0
        for h in habits {
            if h.ateMeat == false {
                count += 1
            }
        }
        perc = count * 100 / total
        return perc
    }

    // MARK: Computing ateSuger Property
    var filteredSugar: Int {
        var total: Int {
            if habits.count == 0 {
                return 1
            } else {
                return habits.count
            }
        }
        var count = 0
        var perc = 0
        for h in habits {
            if h.ateSugar == false {
                count += 1
            }
        }
        perc = count * 100 / total
        return perc
    }

    // MARK: Computing didSports Property
    var filteredSport: Int {
        var total: Int {
            if habits.count == 0 {
                return 1
            } else {
                return habits.count
            }
        }
        var count = 0
        var perc = 0
        for h in habits {
            if h.didSports == true {
                count += 1
            }
        }
        perc = count * 100 / total
        return perc
    }

    var body: some View {
        VStack(alignment: .leading, spacing: 0) {
            // Headline
            Text("This Week")
                .bold()
            VStack {
                Text("Meatfree \(filteredMeat) %")
                     Text("Sugarfree \(filteredSugar) %")
                     Text("Sportsrate \(filteredSport)%")
                     Text("Average Time Loss \(filteredEarlyBird) Min lost")
            }
        }
    }
}
</code>```

Daily Form:

```<code>struct DailyForm: View {

    @Environment(\.managedObjectContext) private var viewContext
//    @EnvironmentObject var model: HabitModel
    @FetchRequest(sortDescriptors: []) var habits: FetchedResults<Habit>

    @State var getUpTime = Date()
    @State var ateMeat = false
    @State var ateSugar = false
    @State var didSports = false

    var body: some View {

        VStack {
            HStack {
                Button("Clear") {
                    clear()
                }
                Spacer()
                Button("Add") {
                    addHabit()
                    clear()
                }

            }
            .padding()

            ScrollView (showsIndicators: false) {

                VStack (alignment: .leading) {
                    DatePicker("Get up Time", selection: $getUpTime, displayedComponents: .hourAndMinute)
                    Toggle("Ate Meat?", isOn: $ateMeat)
                    Toggle("Ate Sugar?", isOn: $ateSugar)
                    Toggle("Did Sports?", isOn: $didSports)
                }
                .padding(.horizontal)
            }

        }
    }

    func clear() {
        getUpTime = Date()
        ateMeat = false
        ateSugar = false
        didSports = false
    }

    func addHabit() {
        let habit = Habit(context: viewContext)
        habit.id = UUID()
        habit.getUpTime = getUpTime
        habit.ateMeat = ateMeat
        habit.ateSugar = ateSugar
        habit.didSports = didSports

        do {
            try viewContext.save()
        }
        catch {
            // Couldn't save the recipe
        }
    }
}
</code>```

Body:
I´m using core data to safe date in my iOS app. On button click I safe data to core data. In a separate tab the data is used in computed properties to get averages out of the added values and display them to the view. This works but the data only updates after the app is closed in the background. I've tried to pass the data into a viewModel and pass the data with an Environment Object but that didn't work (Sorry if this isn't very precise, that's my first post).

import SwiftUI

struct HabitStatistics: View {

    @Environment(\.managedObjectContext) private var viewContext

    @FetchRequest(sortDescriptors: []) var habits: FetchedResults<Habit>

        // MARK: Computing EarlyBird Property
        var filteredEarlyBird: Int {
            var earlyBird = 0
            var counter = 0
            for h in habits {
                let component = Calendar.current.dateComponents([.hour, .minute], from: h.getUpTime ?? Date())
                let hour = component.hour ?? 0
                let minute = component.minute ?? 0
                let difference = (hour * 60 + minute) - 270
                earlyBird += difference
                counter += 1
            }
            if counter != 0 {
                earlyBird /= counter
                return earlyBird
            } else {
                return 0
            }
        }

            // MARK: Computing ateMeat Property
        var filteredMeat: Int {
            var total: Int {
                if habits.count == 0 {
                    return 1
                } else {
                    return habits.count
                }
            }
            var count = 0
            var perc = 0
            for h in habits {
                if h.ateMeat == 0 {
                    count += 1
                }
            }
            perc = count * 100 / total
            return perc
        }

            // MARK: Computing ateSuger Property
        var filteredSugar: Int {
            var total: Int {
                if habits.count == 0 {
                    return 1
                } else {
                    return habits.count
                }
            }
            var count = 0
            var perc = 0
            for h in habits {
                if h.ateSugar == 0 {
                    count += 1
                }
            }
            perc = count * 100 / total
            return perc
        }

            // MARK: Computing didSports Property
        var filteredSport: Int {
            var total: Int {
                if habits.count == 0 {
                    return 1
                } else {
                    return habits.count
                }
            }
            var count = 0
            var perc = 0
            for h in habits {
                if h.didSports == 1 {
                    count += 1
                }
            }
            perc = count * 100 / total
            return perc
        }

    var body: some View {

        VStack(alignment: .leading, spacing: 0) {
                // Headline
            Text("This Week")
                .bold()
            VStack {
                RectangleCard(textLeft: "Meatfree", textRight: "\(filteredMeat) %")
                RectangleCard(textLeft: "Sugarfree", textRight: "\(filteredSugar) %")
                RectangleCard(textLeft: "Sportsrate", textRight: "\(filteredSport)%")
                RectangleCard(textLeft: "Average Time Loss", textRight: "\(filteredEarlyBird) Min lost")

            }
        }

    }
}

import SwiftUI
struct DailyForm: View {

    @Environment(\.managedObjectContext) private var viewContext
    @EnvironmentObject var model: HabitModel

    @State var getUpTime = Date()
    @State var ateMeat = InputOptions.nein
    @State var ateSugar = InputOptions.nein
    @State var didSports = InputOptions.nein

    var body: some View {

        VStack {
            HStack {
                Button("Clear") {
                    clear()
                }
                Spacer()
                Button("Add") {
                    addHabit()
                    clear()
                }

            }
            .padding()

            ScrollView (showsIndicators: false) {

                VStack (alignment: .leading) {
                    AddPickerValues(getUpTime: $getUpTime,
                                    ateMeat: $ateMeat,
                                    ateSugar: $ateSugar,
                                    didSports: $didSports)
                }
                .padding(.horizontal)
            }

        }
    }

    func clear() {
        getUpTime = Date()
        ateMeat = InputOptions.nein
        ateSugar = InputOptions.nein
        didSports = InputOptions.nein
    }

    func addHabit() {
        let habit = Habit(context: viewContext)
        habit.id = UUID()
        habit.getUpTime = getUpTime
        habit.ateMeat = convertValue(habit: ateMeat)
        habit.ateSugar = convertValue(habit: ateSugar)
        habit.didSports = convertValue(habit: didSports)

        do {
            try viewContext.save()
        }
        catch {
                // Couldn't save the recipe
        }
    }

    func convertValue (habit: InputOptions) -> Int {
        if habit == InputOptions.nein {
            return 0
        } else {
            return 1
        }
    }
}

Body:
This is working:

Main:

@main
struct coretatatestApp: App {
    let persistenceController = PersistenceController.shared

    var body: some Scene {
        WindowGroup {
            TabView {
                DailyForm()
                    .tabItem {
                        Label("Daily Form", systemImage: "calendar" )
                    }
                HabitStatistics()
                    .tabItem {
                        Label("Statistics", systemImage: "chart.bar.fill" )
                    }
            }
            .environment(\.managedObjectContext, persistenceController.container.viewContext)
        }
    }
}

Statistics:

struct HabitStatistics: View {

    @Environment(\.managedObjectContext) private var viewContext

    @FetchRequest(sortDescriptors: []) var habits: FetchedResults<Habit>

    // MARK: Computing EarlyBird Property
    var filteredEarlyBird: Int {
        var earlyBird = 0
        var counter = 0
        for h in habits {
            let component = Calendar.current.dateComponents([.hour, .minute], from: h.getUpTime ?? Date())
            let hour = component.hour ?? 0
            let minute = component.minute ?? 0
            let difference = (hour * 60 + minute) - 270
            earlyBird += difference
            counter += 1
        }
        if counter != 0 {
            earlyBird /= counter
            return earlyBird
        } else {
            return 0
        }
    }

    // MARK: Computing ateMeat Property
    var filteredMeat: Int {
        var total: Int {
            if habits.count == 0 {
                return 1
            } else {
                return habits.count
            }
        }
        var count = 0
        var perc = 0
        for h in habits {
            if h.ateMeat == false {
                count += 1
            }
        }
        perc = count * 100 / total
        return perc
    }

    // MARK: Computing ateSuger Property
    var filteredSugar: Int {
        var total: Int {
            if habits.count == 0 {
                return 1
            } else {
                return habits.count
            }
        }
        var count = 0
        var perc = 0
        for h in habits {
            if h.ateSugar == false {
                count += 1
            }
        }
        perc = count * 100 / total
        return perc
    }

    // MARK: Computing didSports Property
    var filteredSport: Int {
        var total: Int {
            if habits.count == 0 {
                return 1
            } else {
                return habits.count
            }
        }
        var count = 0
        var perc = 0
        for h in habits {
            if h.didSports == true {
                count += 1
            }
        }
        perc = count * 100 / total
        return perc
    }

    var body: some View {
        VStack(alignment: .leading, spacing: 0) {
            // Headline
            Text("This Week")
                .bold()
            VStack {
                Text("Meatfree \(filteredMeat) %")
                     Text("Sugarfree \(filteredSugar) %")
                     Text("Sportsrate \(filteredSport)%")
                     Text("Average Time Loss \(filteredEarlyBird) Min lost")
            }
        }
    }
}

Daily Form:

struct DailyForm: View {

    @Environment(\.managedObjectContext) private var viewContext
//    @EnvironmentObject var model: HabitModel
    @FetchRequest(sortDescriptors: []) var habits: FetchedResults<Habit>

    @State var getUpTime = Date()
    @State var ateMeat = false
    @State var ateSugar = false
    @State var didSports = false

    var body: some View {

        VStack {
            HStack {
                Button("Clear") {
                    clear()
                }
                Spacer()
                Button("Add") {
                    addHabit()
                    clear()
                }

            }
            .padding()

            ScrollView (showsIndicators: false) {

                VStack (alignment: .leading) {
                    DatePicker("Get up Time", selection: $getUpTime, displayedComponents: .hourAndMinute)
                    Toggle("Ate Meat?", isOn: $ateMeat)
                    Toggle("Ate Sugar?", isOn: $ateSugar)
                    Toggle("Did Sports?", isOn: $didSports)
                }
                .padding(.horizontal)
            }

        }
    }

    func clear() {
        getUpTime = Date()
        ateMeat = false
        ateSugar = false
        didSports = false
    }

    func addHabit() {
        let habit = Habit(context: viewContext)
        habit.id = UUID()
        habit.getUpTime = getUpTime
        habit.ateMeat = ateMeat
        habit.ateSugar = ateSugar
        habit.didSports = didSports

        do {
            try viewContext.save()
        }
        catch {
            // Couldn't save the recipe
        }
    }
}


问:
OAuth 2.0 flow to authentication via access token
I have a public client which gets JWT access token. I need it to get another one (not refresh, but for some other purpose) and I need it to do it without a user interaction.

As a result, I am trying to figure out whether there is a standard OAuth flow where I can use (JWT) access token (issued in a previous OAuth flow) to be used to authenticate for another OAuth flow (I can't authentication with the client secret since it's a public client).

All the things which I found are not a perfect match.

RFC 7523 JSON Web Token (JWT) Profile for OAuth 2.0 Client Authentication and Authorization Grants

It does allow to authenticate via JWT token. However, it requires a client to issue JWT token (signed by a certificate owned by the client) and it checks for the signature. As a result, I can't use JWT access token which was issued by the Authorization server for this purpose.

RFC 8693 OAuth 2.0 Token Exchange

This one allows using JWT access token and get another JWT access token. So close, but no cigar. JWT access token is not used for authentication in this flow. As a result, you still need client id + client secret to authenticate

Token refresh

This one potentially can be used it. Just use the refresh token to get a new JWT access token. However, it feels hacky. (I may need to do this operation a lot, as a result, it feels like an abuse of token refresh mechanics. Also, my guess is it will gradually pollute DB with used refresh tokens (this is a tiny secondary concern, however, again this solution feels hacky).

Am I missing anything?

答:
Why do you need to avoid "user interaction" for the second token request? I can understand the desire (less interruption, etc.) but what's the reason behind it?

A user-based OAuth flow is going to require authentication with user credentials. That leaves you password flow or authorization code flow.

Password means you need the user's credentials to send...which I'm assuming you don't (and shouldn't have)

Authorization Code means that you need to redirect the user's browser to the authorization server's authorization endpoint (i.e. at least the potential for "user interaction") because the credentials were entered there to create a valid session. If the session at the authorization server is still valid, redirecting to the authorization server for the second authorization shouldn't require the user to type or click anything. However, if the session has expired, they would need to re-enter their credentials.

Update:

Token Exchange, to me, doesn't make sense for your use-case. If you're "impersonating", then your second token has the same privileges as the first. If you're "delegating" your new token has a subset of the privileges of the first.

Delegation semantics are different than impersonation semantics,
though the two are closely related.  With delegation semantics,
principal A still has its own identity separate from B, and it is
explicitly understood that while B may have delegated some of its
rights to A, any actions taken are being taken by A representing B. In a sense, A is an agent for B.

ref: https://datatracker.ietf.org/doc/html/rfc8693#section-1.1

You can't delegate privileges you don't have.


问:
Handling test data for multiple scenarios and Environments in Playwright
does playwright have the support/ features to handle multiple test data for various scenarios and for multiple environments.
Could someone point me to the right approach for handling such scenarios.

scenarios:

Test will be executed in multiple environments ( Acceptance, prod etc).
test will have multiple scenarios which will require different set of test data.
I dont see a proper approach that i can used from the documentation ( or may be i am looking at the wrong place).

thanks in advance.
Allen K

答:
At first you have playwright.config.ts file where you can set projects and their variables.
In ex

```<code>projects: [
    {
      name: 'chromium',
      use: { ...devices['Desktop Chrome'] },
    },
    {
      name: 'firefox',
      use: { ...devices['Desktop Firefox'] },
    },
    {
      name: 'webkit',
      use: { ...devices['Desktop Safari'] },
    },
</code>```

or in your case it can projects with different environment.
Or you can create a Json structure of data that will need for particular test like.

```<code>{
 "tcs":[]
{
 "name": tc1,
 "field1": value,
 "field2": value,
},
{
 "name": tc2,
 "field1": value,
 "field2": value,
}
}
</code>```

Then just import this file in your suit and use all the data for particular test in foreach loop.

Body:
At first you have playwright.config.ts file where you can set projects and their variables.
In ex

projects: [
    {
      name: 'chromium',
      use: { ...devices['Desktop Chrome'] },
    },
    {
      name: 'firefox',
      use: { ...devices['Desktop Firefox'] },
    },
    {
      name: 'webkit',
      use: { ...devices['Desktop Safari'] },
    },

or in your case it can projects with different environment.
Or you can create a Json structure of data that will need for particular test like.

{
 "tcs":[]
{
 "name": tc1,
 "field1": value,
 "field2": value,
},
{
 "name": tc2,
 "field1": value,
 "field2": value,
}
}

Then just import this file in your suit and use all the data for particular test in foreach loop.


问:
How to overwrite one property in .properties without overwriting the whole file?
Basically, I have to overwrite a certain property in a .properties file through a Java app, but when I use Properties.setProperty() and Properties.Store() it overwrites the whole file rather than just that one property.

I've tried constructing the FileOutputStream with append = true, but with that it adds another property and doesn't delete/overwrite the existing property.

How can I code it so that setting one property overwrites that specific property, without overwriting the whole file?

Edit:  I tried reading the file and adding to it.  Here's my updated code:

```<code>FileOutputStream out = new FileOutputStream("file.properties");
FileInputStream in = new FileInputStream("file.properties");
Properties props = new Properties();

props.load(in);
in.close();

props.setProperty("somekey", "somevalue");
props.store(out, null);
out.close();
</code>```

答:
Please use just update file line instead using Properies e.g.</p>
```<code>public static void updateProperty(String key, String oldValue, String newValue)
{
    File f = new File(CONFIG_FILE);
    try {
        List<String> fileContent = new ArrayList<>(Files.readAllLines(f.toPath(), StandardCharsets.UTF_8));

        for (int i = 0; i < fileContent.size(); i++) {
            if (fileContent.get(i).replaceAll("\\s+","").equals(key + "=" + oldValue)) {
                fileContent.set(i, key + " = " + newValue);
                break;
            }
        }
        Files.write(f.toPath(), fileContent, StandardCharsets.UTF_8);
    } catch (Exception e) {

    }
}
</code>```

Body:
Basically, I have to overwrite a certain property in a .properties file through a Java app, but when I use Properties.setProperty() and Properties.Store() it overwrites the whole file rather than just that one property.

I've tried constructing the FileOutputStream with append = true, but with that it adds another property and doesn't delete/overwrite the existing property.

How can I code it so that setting one property overwrites that specific property, without overwriting the whole file?

Edit:  I tried reading the file and adding to it.  Here's my updated code:

FileOutputStream out = new FileOutputStream("file.properties");
FileInputStream in = new FileInputStream("file.properties");
Properties props = new Properties();

props.load(in);
in.close();

props.setProperty("somekey", "somevalue");
props.store(out, null);
out.close();

Body:
Please use just update file line instead using Properies e.g.

public static void updateProperty(String key, String oldValue, String newValue)
{
    File f = new File(CONFIG_FILE);
    try {
        List<String> fileContent = new ArrayList<>(Files.readAllLines(f.toPath(), StandardCharsets.UTF_8));

        for (int i = 0; i < fileContent.size(); i++) {
            if (fileContent.get(i).replaceAll("\\s+","").equals(key + "=" + oldValue)) {
                fileContent.set(i, key + " = " + newValue);
                break;
            }
        }
        Files.write(f.toPath(), fileContent, StandardCharsets.UTF_8);
    } catch (Exception e) {

    }
}


答:
You can create any helper functions and use them inside your reducers.

As long as you DON'T mutate state directly in your reducers or in those functions, that's fine.

Title: Is functions in redux reducers ok?


问:
Where are Odoo Attachment Files is Stored in Odoo 14
I'm planning doing some migration and I need to know where all the attachment files is stored. In this forum, there are some answers, but the binary value for column ir_attachment.db_datas is set to null for every record.

答: As alredy mentioned in the comment section, the default location if not defined otherwise in odoo.conf file data_dir directory or Odoo service command --data-dir option, is ~/.local/share/Odoo/filestore/ODOO_DB_NAME or /var/lib/Odoo/filestore/ODOO_DB_NAME. If defined otherwise using any of the options, you will find the filestore directory at that defined location.


答:
When using functions like that in legacy switch..case reducers, you always have to be very aware if those functions are "safe", which means they cannot modify anything and have to return a modified copy of the original.

I would recommend to refactor that reducer to a "modern Redux" createSlice reducer since in those you can just modify all objects without problems - also that style of reducer is the official recommendation for all Redux code since 2019 anyways. In such a reducer you can use all functions without having to care too much.

Of course you should still avoid side effects, that goes for all reducers.

Title: Is functions in redux reducers ok?


问:
Passing args, kwargs, to run_in_executor
I am trying to pass arguments to run_in_executor like so:

```<code>    loop.run_in_executor(None, update_contacts, data={
        'email': email,
        'access_token': g.tokens['access_token']
    })
</code>```

However, I get the following error:

run_in_executor() got an unexpected keyword argument 'data'

Is there a generic way to pass args to this function?

答:
Create a function that calls it:

def foo():
    update_contacts(data={'email': email,'access_token': g.tokens['access_token']})
loop.run_in_executor(None, foo)
```
<p><strong>or</strong>, the func could also be lambda:</p>
<pre class="lang-py prettyprint-override"><code>loop.run_in_executor(None, lambda: update_contacts(data={'email': email,'access_token': g.tokens['access_token']})
</code>```

or use fuctools

Body:
I am trying to pass arguments to run_in_executor like so:

    loop.run_in_executor(None, update_contacts, data={
        'email': email,
        'access_token': g.tokens['access_token']
    })

However, I get the following error:

run_in_executor() got an unexpected keyword argument 'data'

Is there a generic way to pass args to this function?

Body:
Create a function that calls it:

def foo():
    update_contacts(data={'email': email,'access_token': g.tokens['access_token']})
loop.run_in_executor(None, foo)

or, the func could also be lambda:

loop.run_in_executor(None, lambda: update_contacts(data={'email': email,'access_token': g.tokens['access_token']})

or use fuctools


问:
Unable to use old java projects in new eclipse installation
I did an upgrade of my windows OS and restored my eclipse workspace from my backup. Now, when I try to open any of the older projects, they complain with a message:

```<code>Unbound classpath container: 'JRE System Library [jre6]' in project <ProjectName>
</code>```

When I looked around, I found pages which suggest that I change the JRE version for the project. However, I have about 50 projects in this workspace and do not want to change the value for each of them.

Any suggestions would be welcome.

Thanks and regards,

Karthick S.

答:
You should add a new JRE and name it [jre6] (or rename your current JRE). That will prevent you from changing manually your 50 projects.
 Window -> Preferences -> Java -> Installed JREs -> Add...

Body:
I did an upgrade of my windows OS and restored my eclipse workspace from my backup. Now, when I try to open any of the older projects, they complain with a message:

Unbound classpath container: 'JRE System Library [jre6]' in project <ProjectName>

When I looked around, I found pages which suggest that I change the JRE version for the project. However, I have about 50 projects in this workspace and do not want to change the value for each of them.

Any suggestions would be welcome.

Thanks and regards,

Karthick S.


问:
what is the correct way to inherit class in python
I have a base class as follows:

class BaseSqlClass:
    def __init__(self):
        self.__init__()

    @staticmethod
    def some_func(env, db):
        # do something
```
<p>I have a child class which inherits from base class as follows:</p>
<pre class="lang-py prettyprint-override"><code>class SqlGenerator(BaseSqlClass):
    def __init__(self, env, db, table):
        super().__init__()
        self.env = env
        self.db = db
        self.table = table
</code>```

When i instantiate the child class, I get the error __init__() missing positional arguments, __init__() is of base class?
I don't know what I am doing wrong.

答:
The error you posted does not fit to the code you posted, so I'll go with the code. First, you should be getting an error maximum recursion depth exceeded for

class BaseSqlClass:
    def __init__(self):
        self.__init__()

    @staticmethod
    def some_func(env, db):
        # do something
```
<p>When you create a <code>BaseSqlClass</code> instance, the <code>__init__</code> method is called, from which you call that same method again, which calls itself again, and so on. If you don't want to do anything at instance creation time, just omit the <code>__init__</code> method:</p>
<pre class="lang-py prettyprint-override"><code>class BaseSqlClass:
    @staticmethod
    def some_func(env, db):
        # do something
</code>```

Second issue is in the second code snippet - you are calling some __init method of the parent class - but that doesn't have such a method. I guess you meant super().__init__() instead of super().__init() ?

Body:
I have a base class as follows:

class BaseSqlClass:
    def __init__(self):
        self.__init__()

    @staticmethod
    def some_func(env, db):
        # do something

I have a child class which inherits from base class as follows:

class SqlGenerator(BaseSqlClass):
    def __init__(self, env, db, table):
        super().__init__()
        self.env = env
        self.db = db
        self.table = table

When i instantiate the child class, I get the error __init__() missing positional arguments, __init__() is of base class?
I don't know what I am doing wrong.

Body:
The error you posted does not fit to the code you posted, so I'll go with the code. First, you should be getting an error maximum recursion depth exceeded for

class BaseSqlClass:
    def __init__(self):
        self.__init__()

    @staticmethod
    def some_func(env, db):
        # do something

When you create a BaseSqlClass instance, the __init__ method is called, from which you call that same method again, which calls itself again, and so on. If you don't want to do anything at instance creation time, just omit the __init__ method:

class BaseSqlClass:
    @staticmethod
    def some_func(env, db):
        # do something

Second issue is in the second code snippet - you are calling some __init method of the parent class - but that doesn't have such a method. I guess you meant super().__init__() instead of super().__init() ?


问:
Why should I use 'Volatile' instead of just always using 'Atomic'?
I know the differences between both in terms of visibility and ensuring atomic access and atomic operations. But I was wondering, if for example I only needed to use Volatile, and Atomic wasn't necessary, is there an advantage (maybe memory or efficiency wise) to using just Volatile? Or can I just use Atomic instead?</p>

答:
The get() and set(...) methods of a Java AtomicWhatever object have exactly the same semantics as assignments to, and reads from, a volatile variable. So in effect, "Atomic" is a superset of "volatile."

The semantics are simple: If one thread assigns a volatile variable or, if it set(...)s an AtomicXxxxxx object, then whatever else it did before that assignment is guaranteed to be visible to some other thread after the other thread subsequently reads the same variable or, after it subsequently get()s from the same object.

volatile was in the language from the beginning. Atomics are newer. Some programmers will tell you that because atomics effectively are "volatile," that we don't need the volatile keyword anymore, and you should not use it. That's a matter of opinion, but if you're working on a team with other developers, it's best to use the same style and the same patterns that everybody else on the team uses.


问:
Hide portion of component in home component Angular
this is the ts file of an accordion component that I have called in the Home Page. However I want to use the parameter showOnHome to only display the ones with boolean true. How can I do that?</p>
```<code> @Component({
  selector: "app-faq",
  templateUrl: "./faq.component.html",
  styleUrls: ["./faq.component.css"],
})
export class FaqComponent implements OnInit {

  data = [
    {
      id: 1,
      question: "question1",
      answer: [
        "answer here",
      ],
      bullet: false,
      showOnHome: true,
    },
    {
      id: 2,
      question: "question2",
      answer: [
        "answer2",
      ],
      bullet: false,
      showOnHome: false,
    },]```

Called On Home Page as:
``` <app-faq></app-faq> ```
</code>```

答:
You could filter the list of items before displaying them by doing something like:</p>
```<code>const filteredData = data.filter(d => d.showOnHome);
</code>```

Body:
this is the ts file of an accordion component that I have called in the Home Page. However I want to use the parameter showOnHome to only display the ones with boolean true. How can I do that?

 @Component({
  selector: "app-faq",
  templateUrl: "./faq.component.html",
  styleUrls: ["./faq.component.css"],
})
export class FaqComponent implements OnInit {

  data = [
    {
      id: 1,
      question: "question1",
      answer: [
        "answer here",
      ],
      bullet: false,
      showOnHome: true,
    },
    {
      id: 2,
      question: "question2",
      answer: [
        "answer2",
      ],
      bullet: false,
      showOnHome: false,
    },]```

Called On Home Page as:
``` <app-faq></app-faq> ```

Body:
You could filter the list of items before displaying them by doing something like:

const filteredData = data.filter(d => d.showOnHome);


问:
Setting state to a zero-filled array with Immer in react-toolkit
I was following the TS usage docs and now I'm trying to clear an array using Redux Toolkit but my turnOffAll(state) reducer causes thousands of rerenders (console log outputs) and an error about it in the browser.

I have read that it's possible to return state, rather than "mutate" it from within turnOffAll.
So I've tried a variation of turnOffAll having: return Array(screenSize.width * screenSize.height).fill(0) but this causes an error in app.jsx that dispatch(turnOffAll()); does not provide enough arguments.

Another approach I tried in turnOffAll is state = initialState; but while this doesn't cause unnececary rerenders, the state is not reset if I do a console.log(useAppSelector((state) => state.pixels)); in app.jsx.

The relevant info from the files are below. This code is the situation in my first paragraph above and causes thousands of rerenders when calling dispatch(turnOffAll()); from app.jsx:

pixelsSlice.ts:

```<code>import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import type { RootState } from "./store";
import { Pixel, ScreenSize } from "./types";

//Defining a type for the slice state
interface PixelsState {
  pixels: Array<number>;
}

const screenSize = { width: 128, height: 59 };

//Define the initial state using the above type.
const initialState: PixelsState = {
  pixels: Array(screenSize.width * screenSize.height).fill(0),
};

export const pixelsSlice = createSlice({
  name: "pixels",
  initialState,
  reducers: {
    turnOn(state, action: PayloadAction<Pixel>) {
      //This may look like mutating state, but Immer makes it ok:
      state.pixels[
        screenSize.width * action.payload.row + action.payload.column
      ] = 1;
    },
    turnOffAll(state) {
      state = initialState;
    },
  },
});

export const { turnOn, turnOffAll } = pixelsSlice.actions;

//Other code such as selectors can use the imported `RootState` type...
export const selectPixels = (state: RootState) => state.pixels;

export default pixelsSlice.reducer;

</code>```

app.tsx:

```<code>import React, { useEffect } from "react";
import { useAppSelector, useAppDispatch } from "./app/hooks";
import { turnOn, turnOffAll } from "./app/pixelsSlice";
import type { Pixel } from "./app/types";

function App() {
  const dispatch = useAppDispatch();

  //Demonstrating reading and writing pixels from the redux store.
  console.log(useAppSelector((state) => state.pixels));

  let p: Pixel = { row: 1, column: 2 };
  dispatch(turnOn(p));
  console.log(useAppSelector((state) => state.pixels));

  dispatch(turnOffAll()); //THIS CAUSES THOUSANDS OF RERENDERS AND CONSOLE LOG OUTPUTS :(
  console.log(useAppSelector((state) => state.pixels));

  return <div className="App"></div>;
}

export default App;
</code>```

hooks.ts:

```<code>import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux";
import type { RootState, AppDispatch } from "./store";

// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
</code>```

答:
In addition to @phry 's comment, the line state = in an Immer-powered reducer is always incorrect.  You need to either mutate a value inside of state, or return a new value.

If you want to replace the existing state, do return initialState.

See the RTK usage guide page on "Writing Reducers with Immer" for more details.

Body:
I was following the TS usage docs and now I'm trying to clear an array using Redux Toolkit but my turnOffAll(state) reducer causes thousands of rerenders (console log outputs) and an error about it in the browser.

I have read that it's possible to return state, rather than "mutate" it from within turnOffAll.
So I've tried a variation of turnOffAll having: return Array(screenSize.width * screenSize.height).fill(0) but this causes an error in app.jsx that dispatch(turnOffAll()); does not provide enough arguments.

Another approach I tried in turnOffAll is state = initialState; but while this doesn't cause unnececary rerenders, the state is not reset if I do a console.log(useAppSelector((state) => state.pixels)); in app.jsx.

The relevant info from the files are below. This code is the situation in my first paragraph above and causes thousands of rerenders when calling dispatch(turnOffAll()); from app.jsx:

pixelsSlice.ts:

import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import type { RootState } from "./store";
import { Pixel, ScreenSize } from "./types";

//Defining a type for the slice state
interface PixelsState {
  pixels: Array<number>;
}

const screenSize = { width: 128, height: 59 };

//Define the initial state using the above type.
const initialState: PixelsState = {
  pixels: Array(screenSize.width * screenSize.height).fill(0),
};

export const pixelsSlice = createSlice({
  name: "pixels",
  initialState,
  reducers: {
    turnOn(state, action: PayloadAction<Pixel>) {
      //This may look like mutating state, but Immer makes it ok:
      state.pixels[
        screenSize.width * action.payload.row + action.payload.column
      ] = 1;
    },
    turnOffAll(state) {
      state = initialState;
    },
  },
});

export const { turnOn, turnOffAll } = pixelsSlice.actions;

//Other code such as selectors can use the imported `RootState` type...
export const selectPixels = (state: RootState) => state.pixels;

export default pixelsSlice.reducer;

app.tsx:

import React, { useEffect } from "react";
import { useAppSelector, useAppDispatch } from "./app/hooks";
import { turnOn, turnOffAll } from "./app/pixelsSlice";
import type { Pixel } from "./app/types";

function App() {
  const dispatch = useAppDispatch();

  //Demonstrating reading and writing pixels from the redux store.
  console.log(useAppSelector((state) => state.pixels));

  let p: Pixel = { row: 1, column: 2 };
  dispatch(turnOn(p));
  console.log(useAppSelector((state) => state.pixels));

  dispatch(turnOffAll()); //THIS CAUSES THOUSANDS OF RERENDERS AND CONSOLE LOG OUTPUTS :(
  console.log(useAppSelector((state) => state.pixels));

  return

;
}

export default App;

hooks.ts:

import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux";
import type { RootState, AppDispatch } from "./store";

// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;


问:
Using cmd to start TabPy
I am trying to run some cmd commands using a .bat file. This will be ran on a server so we can use python with Tableau server. The .bat file needs to first start the command prompt then navigate to the target folder and run the activate.bat file. This starts my anaconda prompt window. In there, I execute tabpy to start tabpy.

These are the lines verbatim I have in my .bat file.

```<code>@ECHO OFF
start cmd
/k cd C:\Users\John Smith\Anaconda3\Scripts
/k activate.bat
/k tabpy
pause
</code>```

When I run this .bat, a cmd window opens but nothing happens. I'm new to cmd and kind of have no idea what I'm doing. I put this together after reading a couple random sites. Thanks in advance!

Just to clarify, If I go into cmd prompt and type the following in this order, I get what I want:

cd C:\Users\Michael B Smith\Anaconda3\Scripts

activate.bat

tabpy

I just need to duplicate that using a .bat file.

答:
Assuming tabpy is a python script.

```<code>@ECHO OFF
cd /d C:\Users\John Smith\Anaconda3\Scripts
call activate.bat
py.exe tabpy
pause
</code>```

Title: Using cmd to start TabPy

Body:
I am trying to run some cmd commands using a .bat file. This will be ran on a server so we can use python with Tableau server. The .bat file needs to first start the command prompt then navigate to the target folder and run the activate.bat file. This starts my anaconda prompt window. In there, I execute tabpy to start tabpy.

These are the lines verbatim I have in my .bat file.

@ECHO OFF
start cmd
/k cd C:\Users\John Smith\Anaconda3\Scripts
/k activate.bat
/k tabpy
pause

When I run this .bat, a cmd window opens but nothing happens. I'm new to cmd and kind of have no idea what I'm doing. I put this together after reading a couple random sites. Thanks in advance!

Just to clarify, If I go into cmd prompt and type the following in this order, I get what I want:

cd C:\Users\Michael B Smith\Anaconda3\Scripts

activate.bat

tabpy

I just need to duplicate that using a .bat file.

Body:
Assuming tabpy is a python script.

@ECHO OFF
cd /d C:\Users\John Smith\Anaconda3\Scripts
call activate.bat
py.exe tabpy
pause


问:
Select values along the ocean floor in xarray
I have a coastal oceanic dataset with coordinates (time, depth, lat, lon). Data for deep layers is masked out with nan close to the coast. I want to make a new dataset with coordinates (time, lat, lon) by selecting values along the ocean floor.

Currently I am doing this using dataset.bfill('depth').isel({'depth': 0}), which backfills all the nans using the deepest data present, then slices off the deepest layer. This works, but is inefficient. bfill will update every variable, across all timesteps, to fill the missing values downwards.

The depth of the ocean floor does not change between timesteps or across variables. I would like to use this fact to make this operation more efficient. Assume I have a (lat, lon) array which contains an index into the depth coordinate, indicating where the ocean floor is at that coordinate. Making this index array is relatively easy, but I don't know how to then use it to select the right data.

Is there a way of using this (lat, lon) array of depth indices to select just the depth index that I am interested in, efficiently, across all variables and timesteps? i.e. something like:

>>> dataset
Dimensions:  (t: 5, z: 5, y: 5, x: 5)
Coordinates:
    time     (t) datetime64 2022-02-08 ...
    lon      (x) int64 0 -1 -2 -3 -4
    lat      (y) int64 0 1 2 3 4
    depth    (z) float64 4.25 3.25 2.25 1.25 0.25
Dimensions without coordinates: z, y, x, t
Data variables:
    temp     (t, z, y, x) float64 0.0 nan nan nan nan nan ... 4.0 4.0 4.0 4.0 4.0

>>> depth_indices = compute_ocean_floor_index(
    dataset, depth_variable='depth', coordinate_variables=['lon', 'lat'])
>>> depth_indices
array([[0, 1, 2, 3, 4],
       [1, 1, 2, 3, 4],
       [2, 2, 2, 3, 4],
       [3, 3, 3, 3, 4],
       [4, 4, 4, 4, 4]])
>>> dataset_floor = dataset.some_selector(depth_indices)
>>> dataset_floor
Dimensions:  (t: 5, y: 5, x: 5)
Coordinates:
    time     (t) datetime64 2022-02-08 ...
    lon      (x) int64 0 -1 -2 -3 -4
    lat      (y) int64 0 1 2 3 4
Data variables:
    temp     (t, y, x) float64 0.0 1.0 2.0 3.0 4.0 1.0 ... 4.0 4.0 4.0 4.0 4.0
```
<p>The current implementation passes the following test function. The new implementation I am after would pass the same test, without using <code>bfill()</code>:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import pandas as pd
import xarray as xr
from numpy.testing import assert_equal

from cemarray.operations import ocean_floor

def test_ocean_floor():
    # Values will be a 3D cube of values, with a slice along the x-axis like
    #     y
    #   44444
    #   3333.
    # d 222..
    #   11...
    #   0....
    values = np.full((5, 5, 5, 5), fill_value=np.nan)
    for i in range(5):
        values[:, i, :i + 1, :i + 1] = i

    temp = xr.DataArray(
        data=values,
        dims=['t', 'z', 'y', 'x'],
    )
    dataset = xr.Dataset(
        data_vars={"temp": temp},
        coords={
            'time': (['t'], pd.date_range('2022-02-08', periods=5)),
            'lon': (['x'], -np.arange(5)),
            'lat': (['y'], np.arange(5)),
            'depth': (['z'], 4.25 - np.arange(5), {'positive': 'down'}),
        }
    )

    floor_dataset = ocean_floor(dataset, ['depth'])

    assert floor_dataset.dims == {
        't': 5,
        'x': 5,
        'y': 5,
    }
    assert set(floor_dataset.coords.keys()) == {'time', 'lon', 'lat'}
    # We should see values for the deepest layer that has a value there
    expected_values = [
        [0, 1, 2, 3, 4],
        [1, 1, 2, 3, 4],
        [2, 2, 2, 3, 4],
        [3, 3, 3, 3, 4],
        [4, 4, 4, 4, 4],
    ]
    assert_equal(
        floor_dataset['temp'].values,
        np.array([expected_values] * 5)
    )
</code>```

答:
Yep! xarray's Advanced Indexing works in many dimensions too!

Create the indexer "some_selector" you thought up (which totally does exist!) by indexing using a DataArray with the values equal to the coordinates you'd like to select, and the dimensions/coordinates matching  the target result. In this case, you want a DataArray of z indexed by x, y:

>>> depth_indices = compute_ocean_floor_index(
    dataset, depth_variable='depth', coordinate_variables=['lon', 'lat'])
>>> depth_indices
array([[0, 1, 2, 3, 4],
       [1, 1, 2, 3, 4],
       [2, 2, 2, 3, 4],
       [3, 3, 3, 3, 4],
       [4, 4, 4, 4, 4]])
>>> selector = xr.DataArray(depth_indices, dims=('y', 'x'))
```
<p>This selector can now be used to pull out the z levels for each <code>(x, y)</code> pair, ignoring <code>t</code>:</p>
<pre class="lang-py prettyprint-override"><code>>>> dataset_floor = dataset.isel(z=selector)
>>> dataset_floor
Dimensions:  (t: 5, y: 5, x: 5)
Coordinates:
    time     (t) datetime64 2022-02-08 ...
    lon      (x) int64 0 -1 -2 -3 -4
    lat      (y) int64 0 1 2 3 4
Data variables:
    temp     (t, y, x) float64 0.0 1.0 2.0 3.0 4.0 1.0 ... 4.0 4.0 4.0 4.0 4.0
</code>```

Body:
I have a coastal oceanic dataset with coordinates (time, depth, lat, lon). Data for deep layers is masked out with nan close to the coast. I want to make a new dataset with coordinates (time, lat, lon) by selecting values along the ocean floor.

Currently I am doing this using dataset.bfill('depth').isel({'depth': 0}), which backfills all the nans using the deepest data present, then slices off the deepest layer. This works, but is inefficient. bfill will update every variable, across all timesteps, to fill the missing values downwards.

The depth of the ocean floor does not change between timesteps or across variables. I would like to use this fact to make this operation more efficient. Assume I have a (lat, lon) array which contains an index into the depth coordinate, indicating where the ocean floor is at that coordinate. Making this index array is relatively easy, but I don't know how to then use it to select the right data.

Is there a way of using this (lat, lon) array of depth indices to select just the depth index that I am interested in, efficiently, across all variables and timesteps? i.e. something like:

>>> dataset
Dimensions:  (t: 5, z: 5, y: 5, x: 5)
Coordinates:
    time     (t) datetime64 2022-02-08 ...
    lon      (x) int64 0 -1 -2 -3 -4
    lat      (y) int64 0 1 2 3 4
    depth    (z) float64 4.25 3.25 2.25 1.25 0.25
Dimensions without coordinates: z, y, x, t
Data variables:
    temp     (t, z, y, x) float64 0.0 nan nan nan nan nan ... 4.0 4.0 4.0 4.0 4.0

>>> depth_indices = compute_ocean_floor_index(
    dataset, depth_variable='depth', coordinate_variables=['lon', 'lat'])
>>> depth_indices
array([[0, 1, 2, 3, 4],
       [1, 1, 2, 3, 4],
       [2, 2, 2, 3, 4],
       [3, 3, 3, 3, 4],
       [4, 4, 4, 4, 4]])
>>> dataset_floor = dataset.some_selector(depth_indices)
>>> dataset_floor
Dimensions:  (t: 5, y: 5, x: 5)
Coordinates:
    time     (t) datetime64 2022-02-08 ...
    lon      (x) int64 0 -1 -2 -3 -4
    lat      (y) int64 0 1 2 3 4
Data variables:
    temp     (t, y, x) float64 0.0 1.0 2.0 3.0 4.0 1.0 ... 4.0 4.0 4.0 4.0 4.0

The current implementation passes the following test function. The new implementation I am after would pass the same test, without using bfill():

import numpy as np
import pandas as pd
import xarray as xr
from numpy.testing import assert_equal

from cemarray.operations import ocean_floor

def test_ocean_floor():
    # Values will be a 3D cube of values, with a slice along the x-axis like
    #     y
    #   44444
    #   3333.
    # d 222..
    #   11...
    #   0....
    values = np.full((5, 5, 5, 5), fill_value=np.nan)
    for i in range(5):
        values[:, i, :i + 1, :i + 1] = i

    temp = xr.DataArray(
        data=values,
        dims=['t', 'z', 'y', 'x'],
    )
    dataset = xr.Dataset(
        data_vars={"temp": temp},
        coords={
            'time': (['t'], pd.date_range('2022-02-08', periods=5)),
            'lon': (['x'], -np.arange(5)),
            'lat': (['y'], np.arange(5)),
            'depth': (['z'], 4.25 - np.arange(5), {'positive': 'down'}),
        }
    )

    floor_dataset = ocean_floor(dataset, ['depth'])

    assert floor_dataset.dims == {
        't': 5,
        'x': 5,
        'y': 5,
    }
    assert set(floor_dataset.coords.keys()) == {'time', 'lon', 'lat'}
    # We should see values for the deepest layer that has a value there
    expected_values = [
        [0, 1, 2, 3, 4],
        [1, 1, 2, 3, 4],
        [2, 2, 2, 3, 4],
        [3, 3, 3, 3, 4],
        [4, 4, 4, 4, 4],
    ]
    assert_equal(
        floor_dataset['temp'].values,
        np.array([expected_values] * 5)
    )

Body:
Yep! xarray's Advanced Indexing works in many dimensions too!

Create the indexer "some_selector" you thought up (which totally does exist!) by indexing using a DataArray with the values equal to the coordinates you'd like to select, and the dimensions/coordinates matching  the target result. In this case, you want a DataArray of z indexed by x, y:

>>> depth_indices = compute_ocean_floor_index(
    dataset, depth_variable='depth', coordinate_variables=['lon', 'lat'])
>>> depth_indices
array([[0, 1, 2, 3, 4],
       [1, 1, 2, 3, 4],
       [2, 2, 2, 3, 4],
       [3, 3, 3, 3, 4],
       [4, 4, 4, 4, 4]])
>>> selector = xr.DataArray(depth_indices, dims=('y', 'x'))

This selector can now be used to pull out the z levels for each (x, y) pair, ignoring t:

>>> dataset_floor = dataset.isel(z=selector)
>>> dataset_floor
Dimensions:  (t: 5, y: 5, x: 5)
Coordinates:
    time     (t) datetime64 2022-02-08 ...
    lon      (x) int64 0 -1 -2 -3 -4
    lat      (y) int64 0 1 2 3 4
Data variables:
    temp     (t, y, x) float64 0.0 1.0 2.0 3.0 4.0 1.0 ... 4.0 4.0 4.0 4.0 4.0


问:
laravel livewire exception: Queueing collections with multiple model connections is not supported
I´m beggining my Livewire journey and have created a list component which contains a form component for each of the list elements, and as I am trying to make it all work I keep getting the following never before seen exception:

LogicException Queueing collections with multiple model connections is
not supported.

I use the same single connection for every model in my project, and I am not queueing anything on purpose in any of the components I'm currently working, so I have no clue as to where to start debugging this exception. The error message doesn´t help much either. In fact, I don´t even know what to post here for you guys to help me, short of posting the whole project... I guess I´m just angling for any clue as to where to start looking to get this fixed, so any help is much appreciated.

Here's the error message Stack trace:

C:\Users\bfcba\OneDrive\aplicaciones\duki\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Collection.php:705

public function getQueueableConnection()
{
    if ($this->isEmpty()) {
        return;
    }

    $connection = $this->first()->getConnectionName();

    $this->each(function ($model) use ($connection) {
        if ($model->getConnectionName() !== $connection) {
            throw new LogicException('Queueing collections with multiple model connections is not supported.');
        }
    });

    return $connection;
}
```

I´ll be happy to post all the information that you consider necessary. Just let me know.

Thanks in advance.

答:
Set the connection name in the Model:

class ModelName extends Model
{
    protected $connection = "mysql";
}
```

Body:
I´m beggining my Livewire journey and have created a list component which contains a form component for each of the list elements, and as I am trying to make it all work I keep getting the following never before seen exception:

LogicException Queueing collections with multiple model connections is
not supported.

I use the same single connection for every model in my project, and I am not queueing anything on purpose in any of the components I'm currently working, so I have no clue as to where to start debugging this exception. The error message doesn´t help much either. In fact, I don´t even know what to post here for you guys to help me, short of posting the whole project... I guess I´m just angling for any clue as to where to start looking to get this fixed, so any help is much appreciated.

Here's the error message Stack trace:

C:\Users\bfcba\OneDrive\aplicaciones\duki\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Collection.php:705

public function getQueueableConnection()
{
    if ($this->isEmpty()) {
        return;
    }

    $connection = $this->first()->getConnectionName();

    $this->each(function ($model) use ($connection) {
        if ($model->getConnectionName() !== $connection) {
            throw new LogicException('Queueing collections with multiple model connections is not supported.');
        }
    });

    return $connection;
}

I´ll be happy to post all the information that you consider necessary. Just let me know.

Thanks in advance.


问:
SQL 5.7 Lead Function
I'm struggling emulating a lead function to calculate the difference of (after date - current date)

I'm currently using mysql 5.7 to accomplish this. I have tried looking at various sources on stack overflow but I'm not sure how to get the result.

This is what I want:

What I currently have now is the same thing without the days column.

I would also like to know how to get a column of dates that grabs the date after the current date.

Title: SQL 5.7 Lead Function

Body:
This seems to work (except for the unclear row=4):

DROP TABLE IF EXISTS table4;
CREATE TABLE table4 (id integer, user_id integer, product varchar(10), `date` date);
INSERT INTO table4 VALUES
  (1,1,'item1','2020-01-01'),
  (2,1,'item2','2020-01-01'),
  (3,1,'item3','2020-01-02'),
  (4,1,'item4','2020-01-02'),
  (5,2,'item5','2020-01-06'),
  (6,2,'item6','2020-01-09'),
  (7,2,'item7','2020-01-09'),
  (8,2,'item8','2020-01-10');

SELECT
   id,
   user_id,
   product,
   date,
   (SELECT date FROM table4 t4 WHERE t4.id>t1.id LIMIT 1) x,
   COALESCE(DATEDIFF((SELECT date FROM table4 t4 WHERE t4.id>t1.id LIMIT 1),date),0) as days
FROM table4 t1

output:

+ ------- + ------------ + ------------ + --------- + ----------- + --------- +
| id      | user_id      | product      | date      | x           | days      |
+ ------- + ------------ + ------------ + --------- + ----------- + --------- +
| 1       | 1            | item1        | 2020-01-01 | 2020-01-01 | 0         |
| 2       | 1            | item2        | 2020-01-01 | 2020-01-02 | 1         |
| 3       | 1            | item3        | 2020-01-02 | 2020-01-02 | 0         |
| 4       | 1            | item4        | 2020-01-02 | 2020-01-06 | 4         |
| 5       | 2            | item5        | 2020-01-06 | 2020-01-09 | 3         |
| 6       | 2            | item6        | 2020-01-09 | 2020-01-09 | 0         |
| 7       | 2            | item7        | 2020-01-09 | 2020-01-10 | 1         |
| 8       | 2            | item8        | 2020-01-10 |            | 0         |
+ ------- + ------------ + ------------ + ---------- + ---------- + --------- +

The column x is only here for to see which date is returned from the subquery, and not really needed for the final result.

DBFIDDLE

EDIT: when there are no "gaps" in the numbering of id, you could do this to get a solution which should have more performance:

SELECT
   t1.id,
   t1.user_id,
   t1.product,
   t1.date,
   COALESCE(DATEDIFF(t2.date,t1.date),0) as days
FROM table4 t1
LEFT JOIN table4 t2 on t2.id = t1.id+1

I added this to the DBFIDDLE


问:
jQuery if visible
```<code> <div id="chatCenterMembers">
   <div class="chatmember">
       <a title="Blah Blah Blah">
          <div class="newchatmessage" style="display: block;"></div>
</code>```

How can I capture the visible div in an if statement?

I have $(this) set to
 - second line from the top.

I've been working with below but had now luck so far.

```<code>if($(this+' a div.newchatmessage').filter(":visible")) {
</code>```

Above just drops out...

I've also tried below and it doesn't work either

```<code>if ($(this + 'a div.newchatmessage').is(':visible')) {
</code>```

答:
.is()

for any detailed information on this method, just scroll down a bit ... there's a bunch of examples!

edit (thanks for the hint @Wesley Murch):
if this does not work, your selector might be wrong ... $(this+' a div.newchatmessage') looks quite strange ... it might rather be $('a div.newchatmessage', this) or $('a div.newchatmessage', $(this)) depending on this being a jQuery-variable or not

Title: jQuery if visible

Body:
How can I capture the visible div in an if statement?

I have $(this) set to
 - second line from the top.

I've been working with below but had now luck so far.

if($(this+' a div.newchatmessage').filter(":visible")) {

Above just drops out...

I've also tried below and it doesn't work either

if ($(this + 'a div.newchatmessage').is(':visible')) {


问:
Get User Accounts and Passwords from OS for application Initialization
I am working on an application in java that will connect to an sql database, but will also have an internal encrypted database used for user accounts and passwords for security. My question is, is there a way to get(when the application would first be installed on the users machine) to grab with with authorization a list of user accounts, and their passwords and possibly privilege sets for these accounts to be used for security later. this will be similar to the way that plesk or cpanel uses user accounts on the system for logging into a web interface of the application. this will use angular front end and a java backend with database for storage and things alike. This will be deployed on many machines, mainly would be linux(RHEL) and Windows, with the possibility of mac. how would you go about this? any advice or help would be greatly appreciated.</p>

答: I was thinking originally of having Java authenticate with the OS, however this defeats the purpose. I will just have during the setup process the user setup passwords, store them encrypted in some SQL database for authentication. This makes more sense as JAVA is typically running in a Virtual machine completely separate of the OS. This can also make it more secure, as if the OS gets breached, unless you have the passwords for the encrypted files, your data is safe.</p>


问:
Converting XCF and other files using command line with GIMP?
If I have an XCF file (or any other supported by Gimp) how can I convert it to, for example, PNG for display or further processing?</p>

答:
Bash oneliner. Only needs convert (which usually already installed from imagemagick).

```<code>convert -alpha on -background none -layers merge t2.xcf t2.png
</code>```

Script that iterates over xcf files to convert them with appropriate names:

```<code>for i in *.xcf; do convert -alpha on -background none -layers merge $i ${i/xcf/png}; done
</code>```

OwnerDisplayName: ivucica

Body:
Bash oneliner. Only needs convert (which usually already installed from imagemagick).

convert -alpha on -background none -layers merge t2.xcf t2.png

Script that iterates over xcf files to convert them with appropriate names:

for i in *.xcf; do convert -alpha on -background none -layers merge $i ${i/xcf/png}; done