问:
Export a matrix with symbolic variables from Matlab to Python
I have a matrix with symbolic variable in MATLAB like this:

```<code>syms x
f = [x^2 x^3 x^4];
save ('sym.mat','f')
</code>```

Thus I saved the f matrix as sym.mat. Now I want to import this matrix into python. So I tried this:

```<code>import scipy.io as sio
matrix = sio.loadmat('sym.mat')
sym = matrix['f']
</code>```

But it didn't work. I got this error, which is just a regular python keyerror.

```<code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'f'
</code>```

However if f is not a symbolic matrix then this code works fine. Any ideas how I can deal with these matrices with symbolic variables?

答:
Scipy can't load MATLAB symbolic variables.

The best way to deal with your problem is to convert your Symbolic matrix into Matrix of chars(not matlab strings since it will cause errors too)

So here is what I mean:

In MATLAB, you can do something like that:

```<code>syms x
f = [x^2 x^3 x^4];
for i = 1:numel(f)
    if i == 1
        f2 = char(f(i));
    else
        f2 = [f2 ',' char(f(i))];

    end
end

save('sym.mat','f2')
</code>```

This will display:

```<code>x^2,x^3,x^4
</code>```

Now, In python you could do something like that:

```<code>import scipy.io as sio
path = 'H:\MatlabScripts'
matrix = sio.loadmat(path + '\sym.mat')
sym = matrix['f2'][0].split(',')
print(sym)
</code>```

The result will be:

```<code>['x^2', 'x^3', 'x^4']
</code>```

Body:
I have a matrix with symbolic variable in MATLAB like this:

syms x
f = [x^2 x^3 x^4];
save ('sym.mat','f')

Thus I saved the f matrix as sym.mat. Now I want to import this matrix into python. So I tried this:

import scipy.io as sio
matrix = sio.loadmat('sym.mat')
sym = matrix['f']

But it didn't work. I got this error, which is just a regular python keyerror.

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'f'

However if f is not a symbolic matrix then this code works fine. Any ideas how I can deal with these matrices with symbolic variables?

Body:
Scipy can't load MATLAB symbolic variables.

The best way to deal with your problem is to convert your Symbolic matrix into Matrix of chars(not matlab strings since it will cause errors too)

So here is what I mean:

In MATLAB, you can do something like that:

syms x
f = [x^2 x^3 x^4];
for i = 1:numel(f)
    if i == 1
        f2 = char(f(i));
    else
        f2 = [f2 ',' char(f(i))];

    end
end

save('sym.mat','f2')

This will display:

x^2,x^3,x^4

Now, In python you could do something like that:

import scipy.io as sio
path = 'H:\MatlabScripts'
matrix = sio.loadmat(path + '\sym.mat')
sym = matrix['f2'][0].split(',')
print(sym)

The result will be:

['x^2', 'x^3', 'x^4']


来源: stackexchange

