问:
Best way restructure object in JS
I have array of objects, width date and time property like below. I try restructure elements by day and time.

```<code>[
  {
    data: 'data1',
    date: '15-02-2020 06:00:00'
  },
  {
    data: 'data2',
    date: '15-02-2020 12:00:00'
  },
  ...
  {
    data: 'data6',
    date: '17-02-2020 07:00:00'
  },
  {
    data: 'data7',
    date: '17-02-2020 09:00:00'
  }
]
</code>```

I want to get this:

```<code>{
  '15-02-2020' : {
    '06:00:00' : 'data1',
    '12:00:00' : 'data2'
  },
  '16-02-2020' : {
    '06:00:00' : 'data3',
    '12:00:00' : 'data4'
  },
  '17-02-2020' : {
    '01:00:00' : 'data5',
    '07:00:00' : 'data6',
    '09:00:00' : 'data7'
  }
}
</code>```

I tried use reduce, but cant. I want do that, without temporary variables in one loop.

```<code>list.reduce((obj, item) => Object.assign(obj, {[item.date]: item}), {});
</code>```

答:
You could reduce the array, split date and use the day ad key for another object.

var data = [{ data: 'data1', date: '15-02-2020 06:00:00' }, { data: 'data2', date: '15-02-2020 12:00:00' }, { data: 'data6', date: '17-02-2020 07:00:00' }, { data: 'data7', date: '17-02-2020 09:00:00' }],
    result = data.reduce((r, { data, date }) => {
        const [day, time] = date.split(' ');
        r[day] = r[day] || {};
        r[day][time] = data;
        return r;
    }, {});

console.log(result);```

Title: Best way restructure object in JS

Body:
I have array of objects, width date and time property like below. I try restructure elements by day and time.

[
  {
    data: 'data1',
    date: '15-02-2020 06:00:00'
  },
  {
    data: 'data2',
    date: '15-02-2020 12:00:00'
  },
  ...
  {
    data: 'data6',
    date: '17-02-2020 07:00:00'
  },
  {
    data: 'data7',
    date: '17-02-2020 09:00:00'
  }
]

I want to get this:

{
  '15-02-2020' : {
    '06:00:00' : 'data1',
    '12:00:00' : 'data2'
  },
  '16-02-2020' : {
    '06:00:00' : 'data3',
    '12:00:00' : 'data4'
  },
  '17-02-2020' : {
    '01:00:00' : 'data5',
    '07:00:00' : 'data6',
    '09:00:00' : 'data7'
  }
}

I tried use reduce, but cant. I want do that, without temporary variables in one loop.

list.reduce((obj, item) => Object.assign(obj, {[item.date]: item}), {});


来源: stackexchange

问:
Heroku 403 Forbidden - Laravel 5
I have a Laravel 5.8 site

https://boss-security-2.herokuapp.com/

I deployed to Heorku to test with this script that I created

```<code>appName='boss-security-2'
echo 'appName =' $appName

# heroku apps
# heroku apps:destroy appName --confirm appName
# ----------------------

echo web: vendor/bin/heroku-php-apache2 public/ > Procfile
git init
git status
git add -A
git commit -m "Initial commit"

heroku create $appName
heroku git:remote -a $appName
heroku buildpacks:set heroku/php
heroku config:set APP_KEY=9O7AegDFJhVC16jLfNNepT7TEQ7FyFZc

git push heroku master

heroku apps:info
heroku open
echo "done"
#
</code>```

I kept getting

Forbidden

>

You don't have permission to access this resource

Anything wrong in my script ?

Composer.json

```<code>{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.1.3",
        "fideloper/proxy": "^4.0",
        "guzzlehttp/guzzle": "~6.0",
        "laravel/framework": "5.8.*",
        "laravel/tinker": "^1.0",
        "laravelcollective/html": "~5.0",
        "nesbot/carbon": "^2.19",
        "pusher/pusher-php-server": "^3.4"
    },
    "require-dev": {
        "beyondcode/laravel-dump-server": "^1.0",
        "filp/whoops": "^2.0",
        "fzaninotto/faker": "^1.4",
        "mockery/mockery": "^1.0",
        "nunomaduro/collision": "^2.0",
        "phpunit/phpunit": "^7.5"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories"
        ]
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ],
        "post-install-cmd": [
            "php artisan clear-compiled",
            "chmod -R 777 public/"
        ]
    },

}
</code>```

Update 1

I checked the log, I saw this

Cannot serve directory /app/: No matching DirectoryIndex (index.php,index.html,index.htm) found, and server-generated directory index forbidden by Options directive

Update 2

I have no idea why my composer.json in my dyno doesn't seem to have my latest code. I SSHed in and check.

heroku ps:exec

Is this has something to do with my composer.lock ?

答:
I've tried http://boss-security-2.herokuapp.com/artisan and it shows the artisan sourcecode. (It should not)

I think you misconfigured the root folder.

Update

You've said that your composer.json is not updated. Have you tried to commit and push all your changes?

```<code>git add -A && git commit -m 'update' && git push heroku master
</code>```

Then try to SSH and list the contents

```<code>heroku ps:exec
</code>```

```<code>pwd && ls -la && cat Procfile
</code>```

ContentLicense: CC BY-SA 4.0

Title: Heroku 403 Forbidden - Laravel 5

Body:
I have a Laravel 5.8 site

https://boss-security-2.herokuapp.com/

I deployed to Heorku to test with this script that I created

appName='boss-security-2'
echo 'appName =' $appName

# heroku apps
# heroku apps:destroy appName --confirm appName
# ----------------------

echo web: vendor/bin/heroku-php-apache2 public/ > Procfile
git init
git status
git add -A
git commit -m "Initial commit"

heroku create $appName
heroku git:remote -a $appName
heroku buildpacks:set heroku/php
heroku config:set APP_KEY=9O7AegDFJhVC16jLfNNepT7TEQ7FyFZc

git push heroku master

heroku apps:info
heroku open
echo "done"
#

I kept getting

Forbidden

>

You don't have permission to access this resource

Anything wrong in my script ?

Composer.json

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.1.3",
        "fideloper/proxy": "^4.0",
        "guzzlehttp/guzzle": "~6.0",
        "laravel/framework": "5.8.*",
        "laravel/tinker": "^1.0",
        "laravelcollective/html": "~5.0",
        "nesbot/carbon": "^2.19",
        "pusher/pusher-php-server": "^3.4"
    },
    "require-dev": {
        "beyondcode/laravel-dump-server": "^1.0",
        "filp/whoops": "^2.0",
        "fzaninotto/faker": "^1.4",
        "mockery/mockery": "^1.0",
        "nunomaduro/collision": "^2.0",
        "phpunit/phpunit": "^7.5"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories"
        ]
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ],
        "post-install-cmd": [
            "php artisan clear-compiled",
            "chmod -R 777 public/"
        ]
    },

}

Update 1

I checked the log, I saw this

Cannot serve directory /app/: No matching DirectoryIndex (index.php,index.html,index.htm) found, and server-generated directory index forbidden by Options directive

Update 2

I have no idea why my composer.json in my dyno doesn't seem to have my latest code. I SSHed in and check.

heroku ps:exec

Is this has something to do with my composer.lock ?

Body:
I've tried http://boss-security-2.herokuapp.com/artisan and it shows the artisan sourcecode. (It should not)

I think you misconfigured the root folder.

Update

You've said that your composer.json is not updated. Have you tried to commit and push all your changes?

git add -A && git commit -m 'update' && git push heroku master

Then try to SSH and list the contents

heroku ps:exec

pwd && ls -la && cat Procfile


问:
__call__ from metaclass shadows signature of __init__
I would like to have in the code underneath that when i type  instance_of_A = A(, that the name of the supposed arguments is init_argumentA and not *meta_args, **meta_kwargs. But unfortunatally, the arguments of the __call__ method of the metaclass are shown.

```<code>class Meta(type):
    def __call__(cls,*meta_args,**meta_kwargs):
        # Something here
        return super().__call__(*meta_args, **meta_kwargs)

class A(metaclass = Meta):
    def __init__(self,init_argumentA):
        # something here

class B(metaclass = Meta):
    def __init__(self,init_argumentB):
        # something here
</code>```

I have searched for a solution and found the question How to dynamically change signatures of method in subclass?
 and Signature-changing decorator: properly documenting additional argument. But none, seem to be completely what I want. The first link uses inspect to change the amount of variables given to a function, but i can't seem to let it work for my case and I think there has to be a more obvious solution.
The second one isn't completely what I want, but something in that way might be a good alternative.

Edit: I am working in Spyder. I want this because I have thousands of classes of the Meta type and each class have different arguments, which is impossible to remember, so the idea is that the user can remember it when seeing the correct arguments show up.

答:
Using the code you provided, you can change the Meta class

class Meta(type):
    def __call__(cls, *meta_args, **meta_kwargs):
        # Something here
        return super().__call__(*meta_args, **meta_kwargs)

class A(metaclass=Meta):
    def __init__(self, x):
        pass
```

<p>to</p>

<pre class="lang-py prettyprint-override"><code>import inspect

class Meta(type):
    def __call__(cls, *meta_args, **meta_kwargs):
        # Something here

        # Restore the signature of __init__
        sig = inspect.signature(cls.__init__)
        parameters = tuple(sig.parameters.values())
        cls.__signature__ = sig.replace(parameters=parameters[1:])

        return super().__call__(*meta_args, **meta_kwargs)
