问:
Grouping SQL results from a Union
I have a table in my database used for users to follow eachother.

The table goes as follows:

```<code>UniqueID
FollowerID
FollowedUserID
</code>```

FollowID is the UserID of the person who is following someone else.

FollowedUserID is the UserID of the person who is being followed by the FollowID User.

I'd like to retrieve a list of connections from this table based off a single user. My query should return all the other UserIDs that the current user is either following or being followed by with no overlaps.

So say we have a few entries here:

```<code>FollowerID   FollowedUserID
    1              2
    1              3
    4              1
    2              1
</code>```

This would show that the User 1 is following users 2 and 3, and thus users 2 and 3 are being followed by user 1. On the other side of the spectrum it shows that User 1 is followed by users 2 and 3.

What I'd like to do is find out the connections that user 1 has, so the query should return users: 2, 3, and 4 (user 1 is following users 2 and 3 and is being followed by user 4)

How can I achieve this from a single query?

A connection is considered either being followed or following someone else, so it is possible that some duplicate results can occur (if both users are following eachother). I'd like to be able to group these results so that the result is distinct.

I've tried a UNION query similar to:

```<code>SELECT FollowerID, FollowedUserID From Follows WHERE FollowerID = 1
UNION
SELECT FollowerID, FollowedUserID FROM Follows WHERE FollowedUserID = 1
</code>```

Theoretically I'd like to Group FollowerID and FollowedUserID together to keep them distinct.

I'm not interested in retrieving a non-distinct result and then creating a dataset of unique results php side -- the query should return distinct values only.

答:
I think you'd need to revise your query:

```<code>edit: removed the un-needed select distinct
SELECT FollowedUserID as ID From Follows WHERE FollowerID = 1
UNION
SELECT FollowerID as ID FROM Follows WHERE FollowedUserID = 1
</code>```

But that doesn't quite answer the question of direction.

```<code>SELECT FollowedUserID as ID, "follow" as direction
From Follows
WHERE FollowerID = 1
UNION
SELECT FollowerID as ID, "followed" as direction
FROM Follows
WHERE FollowedUserID = 1
</code>```

Now you know the direction of the connection as well.

Title: Grouping SQL results from a Union

Body:
I have a table in my database used for users to follow eachother.

The table goes as follows:

UniqueID
FollowerID
FollowedUserID

FollowID is the UserID of the person who is following someone else.

FollowedUserID is the UserID of the person who is being followed by the FollowID User.

I'd like to retrieve a list of connections from this table based off a single user. My query should return all the other UserIDs that the current user is either following or being followed by with no overlaps.

So say we have a few entries here:

FollowerID   FollowedUserID
    1              2
    1              3
    4              1
    2              1

This would show that the User 1 is following users 2 and 3, and thus users 2 and 3 are being followed by user 1. On the other side of the spectrum it shows that User 1 is followed by users 2 and 3.

What I'd like to do is find out the connections that user 1 has, so the query should return users: 2, 3, and 4 (user 1 is following users 2 and 3 and is being followed by user 4)

How can I achieve this from a single query?

A connection is considered either being followed or following someone else, so it is possible that some duplicate results can occur (if both users are following eachother). I'd like to be able to group these results so that the result is distinct.

I've tried a UNION query similar to:

SELECT FollowerID, FollowedUserID From Follows WHERE FollowerID = 1
UNION
SELECT FollowerID, FollowedUserID FROM Follows WHERE FollowedUserID = 1

Theoretically I'd like to Group FollowerID and FollowedUserID together to keep them distinct.

I'm not interested in retrieving a non-distinct result and then creating a dataset of unique results php side -- the query should return distinct values only.

Body:
I think you'd need to revise your query:

edit: removed the un-needed select distinct
SELECT FollowedUserID as ID From Follows WHERE FollowerID = 1
UNION
SELECT FollowerID as ID FROM Follows WHERE FollowedUserID = 1

But that doesn't quite answer the question of direction.

SELECT FollowedUserID as ID, "follow" as direction
From Follows
WHERE FollowerID = 1
UNION
SELECT FollowerID as ID, "followed" as direction
FROM Follows
WHERE FollowedUserID = 1

Now you know the direction of the connection as well.


来源: stackexchange

问:
How to separate string using by commas in multicomma line
What should I do to for separate (test(1,2) , test(3,4)) as test(1,2) and test(3,4). What can I use as delimiter value instead of x here? Thanks</p>

```<code>    StringTokenizer tokenizer = new StringTokenizer(str, "x");
</code>```

答:
Try this :-</p>

```<code>    String s = "(test(1,2) , test(3,4))";
    s=s.substring(1).substring(0,s.length()-2);
    String[] arr = s.split(" ,");
    System.out.println(arr[0].trim());
    System.out.println(arr[1].trim());
</code>```

ContentLicense: CC BY-SA 4.0

Body:
What should I do to for separate (test(1,2) , test(3,4)) as test(1,2) and test(3,4). What can I use as delimiter value instead of x here? Thanks

    StringTokenizer tokenizer = new StringTokenizer(str, "x");

Body:
Try this :-

    String s = "(test(1,2) , test(3,4))";
    s=s.substring(1).substring(0,s.length()-2);
    String[] arr = s.split(" ,");
    System.out.println(arr[0].trim());
    System.out.println(arr[1].trim());


问:
Running each kernel function on multiple gpus in cuda 10.0
```<code>// Four Kernel Runs Simultaneously
Kernel1 <<< numBlocks, threadPerBlock >>> (args); // GPU 0
Kernel2 <<< numBlocks, threadPerBlock >>> (args); // GPU 1
Kernel3 <<< numBlocks, threadPerBlock >>> (args); // GPU 2
Kernel4 <<< numBlocks, threadPerBlock >>> (args); // GPU 3
</code>```

I want it to work like this code.

Do you have any samples or document for reference?

答:
You can use cudaSetDevice(int device) before each kernel call.

__host__ cudaError_t cudaSetDevice ( int  device )
      Set device to be used for GPU executions.

```<code>// Four Kernel Runs Simultaneously
cudaSetDevice(0);
Kernel1 <<< numBlocks, threadPerBlock >>> (args); // GPU 0
cudaSetDevice(1);
Kernel2 <<< numBlocks, threadPerBlock >>> (args); // GPU 1
cudaSetDevice(2);
Kernel3 <<< numBlocks, threadPerBlock >>> (args); // GPU 2
cudaSetDevice(3);
Kernel4 <<< numBlocks, threadPerBlock >>> (args); // GPU 3
</code>```

Body:
// Four Kernel Runs Simultaneously
Kernel1 <<< numBlocks, threadPerBlock >>> (args); // GPU 0
Kernel2 <<< numBlocks, threadPerBlock >>> (args); // GPU 1
Kernel3 <<< numBlocks, threadPerBlock >>> (args); // GPU 2
Kernel4 <<< numBlocks, threadPerBlock >>> (args); // GPU 3

I want it to work like this code.

Do you have any samples or document for reference?

Body:
You can use cudaSetDevice(int device) before each kernel call.

__host__ cudaError_t cudaSetDevice ( int  device )
      Set device to be used for GPU executions.

// Four Kernel Runs Simultaneously
cudaSetDevice(0);
Kernel1 <<< numBlocks, threadPerBlock >>> (args); // GPU 0
cudaSetDevice(1);
Kernel2 <<< numBlocks, threadPerBlock >>> (args); // GPU 1
cudaSetDevice(2);
Kernel3 <<< numBlocks, threadPerBlock >>> (args); // GPU 2
cudaSetDevice(3);
Kernel4 <<< numBlocks, threadPerBlock >>> (args); // GPU 3


问:
How to get all selectlist items in razor page?
I have a select list:

```<code>[BindProperty]
public List<SelectListItem> FooList { get; set; }
</code>```

The list is then instantiated as an empty list and the razor page loads. The list is then populated by the user on the client side using jquery. The server doesn't know the items in the list until the form is posted. So far, so good.

In the page I'm using the select tag helpers like so...

```<code>   <select asp-for="FooList" multiple="multiple" asp-items="FooList" class="form-control form">
</code>```

I'm wondering how can I retrieve all items in a mulitple selectlist "list box" (whether they're selected or not) OnPost using model binding?

I'm using razor pages 2.2 and I'm really struggling to figure this out.

```<code>        public IActionResult OnPost()
    {

        // not sure how to get the selectlist and all of its items?
        foreach (var item in FooList)
        {

            // do stuff with the items

        }

        return Page();
    }
</code>```

I know it's got to be something simple, just need a fresh set of eyes to point me in the right direction. Thanks!

答:
I'm wondering how can I retrieve all items in a mulitple selectlist
  "list box" (whether they're selected or not) OnPost using model
  binding?

You can't. Only the values of the selected items are posted and can take part in model binding. If you want to get the selected items in a multiple select list, you need to bind them to a collection. Your asp-for attribute should reference the name of the collection that you are binding the posted values to. You should not have [BindProprty] on the List<SelectListItem> type. They only represent the items that populate the select list.

You can find out more about the basics of Select Lists in Razor Pages here.

Body:
I have a select list:

[BindProperty]
public List<SelectListItem> FooList { get; set; }

The list is then instantiated as an empty list and the razor page loads. The list is then populated by the user on the client side using jquery. The server doesn't know the items in the list until the form is posted. So far, so good.

In the page I'm using the select tag helpers like so...

   <select asp-for="FooList" multiple="multiple" asp-items="FooList" class="form-control form">

I'm wondering how can I retrieve all items in a mulitple selectlist "list box" (whether they're selected or not) OnPost using model binding?

I'm using razor pages 2.2 and I'm really struggling to figure this out.

        public IActionResult OnPost()
    {

        // not sure how to get the selectlist and all of its items?
        foreach (var item in FooList)
        {

            // do stuff with the items

        }

        return Page();
    }

I know it's got to be something simple, just need a fresh set of eyes to point me in the right direction. Thanks!


问:
JSON object instead of array when a single element is present on XML SOAP response
I am consuming a web service that returns some XML data. The problems start when I convert the xml data to json. Some elements that are supposed to return an array of objects, when they have only one value, they are not converted to an array with a single object inside, they turn into an object. So instead of having:

```<code>{
"products":[ { "title":"Title 1",  "attributes":[{"color":"blue"}] } ]
}
</code>```

I get

```<code>{
"products":{ "title":"Title 1", "attributes":{"color":"blue"} }
}
</code>```

and the php array looks like this

[products] => Array ( [title] => Title 1 [attributes] => Array ( [color] => blue ) )

instead of this