问:
How to override a Python module's default logging level?
I have a utility module (let's call it "uapi.py") which provides me access to an API. My module contains several functions which perform various calls to the API in different ways. I have written a Pytest script for it ("uapi-pytest.py"), which exercises each of the functions, and hence the different calls supported by the API.

Module uapi.py uses the standard 'logging' module to log events. The default config is defined 'globally' within uapi.py, right below the import statements, and is set to a level of WARN. This level is fine when I use the module interactively (through main, which incorporates a CLI). However, I would also like to be able to import the module into my Pytest script and override the default log level to something lower (e.g. INFO or DEBUG), so that if any tests fail I can see the more detailed output, and figure out what went wrong.

So far the only way I've figured out how to do this is by editing uapi.py and setting the level to INFO before each Pytest run, then setting it back afterwards. Since my Pytest script imports uapi.py, I think I should be able to override its default logging behavior, but so far I haven't been able to figure out how. I tried directly setting the module's logging attribute but I end up getting this error (when run as "pytest -v uapi_pytest.py"):

```<code>============================================= ERRORS =============================================
________________________________ ERROR collecting uapi_pytest.py _________________________________
uapi_pytest.py:5: in <module>
    u.logging.Logger.setLevel(logging.INFO)
E   TypeError: setLevel() missing 1 required positional argument: 'level'
==================================== short test summary info =====================================
ERROR uapi_pytest.py - TypeError: setLevel() missing 1 required positional argument: 'level'
!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
======================================== 1 error in 0.64s ========================================
</code>```

Can anyone help me figure this out? Maybe I am missing something obvious, but to be honest, I can't see the forest for the trees with the Python logging module, which seems unnecessarily abstract.

Here is some stripped down code that shows the error I am getting:

uapi.py:

```<code>import logging
import requests
import fire

logging.basicConfig(level=logging.WARN,
                    format='%(asctime)s %(filename)s %(funcName)s %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S')

def uapi_get_site_info(site_id, url, username, password):
    logger = logging.getLogger('uapi.uapi_get_site_info')
    r = requests.post('https://httpbin.org/post', data = {'SiteID': site_id})
    logger.info('GET_SITE_INFO_REQUEST response:%s', r)
    return r

def uapi_get_site_version_info(site_id, version, url, username, password):
    logger = logging.getLogger('uapi.uapi_get_site_version_info')
    r = requests.post('https://httpbin.org/post', data = {'SiteID': site_id, 'Version': version})
    logger.info('GET_SITE_VERSION_INFO_REQUEST response:%s', r)
    return r

def main():
    # Configure the CLI using Python Fire
    fire.Fire({
        'get_info': uapi_get_site_info,
        'version_info': uapi_get_site_version_info,
    })

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

uapi_pytest.py:

```<code>import pytest
import logging
import uapi as u

u.logging.Logger.setLevel(logging.INFO)

def test_uapi_get_site_info_before_config_change():
    assert True

def test_uapi_get_site_version_info():
    assert True
</code>```

答:
Since uapy.py is using the default Logger object, which can be obtained by calling logging.getLogger(), you can set the desired logging level for it by calling its bound method of setLevel instead:

```<code>logging.getLogger().setLevel(logging.INFO)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a utility module (let's call it "uapi.py") which provides me access to an API. My module contains several functions which perform various calls to the API in different ways. I have written a Pytest script for it ("uapi-pytest.py"), which exercises each of the functions, and hence the different calls supported by the API.

Module uapi.py uses the standard 'logging' module to log events. The default config is defined 'globally' within uapi.py, right below the import statements, and is set to a level of WARN. This level is fine when I use the module interactively (through main, which incorporates a CLI). However, I would also like to be able to import the module into my Pytest script and override the default log level to something lower (e.g. INFO or DEBUG), so that if any tests fail I can see the more detailed output, and figure out what went wrong.

So far the only way I've figured out how to do this is by editing uapi.py and setting the level to INFO before each Pytest run, then setting it back afterwards. Since my Pytest script imports uapi.py, I think I should be able to override its default logging behavior, but so far I haven't been able to figure out how. I tried directly setting the module's logging attribute but I end up getting this error (when run as "pytest -v uapi_pytest.py"):

============================================= ERRORS =============================================
________________________________ ERROR collecting uapi_pytest.py _________________________________
uapi_pytest.py:5: in <module>
    u.logging.Logger.setLevel(logging.INFO)
E   TypeError: setLevel() missing 1 required positional argument: 'level'
==================================== short test summary info =====================================
ERROR uapi_pytest.py - TypeError: setLevel() missing 1 required positional argument: 'level'
!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
======================================== 1 error in 0.64s ========================================

Can anyone help me figure this out? Maybe I am missing something obvious, but to be honest, I can't see the forest for the trees with the Python logging module, which seems unnecessarily abstract.

Here is some stripped down code that shows the error I am getting:

uapi.py:

import logging
import requests
import fire

logging.basicConfig(level=logging.WARN,
                    format='%(asctime)s %(filename)s %(funcName)s %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S')

def uapi_get_site_info(site_id, url, username, password):
    logger = logging.getLogger('uapi.uapi_get_site_info')
    r = requests.post('https://httpbin.org/post', data = {'SiteID': site_id})
    logger.info('GET_SITE_INFO_REQUEST response:%s', r)
    return r

def uapi_get_site_version_info(site_id, version, url, username, password):
    logger = logging.getLogger('uapi.uapi_get_site_version_info')
    r = requests.post('https://httpbin.org/post', data = {'SiteID': site_id, 'Version': version})
    logger.info('GET_SITE_VERSION_INFO_REQUEST response:%s', r)
    return r

def main():
    # Configure the CLI using Python Fire
    fire.Fire({
        'get_info': uapi_get_site_info,
        'version_info': uapi_get_site_version_info,
    })

if __name__ == "__main__":
    main()

uapi_pytest.py:

import pytest
import logging
import uapi as u

u.logging.Logger.setLevel(logging.INFO)

def test_uapi_get_site_info_before_config_change():
    assert True

def test_uapi_get_site_version_info():
    assert True

Body:
Since uapy.py is using the default Logger object, which can be obtained by calling logging.getLogger(), you can set the desired logging level for it by calling its bound method of setLevel instead:

logging.getLogger().setLevel(logging.INFO)


问:
jQuery Validate not firing submitHandler
I have a simple FORM:

```<code><form method="post" action="/home/keepintouch" id="stay-in-touch">
              <div>
                <label for="email">Stay in touch</label>
                <input type="text" value="enter your email address" title="Keep up-to-date with new products, services, news and special offers." size="20" name="email" id="email" class="off field required email">
                <input type="image" src="/content/images/contact-arrow.png" name="intouch-submit" class="imgbtn">
              </div>
            </form>
</code>```

In my page I'm including the following JS files:

And in my script file I do this:

```<code>// contact form.
$('#stay-in-touch').validate({
    submitHandler: function (form) {
        $(form).ajaxSubmit({
            success: function (response, status, xhr, form) {
                $('#stay-in-touch div').fadeOut('slow', function () {
                    $('#stay-in-touch').append('<div class="msg">' + response.msg + '</div>');
                });
            }
        });
        return false;
    }
});
</code>```

But the submitHandler doesn't fire.

Any ideas?

I've tried placing an ALERT(..) inside the submitHandler but no joy. The code to map validation is definitely running.

You can see the live code here:

http://www.energyjump.co.uk/

答: I believe that you need an <input type="submit" , not just a regular button/ image.

ContentLicense: CC BY-SA 3.0

Body:
I have a simple FORM:

<form method="post" action="/home/keepintouch" id="stay-in-touch">

                Stay in touch
                <input type="text" value="enter your email address" title="Keep up-to-date with new products, services, news and special offers." size="20" name="email" id="email" class="off field required email">
                <input type="image" src="/content/images/contact-arrow.png" name="intouch-submit" class="imgbtn">

            </form>

In my page I'm including the following JS files:

And in my script file I do this:

// contact form.
$('#stay-in-touch').validate({
    submitHandler: function (form) {
        $(form).ajaxSubmit({
            success: function (response, status, xhr, form) {
                $('#stay-in-touch div').fadeOut('slow', function () {
                    $('#stay-in-touch').append('
' + response.msg + '
');
                });
            }
        });
        return false;
    }
});

But the submitHandler doesn't fire.

Any ideas?

I've tried placing an ALERT(..) inside the submitHandler but no joy. The code to map validation is definitely running.

You can see the live code here:

http://www.energyjump.co.uk/


问:
In R ggplot,what's the usage of `..density..`?
```<code>iris %>%
ggplot(.,aes(x=Sepal.Length,y=..density..,fill=Species))+
  scale_x_continuous(limit=c(0,10),breaks =seq(0,10,1))+
  geom_density(alpha=.2)
</code>```

Above script works well,but I never seen ..density.. in R.

What's ..density..?

答:
As teunbrand said,.. is replaced by after_stat.

after_stat() replaces the old approaches of using either stat() or
  surrounding the variable names with ...

Body:
iris %>%
ggplot(.,aes(x=Sepal.Length,y=..density..,fill=Species))+
  scale_x_continuous(limit=c(0,10),breaks =seq(0,10,1))+
  geom_density(alpha=.2)

Above script works well,but I never seen ..density.. in R.

What's ..density..?


问:
Create kubernetes secret for docker registry - Terraform
Using kubectl we can create docker registry authentication secret as follows

```<code>kubectl create secret docker-registry regsecret \
--docker-server=docker.example.com \
--docker-username=kube \
--docker-password=PW_STRING \
--docker-email=my@email.com \
</code>```

How do i create this secret using terraform, i saw this link, it has data, in the flow of terraform the kubernetes instance is being created in azure and i get the data required from there and i created something like below

```<code>resource "kubernetes_secret" "docker-registry" {
  metadata {
    name = "registry-credentials"
  }

  data = {
    docker-server = data.azurerm_container_registry.docker_registry_data.login_server
    docker-username = data.azurerm_container_registry.docker_registry_data.admin_username
    docker-password = data.azurerm_container_registry.docker_registry_data.admin_password
  }

}
</code>```

It seems that it is wrong as the images are not being pulled. What am i missing here.

答:
If you run following command

```<code>kubectl create secret docker-registry regsecret \
--docker-server=docker.example.com \
--docker-username=kube \
--docker-password=PW_STRING \
--docker-email=my@email.com
</code>```

It will create a secret like following

```<code>$ kubectl get secrets regsecret -o yaml
apiVersion: v1
data:
  .dockerconfigjson: eyJhdXRocyI6eyJkb2NrZXIuZXhhbXBsZS5jb20iOnsidXNlcm5hbWUiOiJrdWJlIiwicGFzc3dvcmQiOiJQV19TVFJJTkciLCJlbWFpbCI6Im15QGVtYWlsLmNvbSIsImF1dGgiOiJhM1ZpWlRwUVYxOVRWRkpKVGtjPSJ9fX0=
kind: Secret
metadata:
  creationTimestamp: "2020-06-01T18:31:07Z"
  name: regsecret
  namespace: default
  resourceVersion: "42304"
  selfLink: /api/v1/namespaces/default/secrets/regsecret
  uid: 59054483-2789-4dd2-9321-74d911eef610
type: kubernetes.io/dockerconfigjson

</code>```

If we decode .dockerconfigjson we will get

```<code>{"auths":{"docker.example.com":{"username":"kube","password":"PW_STRING","email":"my@email.com","auth":"a3ViZTpQV19TVFJJTkc="}}}
</code>```

So, how can we do that using terraform?

I created a file config.json with following data

```<code>{"auths":{"${docker-server}":{"username":"${docker-username}","password":"${docker-password}","email":"${docker-email}","auth":"${auth}"}}}
</code>```

Then in main.tf file

```<code>resource "kubernetes_secret" "docker-registry" {
  metadata {
    name = "regsecret"
  }

  data = {
    ".dockerconfigjson" = "${data.template_file.docker_config_script.rendered}"
  }

  type = "kubernetes.io/dockerconfigjson"
}

data "template_file" "docker_config_script" {
  template = "${file("${path.module}/config.json")}"
  vars = {
    docker-username           = "${var.docker-username}"
    docker-password           = "${var.docker-password}"
    docker-server             = "${var.docker-server}"
    docker-email              = "${var.docker-email}"
    auth                      = base64encode("${var.docker-username}:${var.docker-password}")
  }
}
</code>```

then run

```<code>$ terraform apply
</code>```

This will generate same secrets. Hope it will helps

Body:
Using kubectl we can create docker registry authentication secret as follows

kubectl create secret docker-registry regsecret \
--docker-server=docker.example.com \
--docker-username=kube \
--docker-password=PW_STRING \
--docker-email=my@email.com \

How do i create this secret using terraform, i saw this link, it has data, in the flow of terraform the kubernetes instance is being created in azure and i get the data required from there and i created something like below

resource "kubernetes_secret" "docker-registry" {
  metadata {
    name = "registry-credentials"
  }

  data = {
    docker-server = data.azurerm_container_registry.docker_registry_data.login_server
    docker-username = data.azurerm_container_registry.docker_registry_data.admin_username
    docker-password = data.azurerm_container_registry.docker_registry_data.admin_password
  }

}

It seems that it is wrong as the images are not being pulled. What am i missing here.

Body:
If you run following command

kubectl create secret docker-registry regsecret \
--docker-server=docker.example.com \
--docker-username=kube \
--docker-password=PW_STRING \
--docker-email=my@email.com

It will create a secret like following

$ kubectl get secrets regsecret -o yaml
apiVersion: v1
data:
  .dockerconfigjson: eyJhdXRocyI6eyJkb2NrZXIuZXhhbXBsZS5jb20iOnsidXNlcm5hbWUiOiJrdWJlIiwicGFzc3dvcmQiOiJQV19TVFJJTkciLCJlbWFpbCI6Im15QGVtYWlsLmNvbSIsImF1dGgiOiJhM1ZpWlRwUVYxOVRWRkpKVGtjPSJ9fX0=
kind: Secret
metadata:
  creationTimestamp: "2020-06-01T18:31:07Z"
  name: regsecret
  namespace: default
  resourceVersion: "42304"
  selfLink: /api/v1/namespaces/default/secrets/regsecret
  uid: 59054483-2789-4dd2-9321-74d911eef610
type: kubernetes.io/dockerconfigjson

If we decode .dockerconfigjson we will get

{"auths":{"docker.example.com":{"username":"kube","password":"PW_STRING","email":"my@email.com","auth":"a3ViZTpQV19TVFJJTkc="}}}

So, how can we do that using terraform?

I created a file config.json with following data

{"auths":{"${docker-server}":{"username":"${docker-username}","password":"${docker-password}","email":"${docker-email}","auth":"${auth}"}}}

Then in main.tf file

resource "kubernetes_secret" "docker-registry" {
  metadata {
    name = "regsecret"
  }

  data = {
    ".dockerconfigjson" = "${data.template_file.docker_config_script.rendered}"
  }

  type = "kubernetes.io/dockerconfigjson"
}

data "template_file" "docker_config_script" {
  template = "${file("${path.module}/config.json")}"
  vars = {
    docker-username           = "${var.docker-username}"
    docker-password           = "${var.docker-password}"
    docker-server             = "${var.docker-server}"
    docker-email              = "${var.docker-email}"
    auth                      = base64encode("${var.docker-username}:${var.docker-password}")
  }
}

then run

$ terraform apply

This will generate same secrets. Hope it will helps


问:
Decrypting using AES returning blank string
```<code>import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.charset.*;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.util.Arrays;

import java.util.*;

public class AES {

    public static void main(String[] args) throws Exception {
        Scanner input = new Scanner(System.in);

        System.out.println("Enter your 16 character key here:");
        String EncryptionKey = input.next();
        byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        IvParameterSpec ivspec = new IvParameterSpec(iv);

        KeyGenerator KeyGen = KeyGenerator.getInstance("AES");
        KeyGen.init(128);

        Cipher AesCipher = Cipher.getInstance("AES/CFB/NoPadding");
        System.out.println("Enter text to encrypt or decrypt:");
        String Text = input.next();

        System.out.println("Do you want to encrypt or decrypt (e/d)");
        String answer = input.next();
        if (answer.equalsIgnoreCase("e")) {

            byte[] byteKey = (EncryptionKey.getBytes());
            byte[] byteText = (Text).getBytes();
            SecretKeySpec secretKeySpec = new SecretKeySpec(byteKey, "AES");
            AesCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivspec);
            AesCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivspec); // ERROR LINE
            byte[] byteCipherText = AesCipher.doFinal(byteText);

            System.out.println(byteCipherText);

        } else if (answer.equalsIgnoreCase("d")) {

            byte[] byteKey = (EncryptionKey.getBytes());
            byte[] byteText = (Text).getBytes();
            String decryptKeyString = input.nextLine();
            Charset charset = StandardCharsets.UTF_16;
            byte[] cipherText = decryptKeyString.getBytes(charset);

            SecretKeySpec secretKeySpec = new SecretKeySpec(byteKey, "AES");
            AesCipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivspec); // ERROR LINE
            //byte[] bytePlainText = AesCipher.doFinal(cipherText);
            String plaintext = new String(AesCipher.doFinal(cipherText), "UTF-8");
            //Files.write(Paths.get(FileName2), bytePlainText);
            System.out.println(plaintext);
        }
    }

}
</code>```

TERMINAL OUTPUT:

```<code>Enter your 16 character key here:
electricboogaloo
Enter text to encrypt or decrypt:
helloworld
Do you want to encrypt or decrypt (e/d)
e
[B@504bae78
//SECOND RUN OF PROGRAM
Enter your 16 character key here:
electricboogaloo
Enter text to encrypt or decrypt:
[B@504bae78
Do you want to encrypt or decrypt (e/d)
d
</code>```

This code is largely repurposed from other code on StackExchange, I just wanted to adapt the code to not use files but to use the console instead. For some reason decryption always returns empty for me though.

If you could help me out with what specific line I have wrong that would be greatly appreciated. Thanks so much.

答:
[B@504bae78 is not the encrypted text but the string representation of a byte array. If you want to print the encoded text, you should convert the byte array to base64 so that it's printed using printable characters.

Then, when your programs asks you to enter the ecrypted text, enter the base64 encoded string, convert it back to a byte array and pass it to the function.

Body:
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.charset.*;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.util.Arrays;

import java.util.*;

public class AES {

    public static void main(String[] args) throws Exception {
        Scanner input = new Scanner(System.in);

        System.out.println("Enter your 16 character key here:");
        String EncryptionKey = input.next();
        byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        IvParameterSpec ivspec = new IvParameterSpec(iv);

        KeyGenerator KeyGen = KeyGenerator.getInstance("AES");
        KeyGen.init(128);

        Cipher AesCipher = Cipher.getInstance("AES/CFB/NoPadding");
        System.out.println("Enter text to encrypt or decrypt:");
        String Text = input.next();

        System.out.println("Do you want to encrypt or decrypt (e/d)");
        String answer = input.next();
        if (answer.equalsIgnoreCase("e")) {

            byte[] byteKey = (EncryptionKey.getBytes());
            byte[] byteText = (Text).getBytes();
            SecretKeySpec secretKeySpec = new SecretKeySpec(byteKey, "AES");
            AesCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivspec);
            AesCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivspec); // ERROR LINE
            byte[] byteCipherText = AesCipher.doFinal(byteText);

            System.out.println(byteCipherText);

        } else if (answer.equalsIgnoreCase("d")) {

            byte[] byteKey = (EncryptionKey.getBytes());
            byte[] byteText = (Text).getBytes();
            String decryptKeyString = input.nextLine();
            Charset charset = StandardCharsets.UTF_16;
            byte[] cipherText = decryptKeyString.getBytes(charset);

            SecretKeySpec secretKeySpec = new SecretKeySpec(byteKey, "AES");
            AesCipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivspec); // ERROR LINE
            //byte[] bytePlainText = AesCipher.doFinal(cipherText);
            String plaintext = new String(AesCipher.doFinal(cipherText), "UTF-8");
            //Files.write(Paths.get(FileName2), bytePlainText);
            System.out.println(plaintext);
        }
    }

}

TERMINAL OUTPUT:

Enter your 16 character key here:
electricboogaloo
Enter text to encrypt or decrypt:
helloworld
Do you want to encrypt or decrypt (e/d)
e
[B@504bae78
//SECOND RUN OF PROGRAM
Enter your 16 character key here:
electricboogaloo
Enter text to encrypt or decrypt:
[B@504bae78
Do you want to encrypt or decrypt (e/d)
d

This code is largely repurposed from other code on StackExchange, I just wanted to adapt the code to not use files but to use the console instead. For some reason decryption always returns empty for me though.

If you could help me out with what specific line I have wrong that would be greatly appreciated. Thanks so much.


问:
DRF: How to get Users object in a get method as a Response?
How can I get all user objects in get method in views.py with other models?

views.py

```<code>class WebDashboardViews(generics.ListAPIView):
    authentication_classes = (authentication.TokenAuthentication,)
    permission_classes = (permissions.IsAdminUser,permissions.IsAuthenticated,)
    serializer_class = serializers.DashboardSerializer

    def get(self, request, format=None):
        all_user_queryset = models.User.objects.all()
        if not all_user_queryset:
            total_user = 0
        else:
            total_user = all_user_queryset.count()
        total_android_user = models.UserMobileDevice.objects.filter(os="Android")
        if not total_android_user:
            total_android_count = 0
        else:
            total_android_count = total_android_user.count()
        content = {'total_user':total_user,'total_android_count':total_android_count, all_users: all_user_queryset}
        return Response(content)
</code>```

I want the user object in all_users key. But I am getting an error:

Object of type User is not JSON serializable

My serializer code is :

```<code>class DashboardSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.User
        field = ['id','created_at','name']

</code>```

I am not sure what I am doing here. Any help will be highly appreciated. Thanks

答:
You get that error because you are trying to respond with not-serialized objects here: all_users: all_user_queryset

You need to serialize them first (I guess you have an UserSerializer, if don't, just rename your DashboardSerializer to UserSerializer because it is just what it is):

```<code>user_serializer = UserSerializer(all_user_queryset, many=True)
content = {'total_user':total_user,'total_android_count':total_android_count, all_users: user_serializer.data}
return Response(content)
</code>```

Body:
How can I get all user objects in get method in views.py with other models?

views.py

class WebDashboardViews(generics.ListAPIView):
    authentication_classes = (authentication.TokenAuthentication,)
    permission_classes = (permissions.IsAdminUser,permissions.IsAuthenticated,)
    serializer_class = serializers.DashboardSerializer

    def get(self, request, format=None):
        all_user_queryset = models.User.objects.all()
        if not all_user_queryset:
            total_user = 0
        else:
            total_user = all_user_queryset.count()
        total_android_user = models.UserMobileDevice.objects.filter(os="Android")
        if not total_android_user:
            total_android_count = 0
        else:
            total_android_count = total_android_user.count()
        content = {'total_user':total_user,'total_android_count':total_android_count, all_users: all_user_queryset}
        return Response(content)

I want the user object in all_users key. But I am getting an error:

Object of type User is not JSON serializable

My serializer code is :

class DashboardSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.User
        field = ['id','created_at','name']

I am not sure what I am doing here. Any help will be highly appreciated. Thanks

Body:
You get that error because you are trying to respond with not-serialized objects here: all_users: all_user_queryset

You need to serialize them first (I guess you have an UserSerializer, if don't, just rename your DashboardSerializer to UserSerializer because it is just what it is):

user_serializer = UserSerializer(all_user_queryset, many=True)
content = {'total_user':total_user,'total_android_count':total_android_count, all_users: user_serializer.data}
return Response(content)


问:
How to determine number of months between two dates in Python?
I have two columns that are datetime64[ns] objects. I am trying to determine the number of months between them.

The columns are:

```<code>city_clean['last_trip_date']
city_clean['signup_date']
</code>```

Format is YYYY-MM-DD

I tried

```<code>from dateutil.relativedelta import relativedelta

city_clean['months_active'] = relativedelta(city_clean['signup_date'], city_clean['last_trip_date'])
</code>```

And get the following error:

```<code>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
</code>```

Does anyone know what could cause this issue? I feel like this is the most accurate way to calculate the number of months.

答:
The first thing that comes to my mind...

>>> from datetime import datetime, timedelta

>>> dt1 = datetime(year=2020, month=3, day=1)
>>> dt2 = datetime(year=2020, month=5, day=1)
>>> # delta = dt2-dt1
>>> delta = abs(dt2-dt1)

>>> delta
datetime.timedelta(61)

>>> delta.days
61
```
<p><strong>UPDATE</strong>:
What I meant to represent is the idea of using the absolute value of the delta -> abs()</p>
<p>In Python 3.10 it works with the <code>dateutil.realtivedelta()</code> too</p>
<pre class="lang-py prettyprint-override"><code>

from datetime import datetime
from dateutil.relativedelta import relativedelta

city_clean_dates = [
    {'signup_date': '2019-12-01', 'last_trip_date': '2020-02-01'},
    {'signup_date': '2021-01-01', 'last_trip_date': '2020-05-01'},
    {'signup_date': '2020-03-01', 'last_trip_date': '2020-05-31'},
]

for city_clean in city_clean_dates:
    city_clean['last_trip_date'] = datetime.strptime(city_clean['last_trip_date'], '%Y-%m-%d')
    city_clean['signup_date'] = datetime.strptime(city_clean['signup_date'], '%Y-%m-%d')

    rd1 = abs(relativedelta(city_clean['last_trip_date'], city_clean['signup_date']))
    rd2 = abs(relativedelta(city_clean['signup_date'], city_clean['last_trip_date']))

    assert rd1 == rd2

    print(f"Recent - old date: {rd1}")
    print(f"Old - recent date: {rd2}")

</code>```

this would print

```<code>Recent - old date: relativedelta(months=+2)
Old - recent date: relativedelta(months=+2)
Recent - old date: relativedelta(months=+8)
Old - recent date: relativedelta(months=+8)
Recent - old date: relativedelta(months=+2, days=+30)
Old - recent date: relativedelta(months=+2, days=+30)
</code>```

Note neither of my solutions returns months, while the first one returns days only, and the second returns whole months + the extra days of the partial month.
The ambiguity of this is very obvious in the case of
{'last_trip_date': '2020-03-01', 'signup_date': '2020-05-31'}

Where normally we could say that's 3 months but in reality, it's one day short.
It's up to the developer to overcome the ambiguity of such values considering the use-case.

Body:
I have two columns that are datetime64[ns] objects. I am trying to determine the number of months between them.

The columns are:

city_clean['last_trip_date']
city_clean['signup_date']

Format is YYYY-MM-DD

I tried

from dateutil.relativedelta import relativedelta

city_clean['months_active'] = relativedelta(city_clean['signup_date'], city_clean['last_trip_date'])

And get the following error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Does anyone know what could cause this issue? I feel like this is the most accurate way to calculate the number of months.

Body:
The first thing that comes to my mind...

>>> from datetime import datetime, timedelta

>>> dt1 = datetime(year=2020, month=3, day=1)
>>> dt2 = datetime(year=2020, month=5, day=1)
>>> # delta = dt2-dt1
>>> delta = abs(dt2-dt1)

>>> delta
datetime.timedelta(61)

>>> delta.days
61

UPDATE:
What I meant to represent is the idea of using the absolute value of the delta -> abs()

In Python 3.10 it works with the dateutil.realtivedelta() too

from datetime import datetime
from dateutil.relativedelta import relativedelta

city_clean_dates = [
    {'signup_date': '2019-12-01', 'last_trip_date': '2020-02-01'},
    {'signup_date': '2021-01-01', 'last_trip_date': '2020-05-01'},
    {'signup_date': '2020-03-01', 'last_trip_date': '2020-05-31'},
]

for city_clean in city_clean_dates:
    city_clean['last_trip_date'] = datetime.strptime(city_clean['last_trip_date'], '%Y-%m-%d')
    city_clean['signup_date'] = datetime.strptime(city_clean['signup_date'], '%Y-%m-%d')

    rd1 = abs(relativedelta(city_clean['last_trip_date'], city_clean['signup_date']))
    rd2 = abs(relativedelta(city_clean['signup_date'], city_clean['last_trip_date']))

    assert rd1 == rd2

    print(f"Recent - old date: {rd1}")
    print(f"Old - recent date: {rd2}")

this would print

Recent - old date: relativedelta(months=+2)
Old - recent date: relativedelta(months=+2)
Recent - old date: relativedelta(months=+8)
Old - recent date: relativedelta(months=+8)
Recent - old date: relativedelta(months=+2, days=+30)
Old - recent date: relativedelta(months=+2, days=+30)

Note neither of my solutions returns months, while the first one returns days only, and the second returns whole months + the extra days of the partial month.
The ambiguity of this is very obvious in the case of
{'last_trip_date': '2020-03-01', 'signup_date': '2020-05-31'}

Where normally we could say that's 3 months but in reality, it's one day short.
It's up to the developer to overcome the ambiguity of such values considering the use-case.


问:
Delete values in line based on column index using shell script
I want to be able to delete the values to the RIGHT(starting from given column index) from the test.txt at the given column index based on a given length, N.

Column index refers to the position when you open the file in the VIM editor in LINUX.

If my test.txt contains 1234 5678, and I call my delete_var function which takes in the column number as 2 to start deleting from and length N as 2 to delete as input, the test.txt would reflect 14 5678 as it deleted the values from column 2 to column 4 as the length to delete was 2.

I have the following code as of now but I am unable to understand what I would put in the sed command.

```<code>delete_var() {

    sed -i -r 's/not sure what goes here' test.txt
}

clmn_index= $1
_N=$2

delete_var "$clmn_index" "$_N"   # call the method with the column index and length to delete
</code>```

```<code>#sample test.txt (before call to fn)
1234 5678
</code>```

```<code>#sample test.txt (after call to fn)
14 5678
</code>```

Can someone guide me?

答:
Assumping OP must use sed (otherwise other options could include cut and awk but would require some extra file IOs to replace the original file with the modified results) ...

Starting with the sed command to remove the 2 characters starting in column 2:

```<code>$ echo '1234 5678' > test.txt
$ sed -i -r "s/(.{1}).{2}(.*$)/\1\2/g" test.txt
$ cat test.txt
14 5678
</code>```

Where:

(.{1}) - match first character in line and store in buffer #1

.{2} - match next 2 characters but don't store in buffer

(.*$) - match rest of line and store in buffer #2

\1\2 - output contents of buffers #1 and #2

Now, how to get variables for start and length into the sed command?

Assume we have the following variables:

```<code>$ s=2     # start
$ n=2     # length
</code>```

To map these variables into our sed command we can break the sed search-replace pattern into parts, replacing the first 1 and 2 with our variables like such:

replace {1} with {$((s-1))}

replace {2} with {${n}}

Bringing this all together gives us:

```<code>$ s=2
$ n=2
$ echo '1234 5678' > test.txt

$ set -x          # echo what sed sees to verify the correct mappings:
$ sed -i -r "s/(.{"$((s-1))"}).{${n}}(.*$)/\1\2/g" test.txt
+ sed -i -r 's/(.{1}).{2}(.*$)/\1\2/g' test.txt

$ set +x
$ cat test.txt
14 5678
</code>```

Alternatively, do the subtraction (s-1) before the sed call and just pass in the new variable, eg:

```<code>$ x=$((s-1))
$ sed -i -r "s/(.{${x}}).{${n}}(.*$)/\1\2/g" test.txt
$ cat test.txt
14 5678
</code>```

Body:
I want to be able to delete the values to the RIGHT(starting from given column index) from the test.txt at the given column index based on a given length, N.

Column index refers to the position when you open the file in the VIM editor in LINUX.

If my test.txt contains 1234 5678, and I call my delete_var function which takes in the column number as 2 to start deleting from and length N as 2 to delete as input, the test.txt would reflect 14 5678 as it deleted the values from column 2 to column 4 as the length to delete was 2.

I have the following code as of now but I am unable to understand what I would put in the sed command.

delete_var() {

    sed -i -r 's/not sure what goes here' test.txt
}

clmn_index= $1
_N=$2

delete_var "$clmn_index" "$_N"   # call the method with the column index and length to delete

#sample test.txt (before call to fn)
1234 5678

#sample test.txt (after call to fn)
14 5678

Can someone guide me?

Body:
Assumping OP must use sed (otherwise other options could include cut and awk but would require some extra file IOs to replace the original file with the modified results) ...

Starting with the sed command to remove the 2 characters starting in column 2:

$ echo '1234 5678' > test.txt
$ sed -i -r "s/(.{1}).{2}(.*$)/\1\2/g" test.txt
$ cat test.txt
14 5678

Where:

(.{1}) - match first character in line and store in buffer #1

.{2} - match next 2 characters but don't store in buffer

(.*$) - match rest of line and store in buffer #2

\1\2 - output contents of buffers #1 and #2

Now, how to get variables for start and length into the sed command?

Assume we have the following variables:

$ s=2     # start
$ n=2     # length

To map these variables into our sed command we can break the sed search-replace pattern into parts, replacing the first 1 and 2 with our variables like such:

replace {1} with {$((s-1))}

replace {2} with {${n}}

Bringing this all together gives us:

$ s=2
$ n=2
$ echo '1234 5678' > test.txt

$ set -x          # echo what sed sees to verify the correct mappings:
$ sed -i -r "s/(.{"$((s-1))"}).{${n}}(.*$)/\1\2/g" test.txt
+ sed -i -r 's/(.{1}).{2}(.*$)/\1\2/g' test.txt

$ set +x
$ cat test.txt
14 5678

Alternatively, do the subtraction (s-1) before the sed call and just pass in the new variable, eg:

$ x=$((s-1))
$ sed -i -r "s/(.{${x}}).{${n}}(.*$)/\1\2/g" test.txt
$ cat test.txt
14 5678


答:
Here's an approach with filter. I'm not sure why you think 2014-01-02 is within 5 days of 2014-03-29 thought.

```<code>library(dplyr)
d %>%
  mutate_at(vars(c("DATE2","DATE")),
            list(~as.Date(.))) %>%
  dplyr::filter(abs(DATE - DATE2) <= 5)
#  ID      DATE2       DATE
#1  1 2001-01-02 2001-01-05
#2  5 2001-01-02 2001-01-02
</code>```

Title: filter observations with date near to other date

Body:
I want to filter dates which lies close to other date (+5 days).

 d <- wrapr::build_frame( "ID","DATE2", "DATE" | 1 , "2001-01-02" , "2001-01-05" | 2 , "2001-01-02" , "2015-04-25" | 3 , "2001-01-02" , "2000-04-01" | 4 , "2014-01-02" , "2014-03-29" | 5 , "2001-01-02" , "2001-01-02" | 6 , "2001-01-02" , "2005-06-16" )

  ID      DATE2       DATE
1  1 2001-01-02 2001-01-05
2  2 2001-01-02 2015-04-25
3  3 2001-01-02 2000-04-01
4  4 2014-01-02 2014-03-29
5  5 2001-01-02 2001-01-02
6  6 2001-01-02 2005-06-16

Should generate this:

ID      DATE2       DATE
1  1 2001-01-02 2001-01-05
2  4 2014-01-02 2014-03-29
3  5 2001-01-02 2001-01-02

I want to use dplyr - d%>%filter(DATE= etc...) if possible.

Thanks ;)
/H

Body:
Here's an approach with filter. I'm not sure why you think 2014-01-02 is within 5 days of 2014-03-29 thought.

library(dplyr)
d %>%
  mutate_at(vars(c("DATE2","DATE")),
            list(~as.Date(.))) %>%
  dplyr::filter(abs(DATE - DATE2) <= 5)
#  ID      DATE2       DATE
#1  1 2001-01-02 2001-01-05
#2  5 2001-01-02 2001-01-02


问:
Colors, label in Python
X is a 100x2 vector that contains sepal and pethal length data for 2 kinds of flowers. y is a 100x1 vector that contains label values for my data: -1 and 1. I create a meshgrid, then I plotted my meshgrid using countourf method and now I load the data in the meshgrid with this code:

```<code>for idx, cl in enumerate (np.unique(y)):
    plt.scatter (x=X[y == cl, 0], y= X[y == cl, 1], alpha=0.8, c=colors[idx], marker= markers [idx], label = cl, edgecolor = 'black')
</code>```

alpha, colors, marker, edgecolor are just secondary things. Also np.unique(y) = [-1 1] .

My question is, Why [y==cl,0] is a false and [y==,1] is a true argument? and, How using == can I classifier my data?

答:
In the for loop, cl loops over the two unique values of y i.e. [-1, 1]. So in the first loop iteration, cl=-1 and y == cl returns the rows where your y values are -1. Therefore, [y == cl, 0] returns the locations where y is -1 and the data is the first column (index 0) which is Sepal length. Similarly, [y == cl, 1] returns the locations where y is -1 and the data is the second column (index 1) which is Petal length.

The same applies in the second iteration of the loop when cl is 1.

Title: Colors, label in Python

Body:
X is a 100x2 vector that contains sepal and pethal length data for 2 kinds of flowers. y is a 100x1 vector that contains label values for my data: -1 and 1. I create a meshgrid, then I plotted my meshgrid using countourf method and now I load the data in the meshgrid with this code:

for idx, cl in enumerate (np.unique(y)):
    plt.scatter (x=X[y == cl, 0], y= X[y == cl, 1], alpha=0.8, c=colors[idx], marker= markers [idx], label = cl, edgecolor = 'black')

alpha, colors, marker, edgecolor are just secondary things. Also np.unique(y) = [-1 1] .

My question is, Why [y==cl,0] is a false and [y==,1] is a true argument? and, How using == can I classifier my data?


问:
How to show full images in a div
I want to show the full image regardless of its dimensions in a div. The dimensions of the div are: Width:400px and Height:400px [400x400] . So even if an image is larger than the div, I want the entire image to be displayed in the div. the image should maintain its aspect ratio. How can I achieve this with CSS or jQuery? Is this possible without manipulating the image with PHP or any other script?

[Sorry for incorrect grammar or bad english]

答:
```<code>height:160px;
width:160px;
background-image: url('images/Science.png');
background-position:center center;
background-repeat:no-repeat;
background-clip:content-box;
</code>```

Title: How to show full images in a div


问:
Valarray slice array no match for 'operator*'
I'm trying to do multidimensional dot product with two valarray, i.e. return a valarray such that each element is the dot product on two rows of the input valarrays.

I use slices to divide by array into rows. Checking the documentation, it states that * is an operator of slice_array, and I believe I works similarly to * to valarrays. It performs elementwise multiplication between two arrays.

```<code>valarray<float> mult(valarray<float> arr1, valarray<float> arr2, int row1, int mid, int col2)
{
    valarray<float> new_arr;
    new_arr.resize(row1*col2);
    for (int i = 0; i < row1*col2; ++i)
    {
    slice s (i*mid,mid,1);
    new_arr[i] = (arr1[s] * arr2[s]).sum();
    }

    return new_arr;
}
</code>```

The error I keep getting is:
|12|error: no match for 'operator*' (operand types are 'std::slice_array<float>' and 'std::slice_array<float>')|

I'm not sure what I'm doing wrong. Before I make my own elementwise multiplying function, is there any mistake in the code or my use of the slice_array?

答:
Documentation for slice_array says that the interface is

```<code>template <class T> class slice_array {
public:
  /* Skipped for brevity */
  void operator*=  (const valarray<T>&) const;
};
</code>```

In other words, you can multiply a slice by a valaray, but it says nothing about multiplying two slices.

Body:
I'm trying to do multidimensional dot product with two valarray, i.e. return a valarray such that each element is the dot product on two rows of the input valarrays.

I use slices to divide by array into rows. Checking the documentation, it states that * is an operator of slice_array, and I believe I works similarly to * to valarrays. It performs elementwise multiplication between two arrays.

valarray<float> mult(valarray<float> arr1, valarray<float> arr2, int row1, int mid, int col2)
{
    valarray<float> new_arr;
    new_arr.resize(row1*col2);
    for (int i = 0; i < row1*col2; ++i)
    {
    slice s (i*mid,mid,1);
    new_arr[i] = (arr1[s] * arr2[s]).sum();
    }

    return new_arr;
}

The error I keep getting is:
|12|error: no match for 'operator*' (operand types are 'std::slice_array<float>' and 'std::slice_array<float>')|

I'm not sure what I'm doing wrong. Before I make my own elementwise multiplying function, is there any mistake in the code or my use of the slice_array?

Body:
Documentation for slice_array says that the interface is

template <class T> class slice_array {
public:
  /* Skipped for brevity */
  void operator*=  (const valarray<T>&) const;
};

In other words, you can multiply a slice by a valaray, but it says nothing about multiplying two slices.


答:
This is Pandas, right? Try it like this:

```<code># calculate the difference between two dates
df['diff_months'] = df['End_date'] - df['Start_date']
# converts the difference in terms of Months (timedelta64(1,’M’)-  capital M indicates Months)
df['diff_months']=df['diff_months']/np.timedelta64(1,'M')
</code>```

Or, if you have proper datetimes objects,

```<code>def diff_month(d1, d2):
    return (d1.year - d2.year) * 12 + d1.month - d2.month
</code>```

Title: How to determine number of months between two dates in Python?

Body:
This is Pandas, right? Try it like this:

# calculate the difference between two dates
df['diff_months'] = df['End_date'] - df['Start_date']
# converts the difference in terms of Months (timedelta64(1,’M’)-  capital M indicates Months)
df['diff_months']=df['diff_months']/np.timedelta64(1,'M')

Or, if you have proper datetimes objects,

def diff_month(d1, d2):
    return (d1.year - d2.year) * 12 + d1.month - d2.month


问:
name 'List' is not defined-Python
I get this error when I run the code.How can I fix?</p>

```<code>class Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
    d, counts = {}, {}
    for n in arr:
        if n in d: d[n] += 1
        else: d[n] = 1

    for k in d:
        if d[k] in counts: return False
        else: counts[d[k]] = 0

    return True
</code>```

答:
Import it:</p>

```<code>from typing import List
</code>```

Title: name 'List' is not defined-Python

Body:
I get this error when I run the code.How can I fix?

class Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
    d, counts = {}, {}
    for n in arr:
        if n in d: d[n] += 1
        else: d[n] = 1

    for k in d:
        if d[k] in counts: return False
        else: counts[d[k]] = 0

    return True

Body:
Import it:

from typing import List


问:
Express Throws TypeError: Cannot read property 'app' of undefined
I have a nodejs server running the common framework express. I have noticed recently that when I make requests from my server, I get this error at seemingly random times, for example, if I were to make a request twice, the error would usually only happen the first request, and not the second. I'm having trouble pinpointing what is causing this error, because I often write my code in one go, then test it later. Here is the error in full:

```<code>TypeError: Cannot read property 'app' of undefined
    at json (/home/user/Desktop/project/node_modules/express/lib/response.js:256:18)
    at process._tickCallback (internal/process/next_tick.js:68:7) 'Unhandled Rejection at Promise' Promise {
  <rejected> TypeError: Cannot read property 'app' of undefined
      at json (/home/user/Desktop/project/node_modules/express/lib/response.js:256:18)
      at process._tickCallback (internal/process/next_tick.js:68:7) }
</code>```

All that I can tell from this error is that it may involve some reference to "app", however I am not sure what it could be specifically, as I haven't changed anything pertaining to "app" in express recently. Here is my express configuration on my server file:

```<code>    const express = require('express'),
        user = require('./routers/User.js'),
        helmet = require('helmet'),
        app = express();
    app.use(helmet());
    app.use(cors());
    app.use(bodyParser.urlencoded({
        extended: false
    }));
    app.use(bodyParser.json());
    app.set('trust proxy', true);

    //map router files to respective urls
    //these are stored in a directory and set above, these contain all of the handlers for each of my routes
    app.use('/user', user);

    //set port and listen on it
    app.listen(5000, () => console.log("Server running on port 5000"));
</code>```

If anything else is needed of me, please ask. I've tried to include every reference pertaining to the word "app" in my code, but that may not be enough.

EDIT: I thank you all for trying to help, but the code I provided was not intended to work, it was simply an example of what I import, this is an error with express, and I'm just trying to find out what kind of behavior would cause it. Sorry for the confusion.

答:
You are most likely missing a comma after "helmet = require('helmet')</p>

```<code>const express = require('express'),
    user = require('./routers/User.js'),
    helmet = require('helmet'),
    app = express();
app.use(helmet());
app.use(cors());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(bodyParser.json());
app.set('trust proxy', true);

//map router files to respective urls
//these are stored in a directory and set above, these contain all of the handlers for each of my routes
app.use('/user', user);

//set port and listen on it
app.listen(5000, () => console.log("Server running on port 5000"));
</code>```

Body:
I have a nodejs server running the common framework express. I have noticed recently that when I make requests from my server, I get this error at seemingly random times, for example, if I were to make a request twice, the error would usually only happen the first request, and not the second. I'm having trouble pinpointing what is causing this error, because I often write my code in one go, then test it later. Here is the error in full:

TypeError: Cannot read property 'app' of undefined
    at json (/home/user/Desktop/project/node_modules/express/lib/response.js:256:18)
    at process._tickCallback (internal/process/next_tick.js:68:7) 'Unhandled Rejection at Promise' Promise {
  <rejected> TypeError: Cannot read property 'app' of undefined
      at json (/home/user/Desktop/project/node_modules/express/lib/response.js:256:18)
      at process._tickCallback (internal/process/next_tick.js:68:7) }

All that I can tell from this error is that it may involve some reference to "app", however I am not sure what it could be specifically, as I haven't changed anything pertaining to "app" in express recently. Here is my express configuration on my server file:

    const express = require('express'),
        user = require('./routers/User.js'),
        helmet = require('helmet'),
        app = express();
    app.use(helmet());
    app.use(cors());
    app.use(bodyParser.urlencoded({
        extended: false
    }));
    app.use(bodyParser.json());
    app.set('trust proxy', true);

    //map router files to respective urls
    //these are stored in a directory and set above, these contain all of the handlers for each of my routes
    app.use('/user', user);

    //set port and listen on it
    app.listen(5000, () => console.log("Server running on port 5000"));

If anything else is needed of me, please ask. I've tried to include every reference pertaining to the word "app" in my code, but that may not be enough.

EDIT: I thank you all for trying to help, but the code I provided was not intended to work, it was simply an example of what I import, this is an error with express, and I'm just trying to find out what kind of behavior would cause it. Sorry for the confusion.

Body:
You are most likely missing a comma after "helmet = require('helmet')

const express = require('express'),
    user = require('./routers/User.js'),
    helmet = require('helmet'),
    app = express();
app.use(helmet());
app.use(cors());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(bodyParser.json());
app.set('trust proxy', true);

//map router files to respective urls
//these are stored in a directory and set above, these contain all of the handlers for each of my routes
app.use('/user', user);

//set port and listen on it
app.listen(5000, () => console.log("Server running on port 5000"));


问:
EF Core check if object in related table exists, if not - add it
I have the following class:

```<code>public class Item
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    [Required]
    [MaxLength(255)]
    public string Name { get; set; }

    [Required]
    public ItemCategory Category { get; set; }
}
</code>```

and an ItemCategory class:

```<code>public class ItemCategory
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    [Required]
    public string Name { get; set; }
}
</code>```

I want each item to have one category and a category to be able to have many items. I am using code first and so far everything looks good - using migrations EF created an "Items" and "ItemCategories" tables with the appropriate foreign keys ("Items" table has a column "CategoryID" that references the "ID" column of the "ItemCategories" table). My problem is that if I have a category of, say, "Book" with ID 1 and I add a new Item with category "Book" in the "ItemCategories" a second entry is inserted that has ID 2 and name "Book". I want to change this behaviour to the following:

When a new Item is added, check if its Category.Name already exists in "ItemCategories". If it does set the "CategoryID" to its ID. If it does not - add a new record to "ItemCategories" and set "CategoryID" to its ID.

How do I achieve that?

答:
Use a navigation property in the Item class.</p>

```<code>public class ItemCategory
{
    [Key]
    public Guid ID { get; set;}

    public string Name { get; set; }
}

public class Item
{
    [Key]
    public Guid ID { get; set; } // Primary Key

    [Required]
    public string Name { get; set; }

    public virtual ItemCategory ItemCategory { get; set; } //Navigation Property
}
</code>```

Body:
I have the following class:

public class Item
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    [Required]
    [MaxLength(255)]
    public string Name { get; set; }

    [Required]
    public ItemCategory Category { get; set; }
}

and an ItemCategory class:

public class ItemCategory
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    [Required]
    public string Name { get; set; }
}

I want each item to have one category and a category to be able to have many items. I am using code first and so far everything looks good - using migrations EF created an "Items" and "ItemCategories" tables with the appropriate foreign keys ("Items" table has a column "CategoryID" that references the "ID" column of the "ItemCategories" table). My problem is that if I have a category of, say, "Book" with ID 1 and I add a new Item with category "Book" in the "ItemCategories" a second entry is inserted that has ID 2 and name "Book". I want to change this behaviour to the following:

When a new Item is added, check if its Category.Name already exists in "ItemCategories". If it does set the "CategoryID" to its ID. If it does not - add a new record to "ItemCategories" and set "CategoryID" to its ID.

How do I achieve that?

Body:
Use a navigation property in the Item class.

public class ItemCategory
{
    [Key]
    public Guid ID { get; set;}

    public string Name { get; set; }
}

public class Item
{
    [Key]
    public Guid ID { get; set; } // Primary Key

    [Required]
    public string Name { get; set; }

    public virtual ItemCategory ItemCategory { get; set; } //Navigation Property
}


问:
Laravel problem loading assets 400 bad request
I have a Laravel website that work perfectly on localhost but when i deploy that, there is a problem with loading assets or other files from public directory.

Bad Request

  Your browser sent a request that this server could not understand.

It's my apache vHost :

```<code><VirtualHost IP:8181>
    ServerName my-domain.com
    ServerAlias www.my-domain.com
    ServerAdmin info@my-domain.com
    DocumentRoot /home/user/public_html/laravel/public
    UseCanonicalName Off
    ScriptAlias /cgi-bin/ /home/user/public_html/cgi-bin/

    ErrorLog /usr/local/apache/domlogs/my-domain.com.error.log

    <IfModule mod_setenvif.c>
        SetEnvIf X-Forwarded-Proto "^https$" HTTPS=on
    </IfModule>

    <IfModule mod_userdir.c>
        UserDir disabled
        UserDir enabled user
    </IfModule>

    <IfModule mod_suexec.c>
        SuexecUserGroup user user
    </IfModule>

    <IfModule mod_suphp.c>
        suPHP_UserGroup user user
        suPHP_ConfigPath /home/user
    </IfModule>

    <IfModule mod_ruid2.c>
        RMode config
        RUidGid user user
    </IfModule>

    <IfModule itk.c>
        AssignUserID user user
    </IfModule>

    <Directory "/home/user/public_html">
        AllowOverride All
    </Directory>

</VirtualHost>
</code>```

And it's apache log :

Invalid URI in request GET \@backend HTTP/1.0

There is many laravel sites and all of them are normal but i have problem with this one. I can't figure out this problem.

My vHost.conf is OK, my .env files is OK, but i can't load any assets such as css / js / robots.txt / etc ... ( anything that saved in public directory ).

Do you have any idea?

答: Change your document root to /home/user/public_html.

Body:
I have a Laravel website that work perfectly on localhost but when i deploy that, there is a problem with loading assets or other files from public directory.

Bad Request

  Your browser sent a request that this server could not understand.

It's my apache vHost :

<VirtualHost IP:8181>
    ServerName my-domain.com
    ServerAlias www.my-domain.com
    ServerAdmin info@my-domain.com
    DocumentRoot /home/user/public_html/laravel/public
    UseCanonicalName Off
    ScriptAlias /cgi-bin/ /home/user/public_html/cgi-bin/

    ErrorLog /usr/local/apache/domlogs/my-domain.com.error.log

    <IfModule mod_setenvif.c>
        SetEnvIf X-Forwarded-Proto "^https$" HTTPS=on
    </IfModule>

    <IfModule mod_userdir.c>
        UserDir disabled
        UserDir enabled user
    </IfModule>

    <IfModule mod_suexec.c>
        SuexecUserGroup user user
    </IfModule>

    <IfModule mod_suphp.c>
        suPHP_UserGroup user user
        suPHP_ConfigPath /home/user
    </IfModule>

    <IfModule mod_ruid2.c>
        RMode config
        RUidGid user user
    </IfModule>

    <IfModule itk.c>
        AssignUserID user user
    </IfModule>

    <Directory "/home/user/public_html">
        AllowOverride All
    </Directory>

</VirtualHost>

And it's apache log :

Invalid URI in request GET \@backend HTTP/1.0

There is many laravel sites and all of them are normal but i have problem with this one. I can't figure out this problem.

My vHost.conf is OK, my .env files is OK, but i can't load any assets such as css / js / robots.txt / etc ... ( anything that saved in public directory ).

Do you have any idea?


答:
We can use base R

```<code>subset(d, abs(as.Date(DATE2) - as.Date(DATE)) <=5)
</code>```

For the second condition

```<code>subset(d, (as.Date(DATE) - as.Date(DATE2)) <=3)
</code>```

Body:
We can use base R

subset(d, abs(as.Date(DATE2) - as.Date(DATE)) <=5)

For the second condition

subset(d, (as.Date(DATE) - as.Date(DATE2)) <=3)


问:
How do I export my project in Android Studio?
I need to export my Android Studio project to an Android phone. I've generated a signed APK already but I don't know what to do after this. What else do I need to do to export my project?</p>

答:
If you have Android Emulator, then you can directly run and check your app contents.
Or
If you want your app to run on your phone, then go to the app folder of your Android project
Directory : app/release/release.apk
Connect your data cable and move that release.apk in your phone directory and install that apk file in your Android phone. </p>


问:
LINQ Querying list in list
I have this situation:

My ModelView:

```<code>public class Subject
{
   public int ID { get; set; }
   public string Name { get; set; }
   public int ProfessorID { get; set; }
   public string ProfessorFullName{ get; set; }
   public IList<Assistant> Assistants { get; set; }
}

public class Assistant
{
   public string AssistantFullName{ get; set; }
}
</code>```

My query:

```<code>var subjects = from subject in Entities.Subjects
                            from professor in subject.Lecturers
                            where professor.Professor == true
                            select new SSVN.ModelView.Subject()
                            {
                                ID = subject.ID,
                                Name= subject.Name,
                                ProfessorFullName= professor.LastName+ " " + professor.Name,
                                Assistants= (from subject1 in Entities.Subjects
                                            from assistant in subject1.Lecturers
                                            where assistant.Professor == false
                                            select new SSVN.ModelView.Assistant()
                                            {
                                                AssistantFullName = assistant.LastName+ " " + assistant.Name
                                            }).ToList()
                            };
</code>```

And when I call:

subjects.ToList(); I get exception:

```<code>LINQ to Entities does not recognize the method
'System.Collections.Generic.List`1[SSVN.ModelView.Assistant] ToList[Assistant]
(System.Collections.Generic.IEnumerable`1[SSVN.ModelView.Assistant])' method, and this
method cannot be translated into a store expression.
</code>```

答: You cannot and should not use a ToList() in an IQueryablle query. Note that this query has to be translated into SQL.

Title: LINQ Querying list in list

Body:
I have this situation:

My ModelView:

public class Subject
{
   public int ID { get; set; }
   public string Name { get; set; }
   public int ProfessorID { get; set; }
   public string ProfessorFullName{ get; set; }
   public IList<Assistant> Assistants { get; set; }
}

public class Assistant
{
   public string AssistantFullName{ get; set; }
}

My query:

var subjects = from subject in Entities.Subjects
                            from professor in subject.Lecturers
                            where professor.Professor == true
                            select new SSVN.ModelView.Subject()
                            {
                                ID = subject.ID,
                                Name= subject.Name,
                                ProfessorFullName= professor.LastName+ " " + professor.Name,
                                Assistants= (from subject1 in Entities.Subjects
                                            from assistant in subject1.Lecturers
                                            where assistant.Professor == false
                                            select new SSVN.ModelView.Assistant()
                                            {
                                                AssistantFullName = assistant.LastName+ " " + assistant.Name
                                            }).ToList()
                            };

And when I call:

subjects.ToList(); I get exception:

LINQ to Entities does not recognize the method
'System.Collections.Generic.List`1[SSVN.ModelView.Assistant] ToList[Assistant]
(System.Collections.Generic.IEnumerable`1[SSVN.ModelView.Assistant])' method, and this
method cannot be translated into a store expression.


问:
multiple AND conditions for a single column in where clause
I have a table with column ID, datatype Integer, now my requirement is to select data from table that matches certain values like

```<code>ID
1
2
3
4
</code>```

Possible conditons:

if ID = 1 and ID = 2 then retrive the dataset, if ID = 1 and ID = 5 then don't return result set.

now here is the whole issue:

I am not sure how to write this condition with And clause

If I write

```<code>select ID where ID = 1 and ID =2
</code>```

this doesn't return any rows.

Not sure how to write query for this particular condition, Also I can't use OR because my requirement is table should contain both the values then return the result set.

答:
You have to use IN clause if you need to filter multiple values from same column. AND should be used to apply filter in different columns. Do not provide 5 in your condition, by default it will be omitted

```<code>select ID from table where ID in (1, 2);
</code>```

You can also use between operator,

```<code>select ID from table where ID between 1 and 2;
</code>```

Body:
I have a table with column ID, datatype Integer, now my requirement is to select data from table that matches certain values like

ID
1
2
3
4

Possible conditons:

if ID = 1 and ID = 2 then retrive the dataset, if ID = 1 and ID = 5 then don't return result set.

now here is the whole issue:

I am not sure how to write this condition with And clause

If I write

select ID where ID = 1 and ID =2

this doesn't return any rows.

Not sure how to write query for this particular condition, Also I can't use OR because my requirement is table should contain both the values then return the result set.

Body:
You have to use IN clause if you need to filter multiple values from same column. AND should be used to apply filter in different columns. Do not provide 5 in your condition, by default it will be omitted

select ID from table where ID in (1, 2);

You can also use between operator,

select ID from table where ID between 1 and 2;


问:
can i sort element in css using attribute value?
I have a list of images, those image elements have a attribute like index, which I want to use to sort the element of the images in ascending order. with the help of CSS.

Because that index attribute value will change dynamically, more image will also be added by Ajax. So when it will update, that time it will be arranged in that order without doing anything.

.img_container {
  width: 100%;
  border: 2px black solid;
}

.img_container img {
  margin-bottom: 5px;
  margin-right: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="img_container">
  <img src="https://dummyimage.com/100x150/000000/ffffff&text=1" index="1">
  <img src="https://dummyimage.com/100x150/000000/ffffff&text=10" index="10">
  <img src="https://dummyimage.com/110x150/000000/ffffff&text=11" index="11">
  <img src="https://dummyimage.com/140x150/000000/ffffff&text=14" index="14">
  <img src="https://dummyimage.com/200x150/000000/ffffff&text=2" index="2">
  <img src="https://dummyimage.com/120x150/000000/ffffff&text=12" index="12">
  <img src="https://dummyimage.com/130x150/000000/ffffff&text=13" index="13">
  <img src="https://dummyimage.com/300x150/000000/ffffff&text=3" index="3">
  <img src="https://dummyimage.com/400x150/000000/ffffff&text=4" index="4">
  <img src="https://dummyimage.com/150x150/000000/ffffff&text=15" index="15">
  <img src="https://dummyimage.com/500x150/000000/ffffff&text=5" index="5">
  <img src="https://dummyimage.com/400x150/000000/ffffff&text=6" index="6">
  <img src="https://dummyimage.com/170x150/000000/ffffff&text=17" index="17">
  <img src="https://dummyimage.com/300x150/000000/ffffff&text=7" index="7">
  <img src="https://dummyimage.com/160x150/000000/ffffff&text=16" index="16">
  <img src="https://dummyimage.com/200x150/000000/ffffff&text=8" index="8">
  <img src="https://dummyimage.com/180x150/000000/ffffff&text=18" index="18">
  <img src="https://dummyimage.com/200x150/000000/ffffff&text=9" index="9">
</div></code>```

Let me know if there is any easy way to do this in CSS.

答:
There is not a good CSS-only solution yet without modifying the HTML or adding inline styles. In the future, it may be possible to achieve this using the attr() function in CSS, but currently this doesn't have wide support for being able to use it outside of the content property.

If the more advanced usage is adopted, a future solution could look like this. Note, this will not work in most current browsers. And you should also use the data- prefix for custom attributes.

.img_container {
  border: 2px black solid;
  display: flex;
  flex-wrap: wrap;
}

.img_container img {
  margin: 5px;
  order: attr(data-index); /* will not work yet in most browsers */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="img_container">
  <img src="https://dummyimage.com/100x150/000000/ffffff&text=1" data-index="1">
  <img src="https://dummyimage.com/100x150/000000/ffffff&text=10" data-index="10">
  <img src="https://dummyimage.com/110x150/000000/ffffff&text=11" data-index="11">
  <img src="https://dummyimage.com/140x150/000000/ffffff&text=14" data-index="14">
  <img src="https://dummyimage.com/200x150/000000/ffffff&text=2" data-index="2">
  <img src="https://dummyimage.com/120x150/000000/ffffff&text=12" data-index="12">
  <img src="https://dummyimage.com/130x150/000000/ffffff&text=13" data-index="13">
  <img src="https://dummyimage.com/300x150/000000/ffffff&text=3" data-index="3">
  <img src="https://dummyimage.com/400x150/000000/ffffff&text=4" data-index="4">
  <img src="https://dummyimage.com/150x150/000000/ffffff&text=15" data-index="15">
  <img src="https://dummyimage.com/500x150/000000/ffffff&text=5" data-index="5">
  <img src="https://dummyimage.com/400x150/000000/ffffff&text=6" data-index="6">
  <img src="https://dummyimage.com/170x150/000000/ffffff&text=17" data-index="17">
  <img src="https://dummyimage.com/300x150/000000/ffffff&text=7" data-index="7">
  <img src="https://dummyimage.com/160x150/000000/ffffff&text=16" data-index="16">
  <img src="https://dummyimage.com/200x150/000000/ffffff&text=8" data-index="8">
  <img src="https://dummyimage.com/180x150/000000/ffffff&text=18" data-index="18">
  <img src="https://dummyimage.com/200x150/000000/ffffff&text=9" data-index="9">
</div></code>```

Body:
I have a list of images, those image elements have a attribute like index, which I want to use to sort the element of the images in ascending order. with the help of CSS.

Because that index attribute value will change dynamically, more image will also be added by Ajax. So when it will update, that time it will be arranged in that order without doing anything.

.img_container {
  width: 100%;
  border: 2px black solid;
}

.img_container img {
  margin-bottom: 5px;
  margin-right: 5px;
}

Let me know if there is any easy way to do this in CSS.

Body:
There is not a good CSS-only solution yet without modifying the HTML or adding inline styles. In the future, it may be possible to achieve this using the attr() function in CSS, but currently this doesn't have wide support for being able to use it outside of the content property.

If the more advanced usage is adopted, a future solution could look like this. Note, this will not work in most current browsers. And you should also use the data- prefix for custom attributes.

.img_container {
  border: 2px black solid;
  display: flex;
  flex-wrap: wrap;
}

.img_container img {
  margin: 5px;
  order: attr(data-index); /* will not work yet in most browsers */
}

<div class="img_container">
  <img src="https://dummyimage.com/100x150/000000/ffffff&text=1" data-index="1">
  <img src="https://dummyimage.com/100x150/000000/ffffff&text=10" data-index="10">
  <img src="https://dummyimage.com/110x150/000000/ffffff&text=11" data-index="11">
  <img src="https://dummyimage.com/140x150/000000/ffffff&text=14" data-index="14">
  <img src="https://dummyimage.com/200x150/000000/ffffff&text=2" data-index="2">
  <img src="https://dummyimage.com/120x150/000000/ffffff&text=12" data-index="12">
  <img src="https://dummyimage.com/130x150/000000/ffffff&text=13" data-index="13">
  <img src="https://dummyimage.com/300x150/000000/ffffff&text=3" data-index="3">
  <img src="https://dummyimage.com/400x150/000000/ffffff&text=4" data-index="4">
  <img src="https://dummyimage.com/150x150/000000/ffffff&text=15" data-index="15">
  <img src="https://dummyimage.com/500x150/000000/ffffff&text=5" data-index="5">
  <img src="https://dummyimage.com/400x150/000000/ffffff&text=6" data-index="6">
  <img src="https://dummyimage.com/170x150/000000/ffffff&text=17" data-index="17">
  <img src="https://dummyimage.com/300x150/000000/ffffff&text=7" data-index="7">
  <img src="https://dummyimage.com/160x150/000000/ffffff&text=16" data-index="16">
  <img src="https://dummyimage.com/200x150/000000/ffffff&text=8" data-index="8">
  <img src="https://dummyimage.com/180x150/000000/ffffff&text=18" data-index="18">
  <img src="https://dummyimage.com/200x150/000000/ffffff&text=9" data-index="9">
</div>


答:
You should avoid using regex for this task. It is easier to get this done in awk with simple substr function calls:

```<code>awk -v i=2 -v n=2 'i>0{$0 = substr($0, 1, i-1) substr($0, i+n)} 1' file
</code>```

```<code>14 5678
</code>```

Title: Delete values in line based on column index using shell script

Body:
I want to be able to delete the values to the RIGHT(starting from given column index) from the test.txt at the given column index based on a given length, N.

Column index refers to the position when you open the file in the VIM editor in LINUX.

If my test.txt contains 1234 5678, and I call my delete_var function which takes in the column number as 2 to start deleting from and length N as 2 to delete as input, the test.txt would reflect 14 5678 as it deleted the values from column 2 to column 4 as the length to delete was 2.

I have the following code as of now but I am unable to understand what I would put in the sed command.

delete_var() {

    sed -i -r 's/not sure what goes here' test.txt
}

clmn_index= $1
_N=$2

delete_var "$clmn_index" "$_N"   # call the method with the column index and length to delete

#sample test.txt (before call to fn)
1234 5678

#sample test.txt (after call to fn)
14 5678

Can someone guide me?

Body:
You should avoid using regex for this task. It is easier to get this done in awk with simple substr function calls:

awk -v i=2 -v n=2 'i>0{$0 = substr($0, 1, i-1) substr($0, i+n)} 1' file

14 5678


问:
Jquery undefined MVC
I am new here and i hope you can help me with my issue.

First of all i am not familiar with jQuery.

I followed a tutorial to make an autocomplete function for my Website TextBox.

But somehow i get an error for the jquery scripts saying 0x800a1391 Runtime Error in JavaScript jQuery undefinded when running the application.

I tried it with different versions of jQueryfile for autocomplete. Right now im using the latest Version included with NuGet.

Thanks for your help.

Index.cshtml

```<code><script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.js"></script>

<div>
    <label>Markensuche</label>
    <input class="form-control" id="searchInput" />

</div>
<script>
    $("#searchInput").autocomplete{
        source: function(request, response) {
            $.ajax8{
                url: '@Url.Action("GetSearchValue","Home")',
                    dataType: "json",
                    data: { search: $("searchInput").val() },
                success: function (data) {
                    response($.map(data, function (item) {
                        return {label:item.TabakMarke,value:item.TabakMarke}

                    }))
                },
                error: function(xhr, status, error) {
                    alert("Error");
                }
            });
        }
    });
</script>
</code>```

Debbuging Error Code

```<code>  <div class="container body-content">

<script src="/Scripts/jquery-ui-1.12.1.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="/Scripts/jquery-ui-1.12.1.js"></script>

<div>
    <label>Markensuche</label>
    <input class="form-control" id="searchInput" />

</div>
<script>
    $("#searchInput").autocomplete{
        source: function(request, response) {
            $.ajax8{
                url: '/Home/GetSearchValue',
                    dataType: "json",
                    data: { search: $("searchInput").val() },
                success: function (data) {
                    response($.map(data, function (item) {
                        return {label:item.TabakMarke,value:item.TabakMarke}

                    }))
                },
                error: function(xhr, status, error) {
                    alert("Error");
                }
            });
        }
    });
</script>
        <hr />
        <footer>
            <p>© 2020 - Meine ASP.NET-Anwendung</p>
        </footer>
    </div>

    <script src="/Scripts/jquery-3.4.1.js"></script>

    <script src="/Scripts/bootstrap.js"></script>

<!-- Visual Studio Browser Link -->
<script type="text/javascript" src="https://localhost:44399/fcfbda4df83942d79d121bc3bce382d4/browserLink" async="async" id="__browserLink_initializationData" data-requestId="67935583404a485d8c1f16cb2c900e1f" data-appName="Internet Explorer"></script>
<!-- End Browser Link -->

</body>
</html>
</code>```

答:
You're including jQuery UI, but not jQuery itself (jQuery UI does not include jQuery).

Try to include https://code.jquery.com/jquery-3.5.1.min.js as well.

Title: Jquery undefined MVC

Body:
I am new here and i hope you can help me with my issue.

First of all i am not familiar with jQuery.

I followed a tutorial to make an autocomplete function for my Website TextBox.

But somehow i get an error for the jquery scripts saying 0x800a1391 Runtime Error in JavaScript jQuery undefinded when running the application.

I tried it with different versions of jQueryfile for autocomplete. Right now im using the latest Version included with NuGet.

Thanks for your help.

Index.cshtml

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />

    Markensuche
    <input class="form-control" id="searchInput" />

Debbuging Error Code

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />

    Markensuche
    <input class="form-control" id="searchInput" />

© 2020 - Meine ASP.NET-Anwendung


问:
Extracting first line from a file if condition matches in a block
I have the below file and I need to capture all the hostnames in a single file separated by "," which have Failed: 0 in them

file.txt:

```<code>host1:
   name: sudo something
   name: something
   succeeded: 34
   Failed: 0
host2:
   name: something 123
   succeeded: 12
   Failed: 3
host3:
   name: something 1234
   succeeded: 12
   Failed: 13
host4:
   name: something 1234
   succeeded: 12
   Failed: 0
</code>```

So, the output should be host1, host4. I have tried the below code:

```<code>awk -F ':' '/:/{host=$1; getline; if($1 !~ /Failed:0/) NR==1{print host}}' file.txt > output.txt
</code>```

Can anyone, advice how to go about it, please? I would prefer to do it in one line command as I need to pass it via Jenkins pipeline.

========================Update===============================

Using grep - V Name: my input file looks as below:

host1:

Summary for host1

Succeeded: 36 (changed=10)

Failed:     0

host4:

Summary for host4

Succeeded: 36 (changed=10)

Failed:     0

Now, how can I just filter for Failed:  0 cases and get the hostnames?

答:
```<code>$ awk '/:$/{h=$1; sub(/:/,"",h)} /Failed: 0/{print h}' file1 | paste -sd,
host1,host4
</code>```

note that your host4 normally should not appear in the list.  This is after
sed -i '$s/13/0/' file

I guess it can be simplified as suggested

```<code>$ awk -F: '$2==""{h=$1} /Failed: 0/{print h}' file1 | paste -sd,
</code>```

Body:
I have the below file and I need to capture all the hostnames in a single file separated by "," which have Failed: 0 in them

file.txt:

host1:
   name: sudo something
   name: something
   succeeded: 34
   Failed: 0
host2:
   name: something 123
   succeeded: 12
   Failed: 3
host3:
   name: something 1234
   succeeded: 12
   Failed: 13
host4:
   name: something 1234
   succeeded: 12
   Failed: 0

So, the output should be host1, host4. I have tried the below code:

awk -F ':' '/:/{host=$1; getline; if($1 !~ /Failed:0/) NR==1{print host}}' file.txt > output.txt

Can anyone, advice how to go about it, please? I would prefer to do it in one line command as I need to pass it via Jenkins pipeline.

========================Update===============================

Using grep - V Name: my input file looks as below:

host1:

Summary for host1

Succeeded: 36 (changed=10)

Failed:     0

host4:

Summary for host4

Succeeded: 36 (changed=10)

Failed:     0

Now, how can I just filter for Failed:  0 cases and get the hostnames?

Body:
$ awk '/:$/{h=$1; sub(/:/,"",h)} /Failed: 0/{print h}' file1 | paste -sd,
host1,host4

note that your host4 normally should not appear in the list.  This is after
sed -i '$s/13/0/' file

I guess it can be simplified as suggested

$ awk -F: '$2==""{h=$1} /Failed: 0/{print h}' file1 | paste -sd,


问:
Delete part of string between { and | in JavaScript
Currently I am getting strings that look like this:

I like {{Pizza|Pasta}} for breakfast.

I want to manipulate strings in JS so that they only contain the part after the '|' so that the sentence would be

I like Pasta for breakfast.

So far this piece of code has brought me a fair end.

```<code>str.replace(/\{\{.*?\|.*?\}\}/g, "");
</code>```

But if I have a string like:

I eat {{bread}} and {{cereal|yoghurt}} for breakfast.

The results is:

I eat yoghurt for breakfast.

But I want:

I eat bread and yoghurt for breakfast.

So far I have tried this with regex. But it doesn't seem to replace anything.

```<code>str.replace(/\{\{.*((?!]).).*?\|(.*?)\}\}/g, "");
</code>```

答:
Try this one:</p>

```<code>var text = '{{Pizza|Pasta}}';
var replaced = text.replace('{{','').replace('}}','').split('|')[1];
var final = 'I like '+replaced+' for breakfast';
console.log(final);
</code>```

Body:
Currently I am getting strings that look like this:

I like {{Pizza|Pasta}} for breakfast.

I want to manipulate strings in JS so that they only contain the part after the '|' so that the sentence would be

I like Pasta for breakfast.

So far this piece of code has brought me a fair end.

str.replace(/\{\{.*?\|.*?\}\}/g, "");

But if I have a string like:

I eat {{bread}} and {{cereal|yoghurt}} for breakfast.

The results is:

I eat yoghurt for breakfast.

But I want:

I eat bread and yoghurt for breakfast.

So far I have tried this with regex. But it doesn't seem to replace anything.

str.replace(/\{\{.*((?!]).).*?\|(.*?)\}\}/g, "");

Body:
Try this one:

var text = '{{Pizza|Pasta}}';
var replaced = text.replace('{{','').replace('}}','').split('|')[1];
var final = 'I like '+replaced+' for breakfast';
console.log(final);


问:
Why does 'not in' return True with 2-dimensional lists that contain the cited value in their inner lists
I want this statement to return False. Clearly there are plenty of 0s in the list, however it returns True.

```<code>zeros = [[0] * 8] * 8
print(0 not in zeros)
# True
</code>```

Could someone explain this behaviour?
Also, is there a different expression I can use that will evaluate to False?

答:
Look at zeros:

```<code>>>> zeros
[[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]
</code>```

All the elements of zeros are [0, 0, 0, 0, 0, 0, 0, 0].  None of them are just 0.

If you simply want a statement that will evaluate to False there is of course:

```<code>>>> print(False)
False
</code>```

but if you want to specifically test if there are not any 0s in any of the elements of zeros you could do:

```<code>>>> print(not any(0 in z for z in zeros))
False
</code>```

Body:
I want this statement to return False. Clearly there are plenty of 0s in the list, however it returns True.

zeros = [[0] * 8] * 8
print(0 not in zeros)
# True

Could someone explain this behaviour?
Also, is there a different expression I can use that will evaluate to False?

Body:
Look at zeros:

>>> zeros
[[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]]

All the elements of zeros are [0, 0, 0, 0, 0, 0, 0, 0].  None of them are just 0.

If you simply want a statement that will evaluate to False there is of course:

>>> print(False)
False

but if you want to specifically test if there are not any 0s in any of the elements of zeros you could do:

>>> print(not any(0 in z for z in zeros))
False


问:
QModbusTcpClient cant connect to PLC
Im trying to connect to PLC device. I set all configuration in device correct, I was sucessfull connected and tested communication between PC and PLC device by ModbusSlave software.

My QT code is:

```<code>    PLC = new QModbusTcpClient();
    m_port = 502;
    m_host = "10.100.101.2"; //PLC IP
    PLC->setConnectionParameter(QModbusDevice::NetworkPortParameter, this->m_port);
    PLC->setConnectionParameter(QModbusDevice::NetworkAddressParameter, this->m_host);
    PLC->setTimeout(5000);
    PLC->setNumberOfRetries(10);

    qDebug()<<"State: " << PLC->state();

    qDebug()<<"Try to connect...";
    if(!PLC->connectDevice()){
        qDebug()<<"Not connected to PLC: " << PLC->errorString();

    }
    else{
        qDebug()<<"State: " << PLC->state();

        while(PLC->state()!=QModbusDevice::ConnectedState){
        QThread::msleep(5);
        }
        qDebug()<<"Connection to PLC succesed" << PLC->state();
        emit PLCConnected();
    }
</code>```

The output is:

State:  QModbusDevice::UnconnectedState
Try to connect...
State:  QModbusDevice::ConnectingState

答:
first, what does PLC->connectDevice() do?

second, you can not wait for connection in the same thread, just subscribe to QModbusDevice::stateChanged signal and look for state changes

Title: QModbusTcpClient cant connect to PLC

Body:
Im trying to connect to PLC device. I set all configuration in device correct, I was sucessfull connected and tested communication between PC and PLC device by ModbusSlave software.

My QT code is:

    PLC = new QModbusTcpClient();
    m_port = 502;
    m_host = "10.100.101.2"; //PLC IP
    PLC->setConnectionParameter(QModbusDevice::NetworkPortParameter, this->m_port);
    PLC->setConnectionParameter(QModbusDevice::NetworkAddressParameter, this->m_host);
    PLC->setTimeout(5000);
    PLC->setNumberOfRetries(10);

    qDebug()<<"State: " << PLC->state();

    qDebug()<<"Try to connect...";
    if(!PLC->connectDevice()){
        qDebug()<<"Not connected to PLC: " << PLC->errorString();

    }
    else{
        qDebug()<<"State: " << PLC->state();

        while(PLC->state()!=QModbusDevice::ConnectedState){
        QThread::msleep(5);
        }
        qDebug()<<"Connection to PLC succesed" << PLC->state();
        emit PLCConnected();
    }

The output is:

State:  QModbusDevice::UnconnectedState
Try to connect...
State:  QModbusDevice::ConnectingState


问:
Java summing numbers in an array using threads: using a new variable as a lock in a synchronized block: the difference
I have an array of numbers that I sum using threads. To avoid the race condition issue, the block of code that increments the sum variables is wrapped in synchronized. At first I wrapped it in synchronized (this) and it worked fine.

However, I'm trying to understand what happens when something other than this is passed as a lock value. I tried to chance the lock to synchronized (new Object()), so that the lock value is different each time it executes. But it continued to work fine, although I'd expect it to break, because now the value - reference of the lock object changes each time:

```<code>public class SumNumbersCommon {
    private static int totalSum;
    private static int[] numbers = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    public static void main(String[] args) throws  Exception  {
        System.out.printf("Usual sum: %,d\n", sum(numbers));

        int left = numbers.length / 2;
        Thread leftThread = new Thread(new SummerThread(0, left));
        Thread rightThread = new Thread(new SummerThread(left + 1, numbers.length - 1));

        leftThread.start();
        rightThread.start();

        leftThread.join();
        rightThread.join();

        System.out.printf("total sum: %,d\n", totalSum);

    }

    static class SummerThread implements Runnable  {
        private int min;
        private int max;

        public SummerThread(int min, int max)  {
            this.min = min;
            this.max = max;
        }

        @Override
        public void run() {
            for (int i = min; i <= max; i++)  {
                synchronized (new Object()) {
                    totalSum += numbers[i];
                }
            }
        }
    }

    public static int sum(int[] numbers)  {
        int result = 0;
        for (int n: numbers)  {
            result += n;
        }
        return result;
    }

}
</code>```

Why does it still work? In which cases would I use anything other than synchronized (this)?

答:
The point of locking is to prevent concurrent access to shared data. That means that the different threads trying to access the data need to all use the same lock. The posted examples don't do that, the separate threads are each using their own lock, so no kind of useful locking is taking place.

To change this so that you have meaningful locking, move the actual shared data into its own class, and pass the shared data object into each thread.

Here's an example of what the shared data class could look like:

```<code>public class RunningTotal {

    private int totalSum = 0;
    private int[] numbers = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    public void synchronized addNumberAtIndex(int idx) {
         totalSum += numbers[idx];
    }

    public synchronized int getTotalSoFar() {
        return totalSum;
    }
}
</code>```

Here the object controls access to its data using its own intrinsic lock, any thread that wants to update the running total needs to acquire the lock on that object first.

Body:
I have an array of numbers that I sum using threads. To avoid the race condition issue, the block of code that increments the sum variables is wrapped in synchronized. At first I wrapped it in synchronized (this) and it worked fine.

However, I'm trying to understand what happens when something other than this is passed as a lock value. I tried to chance the lock to synchronized (new Object()), so that the lock value is different each time it executes. But it continued to work fine, although I'd expect it to break, because now the value - reference of the lock object changes each time:

public class SumNumbersCommon {
    private static int totalSum;
    private static int[] numbers = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    public static void main(String[] args) throws  Exception  {
        System.out.printf("Usual sum: %,d\n", sum(numbers));

        int left = numbers.length / 2;
        Thread leftThread = new Thread(new SummerThread(0, left));
        Thread rightThread = new Thread(new SummerThread(left + 1, numbers.length - 1));

        leftThread.start();
        rightThread.start();

        leftThread.join();
        rightThread.join();

        System.out.printf("total sum: %,d\n", totalSum);

    }

    static class SummerThread implements Runnable  {
        private int min;
        private int max;

        public SummerThread(int min, int max)  {
            this.min = min;
            this.max = max;
        }

        @Override
        public void run() {
            for (int i = min; i <= max; i++)  {
                synchronized (new Object()) {
                    totalSum += numbers[i];
                }
            }
        }
    }

    public static int sum(int[] numbers)  {
        int result = 0;
        for (int n: numbers)  {
            result += n;
        }
        return result;
    }

}

Why does it still work? In which cases would I use anything other than synchronized (this)?

Body:
The point of locking is to prevent concurrent access to shared data. That means that the different threads trying to access the data need to all use the same lock. The posted examples don't do that, the separate threads are each using their own lock, so no kind of useful locking is taking place.

To change this so that you have meaningful locking, move the actual shared data into its own class, and pass the shared data object into each thread.

Here's an example of what the shared data class could look like:

public class RunningTotal {

    private int totalSum = 0;
    private int[] numbers = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    public void synchronized addNumberAtIndex(int idx) {
         totalSum += numbers[idx];
    }

    public synchronized int getTotalSoFar() {
        return totalSum;
    }
}

Here the object controls access to its data using its own intrinsic lock, any thread that wants to update the running total needs to acquire the lock on that object first.


问:
Delete values in line based on column index using shell script
I want to be able to delete the values to the RIGHT(starting from given column index) from the test.txt at the given column index based on a given length, N.

Column index refers to the position when you open the file in the VIM editor in LINUX.

If my test.txt contains 1234 5678, and I call my delete_var function which takes in the column number as 2 to start deleting from and length N as 2 to delete as input, the test.txt would reflect 14 5678 as it deleted the values from column 2 to column 4 as the length to delete was 2.

I have the following code as of now but I am unable to understand what I would put in the sed command.

```<code>delete_var() {

    sed -i -r 's/not sure what goes here' test.txt
}

clmn_index= $1
_N=$2

delete_var "$clmn_index" "$_N"   # call the method with the column index and length to delete
</code>```

```<code>#sample test.txt (before call to fn)
1234 5678
</code>```

```<code>#sample test.txt (after call to fn)
14 5678
</code>```

Can someone guide me?

答:
Below command result in the elimination of the 2nd character. Try to use this in a loop</p>

```<code>sed s/.//2 test.txt
</code>```

Body:
Below command result in the elimination of the 2nd character. Try to use this in a loop

sed s/.//2 test.txt