</code>```

Now IPython or some IDE will show you the correct signature.

ContentLicense: CC BY-SA 3.0

Body:
I would like to have in the code underneath that when i type  instance_of_A = A(, that the name of the supposed arguments is init_argumentA and not *meta_args, **meta_kwargs. But unfortunatally, the arguments of the __call__ method of the metaclass are shown.

class Meta(type):
    def __call__(cls,*meta_args,**meta_kwargs):
        # Something here
        return super().__call__(*meta_args, **meta_kwargs)

class A(metaclass = Meta):
    def __init__(self,init_argumentA):
        # something here

class B(metaclass = Meta):
    def __init__(self,init_argumentB):
        # something here

I have searched for a solution and found the question How to dynamically change signatures of method in subclass?
 and Signature-changing decorator: properly documenting additional argument. But none, seem to be completely what I want. The first link uses inspect to change the amount of variables given to a function, but i can't seem to let it work for my case and I think there has to be a more obvious solution.
The second one isn't completely what I want, but something in that way might be a good alternative.

Edit: I am working in Spyder. I want this because I have thousands of classes of the Meta type and each class have different arguments, which is impossible to remember, so the idea is that the user can remember it when seeing the correct arguments show up.

Body:
Using the code you provided, you can change the Meta class

class Meta(type):
    def __call__(cls, *meta_args, **meta_kwargs):
        # Something here
        return super().__call__(*meta_args, **meta_kwargs)

class A(metaclass=Meta):
    def __init__(self, x):
        pass

to

import inspect

class Meta(type):
    def __call__(cls, *meta_args, **meta_kwargs):
        # Something here

        # Restore the signature of __init__
        sig = inspect.signature(cls.__init__)
        parameters = tuple(sig.parameters.values())
        cls.__signature__ = sig.replace(parameters=parameters[1:])

        return super().__call__(*meta_args, **meta_kwargs)

Now IPython or some IDE will show you the correct signature.


问:
Android Google Drive API v2 downloadUrl with access token stopped working
My app used to play Google Drive videos using v2's downloadUrl() + access_token

```<code>Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(videoItem.downloadUrl() + "&access_token=" + mAccessToken), "video/avi");
startActivity(intent);
</code>```

However, it stops working one day for no apparent reason.

I have tried using v3's webContent()

```<code>Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(videoItem.webContent()));
startActivity(intent);
</code>```

But this way they will need to log in Google on the device they are viewing the video from.

Does anyone know why v2's downloadUrl() + access_token stops working?
Also why doesn't the following works? Since I want to play my videos in a third party player no in Google Drive app.

```<code>intent.setDataAndType(Uri.parse(videoItem.webContent()), "video/avi");
</code>```

Thank you in advance.

答:
Yes, downloadUrl() + access_token stopped working on January 1, 2020, because of recent changes for the authorization for Google Drive API

Follow the new procedure as described in the documentation, basically

you will need to migrate your requests to authenticate using an HTTP
  header

Body:
My app used to play Google Drive videos using v2's downloadUrl() + access_token

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(videoItem.downloadUrl() + "&access_token=" + mAccessToken), "video/avi");
startActivity(intent);

However, it stops working one day for no apparent reason.

I have tried using v3's webContent()

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(videoItem.webContent()));
startActivity(intent);

But this way they will need to log in Google on the device they are viewing the video from.

Does anyone know why v2's downloadUrl() + access_token stops working?
Also why doesn't the following works? Since I want to play my videos in a third party player no in Google Drive app.

intent.setDataAndType(Uri.parse(videoItem.webContent()), "video/avi");

Thank you in advance.


问:
React Native: View onPress does not work
I'm facing a weird problem. In my react native app, if I set onPress event to View it is not triggered but if I set the same to Text inside View, it fires. What am I missing here?

```<code><View style={{backgroundColor: "red", padding: 20}}>
  <Text onPress={()=> {
    console.log('works');
    }
  }>X</Text>
</View>

<View style={{backgroundColor: "red", padding: 20}} onPress={()=> {
    console.log('does not work');
    }
  }>
  <Text>X</Text>
</View>
</code>```

Why is this so? Is this an issue with React Native? I'm using version 0.43

答:
Alternatively you can also provide onStartShouldSetResponder to your view, like so:</p>

```<code><View onStartShouldSetResponder={() => console.log("View click")}>
  // some code here
</View>
</code>```

Body:
I'm facing a weird problem. In my react native app, if I set onPress event to View it is not triggered but if I set the same to Text inside View, it fires. What am I missing here?

<View style={{backgroundColor: "red", padding: 20}}>
  <Text onPress={()=> {
    console.log('works');
    }
  }>X</Text>
</View>

<View style={{backgroundColor: "red", padding: 20}} onPress={()=> {
    console.log('does not work');
    }
  }>
  <Text>X</Text>
</View>

Why is this so? Is this an issue with React Native? I'm using version 0.43

Body:
Alternatively you can also provide onStartShouldSetResponder to your view, like so:

<View onStartShouldSetResponder={() => console.log("View click")}>
  // some code here
</View>


问:
Override values.yaml in helm chart using nexus
Helm Chart Structure

```<code>web-service
  |_ _ _ templates
  |_ _ _ Chart.yaml
  |_ _ _ values.yaml
</code>```

I have helm chart setup in which my helm charts for my application are packaged .tgz
and pushed to nexus repo consider https://localhost:50714/#browse/browse:helm

Which is added to helm repositories.yaml using

```<code>helm repo add nexus https://localhost:50714/
</code>```

Once Repo is added I can see the chart

```<code>helm search
NAME                                    CHART VERSION   APP VERSION     DESCRIPTION
nexus/web-service                   1.0.0-k8s                       Custom microservice Helm chart
</code>```

To Install I Fire the below command

```<code>helm install nexus/ioc-web-service --version 1.0.0-k8s
</code>```

and application get deployed. So the application is deployed using default values.yaml
I need to make this configurable so that my default values.yaml is overridden by another file lets say
values-override.yaml

```<code>web-service
  |_ _ _ templates
  |_ _ _ Chart.yaml
  |_ _ _ values.yaml
  |_ _ _ values-override.yaml
</code>```

I used helm provision of passing extra file using -f command but it gives values-override.yaml file not found

```<code>helm install nexus/web-service -f values-override.yaml --version 1.0.0-k8s
</code>```

Need Some input on how to get the pass the override values in file format. As the override values can be dynamic. On one environment it can be 1 variable in another there are be 10 variable which needs to be overridden

答:
Here are the docs for Customizing the Chart Before Installing and you can use two ways of passing config data during installation:

--values  (or  -f): Specify a YAML file with overrides. This can be specified multiple times and the rightmost file will take precedence

--set: Specify overrides on the command line.

You have to remember you need to run helm install from the directory where your YAML file is sitting.

If you are still seeing the Error: open values-override.yaml: no such file or directory, this means that Helm is probably installed as a docker container. This happens if you use Kubespray to install Helm in this case can should check which folder is being mounted to the docker by:
$ cat /usr/local/bin/helm
You might see something like this:

```<code>cat /usr/local/bin/helm

#!/bin/bash
/usr/bin/docker run --rm \
  --net=host \
  --name=helm \
  -v /etc/ssl:/etc/ssl:ro \
  -v /root/.helm:/root/.helm:rw \
  -v /usr/share/ca-certificates:/usr/share/ca-certificates:ro \
  lachlanevenson/k8s-helm:2.7.0 \
  "$@"
</code>```

Which will mean you need to copy values-override.yaml to /root/.helm directory.
You can also check the directory by $ helm init:

```<code>$ helm init
$HELM_HOME has been configured at /root/.helm.
Warning: Tiller is already installed in the cluster.
(Use --client-only to suppress this message, or --upgrade to upgrade Tiller to the current version.)
Happy Helming!
</code>```

Body:
Helm Chart Structure

web-service
  |_ _ _ templates
  |_ _ _ Chart.yaml
  |_ _ _ values.yaml

I have helm chart setup in which my helm charts for my application are packaged .tgz
and pushed to nexus repo consider https://localhost:50714/#browse/browse:helm

Which is added to helm repositories.yaml using

helm repo add nexus https://localhost:50714/

Once Repo is added I can see the chart

helm search
NAME                                    CHART VERSION   APP VERSION     DESCRIPTION
nexus/web-service                   1.0.0-k8s                       Custom microservice Helm chart

To Install I Fire the below command

helm install nexus/ioc-web-service --version 1.0.0-k8s

and application get deployed. So the application is deployed using default values.yaml
I need to make this configurable so that my default values.yaml is overridden by another file lets say
values-override.yaml

web-service
  |_ _ _ templates
  |_ _ _ Chart.yaml
  |_ _ _ values.yaml
  |_ _ _ values-override.yaml

I used helm provision of passing extra file using -f command but it gives values-override.yaml file not found

helm install nexus/web-service -f values-override.yaml --version 1.0.0-k8s

Need Some input on how to get the pass the override values in file format. As the override values can be dynamic. On one environment it can be 1 variable in another there are be 10 variable which needs to be overridden

Body:
Here are the docs for Customizing the Chart Before Installing and you can use two ways of passing config data during installation:

--values  (or  -f): Specify a YAML file with overrides. This can be specified multiple times and the rightmost file will take precedence

--set: Specify overrides on the command line.

You have to remember you need to run helm install from the directory where your YAML file is sitting.

If you are still seeing the Error: open values-override.yaml: no such file or directory, this means that Helm is probably installed as a docker container. This happens if you use Kubespray to install Helm in this case can should check which folder is being mounted to the docker by:
$ cat /usr/local/bin/helm
You might see something like this:

cat /usr/local/bin/helm

#!/bin/bash
/usr/bin/docker run --rm \
  --net=host \
  --name=helm \
  -v /etc/ssl:/etc/ssl:ro \
  -v /root/.helm:/root/.helm:rw \
  -v /usr/share/ca-certificates:/usr/share/ca-certificates:ro \
  lachlanevenson/k8s-helm:2.7.0 \
  "$@"

Which will mean you need to copy values-override.yaml to /root/.helm directory.
You can also check the directory by $ helm init:

$ helm init
$HELM_HOME has been configured at /root/.helm.
Warning: Tiller is already installed in the cluster.
(Use --client-only to suppress this message, or --upgrade to upgrade Tiller to the current version.)
Happy Helming!


问:
How to Write Getters and Setters for C-Style String Array?
I am not allowed to use std::string, and required to use C-Style string arrays.

I am working on the Getters and Setters for the string arrays but encountered the following errors:

error: prototype for void Unit::SetName(const char*, unsigned int) does not match any in class 'Unit'

error: candidate is: void Unit::SetName(const char**, unsigned int)

Below is my code snippet.

```<code>#ifndef UNIT_H
#define UNIT_H
#include <iostream>
#include <string.h>
using namespace std;
const unsigned UnitNameSize = 10;

class Unit {
public:
  Unit();
  Unit( const char * nam, unsigned cred );

  const char* GetName() const;
  void SetName( const char *nam[], unsigned UnitNameSize);

  friend ostream & operator <<( ostream & os, const Unit & U );
  friend istream & operator >>( istream & input, Unit & U );

private:
  char name[UnitNameSize];
  int credits;
};

inline const char* Unit::GetName() const{
  return name;
}