[products] => Array ( [0] => Array ( [title] => Title 1
                                      [attributes] => Array ([0] => Array ([color] => blue ) ) )

So what I have done is the below:

```<code>$xml = simplexml_load_string($messageData);
$json = json_encode($xml);
$array = json_decode($json, TRUE);

 if (isset($array['products']) && !isset($array['products'][0])) {
       $array['products'] = array($array['products']);
 }
</code>```

I check if there is an array named products and if it doesn't have an index 0, I nest it inside a new array.
This does the job. Then I do the same for the attributes array like this:

```<code>    $products = $array['products'];

    $array['products'] = [];

    foreach ($products as $product) {

        if (isset($product['attributes']) && !isset($product['attributes'][0])) {

            $product['attributes'] = array($product['attributes']);

        }

        array_push($array['products'], product);
    }
</code>```

Here, I bind the products array to a variable called products to use it in the loop, then I empty the array and after I create the new attributes array, I populate the products array with the changed products.

My question is:

Is there a better way to deal with this thing? I don't like what I am doing here, but I can't think of anything else...

EDIT

This is my soap request:

```<code>
    $client = new SoapClient($wsdl, $soapOptions);

    $soapHeader = WsSecurity::createWsSecuritySoapHeader($username, $password, false, $synced, 60, true, true, false, true);

    $client->__setSoapHeaders($soapHeader);

    $response = $client->dateRetrieveMovement($dateMovementRequest);

    $movements = $response->DateMovementRequestResult->movements;
    $movementInfo = $movements->movementInfo;
    $messages = $movementInfo->messages->messageExchanged;

    $messageData = $messages->IEMessage->xmlData;

    $xml = simplexml_load_string($messageData);
    $json = json_encode($xml);
    $array = json_decode($json, TRUE);
</code>```

答:
The question is "is there a better way of doing the XML to JSON conversion", and I think the answer is "not without doing some coding".

Standard XML-to-JSON conversion libraries simply don't know enough about the semantics of your data model to produce a decent representation of your data. In theory a tool could try an extract such information from a schema, or elsewhere, but I don't know of any that does.

Writing a custom XSLT transformation to produce exactly the JSON you want is not too difficult, especially with XSLT 3.0, and this may well be less effort than patching up the JSON in the receiving application in the way you describe.

Body:
I am consuming a web service that returns some XML data. The problems start when I convert the xml data to json. Some elements that are supposed to return an array of objects, when they have only one value, they are not converted to an array with a single object inside, they turn into an object. So instead of having:

{
"products":[ { "title":"Title 1",  "attributes":[{"color":"blue"}] } ]
}

I get

{
"products":{ "title":"Title 1", "attributes":{"color":"blue"} }
}

and the php array looks like this

[products] => Array ( [title] => Title 1 [attributes] => Array ( [color] => blue ) )

instead of this

[products] => Array ( [0] => Array ( [title] => Title 1
                                      [attributes] => Array ([0] => Array ([color] => blue ) ) )

So what I have done is the below:

$xml = simplexml_load_string($messageData);
$json = json_encode($xml);
$array = json_decode($json, TRUE);

 if (isset($array['products']) && !isset($array['products'][0])) {
       $array['products'] = array($array['products']);
 }

I check if there is an array named products and if it doesn't have an index 0, I nest it inside a new array.
This does the job. Then I do the same for the attributes array like this:

    $products = $array['products'];

    $array['products'] = [];

    foreach ($products as $product) {

        if (isset($product['attributes']) && !isset($product['attributes'][0])) {

            $product['attributes'] = array($product['attributes']);

        }

        array_push($array['products'], product);
    }

Here, I bind the products array to a variable called products to use it in the loop, then I empty the array and after I create the new attributes array, I populate the products array with the changed products.

My question is:

Is there a better way to deal with this thing? I don't like what I am doing here, but I can't think of anything else...

EDIT

This is my soap request:

    $client = new SoapClient($wsdl, $soapOptions);

    $soapHeader = WsSecurity::createWsSecuritySoapHeader($username, $password, false, $synced, 60, true, true, false, true);

    $client->__setSoapHeaders($soapHeader);

    $response = $client->dateRetrieveMovement($dateMovementRequest);

    $movements = $response->DateMovementRequestResult->movements;
    $movementInfo = $movements->movementInfo;
    $messages = $movementInfo->messages->messageExchanged;

    $messageData = $messages->IEMessage->xmlData;

    $xml = simplexml_load_string($messageData);
    $json = json_encode($xml);
    $array = json_decode($json, TRUE);


问:
javascript can't reassignment data to array in map()
```<code>
let obj2 = {
  level2:{
    data:"data"
  }
}

let obj2Array  = [obj2,obj2,obj2];
obj2Array.map(obj=>{
  obj = obj.levle2.data
});
console.log(obj2Array)

</code>```

what I'm expecting is ["data","data","data"].But I still got the original data.
I know I can use forEach() to achieve this, but why I can't reassignment element in map()?

答:
the map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
as this says in the documentation
you can reAssign the obj2Array when doing map </p>

<p>like this </p>

```<code>let obj2 = {
  level2:{
    data:"data"
  }
}

let obj2Array  = [obj2,obj2,obj2];
obj2Array = obj2Array.map(obj=>{
  return obj.level2.data
});

console.log( obj2Array )
// now it is ["data","data","data"];
</code>```

Body:
let obj2 = {
  level2:{
    data:"data"
  }
}

let obj2Array  = [obj2,obj2,obj2];
obj2Array.map(obj=>{
  obj = obj.levle2.data
});
console.log(obj2Array)

what I'm expecting is ["data","data","data"].But I still got the original data.
I know I can use forEach() to achieve this, but why I can't reassignment element in map()?

Body:
the map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
as this says in the documentation
you can reAssign the obj2Array when doing map

like this

let obj2 = {
  level2:{
    data:"data"
  }
}

let obj2Array  = [obj2,obj2,obj2];
obj2Array = obj2Array.map(obj=>{
  return obj.level2.data
});

console.log( obj2Array )
// now it is ["data","data","data"];


问:
The CrashLoopBackOff pod using local persistentVolume in cloud cluster
I tried to create a postgres pod with local persistentVolume.

```<code>kind: PersistentVolume
apiVersion: v1
metadata:
  name: pv-postgres
spec:
  capacity:
    storage: 1Gi
  volumeMode: Filesystem
  accessModes:
  - ReadWriteOnce
  persistentVolumeReclaimPolicy: Retain
  storageClassName: local-storage
  local:
    path: /postgres
  nodeAffinity:
    required:
      nodeSelectorTerms:
      - matchExpressions:
        - key: node-role.kubernetes.io/work
          operator: In
          values:
          - work1
---
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: pvc-postgres
spec:
  accessModes:
  - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi
  storageClassName: local-storage
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: postgres
spec:
  selector:
    matchLabels:
      app: postgres
  replicas: 1
  strategy: {}
  template:
    metadata:
      labels:
        app: postgres
    spec:
      nodeSelector:
        node-role.kubernetes.io/work: work1
      dnsPolicy: ClusterFirstWithHostNet
      hostNetwork: true
      volumes:
      - name: vol-postgres
        persistentVolumeClaim:
          claimName: pvc-postgres
      containers:
      - name: postgres
        image: postgres:12
        imagePullPolicy: Always
        env:
        - name: DB_USER
          value: postgres
        - name: DB_PASS
          value: postgres
        - name: DB_NAME
          value: postgres
        ports:
        - name: postgres
          containerPort: 5432
        volumeMounts:
        - mountPath: /postgres
          name: vol-postgres
        livenessProbe:
          exec:
            command:
            - pg_isready
            - -h
            - localhost
            - -U
            - postgres
          initialDelaySeconds: 30
          timeoutSeconds: 5
        readinessProbe:
          exec:
            command:
            - pg_isready
            - -h
            - localhost
            - -U
            - postgres
          initialDelaySeconds: 5
          timeoutSeconds: 1
---
apiVersion: v1
kind: Service
metadata:
  name: postgres
spec:
  ports:
  - name: postgres
    port: 5432
    targetPort: postgres
  selector:
    app: postgres
</code>```

But the pod status is always CrashLoopBackOff without any other error message when I using kubectl describe pod.

The deployment and service can be running isolation, the error happened when I add pv and pvc to this yaml file. It seems the persistentVolume not be correctly assigned, how should I fix it?

答:
Because of the local type of persistentVolume, it is recommended to add the StorageClass to yaml file.</p>

```<code>apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: local-storage
provisioner: kubernetes.io/no-provisioner
volumeBindingMode: WaitForFirstConsumer
</code>```

Body:
I tried to create a postgres pod with local persistentVolume.

kind: PersistentVolume
apiVersion: v1
metadata:
  name: pv-postgres
spec:
  capacity:
    storage: 1Gi
  volumeMode: Filesystem
  accessModes:
  - ReadWriteOnce
  persistentVolumeReclaimPolicy: Retain
  storageClassName: local-storage
  local:
    path: /postgres
  nodeAffinity:
    required:
      nodeSelectorTerms:
      - matchExpressions:
        - key: node-role.kubernetes.io/work
          operator: In
          values:
          - work1
---
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: pvc-postgres
spec:
  accessModes:
  - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi
  storageClassName: local-storage
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: postgres
spec:
  selector:
    matchLabels:
      app: postgres
  replicas: 1
  strategy: {}
  template:
    metadata:
      labels:
        app: postgres
    spec:
      nodeSelector:
        node-role.kubernetes.io/work: work1
      dnsPolicy: ClusterFirstWithHostNet
      hostNetwork: true
      volumes:
      - name: vol-postgres
        persistentVolumeClaim:
          claimName: pvc-postgres
      containers:
      - name: postgres
        image: postgres:12
        imagePullPolicy: Always
        env:
        - name: DB_USER
          value: postgres
        - name: DB_PASS
          value: postgres
        - name: DB_NAME
          value: postgres
        ports:
        - name: postgres
          containerPort: 5432
        volumeMounts:
        - mountPath: /postgres
          name: vol-postgres
        livenessProbe:
          exec:
            command:
            - pg_isready
            - -h
            - localhost
            - -U
            - postgres
          initialDelaySeconds: 30
          timeoutSeconds: 5
        readinessProbe:
          exec:
            command:
            - pg_isready
            - -h
            - localhost
            - -U
            - postgres
          initialDelaySeconds: 5
          timeoutSeconds: 1
---
apiVersion: v1
kind: Service
metadata:
  name: postgres
spec:
  ports:
  - name: postgres
    port: 5432
    targetPort: postgres
  selector:
    app: postgres

But the pod status is always CrashLoopBackOff without any other error message when I using kubectl describe pod.

The deployment and service can be running isolation, the error happened when I add pv and pvc to this yaml file. It seems the persistentVolume not be correctly assigned, how should I fix it?

Body:
Because of the local type of persistentVolume, it is recommended to add the StorageClass to yaml file.

apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: local-storage
provisioner: kubernetes.io/no-provisioner
volumeBindingMode: WaitForFirstConsumer


问:
How to pass search parameter, into function that will search a c# collection
Assume I have a collection of the form:

```<code>List<Member> myMembers= new List<Member>()
{
    new Member(){ID=1,FirstName="John",LastName="Doe"},
    new Member(){ID=3,FirstName="Allan",LastName="Jones"},
    new Member(){ID=2,FirstName="Martin",LastName="Moe"},
    new Member(){ID=4,FirstName="Ludwig",LastName="Issac"}
};
</code>```

I can sort this list via FirstName by using:

```<code>myMembers.Sort((x, y) => x.FirstName.CompareTo(y.FirstName));
</code>```

I would like to do this inside of a function, so that I can pass the desired search parameter.  Something like:

```<code>public void sortCollection( parameter SearchTerm, List<Member> myCollection )
{
    myCollection ((x, y) => x.SearchTerm.CompareTo(y.FirstName));
}
</code>```

Obviously here, I cannot pass in the desired search field this way, but is it possible to do what I am asking?

答:
Why not simply use the built in function?

```<code>myMembers.OrderBy(m => m.FirstName)
</code>```

If you really want to, you can write your own wrapper around this function, but the call would look more or less identical and would kind of be reinventing the wheel.

something like this extension method:

```<code>public static IEnumerable<T> OrderByWrapper<T, TKey>(this IEnumerable<T> source, Func<T,TKey> keySelector)
{
    return source.OrderBy(keySelector);
}
</code>```

you would call it with:

```<code>myMembers.OrderByWrapper(m => m.FirstName)
</code>```

Body:
Assume I have a collection of the form:

List<Member> myMembers= new List<Member>()
{
    new Member(){ID=1,FirstName="John",LastName="Doe"},
    new Member(){ID=3,FirstName="Allan",LastName="Jones"},
    new Member(){ID=2,FirstName="Martin",LastName="Moe"},
    new Member(){ID=4,FirstName="Ludwig",LastName="Issac"}
};

I can sort this list via FirstName by using:

myMembers.Sort((x, y) => x.FirstName.CompareTo(y.FirstName));

I would like to do this inside of a function, so that I can pass the desired search parameter.  Something like:

public void sortCollection( parameter SearchTerm, List<Member> myCollection )
{
    myCollection ((x, y) => x.SearchTerm.CompareTo(y.FirstName));
}

Obviously here, I cannot pass in the desired search field this way, but is it possible to do what I am asking?

Body:
Why not simply use the built in function?

myMembers.OrderBy(m => m.FirstName)

If you really want to, you can write your own wrapper around this function, but the call would look more or less identical and would kind of be reinventing the wheel.

something like this extension method:

public static IEnumerable<T> OrderByWrapper<T, TKey>(this IEnumerable<T> source, Func<T,TKey> keySelector)
{
    return source.OrderBy(keySelector);
}

you would call it with:

myMembers.OrderByWrapper(m => m.FirstName)


问:
nginx: set cookie in request based on header value
I've just started using nginx, and I'm using it to proxy to an application server.  I want to set a cookie in the proxied request to the application server if a particular custom header is present in the http request.  The logic is:

```<code>if X-SESSID in request
AND SESSID is not already a cookie in the request
    set cookie "SESSID=$http_X-SESSID"
</code>```

In apache 2 I was able to accomplish this by doing this:

```<code>RewriteCond %{HTTP:X-SESSID} ^(.*)$
RewriteCond %{HTTP_COOKIE} !SESSID [NC]
RewriteRule (.*) - [E=SESSID:%1]
RequestHeader set Cookie "SESSID=%{SESSID}e" env=SESSID
</code>```

What would be the equivalent method in nginx?

答:
You can do it this way:

```<code># $sessid variable will get a "sessid=$http_x_sessid" value
# if the X-Sessid HTTP header is set or an empty value otherwise
map $http_x_sessid $sessid {
    ""       "";
    default  "sessid=$http_x_sessid";
}

# $sessid_cookie variable will get a value of $sessid variable
# if no sessid cookie passed with the request or an empty value otherwise
map $cookie_sessid $sessid_cookie {
    ""       $sessid;
    default  "";
}

server {
    ...
    # in the same location block where you have a proxy_pass directive
    proxy_set_header Cookie "$http_cookie$sessid_cookie";
    ...
}
</code>```

See description of map blocks here, $http_... variables here and $cookie_... variables here.

Update @ 2020.11.12

Reviewing an answer I think there is a flaw. If a browser sends some cookies with the incoming request, an additional cookie should be added with ;  prefix to be separated from the other cookies. Here is an updated version:

```<code># prepend cookie with the "; " if the other cookies exists
map $http_cookie $prefix_cookie {
    ""       "";
    default  "; ";
}

# $sessid variable will get a "sessid=$http_x_sessid" value (optionally prepended
# with "; ") if the X-Sessid HTTP header is set or an empty value otherwise
map $http_x_sessid $sessid {
    ""       "";
    default  "${prefix_cookie}sessid=${http_x_sessid}";
}

# $sessid_cookie variable will get a value of $sessid variable
# if no sessid cookie passed with the request or an empty value otherwise
map $cookie_sessid $sessid_cookie {
    ""       $sessid;
    default  "";
}

server {
    ...
    # in the same location block where you have a proxy_pass directive
    proxy_set_header Cookie "$http_cookie$sessid_cookie";
    ...
}
</code>```

Body:
I've just started using nginx, and I'm using it to proxy to an application server.  I want to set a cookie in the proxied request to the application server if a particular custom header is present in the http request.  The logic is:

if X-SESSID in request
AND SESSID is not already a cookie in the request
    set cookie "SESSID=$http_X-SESSID"

In apache 2 I was able to accomplish this by doing this:

RewriteCond %{HTTP:X-SESSID} ^(.*)$
RewriteCond %{HTTP_COOKIE} !SESSID [NC]
RewriteRule (.*) - [E=SESSID:%1]
RequestHeader set Cookie "SESSID=%{SESSID}e" env=SESSID

What would be the equivalent method in nginx?

Body:
You can do it this way:

# $sessid variable will get a "sessid=$http_x_sessid" value
# if the X-Sessid HTTP header is set or an empty value otherwise
map $http_x_sessid $sessid {
    ""       "";
    default  "sessid=$http_x_sessid";
}

# $sessid_cookie variable will get a value of $sessid variable
# if no sessid cookie passed with the request or an empty value otherwise
map $cookie_sessid $sessid_cookie {
    ""       $sessid;
    default  "";
}

server {
    ...
    # in the same location block where you have a proxy_pass directive
    proxy_set_header Cookie "$http_cookie$sessid_cookie";
    ...
}

See description of map blocks here, $http_... variables here and $cookie_... variables here.

Update @ 2020.11.12

Reviewing an answer I think there is a flaw. If a browser sends some cookies with the incoming request, an additional cookie should be added with ;  prefix to be separated from the other cookies. Here is an updated version:

# prepend cookie with the "; " if the other cookies exists
map $http_cookie $prefix_cookie {
    ""       "";
    default  "; ";
}

# $sessid variable will get a "sessid=$http_x_sessid" value (optionally prepended
# with "; ") if the X-Sessid HTTP header is set or an empty value otherwise
map $http_x_sessid $sessid {
    ""       "";
    default  "${prefix_cookie}sessid=${http_x_sessid}";
}

# $sessid_cookie variable will get a value of $sessid variable
# if no sessid cookie passed with the request or an empty value otherwise
map $cookie_sessid $sessid_cookie {
    ""       $sessid;
    default  "";
}

server {
    ...
    # in the same location block where you have a proxy_pass directive
    proxy_set_header Cookie "$http_cookie$sessid_cookie";
    ...
}


问:
how to text align center for the text with space and line break
I have the following example below:

.wrapper {
  text-align: center;
  border: 1px solid red;
  background-color: white;
  color: black;
  width: 240px;
  height: 200px;
  font-size: 36px;
  line-height: 43px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea class="wrapper" autosize>THE GREAT BANGKOK SALE</textarea></code>```

https://jsfiddle.net/ngoctuan001/cgLvh62o/2/

As you can see, I want to text-align the text in the textarea tag. Because the text area got a fixed width, it will try to break to next line when there is a space. However, when that happen, that row is slightly not center in human eyes due to the space.

As you can see in the screen shot above, the red line in the right hand side is always slightly longer than the red line in the left hand side, this is because the computer treats the space (highlighted) as 1 more character. But in human eyes, this is not considered as center aligned

Is there anyway to fix this ?
Thanks

答:
One solution would be to use the contentEditable="true" on a div.

https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Editable_content

```<code><div class="wrapper" contentEditable="true">
  THE GREAT BANGKOK SALE
</div>
</code>```

This will make the content correctly center and also you can edit it.

To get the content you:

```<code>const content = document.querySelector('.wrapper').innerText;
</code>```

Body:
I have the following example below:

.wrapper {
  text-align: center;
  border: 1px solid red;
  background-color: white;
  color: black;
  width: 240px;
  height: 200px;
  font-size: 36px;
  line-height: 43px;
}

<textarea class="wrapper" autosize>THE GREAT BANGKOK SALE</textarea>

https://jsfiddle.net/ngoctuan001/cgLvh62o/2/

As you can see, I want to text-align the text in the textarea tag. Because the text area got a fixed width, it will try to break to next line when there is a space. However, when that happen, that row is slightly not center in human eyes due to the space.

As you can see in the screen shot above, the red line in the right hand side is always slightly longer than the red line in the left hand side, this is because the computer treats the space (highlighted) as 1 more character. But in human eyes, this is not considered as center aligned

Is there anyway to fix this ?
Thanks

Body:
One solution would be to use the contentEditable="true" on a div.

https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Editable_content

<div class="wrapper" contentEditable="true">
  THE GREAT BANGKOK SALE
</div>

This will make the content correctly center and also you can edit it.

To get the content you:

const content = document.querySelector('.wrapper').innerText;


问:
Why is my edmx file not updating
I have a database first ASP.NET MVC 5 EF6 project. I'm using VS2015 CE. When I change my database (SQL Server 2012), I then go to VS to update my edmx file like this:

Double click on the edmx file in the solution explorer

In the edmx file right click on a blank space and select the option 'Update Model From Database'

I click on the button 'Finish'

I Rebuild the solution

When I have a table with the columns ID, Column1, Column2 and I changed Column2 into Column2Changed, my edmx has a model with ID, Column1, Column2, Column2Changed instead of ID, Column1, Column2Changed.

Also, when I change the datatype for a column, this change is not applied in my edmx.

答:
After updating or refreshing and not getting expected results.
I worked as follows:
1. I added procedure without importing it.
2. I opened edmx with text editor and added my return types having complex type like other already present in it.
3. added all values like other procedures had.

That solved my problem!

ContentLicense: CC BY-SA 3.0

Title: Why is my edmx file not updating


问:
Delete file with all history from svn repository
Is there any way to delete file from svn repository including all its history? This issue emerges when I want to get rid of large binary file residing in repo.

I know only one approach that might help in this situation:

Dump all repo with the help of svnadmin utility.

Filter dumped file with grep. Grep should use filename and write in to the other dump-file

Import last dump-file with svnadmin

But this is too complicated and unreliable. Maybe there is another solution?

答:
This has recently become much more straightforward with the command svndumpfilter. Details are available in the subversion documentation here. Basically, to avoid conflicts (explained here), it takes a repo dump and redoes each commit, either including or excluding a given file prefix. Basic syntax:

```<code>svndumpfilter exclude yourfileprefix < yourdump > yournewdump
</code>```

Exclude is probably what the question asker is looking for, but you can also use include to, say, extract a subtree of the repo so as to spin it off as its own repository.

The latest revision of subversion in subversion (very meta) can also take glob patterns. I recently had to remove all pdfs from a repo and it was very easily done like so:

```<code>svndumpfilter exclude --pattern '*.pdf' < dump > dump_nopdfs
</code>```

Further usage information can be found by calling svndumpfilter help and svndumpfilter help exclude.

Body:
This has recently become much more straightforward with the command svndumpfilter. Details are available in the subversion documentation here. Basically, to avoid conflicts (explained here), it takes a repo dump and redoes each commit, either including or excluding a given file prefix. Basic syntax:

svndumpfilter exclude yourfileprefix < yourdump > yournewdump

Exclude is probably what the question asker is looking for, but you can also use include to, say, extract a subtree of the repo so as to spin it off as its own repository.

The latest revision of subversion in subversion (very meta) can also take glob patterns. I recently had to remove all pdfs from a repo and it was very easily done like so:

svndumpfilter exclude --pattern '*.pdf' < dump > dump_nopdfs

Further usage information can be found by calling svndumpfilter help and svndumpfilter help exclude.


问:
Using VBA to insert x number of cells
I am working on a spreadsheet that that generates rows on other sheets based upon a cell in the first sheet. After getting it kind of working and finishing all the dynamic formulas I found that the last cell requires a different set of formulas, and now my original VBA script doesn't work. My original script just added the new rows at the end, now it needs to insert the new cells at row 7 shifting that row down and copying row 6 into all the newly generated cells.

Here's my original script..

```<code>Private Sub CommandButton1_Click()
' This routing will copy rows based on the quantity to a new sheet.
Dim rngSinglecell12 As Range
Dim rngQuantityCells12 As Range

Dim rngSinglecell467 As Range
Dim rngQuantityCells467 As Range

Dim rngSinglecell358 As Range
Dim rngQuantityCells358 As Range

' Set this for the range where the Quantity column exists. This works only if there are no empty cells
Set rngQuantityCells12 = Range("G9", Range("G9").End(xlDown))

Set rngQuantityCells467 = Range("D9", Range("D9").End(xlDown))

Set rngQuantityCells358 = Range("F9", Range("F9").End(xlDown))

For Each rngSinglecell12 In rngQuantityCells12

     'Check if this cell actually contains a number and if the number is greater than 0
    If IsNumeric(rngSinglecell12.Value) And rngSinglecell12.Value > 0 Then

        Sheets("Line 1").Rows("6").Copy (Sheets("Line 1").Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(rngSinglecell12.Value + 1))
        Sheets("Line 2").Rows("6").Copy (Sheets("Line 2").Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(rngSinglecell12.Value + 1))

    End If
Next

For Each rngSinglecell467 In rngQuantityCells467

    ' Check if this cell actually contains a number and if the number is greater than 0
    If IsNumeric(rngSinglecell467.Value) And rngSinglecell467.Value > 0 Then

        Sheets("Line 4").Rows("6").Copy (Sheets("Line 4").Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(rngSinglecell467.Value + 1))
        Sheets("Line 6").Rows("6").Copy (Sheets("Line 6").Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(rngSinglecell467.Value + 1))
        Sheets("Line 7").Rows("6").Copy (Sheets("Line 7").Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(rngSinglecell467.Value + 1))

    End If
Next

For Each rngSinglecell358 In rngQuantityCells358

    ' Check if this cell actually contains a number and if the number is greater than 0
    If IsNumeric(rngSinglecell358.Value) And rngSinglecell358.Value > 0 Then

        Sheets("Line 3").Rows("6").Copy (Sheets("Line 3").Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(rngSinglecell358.Value + 1))
        Sheets("Line 5").Rows("6").Copy (Sheets("Line 5").Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(rngSinglecell358.Value + 1))
        Sheets("Line 8").Rows("6").Copy (Sheets("Line 8").Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(rngSinglecell358.Value + 1))

    End If
Next

End Sub
</code>```

I am assuming it will be something like this

```<code>    Rows("6:6").Select
    Selection.Copy
    Rows("7:7").Select
    Selection.Insert Shift:=xlDown
</code>```

but i"m not sure how to really icorporate that into the script I have or if there is a better way.

答:
I figured it out myself...</p>

```<code>Application.EnableEvents = False
Application.ScreenUpdating = False
Application.Calculation = xlManual

' This routing will copy rows based on the quantity to a new sheet.
Dim rngSinglecell12 As Range
Dim rngQuantityCells12 As Range

Dim rngSinglecell467 As Range
Dim rngQuantityCells467 As Range

Dim rngSinglecell358 As Range
Dim rngQuantityCells358 As Range

' Set this for the range where the Quantity column exists. This works only if there are no empty cells
Set rngQuantityCells12 = Range("G9", Range("G9").End(xlDown))

Set rngQuantityCells467 = Range("D9", Range("D9").End(xlDown))

Set rngQuantityCells358 = Range("F9", Range("F9").End(xlDown))

For Each rngSinglecell12 In rngQuantityCells12

     'Check if this cell actually contains a number and if the number is greater than 0
    If IsNumeric(rngSinglecell12.Value) And rngSinglecell12.Value > 0 Then

        Sheets("Line 1").Rows("6").Copy
        Sheets("Line 1").Rows("7").Resize(rngSinglecell12.Value).Insert Shift:=xlDown
        Sheets("Line 2").Rows("6").Copy
        Sheets("Line 2").Rows("7").Resize(rngSinglecell12.Value).Insert Shift:=xlDown
        Application.CutCopyMode = False

    End If
Next

For Each rngSinglecell467 In rngQuantityCells467

    ' Check if this cell actually contains a number and if the number is greater than 0
    If IsNumeric(rngSinglecell467.Value) And rngSinglecell467.Value > 0 Then

        Sheets("Line 4").Rows("6").Copy
        Sheets("Line 4").Rows("7").Resize(rngSinglecell467.Value - 2).Insert Shift:=xlDown
        Sheets("Line 6").Rows("6").Copy
        Sheets("Line 6").Rows("7").Resize(rngSinglecell467.Value - 2).Insert Shift:=xlDown
        Sheets("Line 7").Rows("6").Copy
        Sheets("Line 7").Rows("7").Resize(rngSinglecell467.Value - 2).Insert Shift:=xlDown
        Application.CutCopyMode = False

    End If
Next

For Each rngSinglecell358 In rngQuantityCells358

    ' Check if this cell actually contains a number and if the number is greater than 0
    If IsNumeric(rngSinglecell358.Value) And rngSinglecell358.Value > 0 Then

        Sheets("Line 3").Rows("6").Copy
        Sheets("Line 3").Rows("7").Resize(rngSinglecell358.Value - 2).Insert Shift:=xlDown
        Sheets("Line 5").Rows("6").Copy
        Sheets("Line 5").Rows("7").Resize(rngSinglecell358.Value - 2).Insert Shift:=xlDown
        Sheets("Line 8").Rows("6").Copy
        Sheets("Line 8").Rows("7").Resize(rngSinglecell358.Value - 2).Insert Shift:=xlDown
        Application.CutCopyMode = False

    End If
Next

Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlAutomatic
Calculate
End Sub
</code>```

Title: Using VBA to insert x number of cells

Body:
I am working on a spreadsheet that that generates rows on other sheets based upon a cell in the first sheet. After getting it kind of working and finishing all the dynamic formulas I found that the last cell requires a different set of formulas, and now my original VBA script doesn't work. My original script just added the new rows at the end, now it needs to insert the new cells at row 7 shifting that row down and copying row 6 into all the newly generated cells.

Here's my original script..

Private Sub CommandButton1_Click()
' This routing will copy rows based on the quantity to a new sheet.
Dim rngSinglecell12 As Range
Dim rngQuantityCells12 As Range

Dim rngSinglecell467 As Range
Dim rngQuantityCells467 As Range

Dim rngSinglecell358 As Range
Dim rngQuantityCells358 As Range

' Set this for the range where the Quantity column exists. This works only if there are no empty cells
Set rngQuantityCells12 = Range("G9", Range("G9").End(xlDown))

Set rngQuantityCells467 = Range("D9", Range("D9").End(xlDown))

Set rngQuantityCells358 = Range("F9", Range("F9").End(xlDown))

For Each rngSinglecell12 In rngQuantityCells12

     'Check if this cell actually contains a number and if the number is greater than 0
    If IsNumeric(rngSinglecell12.Value) And rngSinglecell12.Value > 0 Then

        Sheets("Line 1").Rows("6").Copy (Sheets("Line 1").Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(rngSinglecell12.Value + 1))
        Sheets("Line 2").Rows("6").Copy (Sheets("Line 2").Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(rngSinglecell12.Value + 1))

    End If
Next

For Each rngSinglecell467 In rngQuantityCells467

    ' Check if this cell actually contains a number and if the number is greater than 0
    If IsNumeric(rngSinglecell467.Value) And rngSinglecell467.Value > 0 Then

        Sheets("Line 4").Rows("6").Copy (Sheets("Line 4").Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(rngSinglecell467.Value + 1))
        Sheets("Line 6").Rows("6").Copy (Sheets("Line 6").Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(rngSinglecell467.Value + 1))
        Sheets("Line 7").Rows("6").Copy (Sheets("Line 7").Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(rngSinglecell467.Value + 1))

    End If
Next

For Each rngSinglecell358 In rngQuantityCells358

    ' Check if this cell actually contains a number and if the number is greater than 0
    If IsNumeric(rngSinglecell358.Value) And rngSinglecell358.Value > 0 Then

        Sheets("Line 3").Rows("6").Copy (Sheets("Line 3").Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(rngSinglecell358.Value + 1))
        Sheets("Line 5").Rows("6").Copy (Sheets("Line 5").Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(rngSinglecell358.Value + 1))
        Sheets("Line 8").Rows("6").Copy (Sheets("Line 8").Range("A" & Rows.Count).End(xlUp).Offset(1).Resize(rngSinglecell358.Value + 1))

    End If
Next

End Sub

I am assuming it will be something like this

    Rows("6:6").Select
    Selection.Copy
    Rows("7:7").Select
    Selection.Insert Shift:=xlDown

but i"m not sure how to really icorporate that into the script I have or if there is a better way.

Body:
I figured it out myself...

Application.EnableEvents = False
Application.ScreenUpdating = False
Application.Calculation = xlManual

' This routing will copy rows based on the quantity to a new sheet.
Dim rngSinglecell12 As Range
Dim rngQuantityCells12 As Range

Dim rngSinglecell467 As Range
Dim rngQuantityCells467 As Range

Dim rngSinglecell358 As Range
Dim rngQuantityCells358 As Range

' Set this for the range where the Quantity column exists. This works only if there are no empty cells
Set rngQuantityCells12 = Range("G9", Range("G9").End(xlDown))

Set rngQuantityCells467 = Range("D9", Range("D9").End(xlDown))

Set rngQuantityCells358 = Range("F9", Range("F9").End(xlDown))

For Each rngSinglecell12 In rngQuantityCells12

     'Check if this cell actually contains a number and if the number is greater than 0
    If IsNumeric(rngSinglecell12.Value) And rngSinglecell12.Value > 0 Then

        Sheets("Line 1").Rows("6").Copy
        Sheets("Line 1").Rows("7").Resize(rngSinglecell12.Value).Insert Shift:=xlDown
        Sheets("Line 2").Rows("6").Copy
        Sheets("Line 2").Rows("7").Resize(rngSinglecell12.Value).Insert Shift:=xlDown
        Application.CutCopyMode = False

    End If
Next

For Each rngSinglecell467 In rngQuantityCells467

    ' Check if this cell actually contains a number and if the number is greater than 0
    If IsNumeric(rngSinglecell467.Value) And rngSinglecell467.Value > 0 Then

        Sheets("Line 4").Rows("6").Copy
        Sheets("Line 4").Rows("7").Resize(rngSinglecell467.Value - 2).Insert Shift:=xlDown
        Sheets("Line 6").Rows("6").Copy
        Sheets("Line 6").Rows("7").Resize(rngSinglecell467.Value - 2).Insert Shift:=xlDown
        Sheets("Line 7").Rows("6").Copy
        Sheets("Line 7").Rows("7").Resize(rngSinglecell467.Value - 2).Insert Shift:=xlDown
        Application.CutCopyMode = False

    End If
Next

For Each rngSinglecell358 In rngQuantityCells358

    ' Check if this cell actually contains a number and if the number is greater than 0
    If IsNumeric(rngSinglecell358.Value) And rngSinglecell358.Value > 0 Then

        Sheets("Line 3").Rows("6").Copy
        Sheets("Line 3").Rows("7").Resize(rngSinglecell358.Value - 2).Insert Shift:=xlDown
        Sheets("Line 5").Rows("6").Copy
        Sheets("Line 5").Rows("7").Resize(rngSinglecell358.Value - 2).Insert Shift:=xlDown
        Sheets("Line 8").Rows("6").Copy
        Sheets("Line 8").Rows("7").Resize(rngSinglecell358.Value - 2).Insert Shift:=xlDown
        Application.CutCopyMode = False

    End If
Next

Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlAutomatic
Calculate
End Sub


问:
How to Create a Table from JSON objects?
I am trying to make a table from json objects, actually i have  JSON objects in large quantity. But first i am trying to create tabe for few JSON objects, if this will go right , i willl implement this method later on.

This is what i tried so Far.

```<code>   var  attributes =

     [

      {

        "name": "Asset #",

        "display_name": "Asset #",

        "key": "header2",

        "values": {

          "MSSBL": "4-194169767930##1-2H77NZSQ",

          "SNOW": "4-194169767930##1-2H77NZSQ"},

        "type": "header",

        "data_type": "Text",

        "editable": "N"

      },

      {

        "name": "Serial Number",

        "display_name": "Serial Number",

        "key": "header3",

        "values": {

          "MSSBL": "21256112##1-2H77NZSQ",

          "SNOW": "NA##1-2H77NZSQ"},

        "type": "header",

        "data_type": "Text",

        "editable": "N"

      },

      {

        "name": "ACCOUNT NUMBER",

        "display_name": "ACCOUNT NUMBER",

        "key": "header6",

        "values": { "MSSBL": "532649##1-2H77NZSQ",
          "SNOW": "NA##1-2H77NZSQ"},

        "type": "header",

        "data_type": "Text",

        "editable": "N"

      }
    ]
           var key = [];

           document.write("<table border==\"1\"><tr>");
           for (key in attributes[0]) {
           document.write('<td>' + '<b>' + key + '</b>' + '</td>');
            }

            document.write("</tr>");
            for (var i = 0; i < attributes.length; i++) {
            document.write('<tr>');
            for (key in attributes[i]) {
             document.write('<td>' + attributes[i][key] + '</td>');
             }
            document.write('</tr>');
              }
            document.write("</table>");
</code>```

Actually i am facing a issue when, i am trying  to add Values inside the table if I remove values then the table is visible in output otherwise no output
'

```<code>           "values": {
        "MSSBL": "4-194169767930##1-2H77NZSQ",
          "SNOW": "4-194169767930##1-2H77NZSQ"},
</code>```

答:
attributes[i]["values"] is object

You should iterate again through attributes[i]["values"]. Add one condition:

```<code>if(typeof attributes[i][col[j]]==='object') //then iterate again
</code>```

Body:
I am trying to make a table from json objects, actually i have  JSON objects in large quantity. But first i am trying to create tabe for few JSON objects, if this will go right , i willl implement this method later on.

This is what i tried so Far.

   var  attributes =

     [

      {

        "name": "Asset #",

        "display_name": "Asset #",

        "key": "header2",

        "values": {

          "MSSBL": "4-194169767930##1-2H77NZSQ",

          "SNOW": "4-194169767930##1-2H77NZSQ"},

        "type": "header",

        "data_type": "Text",

        "editable": "N"

      },

      {

        "name": "Serial Number",

        "display_name": "Serial Number",

        "key": "header3",

        "values": {

          "MSSBL": "21256112##1-2H77NZSQ",

          "SNOW": "NA##1-2H77NZSQ"},

        "type": "header",

        "data_type": "Text",

        "editable": "N"

      },

      {

        "name": "ACCOUNT NUMBER",

        "display_name": "ACCOUNT NUMBER",

        "key": "header6",

        "values": { "MSSBL": "532649##1-2H77NZSQ",
          "SNOW": "NA##1-2H77NZSQ"},

        "type": "header",

        "data_type": "Text",

        "editable": "N"

      }
    ]
           var key = [];

           document.write("

");
           for (key in attributes[0]) {
           document.write('' + '' + key + '' + '	');
            }

            document.write("
");
            for (var i = 0; i < attributes.length; i++) {
            document.write('
');
            for (key in attributes[i]) {
             document.write('' + attributes[i][key] + '	');
             }
            document.write('
');
              }
            document.write("
");

Actually i am facing a issue when, i am trying  to add Values inside the table if I remove values then the table is visible in output otherwise no output
'

           "values": {
        "MSSBL": "4-194169767930##1-2H77NZSQ",
          "SNOW": "4-194169767930##1-2H77NZSQ"},

Body:
attributes[i]["values"] is object

You should iterate again through attributes[i]["values"]. Add one condition:

if(typeof attributes[i][col[j]]==='object') //then iterate again


问:
How to use FilerImageField in html template?
I want to know how to use FilerImageField in html tag. i tried

<image src={{ instance.team_background_image_1.file.url }}>

it display full image. but i want to use FilerImageField in many resolutions such as 300x300, 250x300

答:
you have to use easy_thumbnails for that and can use as follows

```<code>{% load thumbnail %}
{% thumbnail model_name.image_field 250x250 crop %}
</code>```

read more here

Body:
you have to use easy_thumbnails for that and can use as follows

{% load thumbnail %}
{% thumbnail model_name.image_field 250x250 crop %}

read more here


问:
Why is this SQL/DDL violating the wrong Integrity constraint?
So it is showing me that the first insert is failing IC4, but it should be good to go as far as IC2 is concerned. IC2 states that 'DB guru' should be above 200--which the first entry is!

For example you'll see that the first entry on the insert list below is:

```<code>INSERT INTO Employee VALUES (10, 'Gray', 'DB guru', 240);
</code>```

But this fails IC4... why?!

How do I specify that a CONSTRAINT has to apply to only a certain categorical value like I am attempting here? Am I missing an important notion with respect to the way that CHECK is implemented? I'm really new to SQL and trying to wrap my head around this:

```<code>SPOOL ddl.out
SET ECHO ON

--
-- IMPORTANT: use the names IC1, IC2, etc. as given below.
-- --------------------------------------------------------------------
/*The following DROP command is inserted for convenience so that if you need to recompile
your code, it will drop the table (if it already exists).
*/
DROP TABLE Employee CASCADE CONSTRAINTS;
DROP TABLE Dependent CASCADE CONSTRAINTS;
--
CREATE TABLE Employee
(
id INTEGER PRIMARY KEY,
name CHAR(10) NOT NULL,
rank CHAR(10) NOT NULL,
salary INTEGER NOT NULL,
/*
IC1: The rank is one of: 'DB guru', 'DB expert', or 'DB rookie'
*/
CONSTRAINT IC1 CHECK (rank IN ('DB guru', 'DB expert', 'DB rookie')),
/*
IC2: The salary of a 'DB guru' is above 200.
*/
CONSTRAINT IC2 CHECK (rank != 'DB guru' OR salary > 200),
/*
IC3: The salary of a 'DB expert' is between 80 and 220 (inclusive).
*/
CONSTRAINT IC3 CHECK (rank != 'DB expert' OR (salary >= 80 AND salary <= 220 )),
/*
IC4: The salary of a 'DB rookie' is less than 100.
*/
CONSTRAINT IC4 CHECK (rank != 'DB rookie' OR salary < 100)
);
--
--
CREATE TABLE Dependent
(
empID INTEGER,
dependentName CHAR(20) NOT NULL,
relationship CHAR(20) NOT NULL,
PRIMARY KEY (empID, dependentName),
/*
IC5: empID must refer to an employee in the company. Also:
if an employee is deleted then his/her dependents must be deleted.
IMPORTANT: DO NOT declare this IC as DEFERRABLE.
*/
CONSTRAINT IC5 FOREIGN KEY (empID) REFERENCES Employee(id)
          ON DELETE CASCADE
);
--
-- ----------------------------------------------------------------
-- TESTING THE SCHEMA
-- ----------------------------------------------------------------
INSERT INTO Employee VALUES (10, 'Gray', 'DB guru', 240);
INSERT INTO Employee VALUES (20, 'Garland', 'DB guru', 190);
INSERT INTO Employee VALUES (30, 'Edison', 'DB expert', 210);
INSERT INTO Employee VALUES (40, 'Eckerd', 'DB expert', 70);
INSERT INTO Employee VALUES (50, 'Roberts', 'DB rookie', 110);
INSERT INTO Employee VALUES (60, 'Rush', 'DB rookie', 90);
SELECT * from Employee;
-- ----------------------------------------------------------------
INSERT INTO Dependent VALUES (10, 'Grace', 'daughter');
INSERT INTO Dependent VALUES (10, 'George', 'son');
INSERT INTO Dependent VALUES (60, 'Reba', 'daughter');
INSERT INTO Dependent VALUES (15, 'Dustin', 'son');
SELECT * FROM Dependent;
--
DELETE FROM Employee WHERE id = 10;
SELECT * From Employee;
SELECT * FROM Dependent;
--
SET ECHO OFF
SPOOL OFF

</code>```

edited: To show the working solution based on the correct answer selected below.

答:
I doubt you can make the constraints mutually exclusive like that. This might help you:

```<code>CHECK ((rank = 'DB guru' AND salary > 200) or
       (rank = 'DB expert' AND salary >= 80 AND salary <=220 ) or
        ....
</code>```

Edit:
Also, your IC4 CHECK CONSTRAINT logic is wrong, it should be:

```<code>/*
IC4: The salary of a 'DB rookie' is less than 100.
*/
CONSTRAINT IC4 CHECK (rank = 'DB rookie' AND salary < 100)
);
</code>```

instead of:

```<code>/*
IC4: The salary of a 'DB rookie' is less than 100.
*/
CONSTRAINT IC4 CHECK (rank = 'DB rookie' AND salary >= 100)
);
</code>```

which makes the consolidated condition as:

```<code>CHECK ((rank = 'DB guru' AND salary > 200) or
       (rank = 'DB expert' AND salary >= 80 AND salary <=220 ) or
       (rank = 'DB rookie' AND salary < 100))
</code>```

Body:
So it is showing me that the first insert is failing IC4, but it should be good to go as far as IC2 is concerned. IC2 states that 'DB guru' should be above 200--which the first entry is!

For example you'll see that the first entry on the insert list below is:

INSERT INTO Employee VALUES (10, 'Gray', 'DB guru', 240);

But this fails IC4... why?!

How do I specify that a CONSTRAINT has to apply to only a certain categorical value like I am attempting here? Am I missing an important notion with respect to the way that CHECK is implemented? I'm really new to SQL and trying to wrap my head around this:

SPOOL ddl.out
SET ECHO ON

--
-- IMPORTANT: use the names IC1, IC2, etc. as given below.
-- --------------------------------------------------------------------
/*The following DROP command is inserted for convenience so that if you need to recompile
your code, it will drop the table (if it already exists).
*/
DROP TABLE Employee CASCADE CONSTRAINTS;
DROP TABLE Dependent CASCADE CONSTRAINTS;
--
CREATE TABLE Employee
(
id INTEGER PRIMARY KEY,
name CHAR(10) NOT NULL,
rank CHAR(10) NOT NULL,
salary INTEGER NOT NULL,
/*
IC1: The rank is one of: 'DB guru', 'DB expert', or 'DB rookie'
*/
CONSTRAINT IC1 CHECK (rank IN ('DB guru', 'DB expert', 'DB rookie')),
/*
IC2: The salary of a 'DB guru' is above 200.
*/
CONSTRAINT IC2 CHECK (rank != 'DB guru' OR salary > 200),
/*
IC3: The salary of a 'DB expert' is between 80 and 220 (inclusive).
*/
CONSTRAINT IC3 CHECK (rank != 'DB expert' OR (salary >= 80 AND salary <= 220 )),
/*
IC4: The salary of a 'DB rookie' is less than 100.
*/
CONSTRAINT IC4 CHECK (rank != 'DB rookie' OR salary < 100)
);
--
--
CREATE TABLE Dependent
(
empID INTEGER,
dependentName CHAR(20) NOT NULL,
relationship CHAR(20) NOT NULL,
PRIMARY KEY (empID, dependentName),
/*
IC5: empID must refer to an employee in the company. Also:
if an employee is deleted then his/her dependents must be deleted.
IMPORTANT: DO NOT declare this IC as DEFERRABLE.
*/
CONSTRAINT IC5 FOREIGN KEY (empID) REFERENCES Employee(id)
          ON DELETE CASCADE
);
--
-- ----------------------------------------------------------------
-- TESTING THE SCHEMA
-- ----------------------------------------------------------------
INSERT INTO Employee VALUES (10, 'Gray', 'DB guru', 240);
INSERT INTO Employee VALUES (20, 'Garland', 'DB guru', 190);
INSERT INTO Employee VALUES (30, 'Edison', 'DB expert', 210);
INSERT INTO Employee VALUES (40, 'Eckerd', 'DB expert', 70);
INSERT INTO Employee VALUES (50, 'Roberts', 'DB rookie', 110);
INSERT INTO Employee VALUES (60, 'Rush', 'DB rookie', 90);
SELECT * from Employee;
-- ----------------------------------------------------------------
INSERT INTO Dependent VALUES (10, 'Grace', 'daughter');
INSERT INTO Dependent VALUES (10, 'George', 'son');
INSERT INTO Dependent VALUES (60, 'Reba', 'daughter');
INSERT INTO Dependent VALUES (15, 'Dustin', 'son');
SELECT * FROM Dependent;
--
DELETE FROM Employee WHERE id = 10;
SELECT * From Employee;
SELECT * FROM Dependent;
--
SET ECHO OFF
SPOOL OFF

edited: To show the working solution based on the correct answer selected below.

Body:
I doubt you can make the constraints mutually exclusive like that. This might help you:

CHECK ((rank = 'DB guru' AND salary > 200) or
       (rank = 'DB expert' AND salary >= 80 AND salary <=220 ) or
        ....

Edit:
Also, your IC4 CHECK CONSTRAINT logic is wrong, it should be:

/*
IC4: The salary of a 'DB rookie' is less than 100.
*/
CONSTRAINT IC4 CHECK (rank = 'DB rookie' AND salary < 100)
);

instead of:

/*
IC4: The salary of a 'DB rookie' is less than 100.
*/
CONSTRAINT IC4 CHECK (rank = 'DB rookie' AND salary >= 100)
);

which makes the consolidated condition as:

CHECK ((rank = 'DB guru' AND salary > 200) or
       (rank = 'DB expert' AND salary >= 80 AND salary <=220 ) or
       (rank = 'DB rookie' AND salary < 100))


问:
ReactJS: e.preventDefault() is not a function
I'm making a simple todo app, where i have put in the logic to edit and delete the todos as well. I'm trying to update the parent state from child component but when i'm trying to click on delete it is throwing me an error e.preventDefault() is not a function and it is removing all of the todos here are the components:

PARENT

```<code>export default class App extends React.Component {
  constructor(props){
    super(props);
    this.state = {
       listArr: [],
    }

  }

 deleteTodos(i) {
   var lists = this.state.listArr;
   lists.splice(i, 1);
   this.setState({listArr: lists})
 }

render() {
 .......
 <ToDoList {...this.state} passDeleteTodos={this.deleteTodos} />
......

}
</code>```

CHILD

```<code>export class ToDoList extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
              editing: false,
            };

        handleDelete(e, i) {
            e.preventDefault();
            this.props.passDeleteTodos()
        }

    renderDisplay() {
        return(
          <div>
           {
            this.props.listArr.map((list,i) => {
               return(
                 <div key={i} index={i} ref="text">
                  <li>{list}
                    <div style={{float: 'right'}}>
                     <button className="btn btn-danger btn-xs glyphicon glyphicon-trash"
                             onClick={() => this.handleDelete(i)}
                     />
                    </div>
                </div>
          </div>
</code>```

答:
arrow function in react doesn't need to bind to this.
But during call to the functions, for example to call this function handleDelete

```<code> handleDelete(e, i) {
        e.preventDefault();
        this.props.passDeleteTodos()
    }
</code>```

we will use synatx as:

```<code>handleDelete.bind(i)
</code>```

Body:
I'm making a simple todo app, where i have put in the logic to edit and delete the todos as well. I'm trying to update the parent state from child component but when i'm trying to click on delete it is throwing me an error e.preventDefault() is not a function and it is removing all of the todos here are the components:

PARENT

export default class App extends React.Component {
  constructor(props){
    super(props);
    this.state = {
       listArr: [],
    }

  }

 deleteTodos(i) {
   var lists = this.state.listArr;
   lists.splice(i, 1);
   this.setState({listArr: lists})
 }

render() {
 .......
 <ToDoList {...this.state} passDeleteTodos={this.deleteTodos} />
......

}

CHILD

export class ToDoList extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
              editing: false,
            };

        handleDelete(e, i) {
            e.preventDefault();
            this.props.passDeleteTodos()
        }

    renderDisplay() {
        return(

           {
            this.props.listArr.map((list,i) => {
               return(

{list}

                     <button className="btn btn-danger btn-xs glyphicon glyphicon-trash"
                             onClick={() => this.handleDelete(i)}
                     />

Body:
arrow function in react doesn't need to bind to this.
But during call to the functions, for example to call this function handleDelete

 handleDelete(e, i) {
        e.preventDefault();
        this.props.passDeleteTodos()
    }

we will use synatx as:

handleDelete.bind(i)


问:
Create database link to connect another PC in SQL Server?
On Oracle/SQLDeveloper I use

```<code>CONNECT TO username IDENTIFIED BY p123
</code>```

for distributing project but in SQL Server I can't do this.

I mean one PC for example PC1 is a global table on this pc,  and I want others PC to be able to access this PC1 such as fragment and distribute, I try it in SQL developer successfully but I can't this in SQL Server.

答:
Check your network settings. Makes sure the ports that need to be exposed are exposed. Consider reviewing the SQL Distributed Server documentation:

https://learn.microsoft.com/en-us/sql/sql-server/?view=sql-server-ver15

This looks like a good place to start. Your English is good, keep practicing!

I would have left a comment but I don't have enough reputation

Body:
On Oracle/SQLDeveloper I use

CONNECT TO username IDENTIFIED BY p123

for distributing project but in SQL Server I can't do this.

I mean one PC for example PC1 is a global table on this pc,  and I want others PC to be able to access this PC1 such as fragment and distribute, I try it in SQL developer successfully but I can't this in SQL Server.


问:
How to tell if the user already rated my UWP app?
Windows 10 Store UWP apps can use StoreContext.RequestRateAndReviewAppAsync function, or simply a URL like this ms-windows-store://review/?ProductId=9WZDNCRFHVJL, to display a user rating window for the app:

I prefer the URL method since I can simply invoke it via ShellExecute method.

But my question is how do I find out if the user had already rated my app, so that I don't display that rating window again?

答:
Currently there is no such api can directly tell if the user already rated the UWP app, but you could use roaming data in your app which keeps your app's app data in sync across multiple devices.

If the user has rated your app, you can set "Yes" in the RoamingSettings, if the value from RoamingSettings is "No", you can display that rating window again. You could determine whether the rating is successful, e.g. in StoreContext.RequestRateAndReviewAppAsync method, the ExtendedJsonData property of the StoreRateAndReviewResult class contains a JSON-formatted string that indicates whether the rating request was successful. By ExtendedJsonData property, you can know if the rating is successful and then set the value to "Yes" in the RoamingSettings.

```<code>private async void Button_Click(object sender, RoutedEventArgs e)
{
    ApplicationDataContainer RatingSettings = ApplicationData.Current.RoamingSettings;
    //initialization
    if (RatingSettings.Values["isRated"] == null)
    {
        RatingSettings.Values["isRated"] = "No";
    }
    var isRatedStr = RatingSettings.Values["isRated"].ToString();

    if (isRatedStr == "No")
    {
        //display the rate windows
        if (//if rated successfully)
        {
            RatingSettings.Values["isRated"] = "Yes";
        }

    }
}
</code>```

Or you can use the Get app ratings and Get app reviews methods in the Store analytics API to programmatically retrieve the ratings and reviews from your customers in JSON format. For more details, you can refer to this document.

Body:
Currently there is no such api can directly tell if the user already rated the UWP app, but you could use roaming data in your app which keeps your app's app data in sync across multiple devices.

If the user has rated your app, you can set "Yes" in the RoamingSettings, if the value from RoamingSettings is "No", you can display that rating window again. You could determine whether the rating is successful, e.g. in StoreContext.RequestRateAndReviewAppAsync method, the ExtendedJsonData property of the StoreRateAndReviewResult class contains a JSON-formatted string that indicates whether the rating request was successful. By ExtendedJsonData property, you can know if the rating is successful and then set the value to "Yes" in the RoamingSettings.

private async void Button_Click(object sender, RoutedEventArgs e)
{
    ApplicationDataContainer RatingSettings = ApplicationData.Current.RoamingSettings;
    //initialization
    if (RatingSettings.Values["isRated"] == null)
    {
        RatingSettings.Values["isRated"] = "No";
    }
    var isRatedStr = RatingSettings.Values["isRated"].ToString();

    if (isRatedStr == "No")
    {
        //display the rate windows
        if (//if rated successfully)
        {
            RatingSettings.Values["isRated"] = "Yes";
        }

    }
}

Or you can use the Get app ratings and Get app reviews methods in the Store analytics API to programmatically retrieve the ratings and reviews from your customers in JSON format. For more details, you can refer to this document.


问:
Substr in mongodb conditional aggregate
I have to count the employees with valid mail id suffix with '@test.com'. I tried below queries,

```<code>db.emp.aggregate([
        { $match: {} },
        { $addFields:{
          "validEmail":{$cond:[{$eq:[{"$substr":["$emp_email",9,-1]},"@test.com"]},1,0]}
           }
        }
    ])
</code>```

Here, the $substr operator is not returning the output in reverse way. My assumption is that -1 on the 3rd argument should substr with reverse way. It is not working.

I am using mongodb version lesser than 4.2 and not able to use $regexMatch. Is there any way to achieve this.

答:
You can $split using @ and check whether the last index contains test.com.

```<code>  .aggregate([
    {
      "$project": {
        "validEmail": {
          "$eq": [
            { "$arrayElemAt": [{ "$split": ["$emp_email", "@"] }, -1] },
            "test.com"
          ]
        }
      }
    }
  ])
</code>```

MongoPlayground

Title: Substr in mongodb conditional aggregate

Body:
I have to count the employees with valid mail id suffix with '@test.com'. I tried below queries,

db.emp.aggregate([
        { $match: {} },
        { $addFields:{
          "validEmail":{$cond:[{$eq:[{"$substr":["$emp_email",9,-1]},"@test.com"]},1,0]}
           }
        }
    ])

Here, the $substr operator is not returning the output in reverse way. My assumption is that -1 on the 3rd argument should substr with reverse way. It is not working.

I am using mongodb version lesser than 4.2 and not able to use $regexMatch. Is there any way to achieve this.

Body:
You can $split using @ and check whether the last index contains test.com.

  .aggregate([
    {
      "$project": {
        "validEmail": {
          "$eq": [
            { "$arrayElemAt": [{ "$split": ["$emp_email", "@"] }, -1] },
            "test.com"
          ]
        }
      }
    }
  ])

MongoPlayground


问:
Why doesn't this RegEx work with `git grep`?
The input is Unicode texts.

input

```<code>あいうえお
</code>```

command

Execution environment is macOS.

```<code>git grep '[い]' # -> matched
grep 'あ[い]う' # -> matched

git grep 'あ[い]う' # -> not matched
</code>```

Why doesn't the RegEx work in git grep when normal grep is works?

environment

OS: macOS

Locale: ja_JP.UTF-8

Input file encoding is 'UTF-8'.

答:
It seems to work fine for me:

$ echo 'あいうえお' > afile
$ git add afile
$ grep 'あ[い]う' afile
あいうえお
$ git grep 'あ[い]う'
afile:あいうえお
```

Maybe you've configured patternType away from the default somehow?

grep.patternType

Set the default matching behavior. Using a value of basic, extended, fixed, or perl will enable the --basic-regexp, --extended-regexp, --fixed-strings, or --perl-regexp option accordingly, while the value default will return to the default matching behavior.

Try invoking git grep -G to force basic patterns and see what happens. Or git config --get grep.patternType to see if it's been set to somethig odd.

Also be aware that git grep only looks in "the tracked files in the work tree, blobs registered in the index file, or blobs in given tree objects". So if you add the string to a file but don't add the file to the index, there will be no match.

Likewise if the string is in an old commit, which is very much unlike hg grep (which greps through the history by default)

Body:
The input is Unicode texts.

input

あいうえお

command

Execution environment is macOS.

git grep '[い]' # -> matched
grep 'あ[い]う' # -> matched

git grep 'あ[い]う' # -> not matched

Why doesn't the RegEx work in git grep when normal grep is works?

environment

OS: macOS

Locale: ja_JP.UTF-8

Input file encoding is 'UTF-8'.

Body:
It seems to work fine for me:

$ echo 'あいうえお' > afile
$ git add afile
$ grep 'あ[い]う' afile
あいうえお
$ git grep 'あ[い]う'
afile:あいうえお

Maybe you've configured patternType away from the default somehow?

grep.patternType

Set the default matching behavior. Using a value of basic, extended, fixed, or perl will enable the --basic-regexp, --extended-regexp, --fixed-strings, or --perl-regexp option accordingly, while the value default will return to the default matching behavior.

Try invoking git grep -G to force basic patterns and see what happens. Or git config --get grep.patternType to see if it's been set to somethig odd.

Also be aware that git grep only looks in "the tracked files in the work tree, blobs registered in the index file, or blobs in given tree objects". So if you add the string to a file but don't add the file to the index, there will be no match.

Likewise if the string is in an old commit, which is very much unlike hg grep (which greps through the history by default)


问:
RMI (JDK 1.6): ClassNotFoundException for <server>_Stub in client-app
After 2 days of googling, stackoverflow-ing and looking for answers in other forums, I finally gave up and hope to find an answer here!

I have an annoying problem in getting a simple RMI client-server application to run although it seems (or maybe I'm simply missing a tiny bit) to be a well-known issue with RMI.

I'm using Eclipse and m2eclipse (Maven integration) for dependency management. My project structure is as follows:
 - client: the client code, dependency to shared
 - server: server code, dependency to shared
 - shared: remote interfaces and shared classes between server and client
 - integrationtest: test project, having both dependencies on client and server

Shared:

The remote interface clients can call is:

```<code>public interface IServerReceiver extends Remote, Serializable {
  void connect(long clientId) throws RemoteException;
}
</code>```

This interface is in the shared project where both client and server have dependencies on so it is in the client's classpath.

Server-side:

The Server class is responsible for creating a registry and exporting the remote object (ServerReceiver implements IServerReceiver):

```<code>registry = LocateRegistry.createRegistry(rmiRegistryPort);
serverReceiver = new ServerReceiver(rmiRegistryPort);

registry.rebind(IConstants.RMI_SERVER_RECEIVER_ID, UnicastRemoteObject.exportObject(serverReceiver, 0));
</code>```

When starting the server, a security policy file is provided to the server's JVM by defining -Djava.security.policy (although I don't think that this has to do with the issue described here).

Client-side

The class responsible for connecting the client to the server is the ServerConnector class:

```<code>...
public ServerConnector() {
 ...
 registry = LocateRegistry.getRegistry(serverRMIHost, serverRMIPort);
 serverReceiver = (IServerReceiver) registry.lookup(IConstants.RMI_SERVER_RECEIVER_ID);
 serverReceiver.connect(client.getId());
 ...
}
</code>```

The Client class' constructor looks like this (some lines omitted):

```<code>public Client(..) {
 ....
 serverConnector = new ServerConnector(serverRMIHost, serverRMIPort, this);
 ....
}
</code>```

As well as the server, the client also gets a security policy file.

Testing

When I fire up an integration test creating a server and then a client: all works fine as expected and the connect()-method returns the expected result.

However, when I try to normally start a Server instance, then starting the client instance which tries to connect() to the server, the following exception gets throws:

```<code>Caused by: java.rmi.UnmarshalException: error unmarshalling return; nested exception is:
java.lang.ClassNotFoundException: assign2.comm.ServerReceiver_Stub
at sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
at assign2.comm.ServerConnector.<init>(ServerConnector.java:65)
</code>```

While looking for answers, the most prominent was: the client must have access to the servers interface definition (IServerReceiver). However, to me it seems like that's the case here as proper dependencies are in place (client->shared, server->shared, IServerReceiver place in shared).
Another aspect of the exception I don't quite understand is: since JDK 1.5, stub generation through rmic is no longer necessary and is achieved through dynamic proxyies. The client therefore only needs access to the interface IServerReceiver in order to create the dynamic proxy. Why would he be complaining about not finding the ServerReceiver_Stub class at all then?

Since the integration test runs successfully and within that test the client also has access to the implementation of the IServerReceiver interface, am I right in assuming that the client needs not only access to the remote interface but also it's implementation?

I'm pretty confused by now so maybe you can help me shed some light on this matter? Thanks for having read that long post! ;-)

Cheers,
Chris

答: IServerReceiver should not be Serializable.  my guess is that your server instance is being sent over the network instead of the proxy.

Body:
After 2 days of googling, stackoverflow-ing and looking for answers in other forums, I finally gave up and hope to find an answer here!

I have an annoying problem in getting a simple RMI client-server application to run although it seems (or maybe I'm simply missing a tiny bit) to be a well-known issue with RMI.

I'm using Eclipse and m2eclipse (Maven integration) for dependency management. My project structure is as follows:
 - client: the client code, dependency to shared
 - server: server code, dependency to shared
 - shared: remote interfaces and shared classes between server and client
 - integrationtest: test project, having both dependencies on client and server

Shared:

The remote interface clients can call is:

public interface IServerReceiver extends Remote, Serializable {
  void connect(long clientId) throws RemoteException;
}

This interface is in the shared project where both client and server have dependencies on so it is in the client's classpath.

Server-side:

The Server class is responsible for creating a registry and exporting the remote object (ServerReceiver implements IServerReceiver):

registry = LocateRegistry.createRegistry(rmiRegistryPort);
serverReceiver = new ServerReceiver(rmiRegistryPort);

registry.rebind(IConstants.RMI_SERVER_RECEIVER_ID, UnicastRemoteObject.exportObject(serverReceiver, 0));

When starting the server, a security policy file is provided to the server's JVM by defining -Djava.security.policy (although I don't think that this has to do with the issue described here).

Client-side

The class responsible for connecting the client to the server is the ServerConnector class:

...
public ServerConnector() {
 ...
 registry = LocateRegistry.getRegistry(serverRMIHost, serverRMIPort);
 serverReceiver = (IServerReceiver) registry.lookup(IConstants.RMI_SERVER_RECEIVER_ID);
 serverReceiver.connect(client.getId());
 ...
}

The Client class' constructor looks like this (some lines omitted):

public Client(..) {
 ....
 serverConnector = new ServerConnector(serverRMIHost, serverRMIPort, this);
 ....
}

As well as the server, the client also gets a security policy file.

Testing

When I fire up an integration test creating a server and then a client: all works fine as expected and the connect()-method returns the expected result.

However, when I try to normally start a Server instance, then starting the client instance which tries to connect() to the server, the following exception gets throws:

Caused by: java.rmi.UnmarshalException: error unmarshalling return; nested exception is:
java.lang.ClassNotFoundException: assign2.comm.ServerReceiver_Stub
at sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
at assign2.comm.ServerConnector.<init>(ServerConnector.java:65)

While looking for answers, the most prominent was: the client must have access to the servers interface definition (IServerReceiver). However, to me it seems like that's the case here as proper dependencies are in place (client->shared, server->shared, IServerReceiver place in shared).
Another aspect of the exception I don't quite understand is: since JDK 1.5, stub generation through rmic is no longer necessary and is achieved through dynamic proxyies. The client therefore only needs access to the interface IServerReceiver in order to create the dynamic proxy. Why would he be complaining about not finding the ServerReceiver_Stub class at all then?

Since the integration test runs successfully and within that test the client also has access to the implementation of the IServerReceiver interface, am I right in assuming that the client needs not only access to the remote interface but also it's implementation?

I'm pretty confused by now so maybe you can help me shed some light on this matter? Thanks for having read that long post! ;-)

Cheers,
Chris


问:
Django - logout view customisation fail

Although the original question is cleared out, there's a new related question which is quite interesting: (please let me know if my theory is remotely correct...)

Please checkout my urlpatterns below:

from django.contrib.auth import views as auth_views
from boutique.models import Category
from django.urls import path, include
from . import views

app_name = 'users'
urlpatterns = [

    # to customise login view
    path('login/', auth_views.LoginView.as_view(extra_context = {'categories': Category.objects.get_categories_with_item()})),
    # path('login/', views.NewLoginView.as_view()),

    # to customise default logout view
    path('logout/', auth_views.LogoutView.as_view(), {'categories': Category.objects.get_categories_with_item()}),

    # include django authentication urls
    path('', include('django.contrib.auth.urls')),

```

<p>As you probably noticed that there are two different ways to pass in <code>extra_context</code>, the interesting thing is: The method used on <code>LogoutView</code> can not be used on <code>LoginView</code>!! However, The method used on <code>LoginView</code> does work on <code>LogoutView</code>.</p>

<p>I think the possible explanation and yet to be confirmed by you lot is that they inherit different views:</p>

<p><code>LoginView</code>:</p>

<pre class="lang-py prettyprint-override"><code>class LoginView(SuccessURLAllowedHostsMixin, FormView):
    """
    Display the login form and handle the login action.
    """
    form_class = AuthenticationForm
    authentication_form = None
    redirect_field_name = REDIRECT_FIELD_NAME
    template_name = 'registration/login.html'
    redirect_authenticated_user = False
    extra_context = None

    ...

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        current_site = get_current_site(self.request)
        context.update({
            self.redirect_field_name: self.get_redirect_url(),
            'site': current_site,
            'site_name': current_site.name,
            **(self.extra_context or {})
        })
        return context
</code>```

LogoutView:

class LogoutView(SuccessURLAllowedHostsMixin, TemplateView):
    """
    Log out the user and display the 'You are logged out' message.
    """
    next_page = None
    redirect_field_name = REDIRECT_FIELD_NAME
    template_name = 'registration/logged_out.html'
    extra_context = None

    ...

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        current_site = get_current_site(self.request)
        context.update({
            'site': current_site,
            'site_name': current_site.name,
            'title': _('Logged out'),
            **(self.extra_context or {})
        })
        return context

```

<p>I think the reason that <code>LoginView</code> has to pass the <code>extra_context</code> as a positional argument into <code>.as_view()</code> is that it doesn't inherit from <code>TemplateView</code>:</p>

<pre class="lang-py prettyprint-override"><code>class TemplateView(TemplateResponseMixin, ContextMixin, View):
    """
    Render a template. Pass keyword arguments from the URLconf to the context.
    """
    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        return self.render_to_response(context)

</code>```

which has a get method to get context data... if i'm not mistaken.

Could anyone confirm this?

I'm quite new to python and django framework. Thanks a lot!!!

The Original question has been answered

Please checkout the answers in the comments session --

I'm fairly new to Django and in order to pass in more context to logout view I tried 2 methods to customise the logout view:

Method 1:

from django.contrib.auth import views as auth_views
from boutique.models import Category

app_name = 'users'
urlpatterns = [
    ...
    path('logout/', auth_views.LogoutView.as_view(), {'categories': Category.objects.all()}),

    # I also tried this:
    # path('logout/', auth_views.LogoutView.as_view({'categories': Category.objects.all()}),

    # I also tried this:
    # path('logout-customised-url/', auth_views.LogoutView.as_view(), {'categories': Category.objects.all()}),
    # This is working tho it wouldn't be automatically redirect to this path when logged out
```

<h2>Method 2:</h2>

<pre class="lang-py prettyprint-override"><code>    ...
    path('logout/', views.NewLogoutView.as_view()),
    # NewLogoutView code below:
</code>```

views.py

from boutique.models import Category
from django.contrib.auth.views import LogoutView

class NewLogoutView(LogoutView):

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['categories'] = Category.objects.all()
        return context
```

Still not working, and the outcome is exactly the same: if a customised url is in use such as 'logged-out/' instead of 'logout/', and you type out the url, it renders the correct page with the extra context. However, wouldn't go to the page when users log out normally...

Is there any workaround? Thanks!

答:
Got it!! The problem was in the order of my urlpatterns, originally it was like this:

urlpatterns = [

    # include django authentication urls
    path('', include('django.contrib.auth.urls')),

    # to customise default logout view
    path('logout/', auth_views.LogoutView.as_view(), {'categories': Category.objects.get_categories_with_item()}),
```

<p>Based on official doc: Authentication Views, <code>django.contrib.auth.urls</code> includes many url patterns, such as:</p>

<pre class="lang-py prettyprint-override"><code>accounts/login/ [name='login']
accounts/logout/ [name='logout']
accounts/password_change/ [name='password_change']
accounts/password_change/done/ [name='password_change_done']
accounts/password_reset/ [name='password_reset']
accounts/password_reset/done/ [name='password_reset_done']
accounts/reset/<uidb64>/<token>/ [name='password_reset_confirm']
accounts/reset/done/ [name='password_reset_complete']
</code>```

Therefore, they take precedence if they were declared before the customised. So:

urlpatterns = [

    # to customise default logout view
    path('logout/', auth_views.LogoutView.as_view(), {'categories': Category.objects.get_categories_with_item()}),

    # include django authentication urls
    path('', include('django.contrib.auth.urls')),

```

<p>To swap the order, it works.</p>

<hr>

<p>To the roockies like me:
<em>Method 1</em> does work. Just pass in the additional context/argument like it states in the official doc after the view.</p>

<p>Also, I checked <code>django.contrib.auth.views.LogoutView</code>:</p>

<pre class="lang-py prettyprint-override"><code>class LogoutView(SuccessURLAllowedHostsMixin, TemplateView):
    """
    Log out the user and display the 'You are logged out' message.
    """
    next_page = None
    redirect_field_name = REDIRECT_FIELD_NAME
    template_name = 'registration/logged_out.html'
    extra_context = None
    ...
</code>```

The extra_context is set to None for you to add extra context. Easy to customise if were to subclass it or simply pass in a positional argument into .as_view() -- which means:

urlpatterns = [

    # to customise login view
    path('login/', auth_views.LoginView.as_view(extra_context = {'categories': Category.objects.get_categories_with_item()})),

]

`Loginview` has the same the same convenient settings...

```

Title: Django - logout view customisation fail

Body:
Although the original question is cleared out, there's a new related question which is quite interesting: (please let me know if my theory is remotely correct...)

Please checkout my urlpatterns below:

from django.contrib.auth import views as auth_views
from boutique.models import Category
from django.urls import path, include
from . import views

app_name = 'users'
urlpatterns = [

    # to customise login view
    path('login/', auth_views.LoginView.as_view(extra_context = {'categories': Category.objects.get_categories_with_item()})),
    # path('login/', views.NewLoginView.as_view()),

    # to customise default logout view
    path('logout/', auth_views.LogoutView.as_view(), {'categories': Category.objects.get_categories_with_item()}),

    # include django authentication urls
    path('', include('django.contrib.auth.urls')),

As you probably noticed that there are two different ways to pass in extra_context, the interesting thing is: The method used on LogoutView can not be used on LoginView!! However, The method used on LoginView does work on LogoutView.

I think the possible explanation and yet to be confirmed by you lot is that they inherit different views:

LoginView:

class LoginView(SuccessURLAllowedHostsMixin, FormView):
    """
    Display the login form and handle the login action.
    """
    form_class = AuthenticationForm
    authentication_form = None
    redirect_field_name = REDIRECT_FIELD_NAME
    template_name = 'registration/login.html'
    redirect_authenticated_user = False
    extra_context = None

    ...

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        current_site = get_current_site(self.request)
        context.update({
            self.redirect_field_name: self.get_redirect_url(),
            'site': current_site,
            'site_name': current_site.name,
            **(self.extra_context or {})
        })
        return context

LogoutView:

class LogoutView(SuccessURLAllowedHostsMixin, TemplateView):
    """
    Log out the user and display the 'You are logged out' message.
    """
    next_page = None
    redirect_field_name = REDIRECT_FIELD_NAME
    template_name = 'registration/logged_out.html'
    extra_context = None

    ...

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        current_site = get_current_site(self.request)
        context.update({
            'site': current_site,
            'site_name': current_site.name,
            'title': _('Logged out'),
            **(self.extra_context or {})
        })
        return context

I think the reason that LoginView has to pass the extra_context as a positional argument into .as_view() is that it doesn't inherit from TemplateView:

class TemplateView(TemplateResponseMixin, ContextMixin, View):
    """
    Render a template. Pass keyword arguments from the URLconf to the context.
    """
    def get(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        return self.render_to_response(context)

which has a get method to get context data... if i'm not mistaken.

Could anyone confirm this?

I'm quite new to python and django framework. Thanks a lot!!!

The Original question has been answered

Please checkout the answers in the comments session --

I'm fairly new to Django and in order to pass in more context to logout view I tried 2 methods to customise the logout view:

Method 1:

from django.contrib.auth import views as auth_views
from boutique.models import Category

app_name = 'users'
urlpatterns = [
    ...
    path('logout/', auth_views.LogoutView.as_view(), {'categories': Category.objects.all()}),

    # I also tried this:
    # path('logout/', auth_views.LogoutView.as_view({'categories': Category.objects.all()}),

    # I also tried this:
    # path('logout-customised-url/', auth_views.LogoutView.as_view(), {'categories': Category.objects.all()}),
    # This is working tho it wouldn't be automatically redirect to this path when logged out

Method 2:

    ...
    path('logout/', views.NewLogoutView.as_view()),
    # NewLogoutView code below:

views.py

from boutique.models import Category
from django.contrib.auth.views import LogoutView

class NewLogoutView(LogoutView):

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['categories'] = Category.objects.all()
        return context

Still not working, and the outcome is exactly the same: if a customised url is in use such as 'logged-out/' instead of 'logout/', and you type out the url, it renders the correct page with the extra context. However, wouldn't go to the page when users log out normally...

Is there any workaround? Thanks!

Body:
Got it!! The problem was in the order of my urlpatterns, originally it was like this:

urlpatterns = [

    # include django authentication urls
    path('', include('django.contrib.auth.urls')),

    # to customise default logout view
    path('logout/', auth_views.LogoutView.as_view(), {'categories': Category.objects.get_categories_with_item()}),

Based on official doc: Authentication Views, django.contrib.auth.urls includes many url patterns, such as:

accounts/login/ [name='login']
accounts/logout/ [name='logout']
accounts/password_change/ [name='password_change']
accounts/password_change/done/ [name='password_change_done']
accounts/password_reset/ [name='password_reset']
accounts/password_reset/done/ [name='password_reset_done']
accounts/reset/<uidb64>/<token>/ [name='password_reset_confirm']
accounts/reset/done/ [name='password_reset_complete']

Therefore, they take precedence if they were declared before the customised. So:

urlpatterns = [

    # to customise default logout view
    path('logout/', auth_views.LogoutView.as_view(), {'categories': Category.objects.get_categories_with_item()}),

    # include django authentication urls
    path('', include('django.contrib.auth.urls')),

To swap the order, it works.

To the roockies like me:
Method 1 does work. Just pass in the additional context/argument like it states in the official doc after the view.

Also, I checked django.contrib.auth.views.LogoutView:

class LogoutView(SuccessURLAllowedHostsMixin, TemplateView):
    """
    Log out the user and display the 'You are logged out' message.
    """
    next_page = None
    redirect_field_name = REDIRECT_FIELD_NAME
    template_name = 'registration/logged_out.html'
    extra_context = None
    ...

The extra_context is set to None for you to add extra context. Easy to customise if were to subclass it or simply pass in a positional argument into .as_view() -- which means:

urlpatterns = [

    # to customise login view
    path('login/', auth_views.LoginView.as_view(extra_context = {'categories': Category.objects.get_categories_with_item()})),

]

`Loginview` has the same the same convenient settings...


问:
How to separate string using by commas in multicomma line
What should I do to for separate (test(1,2) , test(3,4)) as test(1,2) and test(3,4). What can I use as delimiter value instead of x here? Thanks</p>

```<code>    StringTokenizer tokenizer = new StringTokenizer(str, "x");
</code>```

答:
Use String.split() instead:

String s = "test(1,2), test2(4,5), test3(2,3)";
String[] arr = s.split("(?<=\\w*[(]\\d,\\d[)]),");
System.out.println(Arrays.toString(arr));
```

<p>Output:</p>

```[test(1,2),  test2(4,5),  test3(2,3)]
```

Body:
What should I do to for separate (test(1,2) , test(3,4)) as test(1,2) and test(3,4). What can I use as delimiter value instead of x here? Thanks

    StringTokenizer tokenizer = new StringTokenizer(str, "x");

Body:
Use String.split() instead:

String s = "test(1,2), test2(4,5), test3(2,3)";
String[] arr = s.split("(?<=\\w*[(]\\d,\\d[)]),");
System.out.println(Arrays.toString(arr));

Output:

[test(1,2),  test2(4,5),  test3(2,3)]