//error-ed set method
inline void Unit::SetName( const char* nam , unsigned namSize){
  name[] = nam[namSize];
}
#endif
</code>```

答:
The error message is pointing to the fact that SetName's declaration and definition's signature does not match. In one you are expecting pointer to c string in the other a c string. Also, your SetName function is wrong, it would attempt to access the char pass the end of the string of the param.
 Why can't you use std:: string?</p>

Body:
I am not allowed to use std::string, and required to use C-Style string arrays.

I am working on the Getters and Setters for the string arrays but encountered the following errors:

error: prototype for void Unit::SetName(const char*, unsigned int) does not match any in class 'Unit'

error: candidate is: void Unit::SetName(const char**, unsigned int)

Below is my code snippet.

#ifndef UNIT_H
#define UNIT_H
#include <iostream>
#include <string.h>
using namespace std;
const unsigned UnitNameSize = 10;

class Unit {
public:
  Unit();
  Unit( const char * nam, unsigned cred );

  const char* GetName() const;
  void SetName( const char *nam[], unsigned UnitNameSize);

  friend ostream & operator <<( ostream & os, const Unit & U );
  friend istream & operator >>( istream & input, Unit & U );

private:
  char name[UnitNameSize];
  int credits;
};

inline const char* Unit::GetName() const{
  return name;
}

//error-ed set method
inline void Unit::SetName( const char* nam , unsigned namSize){
  name[] = nam[namSize];
}
#endif


问:
Get Bastion Shareable Link REST api results into an error
We have provisioned few Azure VMs and have also provisioned the Azure Bastion resource within the same Azure VNET (inside its own dedicated subnet) as that of VMs, the entire set up appear to work fine as we can establish the RDP and SSH sessions using bastion, however the REST endpoint to get the bastion shareable links does not appear to work and always comes back with an error below

No HTTP resource was found that matches the request URI 'https://{bastionregion}.network.azure.com:30018/xxxxxxx-ca3c-xxxx-ae7c-xxxxxxxxxx/132229390607747023/subscriptions/{subscription-id}/resourceGroups/{bastion-rg}/providers/Microsoft.Network/bastionHosts/{bastion-host-name}/getShareableLinks?api-version=2019-11-01'

It also appears that the documentation's 'Try It' also results into the same error.
Has anyone else tried it or have ever managed to get it working?

答:
Based on the doc that you've shared, the call should be to the management endpoint -
https://management.azure.com.

Also, since there is no public documentation for this, I believe this feature is still a work-in-progress. Anyhow, let me confirm with the respective backend team and will update you on this.

Update:
This is still only in private preview and not GA.We are working on opening the API to everyone. We will however not be providing official support for this at this time. We will reassess providing support at a future time.


答:
Since the length of the name in your class is a fixed length, the easiest way to do this std::strncpy. That would work as follows:

```<code>inline void Unit::SetName (char const * name) {
  std::strncpy(this->name, name, UnitNameSize);
  // Ensure name member ends in null-terminator,
  // even if new name length is >= UnitNameSize.
  this->name[UnitNameSize - 1] = 0;
}
</code>```

Title: How to Write Getters and Setters for C-Style String Array?

Body:
Since the length of the name in your class is a fixed length, the easiest way to do this std::strncpy. That would work as follows:

inline void Unit::SetName (char const * name) {
  std::strncpy(this->name, name, UnitNameSize);
  // Ensure name member ends in null-terminator,
  // even if new name length is >= UnitNameSize.
  this->name[UnitNameSize - 1] = 0;
}


问:
How to create property to define different schema name with universal prefix?
The problem is that I have a lot of nativeQueries where I use schema name prefix to define table which I want to use.

For example:

SELECT * FROM SCHEMA.USERS u WHERE u.id = 100;
```

<p>The problem is that now I have 2 database with the same tables but different schema names.</p>

```DB1: SCHEMA_1.USERS
DB2: SCHEMA_2.USERS
```

Is this possible to create property for hibernate where I can define that SCHEMA_1 and SCHEMA_2 will be known as SCHEMA? As I checked, Oracle SYNONYM is not working for schemas..

答:
I am not from Hibernate background, so I don't know if there is any native way to do this in Hibernate itself. In pure Oracle method, when you connect to the database, get the current schema name and assign it to a variable and then use it in the SQL statement.

```<code>select sys_context( 'userenv', 'current_schema' ) as SCHEMA from dual;
</code>```

The above output you could assign to the SCHEMA variable in your Hibernate application code(again I am not sure what is the Hibernate method of using a variable so assume $ for now):

```<code>SELECT * FROM $SCHEMA.USERS u WHERE u.id = 100;
</code>```

So, when you connect to DB1, you will get schema name let's say SCHEMA_1 and then from DB2 you will get SCHEMA_2. But these values will be assigned to $SCHEMA variable so you need not worry about changing it as it will dynamically take the schema name.

Body:
The problem is that I have a lot of nativeQueries where I use schema name prefix to define table which I want to use.

For example:

SELECT * FROM SCHEMA.USERS u WHERE u.id = 100;

The problem is that now I have 2 database with the same tables but different schema names.

DB1: SCHEMA_1.USERS
DB2: SCHEMA_2.USERS

Is this possible to create property for hibernate where I can define that SCHEMA_1 and SCHEMA_2 will be known as SCHEMA? As I checked, Oracle SYNONYM is not working for schemas..

Body:
I am not from Hibernate background, so I don't know if there is any native way to do this in Hibernate itself. In pure Oracle method, when you connect to the database, get the current schema name and assign it to a variable and then use it in the SQL statement.

select sys_context( 'userenv', 'current_schema' ) as SCHEMA from dual;

The above output you could assign to the SCHEMA variable in your Hibernate application code(again I am not sure what is the Hibernate method of using a variable so assume $ for now):

SELECT * FROM $SCHEMA.USERS u WHERE u.id = 100;

So, when you connect to DB1, you will get schema name let's say SCHEMA_1 and then from DB2 you will get SCHEMA_2. But these values will be assigned to $SCHEMA variable so you need not worry about changing it as it will dynamically take the schema name.


问:
Showing JSON data in ReactJS
I cant show the JSON response to the HTML, all I am getting is his.state.selectedData.map is not a function.

This is the payload

```<code>{
    "id": 1,
    "name":"john",
    "age" : 22
}
</code>```

This is in the constructor

```<code>this.state = {
selectedData : []
}
</code>```

This is the HTTP request:

```<code>axios.post("/api/data", data)
          .then(res =>{
             console.log(res)
             this.setState({
                selectedData : res.data
             })

          })
</code>```

And this is how I am trying to show the result

```<code> <div>
  <ul>
    { this.state.selectedData.map(data => {
      <li>{data.name}</li>
    })}
  </ul>
  </div>
</code>```

what I am doing wrong ?

答:
constructor(props) {
super(props);
this.state = {
  loadedList: [],
  lists: [],
};
  }

componentDidMount() {
    axios.get('http://localhost:3001/../static/data/terrifdata.json')
      .then(response => {
       this.setState({
         lists: response.data,
         loadedList: response.data,
         isLoading: false
        })
    })
 }

{loadedList.map((postDetail, index) => {
                    return (

                     {postDetail.name}

                  )}
               }

```

Title: Showing JSON data in ReactJS

Body:
I cant show the JSON response to the HTML, all I am getting is his.state.selectedData.map is not a function.

This is the payload

{
    "id": 1,
    "name":"john",
    "age" : 22
}

This is in the constructor

this.state = {
selectedData : []
}

This is the HTTP request:

axios.post("/api/data", data)
          .then(res =>{
             console.log(res)
             this.setState({
                selectedData : res.data
             })

          })

And this is how I am trying to show the result

    { this.state.selectedData.map(data => {

{data.name}

    })}

what I am doing wrong ?

Body:
constructor(props) {
super(props);
this.state = {
  loadedList: [],
  lists: [],
};
  }

componentDidMount() {
    axios.get('http://localhost:3001/../static/data/terrifdata.json')
      .then(response => {
       this.setState({
         lists: response.data,
         loadedList: response.data,
         isLoading: false
        })
    })
 }

<div>
{loadedList.map((postDetail, index) => {
                    return (
                  <h5>
                     {postDetail.name}
                  </h5>
                  )}
               }
</div>


问:
is it bad practice to call another interface method from a interface on a java interface?
For example i have an interface as following:

```<code>interface Test  {
    void a();
    void b();
}

class TestImpl implements Test {
    public void a() {
        // Do something
    }

    public void b() {
        // Do something
        a();
    }
}
</code>```

i think this is bad practice. is it true? or is there any theory on this?

答:
This not bad practice. For example check the following use cases.

```<code>interface Test  {
   void bigTask();
   void validateBigTask();
   void performBigTask();
}
</code>```

In this case you might subdivide your big task for clarity and readability.

Body:
For example i have an interface as following:

interface Test  {
    void a();
    void b();
}

class TestImpl implements Test {
    public void a() {
        // Do something
    }

    public void b() {
        // Do something
        a();
    }
}

i think this is bad practice. is it true? or is there any theory on this?

Body:
This not bad practice. For example check the following use cases.

interface Test  {
   void bigTask();
   void validateBigTask();
   void performBigTask();
}

In this case you might subdivide your big task for clarity and readability.


问:
Chat history of tensor flow chat bot in XML
How to store the chat history as xml data using python ?

Chat bot is built using tensorflow,tflearn.

Please do help me on this.

答: Hi you can try looking at xml.etree  outstanding library for xml. If you need any specific details on how to create/read/write the docs have everything, or just reach out.</p>


问:
How to use lambda if else in map() on list in python?
I have a list ['apple', 'banana', 'cherry']

I want to run map on it which will select a few items

```<code>l = map(lambda x : x if x == "apple" else pass, ['apple', 'banana', 'cherry'])
</code>```

it seems that it should work but its giving syntax error

What is the issue here?

答:
Depending on size of your list it might be better to use generator rather than list comprehension, that is:

```<code>l = (x for x in ['apple', 'banana', 'cherry'] if x=='apple')
</code>```

generally list comprehensions will lead to bigger memory usage, than equivalent generators, though for small sizes difference might be neglible.

Body:
I have a list ['apple', 'banana', 'cherry']

I want to run map on it which will select a few items

l = map(lambda x : x if x == "apple" else pass, ['apple', 'banana', 'cherry'])

it seems that it should work but its giving syntax error

What is the issue here?

Body:
Depending on size of your list it might be better to use generator rather than list comprehension, that is:

l = (x for x in ['apple', 'banana', 'cherry'] if x=='apple')

generally list comprehensions will lead to bigger memory usage, than equivalent generators, though for small sizes difference might be neglible.


问:
How can I run a protractor config file (.ts) with ts-node?
I used to compile e2e protractor tests written in TS before run, but now I figured out how to compile ts files in run-time -- ts-node appeared to be a great tool for that. As many articles say, I registered ts-node in protractor config file, so that I can run my test specs as if they are .ts files and they will be compiled in tun-time. Something like this:

```<code>beforeLaunch: () => {
        require('ts-node').register({
            compilerOptions: {
                module: 'commonjs'
            },
            disableWarnings: true,
            fast: true
          });
    },

</code>```

That's great. But all cases I met included examples with .js config files --> you don't need to compile config files, but all specs can be in TS and will be compiled with ts-node.
What I wish to have is having all my files in TypeScript: both configs and specs. How can I run my protractor tests giving config.ts and having specs.ts in there?
Something like protractor ts-node config.ts would be just awesome.

答:
Add the below code in your onPrepare() of config.js

```<code>  onPrepare() {
    /* Compile TS files */
    require('ts-node').register({
      project: './tsconfig.json'
    });
</code>```

Hope it helps you

Body:
I used to compile e2e protractor tests written in TS before run, but now I figured out how to compile ts files in run-time -- ts-node appeared to be a great tool for that. As many articles say, I registered ts-node in protractor config file, so that I can run my test specs as if they are .ts files and they will be compiled in tun-time. Something like this:

beforeLaunch: () => {
        require('ts-node').register({
            compilerOptions: {
                module: 'commonjs'
            },
            disableWarnings: true,
            fast: true
          });
    },

That's great. But all cases I met included examples with .js config files --> you don't need to compile config files, but all specs can be in TS and will be compiled with ts-node.
What I wish to have is having all my files in TypeScript: both configs and specs. How can I run my protractor tests giving config.ts and having specs.ts in there?
Something like protractor ts-node config.ts would be just awesome.

Body:
Add the below code in your onPrepare() of config.js

  onPrepare() {
    /* Compile TS files */
    require('ts-node').register({
      project: './tsconfig.json'
    });

Hope it helps you


问:
Regular Expression in .NET
I am new to .NET regular expressions.

My regular expression below alerted too many ) at run time. I don't know how to handle the ()

```<code>input = "Get_MyAppList()";
Match match = Regex.Match(input, @"Get_([A-Za-z0-9\-]+)\()$", RegexOptions.IgnoreCase);
</code>```

答:
get some regex tool that will help you create regexes that provides regex check on the fly with hints about mistakes whereabouts, generic error messages aren't good enough often.

I can recommend Expresso that I use, remember that most tricky stuff has to be preceded by

\

when you create regex (except letters & numbers basicly)
so for "()" to match you need \(\)

Title: Regular Expression in .NET

Body:
I am new to .NET regular expressions.

My regular expression below alerted too many ) at run time. I don't know how to handle the ()

input = "Get_MyAppList()";
Match match = Regex.Match(input, @"Get_([A-Za-z0-9\-]+)\()$", RegexOptions.IgnoreCase);


问:
How can I update user model extended via "OneToOneField"
I have some issues with updating my database, in my serializer I use extended via OneToOneField django user model with two extra fields with user image and his motto. So I think the problem with instance in my serializer, but I can't figure out how to do that. </p>

```<code>#core.models
class MangaUser(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    user_image = models.ImageField(upload_to='upicks')
    user_motto = models.CharField(max_length=256)

#api.serializers
class UserSerializer(serializers.ModelSerializer):
    #mangauser_set = serializers.SerializerMethodField()
    user_image = serializers.ImageField(source='mangauser.user_image')
    user_moto = serializers.CharField(source='mangauser.user_motto')

    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'password', 'user_image', 'user_motto']
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        password = validated_data.pop('password', None)
        instance = self.Meta.model(**validated_data)
        if password is not None:
            instance.set_password(password)
        instance.save()
        return instance

    def update(self, instance, validated_data):
        for attr, value in validated_data.items():
            if attr == 'password':
                instance.set_password(value)
            else:
                setattr(instance, attr, value)
        instance.save()
        return instance

#api.view
class GetUserInfo(APIView):

    permission_classes = (IsAuthenticated,)
    serializer_class = UserSerializer

    def get(self, request, *args, **kwargs):
        # serializer to handle turning our `User` object into something that
        # can be JSONified and sent to the client.
        serializer = self.serializer_class(request.user, context={"request":request})

        return Response(serializer.data, status=status.HTTP_200_OK)

    def put(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response(serializer.data, status=status.HTTP_200_OK)
#response
ValueError at /api/v1/userinfo/
Cannot assign "{'user_motto': 'js говно'}": "User.mangauser" must be a "MangaUser" instance.
</code>```

答:
What you did seems pretty complicated to me.
Did you read : https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#extending-the-existing-user-model ?

This is what I use :

from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
    def get_profile(self):
        return Profil.objects.get(user=self)
    class Meta(AbstractUser.Meta):
        db_table = 'auth_user'

class Profil (models.Model):
    user = models.OneToOneField (settings.AUTH_USER_MODEL, unique=True, editable=False, help_text="1-to-1 to user", on_delete=models.CASCADE)

    image_one = models.ImageField(upload_to="upload_to/images/", blank=True, null=True, help_text=_(u"Image qui sera accolée à votre profil."))

    class Meta:
        order_with_respect_to = 'user'```

Body:
I have some issues with updating my database, in my serializer I use extended via OneToOneField django user model with two extra fields with user image and his motto. So I think the problem with instance in my serializer, but I can't figure out how to do that.

#core.models
class MangaUser(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    user_image = models.ImageField(upload_to='upicks')
    user_motto = models.CharField(max_length=256)

#api.serializers
class UserSerializer(serializers.ModelSerializer):
    #mangauser_set = serializers.SerializerMethodField()
    user_image = serializers.ImageField(source='mangauser.user_image')
    user_moto = serializers.CharField(source='mangauser.user_motto')

    class Meta:
        model = User
        fields = ['id', 'username', 'email', 'password', 'user_image', 'user_motto']
        extra_kwargs = {'password': {'write_only': True}}

    def create(self, validated_data):
        password = validated_data.pop('password', None)
        instance = self.Meta.model(**validated_data)
        if password is not None:
            instance.set_password(password)
        instance.save()
        return instance

    def update(self, instance, validated_data):
        for attr, value in validated_data.items():
            if attr == 'password':
                instance.set_password(value)
            else:
                setattr(instance, attr, value)
        instance.save()
        return instance

#api.view
class GetUserInfo(APIView):

    permission_classes = (IsAuthenticated,)
    serializer_class = UserSerializer

    def get(self, request, *args, **kwargs):
        # serializer to handle turning our `User` object into something that
        # can be JSONified and sent to the client.
        serializer = self.serializer_class(request.user, context={"request":request})

        return Response(serializer.data, status=status.HTTP_200_OK)

    def put(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response(serializer.data, status=status.HTTP_200_OK)
#response
ValueError at /api/v1/userinfo/
Cannot assign "{'user_motto': 'js говно'}": "User.mangauser" must be a "MangaUser" instance.


问:
INSERT INTO SELECT and other data
I want to copy data from first table to second table and add other data to other columns,

First table: (id, name)
Second table: (id, name, turn)

Result: s.id = f.id, s.name = f.name, s.turn = '?' (my other data)

Example (may be) sql:

```<code>INSERT INTO second (SELECT id, name FROM first), 'other'
</code>```

答:
The correct syntax is:

```<code>INSERT INTO second (id, name, turn)
    SELECT id, name, 'other'
    FROM first;
</code>```

Note the listing of the column names for the INSERT.  This is not strictly required, but highly recommended to avoid unexpected problems.

Title: INSERT INTO SELECT and other data

Body:
I want to copy data from first table to second table and add other data to other columns,

First table: (id, name)
Second table: (id, name, turn)

Result: s.id = f.id, s.name = f.name, s.turn = '?' (my other data)

Example (may be) sql:

INSERT INTO second (SELECT id, name FROM first), 'other'

Body:
The correct syntax is:

INSERT INTO second (id, name, turn)
    SELECT id, name, 'other'
    FROM first;

Note the listing of the column names for the INSERT.  This is not strictly required, but highly recommended to avoid unexpected problems.


问:
My varnish config doesn't seem to be working properly
I'm very new on varnish and I've a business on my hands recently. It's a local magazine website http caching (Tech Stack is Javascript + PHP). I'm trying to use varnish 4 for caching the website. What they want me to do is; any new articles should be appeared on FE immediately, any deleted articles should be erased from the FE immediately, any changes on website's current appereance should be applied directly (changing articles' current locations, they can be dragged anywhere on the website based on articles' popularity change.) and finally any changes on existing articles should be applied to website immediately. As you see on the config below, in sub vcl_recv block I tried to use return(purge) for POST requests, because new articles and article changes is applied via POST request. But it doesn't work at all. When I try create a new dummy content or make changes on existing articles, it's not purging the cache and showing the fresh content even if POST request is successful. Also, on the BE side, I tried to use if (beresp.status == 404) for deleted articles, but it doesn't work too. When I delete the dummy article I created, it's not being deleted too, I'm still seein the stale content. How should I change my config to get all these things done? Thank you.

my varnish config is ;

```<code>
import directors;
import std;

backend server1 {
    .host = "<some ip>";
    .port = "<some port>";
}

sub vcl_init {
    new bar = directors.round_robin();
    bar.add_backend(server1);
}
sub vcl_recv {
    set req.backend_hint = bar.backend();

    if (req.http.Cookie == "") {
        unset req.http.Cookie;
    }

    set req.http.Cookie = regsuball(req.http.Cookie, "(^|;\s*)(__[a-z]+|has_js)=[^;]*", "");

    if (req.url ~ "\.(css|js|png|gif|jp(e)?g|swf|ico)") {
        unset req.http.cookie;
    }
    if (req.url ~ "\.*") {
        unset req.http.cookie;
    }
    if (req.method == "POST") {
        return(purge);
    }
}
sub vcl_deliver {

    # A bit of debugging info.
    if (obj.hits > 0) {
        set resp.http.X-Cache = "HIT";
    }
    else {
        set resp.http.X-Cache = "MISS";
    }
}

sub vcl_backend_response {

    set beresp.grace = 1h;

    set beresp.ttl = 120s;

    if (bereq.url ~ "\.*") {
        unset beresp.http.Set-Cookie;
        unset beresp.http.Cache-Control;
    }
    if (bereq.method == "POST") {
       return(abandon);
   }
    if (beresp.status == 404) {
       return(abandon);
    }
    return (deliver);
}
</code>```

答:
No need to use the director if you only have one backend. Varnish will automatically select the backend you declared if there's only 1 backend.

Purging content

The POST purge call you're doing is not ideal. Please have a look at the following page to learn more about content invalidation in Varnish: https://varnish-cache.org/docs/6.0/users-guide/purging.html#http-purging

The snippet on that page contains an ACL to protect your platform from unauthorized purges.

It's important to know that you'll need to create a hook into your CMS or your MVC controller, that does the purge call.Here's a simple example using curl in PHP:

```<code>    $curl = curl_init("http://your.varnish.cache/url-to-purge");
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PURGE");
    curl_exec($curl);
</code>```

As you can see, this is an HTTP request done in cURL that uses the custom PURGE HTTP request method. This call needs to be executed in your good right after the changes are stored in the database. This post-publishing hook will ensure that Varnish clears this specific object from cache.

VCL cleanup

The statement below doesn't look like a reliable way to remove cookies, because the expression will remove cookies from all pages dat contain a dot:

```<code>    if (req.url ~ "\.*") {
        unset req.http.cookie;
    }
</code>```

The same applies to the following statement coming from the vcl_backend_response hook:

```<code>    if (bereq.url ~ "\.*") {
        unset beresp.http.Set-Cookie;
        unset beresp.http.Cache-Control;
    }
</code>```

I assume some pages do actually need cookies to properly function. An admin panel for example, or the CMS, or maybe even a header that indicates whether or not you're logged in.

The best way forward is to define a blacklist or whitelist of URL patterns that can or cannot be cached.

Here's an example:

```<code>    if(req.url !~ "^/(admin|user)" {
        unset req.http.Cookie;
    }
</code>```

The example above will only keep cookies for pages that start with /admin or /user. There are other ways as well.

Conclusion

I hope the purging part is clear. If not, please take a closer look at https://varnish-cache.org/docs/6.0/users-guide/purging.html#http-purging.

In regards to the VCL cleanup: purging can only work if the right things are stored in cache. Dealing with cookies can be tricky in Varnish.

Just try to define under what circumstances cookies should be kept for specific pages. Otherwise, you can just remove the cookies.

Hope that helps. Good luck.
Thijs

Body:
I'm very new on varnish and I've a business on my hands recently. It's a local magazine website http caching (Tech Stack is Javascript + PHP). I'm trying to use varnish 4 for caching the website. What they want me to do is; any new articles should be appeared on FE immediately, any deleted articles should be erased from the FE immediately, any changes on website's current appereance should be applied directly (changing articles' current locations, they can be dragged anywhere on the website based on articles' popularity change.) and finally any changes on existing articles should be applied to website immediately. As you see on the config below, in sub vcl_recv block I tried to use return(purge) for POST requests, because new articles and article changes is applied via POST request. But it doesn't work at all. When I try create a new dummy content or make changes on existing articles, it's not purging the cache and showing the fresh content even if POST request is successful. Also, on the BE side, I tried to use if (beresp.status == 404) for deleted articles, but it doesn't work too. When I delete the dummy article I created, it's not being deleted too, I'm still seein the stale content. How should I change my config to get all these things done? Thank you.

my varnish config is ;

import directors;
import std;

backend server1 {
    .host = "<some ip>";
    .port = "<some port>";
}

sub vcl_init {
    new bar = directors.round_robin();
    bar.add_backend(server1);
}
sub vcl_recv {
    set req.backend_hint = bar.backend();

    if (req.http.Cookie == "") {
        unset req.http.Cookie;
    }

    set req.http.Cookie = regsuball(req.http.Cookie, "(^|;\s*)(__[a-z]+|has_js)=[^;]*", "");

    if (req.url ~ "\.(css|js|png|gif|jp(e)?g|swf|ico)") {
        unset req.http.cookie;
    }
    if (req.url ~ "\.*") {
        unset req.http.cookie;
    }
    if (req.method == "POST") {
        return(purge);
    }
}
sub vcl_deliver {

    # A bit of debugging info.
    if (obj.hits > 0) {
        set resp.http.X-Cache = "HIT";
    }
    else {
        set resp.http.X-Cache = "MISS";
    }
}

sub vcl_backend_response {

    set beresp.grace = 1h;

    set beresp.ttl = 120s;

    if (bereq.url ~ "\.*") {
        unset beresp.http.Set-Cookie;
        unset beresp.http.Cache-Control;
    }
    if (bereq.method == "POST") {
       return(abandon);
   }
    if (beresp.status == 404) {
       return(abandon);
    }
    return (deliver);
}

Body:
No need to use the director if you only have one backend. Varnish will automatically select the backend you declared if there's only 1 backend.

Purging content

The POST purge call you're doing is not ideal. Please have a look at the following page to learn more about content invalidation in Varnish: https://varnish-cache.org/docs/6.0/users-guide/purging.html#http-purging

The snippet on that page contains an ACL to protect your platform from unauthorized purges.

It's important to know that you'll need to create a hook into your CMS or your MVC controller, that does the purge call.Here's a simple example using curl in PHP:

    $curl = curl_init("http://your.varnish.cache/url-to-purge");
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PURGE");
    curl_exec($curl);

As you can see, this is an HTTP request done in cURL that uses the custom PURGE HTTP request method. This call needs to be executed in your good right after the changes are stored in the database. This post-publishing hook will ensure that Varnish clears this specific object from cache.

VCL cleanup

The statement below doesn't look like a reliable way to remove cookies, because the expression will remove cookies from all pages dat contain a dot:

    if (req.url ~ "\.*") {
        unset req.http.cookie;
    }

The same applies to the following statement coming from the vcl_backend_response hook:

    if (bereq.url ~ "\.*") {
        unset beresp.http.Set-Cookie;
        unset beresp.http.Cache-Control;
    }

I assume some pages do actually need cookies to properly function. An admin panel for example, or the CMS, or maybe even a header that indicates whether or not you're logged in.

The best way forward is to define a blacklist or whitelist of URL patterns that can or cannot be cached.

Here's an example:

    if(req.url !~ "^/(admin|user)" {
        unset req.http.Cookie;
    }

The example above will only keep cookies for pages that start with /admin or /user. There are other ways as well.

Conclusion

I hope the purging part is clear. If not, please take a closer look at https://varnish-cache.org/docs/6.0/users-guide/purging.html#http-purging.

In regards to the VCL cleanup: purging can only work if the right things are stored in cache. Dealing with cookies can be tricky in Varnish.

Just try to define under what circumstances cookies should be kept for specific pages. Otherwise, you can just remove the cookies.

Hope that helps. Good luck.
Thijs


问:
How to ARRAYFORMULA SUMIF that looks at each row?
I can't work out how to ARRAYFORMULA this formula that I have in each row of a column as it checks whether the cell in the row is in the column:

=IF(L2=1, SUMIFS(G:G,D:D,D2,C:C,C2,B:B,B2),"")

=IF(L3=1, SUMIFS(G:G,D:D,D3,C:C,C3,B:B,B3),"") etc.

I have tried:
=ARRAYFORMULA(IF(INDIRECT(CONCAT("L",ROW(L2:L)))=1,SUMIFS(G2:G,D2:D,INDIRECT(CONCAT("D",ROW(D2:D))),C2:C,INDIRECT(CONCAT("C",ROW(C2:C))),B2:B,INDIRECT(CONCAT("B",ROW(B2:B)))),"")) to try and check the cell on the given row against the column, but the formula isn't working for each row, only the row the formula is in.

Please could someone help?

Solved with =ARRAYFORMULA(IF(L2:L=1,SUMIF(D2:D&C2:C&B2:B,D2:D&C2:C&B2:B,G2:G),""))


问:
bash variable with double-quotes
There is an exported env-variable X:

```<code>X="-t \"2 2.1\""
</code>```

The following command is parsed wrong when using this variable:

```<code>yarn jest $X
</code>```

```<code>yarn jest -t '"2' '2.1"'
</code>```

Instead of:

```<code>yarn jest -t "2 2.1"
</code>```

I have read a-lot of similar questions but none of them worked. Any help?

答:
Try using X="-t '2 2.1'"

Use single quotes inside double quotes instead of using double quotes twice.

Hope this helps

Title: bash variable with double-quotes

Body:
There is an exported env-variable X:

X="-t \"2 2.1\""

The following command is parsed wrong when using this variable:

yarn jest $X

yarn jest -t '"2' '2.1"'

Instead of:

yarn jest -t "2 2.1"

I have read a-lot of similar questions but none of them worked. Any help?


问:
Oozie loading jars provided by user first
I have tried oozie.launcher.mapreduce.job.user.classpath.first property in workflow.xml to load my jars first over sharelib jars.
Unable to run workflow when this property is used.
hadoop-hdfs is available in the provided jar and version is not incompatible

答:
Maven relocation strategy can be used to avoid conflicting classes
http://maven.apache.org/plugins/maven-shade-plugin/examples/class-relocation.html
Posting pom.xml shaded plugin config which worked for me</p>

```<code><plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>3.2.1</version>
        <executions>
            <execution>
                <goals>
                    <goal>shade</goal>
                </goals>
                <configuration>
                    <relocations>
                        <relocation>
                            <pattern>org.apache.http</pattern>
                            <shadedPattern>shaded.org.apache.http</shadedPattern>
                        </relocation>
                    </relocations>
                    <shadedArtifactAttached>true</shadedArtifactAttached>
                    <filters>
                        <filter>
                            <artifact>*:*</artifact>
                            <excludes>
                                <exclude>META-INF/*.SF</exclude>
                                <exclude>META-INF/*.DSA</exclude>
                                <exclude>META-INF/*.RSA</exclude>
                            </excludes>
                        </filter>
                    </filters>
                </configuration>
            </execution>
        </executions>
    </plugin>
</plugins>
</code>```

Body:
Maven relocation strategy can be used to avoid conflicting classes
http://maven.apache.org/plugins/maven-shade-plugin/examples/class-relocation.html
Posting pom.xml shaded plugin config which worked for me

<plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>3.2.1</version>
        <executions>
            <execution>
                <goals>
                    <goal>shade</goal>
                </goals>
                <configuration>
                    <relocations>
                        <relocation>
                            <pattern>org.apache.http</pattern>
                            <shadedPattern>shaded.org.apache.http</shadedPattern>
                        </relocation>
                    </relocations>
                    <shadedArtifactAttached>true</shadedArtifactAttached>
                    <filters>
                        <filter>
                            <artifact>*:*</artifact>
                            <excludes>
                                <exclude>META-INF/*.SF</exclude>
                                <exclude>META-INF/*.DSA</exclude>
                                <exclude>META-INF/*.RSA</exclude>
                            </excludes>
                        </filter>
                    </filters>
                </configuration>
            </execution>
        </executions>
    </plugin>
</plugins>


问:
kubernetes multi domain dynamic routing
Hello I would like to know how to dynamically route multiple domains to different services in Kubernetes, I'm trying to let my users add a domain to their accounts and based on that domain route to a specific service to render their webpage but with their domain. I have no idea where to start and would like to know if this is possible with Kubernetes.</p>

答:
Since you have tagged the question with google cloud my answer is geared towards google cloud.

For HTTP/HTTPS type traffic you can create an ingress resource and the ingress controller(nginx or GKE ingress) will create a HTTP Loadbalancer in google cloud. Then you can provision a static IP to the load balancer. Finally you can configure your domain in DNS to route traffic to that static IP whenever an user hits your domain.

Guide on how to create ingress and provision static IP.

Guide on configuring domain names with static IP.

Full guide on using nginx ingress controller in google cloud.

Here is the architecture of above nginx guide.

For multi domain use case you just extend the above and configure different domains using the same construct.

Title: kubernetes multi domain dynamic routing


问:
getting exception when running soup findall loop
i'm trying to see if specific string it in a table . so i have tried to find it with soup.find all .
my code is :

```<code>for i in soup:
    tmp = soup.findAll("td", {"class": "spec-name"})
    tmp2 = soup.findAll("td", {"class": "spec-value"})
    str1 = tmp[i]
    str2 = tmp[i+1]
    if ('Touch' in str1 and 'yes' in str2 or 'Screen' in str1 and 'YES' in str2):
        IsTouch = "touch screen, "
        FIsTouch = 'yes'
    if ('Touch' in str1 and 'NO' in str2 or 'Screen' in str1 and 'No' in str2):
        IsTouch = "not screen touch"
        FIsTouch = 'no'
        break
</code>```

i would like to see if the "yes" is inline with the category "touch"

but - i'm getting except .

what i'm i doing wrong ?

答:
i have managed to find a solution with 2 for loops :</p>

```<code>def get_touch(short_desc,tempCat,soup):
for i in soup.findAll("td", {"class": "spec-name"}):
    tmp=str(i)
    if ('Touch' in tmp or 'touch' in tmp):
        for z in soup.findAll("td", {"class": "spec-value"}):
            tmp2=str(z)
            if('NO' in tmp2 or 'no' in tmp2 or 'No' in tmp2 or 'no' in tmp2):
                IsTouch = "not touch screen, "
                FIsTouch = 'no'
                break
            elif ('YES' in tmp2 or 'yes' in tmp2 or 'Yes' in tmp2):
                IsTouch = "touch screen, "
                FIsTouch = 'yes'
                break
        else:
            continue
</code>```

Body:
i'm trying to see if specific string it in a table . so i have tried to find it with soup.find all .
my code is :

for i in soup:
    tmp = soup.findAll("td", {"class": "spec-name"})
    tmp2 = soup.findAll("td", {"class": "spec-value"})
    str1 = tmp[i]
    str2 = tmp[i+1]
    if ('Touch' in str1 and 'yes' in str2 or 'Screen' in str1 and 'YES' in str2):
        IsTouch = "touch screen, "
        FIsTouch = 'yes'
    if ('Touch' in str1 and 'NO' in str2 or 'Screen' in str1 and 'No' in str2):
        IsTouch = "not screen touch"
        FIsTouch = 'no'
        break

i would like to see if the "yes" is inline with the category "touch"

but - i'm getting except .

what i'm i doing wrong ?

Body:
i have managed to find a solution with 2 for loops :

def get_touch(short_desc,tempCat,soup):
for i in soup.findAll("td", {"class": "spec-name"}):
    tmp=str(i)
    if ('Touch' in tmp or 'touch' in tmp):
        for z in soup.findAll("td", {"class": "spec-value"}):
            tmp2=str(z)
            if('NO' in tmp2 or 'no' in tmp2 or 'No' in tmp2 or 'no' in tmp2):
                IsTouch = "not touch screen, "
                FIsTouch = 'no'
                break
            elif ('YES' in tmp2 or 'yes' in tmp2 or 'Yes' in tmp2):
                IsTouch = "touch screen, "
                FIsTouch = 'yes'
                break
        else:
            continue


问:
Run a command over SSH with JSch
I'm trying to run a command over SSH with JSch, but JSch has virtually no documentation and the examples I've found are terrible. For example, this one doesn't show code for handling the output stream. And, this one uses an ugly hack to know when to stop reading from the output stream.</p>

答:
I struggled for half a day to get JSCH to work without using the System.in as the input stream to no avail. I tried Ganymed http://www.ganymed.ethz.ch/ssh2/ and had it going in 5 minutes.
All the examples seem to be aimed at one usage of the app and none of the examples showed what i needed. Ganymed's example Basic.java Baaaboof Has everything i need.</p>

Title: Run a command over SSH with JSch


问:
Error: object_detection.utils ModuleNotFoundError
I'm following this tutorial (https://towardsdatascience.com/creating-your-own-object-detector-ad69dda69c85) to create my own object detector.

On the topic 'Generating TFRecords for training', whe i try run this code:

```<code>python generate_tfrecord.py --csv_input=images\train_labels.csv --image_dir=images\train --output_path=train.record
</code>```

I got this error:

```<code>[...]
Traceback (most recent call last):
  File "generate_tfrecord.py", line 20, in <module>
    from object_detection.utils import dataset_util
ModuleNotFoundError: No module named 'object_detection'
</code>```

My folder structure:

```<code>-generate_tfrecord.py
-images/
--test_labels.csv
--train_labels.csv
--test/
---*files*
--train/
---*files*
</code>```

答:
Check this:

git clone

https://github.com/tensorflow/models

Go to folder "research".
Open terminal: cd models-master/research

(for 3.6python) python3.6 setup.py build

(for 3.6python) sudo python3.6 setup.py install

You'll see : "Finished processing dependencies for object-detection==0.1"

Then do the follwing

Add Libraries to PYTHONPATH

When running locally, the tensorflow/models/research/ and slim
  directories should be appended to PYTHONPATH. This can be done by
  running the following from tensorflow/models/research/:

From tensorflow/models/research/

export PYTHONPATH=$PYTHONPATH:pwd:pwd/slim

Source
Source2

Body:
I'm following this tutorial (https://towardsdatascience.com/creating-your-own-object-detector-ad69dda69c85) to create my own object detector.

On the topic 'Generating TFRecords for training', whe i try run this code:

python generate_tfrecord.py --csv_input=images\train_labels.csv --image_dir=images\train --output_path=train.record

I got this error:

[...]
Traceback (most recent call last):
  File "generate_tfrecord.py", line 20, in <module>
    from object_detection.utils import dataset_util
ModuleNotFoundError: No module named 'object_detection'

My folder structure:

-generate_tfrecord.py
-images/
--test_labels.csv
--train_labels.csv
--test/
---*files*
--train/
---*files*


问:
Autocomplete Support Fragment issue : closes search bar during typing
I have been trying to apply Android Google Places Autocomplete feature using new Places SDK by below steps:

added dependency

```<code>implementation 'com.google.android.libraries.places:places:2.2.0'
implementation 'androidx.cardview:cardview:1.0.0'
</code>```

added permission

```<code><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</code>```

at xml file

```<code><androidx.cardview.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:layout_marginTop="5dp"
    app:cardCornerRadius="4dp">
    <fragment
        android:id="@+id/autocomplete_fragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
     android:name="com.google.android.libraries.places.widget.AutocompleteSupportFragment"/>

</androidx.cardview.widget.CardView>
</code>```

at my Activity file

```<code>// Initialize Places.
Places.initialize(getApplicationContext(), "My API KEY");

// Create a new Places client instance.
PlacesClient placesClient = Places.createClient(this);

// Initialize the AutocompleteSupportFragment.
AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment) getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);

// Specify the types of place data to return.
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME));

// Set up a PlaceSelectionListener to handle the response.
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
    @Override
    public void onPlaceSelected(Place place) {
        // TODO: Get info about the selected place.
        //Log.i(TAG, "Place: " + place.getName() + ", " + place.getId());
    }

    @Override
    public void onError(Status status) {
        // TODO: Handle the error.
        //Log.i(TAG, "An error occurred: " + status);
    }
});
</code>```

Problem is while I am trying to type any key on search bar it close the search window.

Note : API key is enabled, and after enabling the API key I got same API which I already enable in this project for 'Maps SDK for Android'.

If anybody got the solution please provide.

Thanks in advance.

答: This place picker method is already deprecated in 2019. please follow the latest one to implement the place picker here is the link   https://developers.google.com/places/android-sdk/client-migration</p>

Body:
I have been trying to apply Android Google Places Autocomplete feature using new Places SDK by below steps:

added dependency

implementation 'com.google.android.libraries.places:places:2.2.0'
implementation 'androidx.cardview:cardview:1.0.0'

added permission

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

at xml file

<androidx.cardview.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:layout_marginTop="5dp"
    app:cardCornerRadius="4dp">
    <fragment
        android:id="@+id/autocomplete_fragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
     android:name="com.google.android.libraries.places.widget.AutocompleteSupportFragment"/>

</androidx.cardview.widget.CardView>

at my Activity file

// Initialize Places.
Places.initialize(getApplicationContext(), "My API KEY");

// Create a new Places client instance.
PlacesClient placesClient = Places.createClient(this);

// Initialize the AutocompleteSupportFragment.
AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment) getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);

// Specify the types of place data to return.
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME));

// Set up a PlaceSelectionListener to handle the response.
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
    @Override
    public void onPlaceSelected(Place place) {
        // TODO: Get info about the selected place.
        //Log.i(TAG, "Place: " + place.getName() + ", " + place.getId());
    }

    @Override
    public void onError(Status status) {
        // TODO: Handle the error.
        //Log.i(TAG, "An error occurred: " + status);
    }
});

Problem is while I am trying to type any key on search bar it close the search window.

Note : API key is enabled, and after enabling the API key I got same API which I already enable in this project for 'Maps SDK for Android'.

If anybody got the solution please provide.

Thanks in advance.


问:
Symfony problem with range Datetime (form)
I don't understand my problem.
If you can just give me an idea.
I have a dateTime field who works but
my field years have a bizzare range (2015-2025).
I want to have a bigger range (e.g : 1960-2040).</p>

```<code>class BookType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title')
            ->add('author')
            ->add('publicationDate')
            ->add('format')
            ->add('language')
            ->add('user')
            ->add('excelFile', FileType::class,[
                'label' => 'Fichier excel (xls/xlsx file)',
                'mapped' => false,
                'required' => false,
                'constraints' => [
                    new File([
                        'maxSize' => '1024k',
                        'mimeTypes' => [
                            'application/vnd.ms-excel',
                            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                        ],
                        'mimeTypesMessage' => 'Please upload a valid xls/xlsx document',
                    ])
                ]
            ])
        ;
    }

</code>```

答:
As you can see here DateType::Class Refrence. The field will have options to configure how your choice box will behave. you can simply use php's range() function to map out your Years in your code like : range(1960, 2040)

```<code>$builder->add('field', DateType::Class , [
    'years' => range(date('Y')-50, date('Y')+50) // Lists 50 Years Before and After
]);
</code>```

In your code simply use :

```<code>class BookType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title')
            ->add('author')
            ->add('publicationDate', DateType::Class , [
                'years' => range(1960, date('Y')+20) // Change As eper your requirements
            ])
            ->add('format')
            ->add('language')
            ->add('user')
            ->add('excelFile', FileType::class,[
                'label' => 'Fichier excel (xls/xlsx file)',
                'mapped' => false,
                'required' => false,
                'constraints' => [
                    new File([
                        'maxSize' => '1024k',
                        'mimeTypes' => [
                            'application/vnd.ms-excel',
                            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                        ],
                        'mimeTypesMessage' => 'Please upload a valid xls/xlsx document',
                    ])
                ]
            ])
        ;
    }
</code>```

Body:
I don't understand my problem.
If you can just give me an idea.
I have a dateTime field who works but
my field years have a bizzare range (2015-2025).
I want to have a bigger range (e.g : 1960-2040).

class BookType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title')
            ->add('author')
            ->add('publicationDate')
            ->add('format')
            ->add('language')
            ->add('user')
            ->add('excelFile', FileType::class,[
                'label' => 'Fichier excel (xls/xlsx file)',
                'mapped' => false,
                'required' => false,
                'constraints' => [
                    new File([
                        'maxSize' => '1024k',
                        'mimeTypes' => [
                            'application/vnd.ms-excel',
                            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                        ],
                        'mimeTypesMessage' => 'Please upload a valid xls/xlsx document',
                    ])
                ]
            ])
        ;
    }

Body:
As you can see here DateType::Class Refrence. The field will have options to configure how your choice box will behave. you can simply use php's range() function to map out your Years in your code like : range(1960, 2040)

$builder->add('field', DateType::Class , [
    'years' => range(date('Y')-50, date('Y')+50) // Lists 50 Years Before and After
]);

In your code simply use :

class BookType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title')
            ->add('author')
            ->add('publicationDate', DateType::Class , [
                'years' => range(1960, date('Y')+20) // Change As eper your requirements
            ])
            ->add('format')
            ->add('language')
            ->add('user')
            ->add('excelFile', FileType::class,[
                'label' => 'Fichier excel (xls/xlsx file)',
                'mapped' => false,
                'required' => false,
                'constraints' => [
                    new File([
                        'maxSize' => '1024k',
                        'mimeTypes' => [
                            'application/vnd.ms-excel',
                            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                        ],
                        'mimeTypesMessage' => 'Please upload a valid xls/xlsx document',
                    ])
                ]
            ])
        ;
    }


问:
ThreadAbortException vs graceful event handle exit in C#
When aborting the execution of a thread I'm always doubting between a graceful exit with an event handler like this:

```<code>int result = WaitHandle.WaitAny(handles);
if (result = WAIT_FINALIZE)
  FinalizeAndExit();
</code>```

and using the event to signal the thread it must terminate

or just handling the ThreadAbortException to finalize the thread...

```<code>try
{
  // Main execution
}
catch(ThreadAbortException e)
{
  // FinalizeAndExit();
}
finally
{
}
</code>```

I'm usually inclined to use the ThreadAbortException approach since it can be handled but it is re-raised at the end of the catch block, and it also avoids the thread from being kept alive by "treacherous" methods, but I've seen both approaches.

What's your opinion? Is there any situation where it's best to use one over another, or is it best to use always approach x?

答:
Surely if the termination event is expected then it's not an exception (by the strict definition of the term) so therefore you should be using the first method.  A graceful exit also shows that you are in control.

While exceptions are useful and in some cases necessary, they can and do get overused.

OwnerDisplayName: Jorge Córdoba

Body:
When aborting the execution of a thread I'm always doubting between a graceful exit with an event handler like this:

int result = WaitHandle.WaitAny(handles);
if (result = WAIT_FINALIZE)
  FinalizeAndExit();

and using the event to signal the thread it must terminate

or just handling the ThreadAbortException to finalize the thread...

try
{
  // Main execution
}
catch(ThreadAbortException e)
{
  // FinalizeAndExit();
}
finally
{
}

I'm usually inclined to use the ThreadAbortException approach since it can be handled but it is re-raised at the end of the catch block, and it also avoids the thread from being kept alive by "treacherous" methods, but I've seen both approaches.

What's your opinion? Is there any situation where it's best to use one over another, or is it best to use always approach x?

OwnerDisplayName: ChrisF

ContentLicense: CC BY-SA 2.5


问:
Is it worth learning Smarty for PHP templating?
I'm building a simple 10-page site using an MVC-like architecture. Is it worth learning the Smarty templating engine?</p>

答:
no need.

a 10-page site is easy to build. if you would like to use Smarty, you will have to spend a little more time to learn it at the beginning~


问:
How to change nav "active" class on different pages with base.html
I have my navbar on my base.html, so I extend it on all other pages.
But I have a class "active" on the home page, so it also stays active in all other pages.

```<code><ul class="navbar-nav">
    <li class="nav-item">
        <a class="nav-link active" href="http://127.0.0.1:8000/backend/">
            <i class="ni ni-shop text-primary"></i>
            <span class="nav-link-text">Dashboard</span>
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="http://127.0.0.1:8000/backend/clientes">
            <i class="ni ni-ungroup text-orange"></i>
            <span class="nav-link-text">Clients</span>
        </a>
    </li>
</ul>
</code>```

How can I change the active class to a different menu item based on the page I am?

答: There's no one-size-fits-all answer to your question, it really depends on your project's structure, url hierarchy etc. But usually, the best solutions are either a custom template tag taking the request as argument (and/or other context variables or plain constants, depending on your own project's logic) to compute the current "section" and render the navbar accordingly.</p>

Body:
I have my navbar on my base.html, so I extend it on all other pages.
But I have a class "active" on the home page, so it also stays active in all other pages.

            Dashboard

            Clients

How can I change the active class to a different menu item based on the page I am?


问:
Python Script Written - GUI options?
I really am lost.

I've written a python script which takes two files, converts one to the same format as the second and outputs the differences.

I now need to create some kind of GUI?

I'm thinking a relatively simple HTML page which allows users to click on two separate boxes to upload each of the files and then submit them - resulting in the output being offered as file which the user can download to the PC.

Any help of direction would be really appreciated. It's only really a guess that HTML will be my best/simplest choice. Working from the command line isn't really an option I can go with. The PC that this will sit on will not have internet access. I intend to have this installed on the PC as an application.

I accept I'll need to make some changes to my Python code. Posted this here as I'm not sure Python questions would have been the best place but I'll move it if suggested.

Please, any help at all will be useful. First timer

答:
This is not a kind of answer that normally gets a reply on StackOverflow because it is much too broad / subjective.

Given the fact that you are quite new I would like to provide a solution anyway that will allow you to build a GUI quite easily like EasyGUI.

A very easy example:

```<code>import easygui
easygui.msgbox('This is a basic message box.', 'Title Goes Here')
</code>```

Other possibilities (less customizable but arguably easier) are Wooey (automatic web interface generation for your script) and Gooey (automatic GUI generation for your script.

Please, for next time, remember to always provide a Minimal Reproducible Example and read https://stackoverflow.com/help/how-to-ask

Title: Python Script Written - GUI options?

Body:
This is not a kind of answer that normally gets a reply on StackOverflow because it is much too broad / subjective.

Given the fact that you are quite new I would like to provide a solution anyway that will allow you to build a GUI quite easily like EasyGUI.

A very easy example:

import easygui
easygui.msgbox('This is a basic message box.', 'Title Goes Here')

Other possibilities (less customizable but arguably easier) are Wooey (automatic web interface generation for your script) and Gooey (automatic GUI generation for your script.

Please, for next time, remember to always provide a Minimal Reproducible Example and read https://stackoverflow.com/help/how-to-ask


问:
The best extension method overload requires a receiver of type List
the best extension method overload requires a receiver of type List
i am facing this problem:

list jvdem does not contain the defination for ToModelListJVDET and the best extension overload method modelhelper.ToModelListJVDET(List) requires a receiver of type list

so please check my code and guide me how can i solve this problem

This is my code:

// Controller

public IActionResult Index() {
    List<JVDM> jVDMs = new LocationHandler().GetjVDM().ToModelListJVDET();

    return View(jVDMs);
}

// ModelHelper class

public static List<JVDetModel> ToModelListJVDET(this List<JVDetModel> entityJVDetModels) {
    List<JVDetModel> jVDetModel = new List<JVDetModel>();

    foreach (var i in entityJVDetModels) {
        jVDetModel.Add(i);
    }

    jVDetModel.TrimExcess();
    return jVDetModel;
}

// Location Handler

public List<JVDM> GetjVDM() {
    using (myDBContext context = new myDBContext()) {
        return (from c in context.JVDetTable select c).ToList();
    }
}
```

答:
Your problem is here:

```<code>GetjVDM().ToModelListJVDET();
</code>```

GetjVDM() returns List<JVDM> while ToModelListJVDET expects List<JVDetModel> entityJVDetModels

You can do the following:

Change the expectation of ToModelListJVDET to List<JDVM>

```<code>public static List<JVDetModel> ToModelListJVDET(this List<JDVM> JDVMs) {
    List<JVDetModel> jVDetModel = new List<JVDetModel>();

    foreach (var i in JDVMs) {
        jVDetModel.Add(
            // Create the new model
            new JVDetModel() {
                 Propery1 = i.Property1
                 // etc in mapping
            }
        );
    }

    jVDetModel.TrimExcess();
    return jVDetModel;
}
</code>```

Another thing you could to is to select the JVDetModel from your linq and effectively return List<JVDetModel> from GetjVDM

```<code>public List<JVDetModel> GetjVDM() {
    using (myDBContext context = new myDBContext()) {
        return (from c in context.JVDetTable select new JVDetModel {/* Create the model here*/}).ToList();
    }
}
</code>```

Body:
Your problem is here:

GetjVDM().ToModelListJVDET();

GetjVDM() returns List<JVDM> while ToModelListJVDET expects List<JVDetModel> entityJVDetModels

You can do the following:

Change the expectation of ToModelListJVDET to List<JDVM>

public static List<JVDetModel> ToModelListJVDET(this List<JDVM> JDVMs) {
    List<JVDetModel> jVDetModel = new List<JVDetModel>();

    foreach (var i in JDVMs) {
        jVDetModel.Add(
            // Create the new model
            new JVDetModel() {
                 Propery1 = i.Property1
                 // etc in mapping
            }
        );
    }

    jVDetModel.TrimExcess();
    return jVDetModel;
}

Another thing you could to is to select the JVDetModel from your linq and effectively return List<JVDetModel> from GetjVDM

public List<JVDetModel> GetjVDM() {
    using (myDBContext context = new myDBContext()) {
        return (from c in context.JVDetTable select new JVDetModel {/* Create the model here*/}).ToList();
    }
}


问:
how to delete nan in df from row without losing the whole row?
G'day, how can I drop the nan values without losing the whole row?
This is how my df looks like.

I have tried the pandasdf = schule.dropna()  But this deleted everything in the rows.

But I have to keep the values, because at the end, I want them to go upwards.

答:
Assuming you're wanting to backfill values and then drop any duplicates that appear in any of the columns this example works:</p>

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

data = [
    ['POINT_1.1', 'POINT_1.2', pd.NA],
    [pd.NA, pd.NA, 'POINT_1.3'],
    ['POINT_2.1', 'POINT_2.2', pd.NA],
    [pd.NA, pd.NA, 'POINT_2.3']

]

df = pd.DataFrame(data)
df

#            0          1          2
# 0  POINT_1.1  POINT_1.2       <NA>
# 1       <NA>       <NA>  POINT_1.3
# 2  POINT_2.1  POINT_2.2       <NA>
# 3       <NA>       <NA>  POINT_2.3

t = df.T.bfill().T.bfill()
t

#            0          1          2
# 0  POINT_1.1  POINT_1.2  POINT_1.3
# 2  POINT_2.1  POINT_2.2  POINT_2.3

for column in t.columns:
    t = t.drop_duplicates(column)
t

#            0          1          2
# 0  POINT_1.1  POINT_1.2  POINT_1.3
# 2  POINT_2.1  POINT_2.2  POINT_2.3

</code>```

Body:
Assuming you're wanting to backfill values and then drop any duplicates that appear in any of the columns this example works:

import pandas as pd
import numpy as np

data = [
    ['POINT_1.1', 'POINT_1.2', pd.NA],
    [pd.NA, pd.NA, 'POINT_1.3'],
    ['POINT_2.1', 'POINT_2.2', pd.NA],
    [pd.NA, pd.NA, 'POINT_2.3']

]

df = pd.DataFrame(data)
df

#            0          1          2
# 0  POINT_1.1  POINT_1.2       <NA>
# 1       <NA>       <NA>  POINT_1.3
# 2  POINT_2.1  POINT_2.2       <NA>
# 3       <NA>       <NA>  POINT_2.3

t = df.T.bfill().T.bfill()
t

#            0          1          2
# 0  POINT_1.1  POINT_1.2  POINT_1.3
# 2  POINT_2.1  POINT_2.2  POINT_2.3

for column in t.columns:
    t = t.drop_duplicates(column)
t

#            0          1          2
# 0  POINT_1.1  POINT_1.2  POINT_1.3
# 2  POINT_2.1  POINT_2.2  POINT_2.3


问:
Custom domain name with SSL on Firebase Storage
I was able to get a custom domain name mapped to my Firebase Storage bucket by simply naming the bucket the same name as my domain name and then pointing the CNAME record to c.storage.googleapis.com. However, https doesn't work because the common name on the certificate is different. Is it possible for me to upload a certificate or, even better, have GCP or Firebase manage a certificate?</p>

答:
I perfectly agree to the previous answer and thanks a lot for that. But I am writing the instruction in a better fashion

Create a bucket with you custom domain name in google cloud platform-> Storage.

Create a permission of legacy object viewer and add it to all users.Note:you have to search legacy object viewer from the filter text

Add a DNS record in your domain service provider account with CNAME assets which will point to c.storage.googleapis.com.

Create a cloudflare account if you do not have

Add website in cloudflre where you need to put your domain name not the subdomain
Copy the nameserver details from cloudflare to your DNS service providers nameserver details

It will take some time to move all the dns records in cloudflare.

Goto page rules in cloudflare and add assets.yourdomain.com and turn on always use https

You are done


问:
how can i show two tables in single view in MVC
How can I use multiple models in a single view page in an MVC application?</p>

答:
The ViewModel exists for the exact reason you mention. Its primary purpose is to service the View. Its the place where you mix up multiple models and provide the View with a single data structure

Imagine you have below models:

```<code>public class A { }

public class B { }
</code>```

You should create a ViewModel Class like below code:

```<code>public class ABViewModel
{
   public A A {get;set;}
   public B B {get;set;}
}
</code>```

then update your view accepted model:

```<code>@model ABViewModel
</code>```

And finally, you should pass this ViewModel to your view. good luck

OwnerDisplayName: Ishan Shah

Body:
The ViewModel exists for the exact reason you mention. Its primary purpose is to service the View. Its the place where you mix up multiple models and provide the View with a single data structure

Imagine you have below models:

public class A { }

public class B { }

You should create a ViewModel Class like below code:

public class ABViewModel
{
   public A A {get;set;}
   public B B {get;set;}
}

then update your view accepted model:

@model ABViewModel

And finally, you should pass this ViewModel to your view. good luck


问:
Continually sending GPS data to the Android emulator
I am writing an app for Android that will measure speed as the Android device is moving, using the GPS receiver. I know I can telnet into the Android emulator and send Geo coordinates using the "geo fix" command. What I want to know though, is there a way to continually send geo fix data to simulate a car moving down a street? Otherwise, how else can I test my application?</p>

答: You can use a library like javassh to programmatically send the telnet commands to the emulator.</p>


问:
Symbol reference resolution for dynamically loaded libraries on linux
I was trying to understand how symbols are resolved in case of dynamically loaded libraries. I observed that the symbols of the libraries are resolved using the libs linked as the dynamic dependencies to the library. The same can be listed using - ldd <share_file_name.so>

Is this correct?

Earlier I assumed that the loader will look at the LD_LIBRARY_PATH and will look at all the libraries for resolving the symbols in the library.
But now I think about it then I can see why this approach might not be used. The reason is that it will be very in-optimised way of resolving the symbols if the loader has to look at all the libraries at the directories listed in the LD_LIBRARY_PATH. What if the directory has a million files then it will be very slow as any file can have the symbol.

答:
Loader basically works by scanning all loaded libraries in the order in which they have been loaded (first direct dependencies of main executable, then their dependencies, etc.). Usually symbols which your library needs will be resolved from it's own dependencies (which you can find by running readelf -l or ldd on your library). But if some other preceding library already provided them, they'll be resolved from there (this is called symbol interposition and is used for various tricks like LD_PRELOAD or Implib.so).

There are many more details which may influence loaders decision (-Bsymbolic, symbol versioning, etc.) which are explained e.g. in canonical How to write shared libraries document.


问:
Where do I find the LibTypes and LibGIS units for FreePascal?
I found some Pascal code in the supplementary material of a paper. After the metadata comment, the program starts with

```<code>unit LibLPMMain;

interface

uses
  {$IfDef DLLShapes}LibFastShareMem,{$EndIf}
  SysUtils, Classes, Math, Linux, SyncObjs,
  {$IfNDef CONSOLE}
  ExtCtrls,
  {$EndIf}
  LibTypes, LibGIS, LibFiles, LibStats, LibPhyStats,
  LibGeometry, LibMCMC,
  LibMatrix, LibProbDistrib;
</code>```

I have loaded the file into Lazarus and attempted compile it using FreePascal, which complains

```<code>LibLPMMain.pas(37,3) Fatal: Cannot find LibTypes used by LibLPMMain of the Project Inspector.
</code>```

Are the units listed here libraries I should be able to find somewhere – and if so, where – or do I have to contact the authors of the paper to provide me with those libraries before I can attempt to execute their simulation?

答:
i found this by searching Github:
https://github.com/EcoComp-UFG/EcoSimulation/blob/8b3adaf99f65db0a94e4fa2c8bf0663d0a0506f1/code_in_delphi/paleo_data/LibTypes.pas

https://github.com/terrobyte-github/CRM/blob/320010aa54137463ee17646b66c54de0626a13ca/Common/smxLibTypes.pas

http://freshmeat.sourceforge.net/projects/libgis

http://gvsigce.sourceforge.net/wiki/index.php/Compiling_GRASS_GIS

https://github.com/GRASS-GIS/grass-ci

https://github.com/Anaphory/settlement-of-americas/blob/cf81e35b569afbeef986a172509d27db00b792f9/supplement/gavin2017processbased/LibLPMMain.pas

Seems like it is port of some graphic/server libraries. Have no further information, sorry, but, try porting this.

Further information shows, that it is either can be a Lazarus integration of QGRISS or delphi of GRASS_GIS,
The're just not as shared as must be, or just paidware

Body:
I found some Pascal code in the supplementary material of a paper. After the metadata comment, the program starts with

unit LibLPMMain;

interface

uses
  {$IfDef DLLShapes}LibFastShareMem,{$EndIf}
  SysUtils, Classes, Math, Linux, SyncObjs,
  {$IfNDef CONSOLE}
  ExtCtrls,
  {$EndIf}
  LibTypes, LibGIS, LibFiles, LibStats, LibPhyStats,
  LibGeometry, LibMCMC,
  LibMatrix, LibProbDistrib;

I have loaded the file into Lazarus and attempted compile it using FreePascal, which complains

LibLPMMain.pas(37,3) Fatal: Cannot find LibTypes used by LibLPMMain of the Project Inspector.

Are the units listed here libraries I should be able to find somewhere – and if so, where – or do I have to contact the authors of the paper to provide me with those libraries before I can attempt to execute their simulation?


问:
Get only specific relations records
I have a Client model and Deposits model relation:
in the Deposits model table, I have column: campaign_id
in the Client model I have:

```<code>public function deposits()
{
    return $this->hasMany(ClientDeposit::class, 'client_id');
}
</code>```

i do simple query:

```<code>private function relations()
{
    return [
        'deposits',
    ];
}

$query->with($this->relations());

$query->whereHas('deposits', function ($query) {
   $query->where('campaign_id', '2');
})
</code>```

this code returns me Clients with 'campaign_id', '2' with but with deposits with all other campaign_id too

```<code>clients[0:{deposits: [id: 18507, client_id: 162186, user_id: 22, campaign_id: 2, amount: 100, method_id: null
0: {id: 18507, client_id: 162186, user_id: 22, campaign_id: 2, amount: 100, method_id: null,…}

1: {id: 18505, client_id: 162186, user_id: 22, campaign_id: 2, amount: 100, method_id: null,…}

2: {id: 18506, client_id: 162186, user_id: 22, campaign_id: 10, amount: 100, method_id: null,…}

3: {id: 18498, client_id: 162186, user_id: 22, campaign_id: 3, amount: 100, method_id: null,…}}]
</code>```

I want that the relation in the Client record will return only Deposits with campaign_id 2 an not all other related

答:
```<code>$query->with([
    'deposits' => function($) {
        $q->where('campaign_id', '2');
    }
])
</code>```

Title: Get only specific relations records

Body:
I have a Client model and Deposits model relation:
in the Deposits model table, I have column: campaign_id
in the Client model I have:

public function deposits()
{
    return $this->hasMany(ClientDeposit::class, 'client_id');
}

i do simple query:

private function relations()
{
    return [
        'deposits',
    ];
}

$query->with($this->relations());

$query->whereHas('deposits', function ($query) {
   $query->where('campaign_id', '2');
})

this code returns me Clients with 'campaign_id', '2' with but with deposits with all other campaign_id too

clients[0:{deposits: [id: 18507, client_id: 162186, user_id: 22, campaign_id: 2, amount: 100, method_id: null
0: {id: 18507, client_id: 162186, user_id: 22, campaign_id: 2, amount: 100, method_id: null,…}

1: {id: 18505, client_id: 162186, user_id: 22, campaign_id: 2, amount: 100, method_id: null,…}

2: {id: 18506, client_id: 162186, user_id: 22, campaign_id: 10, amount: 100, method_id: null,…}

3: {id: 18498, client_id: 162186, user_id: 22, campaign_id: 3, amount: 100, method_id: null,…}}]

I want that the relation in the Client record will return only Deposits with campaign_id 2 an not all other related