问:
Templates inside of Docusign Shared Templates folder through API
Listing the folders and their contents (templates) from the "My Templates" section is easily done, but listing the Folders and Templates inside of the "Shared Templates" section does not seem to be documented.

I am looking for a way to accomplish the same thing as using "GET https://{server}/restapi/{apiVersion}/accounts/{accountId}/templates?folder={folder}", but for a folder inside of the "Shared Templates" section.

I cannot find any documentation for this functionality.

答:
I have been banging my head against this problem for 2 days now and have tried many API calls/configurations to work this out for my self.

I believe (as highlighted from the documentation) that this feature may not be supported.

I'm still investigating a little further and will change this response if I find a solution.

The following information is what I have tried, ultimately did not work.

I am providing this information to help others who stumble across this thread looking for an answer to see what I have tried while looking for an answer, and also for my own clarity if I come back to this problem.

The use of this DocusignIntegration::DocusignModel in the code below is from a custom model that I created that knows how to translate back and forth between snake_case (ruby) and camelCase (Docusign Data)

I have manually moved a template into a local folder and shared a template in a shared folder

The following result is based on the Account::ListSharedAccess endpoint, using the following query options.

Query Shared Access using 'folders' item type

```<code>options.item_type = 'folders'
options.folder_ids = 'id-for-local-folder,id-for-shared-folder'

</code>```

Notice that you don't get any information about templates when querying folders

```<code>{
  "accountId": "040-1111",
  "sharedAccess": [
    {
      "folders": [
        {
          "folderId": "id-for-local-folder",
          "name": "Local Folder",
          "uri": "/folder/id-for-local-folder",
          "sharedUsers": [
            {
              "user": {
                "userName": "David",
                "userId": "30a59"
              },
              "shared": "shared_to"
            }
          ]
        },
        {
          "folderId": "id-for-shared-folder",
          "name": "Shared Folder",
          "uri": "/folder/id-for-shared-folder",
          "sharedUsers": [
            {
              "user": {
                "userName": "David",
                "userId": "30a594"
              },
              "shared": "shared_to"
            }
          ],
          "sharedGroups": [
            {
              "group": {
                "groupId": "7319013",
                "groupName": "CanIShareTemplateToFolderViaGroups-TestNo37",
                "groupType": "custom"
              },
              "shared": "shared_to"
            }
          ]
        }
      ]
    }
  ]
}
</code>```

Query using 'templates' item type

```<code>options.item_type = 'templates'
options.folder_ids = 'id-for-my-template'

</code>```

Notice that you don't get any information about folders when querying templates

```<code>{
  "accountId": "040-1111",
  "sharedAccess": [
    {
      "templates": [
        {
          "templateId": "id-for-my-template",
          "templateName": "red",
          "owner": {
            "userName": "David",
            "userId": "30a594",
          },
          "sharedGroups": [
            {
              "group": {
                "groupId": "7319013",
                "groupName": "CanIShareTemplateToFolderViaGroups-TestNo37",
                "groupType": "custom"
              },
              "shared": "shared_to"
            }
          ]
        }
      ]
    }
  ]
}
</code>```

Update Shared Access using 'templates' item type

The following code for assigning a template to a group works expected.

```<code>options.item_type = 'templates'
</code>```

```<code>def self.share_template_to_group(account_id:, template_id:, group_id:)
  # Group group to share with
  group = DocusignIntegration::DocusignModel.new(group_id: group_id)

  member_group_shared_item = DocusignIntegration::DocusignModel.new(group: group,
                                                                    shared: 'shared_to')

  # What template to share
  template_shared_item = DocusignIntegration::DocusignModel.new(template_id: template_id,
                                                                shared: 'shared_to',
                                                                shared_groups: [member_group_shared_item])

  member_shared_item = DocusignIntegration::DocusignModel.new(templates: [template_shared_item])

  # Configured AccountSharedAccess object
  DocusignIntegration::DocusignModel.new(account_id: account_id,
                                          shared_access: [member_shared_item])
end
</code>```

```<code>{
    "accountId": "040-1111",
    "sharedAccess": [
    {
      "user": {
        "userName": "David",
        "userId": "30a594"
      },
      "templates": [
        {
          "templateId": "id-for-my-template",
          "sharedGroups": [
            {
              "group": {
                "groupId": "7319013",
                "groupName": "CanIShareTemplateToFolderViaGroups-TestNo37",
                "groupType": "custom"
              },
              "shared": "shared_to"
            }
          ]
        }
      ]
    }
  ]
}
</code>```

Linking the template to the Shared Folder.

I have tried multiple techniques via the API.

One of those techniques (which can be done via code or the UX) is to assign a template to a group and then share the shared_folder with that same group.

Unfortunately, that does not mean that the template suddenly becomes visible in the folder, but it does enable the user that is part of the group to share the template into the shared_folder via the user interface, thus making it available to all users in the group.

See this flow:

Select share on shared_folder

Share the folder with the group that you shared the template with

Now the user (who is not the original template owner) can share that template to the Shared Folder

Body:
I have been banging my head against this problem for 2 days now and have tried many API calls/configurations to work this out for my self.

I believe (as highlighted from the documentation) that this feature may not be supported.

I'm still investigating a little further and will change this response if I find a solution.

The following information is what I have tried, ultimately did not work.

I am providing this information to help others who stumble across this thread looking for an answer to see what I have tried while looking for an answer, and also for my own clarity if I come back to this problem.

The use of this DocusignIntegration::DocusignModel in the code below is from a custom model that I created that knows how to translate back and forth between snake_case (ruby) and camelCase (Docusign Data)

I have manually moved a template into a local folder and shared a template in a shared folder

The following result is based on the Account::ListSharedAccess endpoint, using the following query options.

Query Shared Access using 'folders' item type

options.item_type = 'folders'
options.folder_ids = 'id-for-local-folder,id-for-shared-folder'

Notice that you don't get any information about templates when querying folders

{
  "accountId": "040-1111",
  "sharedAccess": [
    {
      "folders": [
        {
          "folderId": "id-for-local-folder",
          "name": "Local Folder",
          "uri": "/folder/id-for-local-folder",
          "sharedUsers": [
            {
              "user": {
                "userName": "David",
                "userId": "30a59"
              },
              "shared": "shared_to"
            }
          ]
        },
        {
          "folderId": "id-for-shared-folder",
          "name": "Shared Folder",
          "uri": "/folder/id-for-shared-folder",
          "sharedUsers": [
            {
              "user": {
                "userName": "David",
                "userId": "30a594"
              },
              "shared": "shared_to"
            }
          ],
          "sharedGroups": [
            {
              "group": {
                "groupId": "7319013",
                "groupName": "CanIShareTemplateToFolderViaGroups-TestNo37",
                "groupType": "custom"
              },
              "shared": "shared_to"
            }
          ]
        }
      ]
    }
  ]
}

Query using 'templates' item type

options.item_type = 'templates'
options.folder_ids = 'id-for-my-template'

Notice that you don't get any information about folders when querying templates

{
  "accountId": "040-1111",
  "sharedAccess": [
    {
      "templates": [
        {
          "templateId": "id-for-my-template",
          "templateName": "red",
          "owner": {
            "userName": "David",
            "userId": "30a594",
          },
          "sharedGroups": [
            {
              "group": {
                "groupId": "7319013",
                "groupName": "CanIShareTemplateToFolderViaGroups-TestNo37",
                "groupType": "custom"
              },
              "shared": "shared_to"
            }
          ]
        }
      ]
    }
  ]
}

Update Shared Access using 'templates' item type

The following code for assigning a template to a group works expected.

options.item_type = 'templates'

def self.share_template_to_group(account_id:, template_id:, group_id:)
  # Group group to share with
  group = DocusignIntegration::DocusignModel.new(group_id: group_id)

  member_group_shared_item = DocusignIntegration::DocusignModel.new(group: group,
                                                                    shared: 'shared_to')

  # What template to share
  template_shared_item = DocusignIntegration::DocusignModel.new(template_id: template_id,
                                                                shared: 'shared_to',
                                                                shared_groups: [member_group_shared_item])

  member_shared_item = DocusignIntegration::DocusignModel.new(templates: [template_shared_item])

  # Configured AccountSharedAccess object
  DocusignIntegration::DocusignModel.new(account_id: account_id,
                                          shared_access: [member_shared_item])
end

{
    "accountId": "040-1111",
    "sharedAccess": [
    {
      "user": {
        "userName": "David",
        "userId": "30a594"
      },
      "templates": [
        {
          "templateId": "id-for-my-template",
          "sharedGroups": [
            {
              "group": {
                "groupId": "7319013",
                "groupName": "CanIShareTemplateToFolderViaGroups-TestNo37",
                "groupType": "custom"
              },
              "shared": "shared_to"
            }
          ]
        }
      ]
    }
  ]
}

Linking the template to the Shared Folder.

I have tried multiple techniques via the API.

One of those techniques (which can be done via code or the UX) is to assign a template to a group and then share the shared_folder with that same group.

Unfortunately, that does not mean that the template suddenly becomes visible in the folder, but it does enable the user that is part of the group to share the template into the shared_folder via the user interface, thus making it available to all users in the group.

See this flow:

Select share on shared_folder

Share the folder with the group that you shared the template with

Now the user (who is not the original template owner) can share that template to the Shared Folder


来源: stackexchange

问:
Python Class property behave as Dictionary
I have a very simple class that defines properties like:

```<code>class Person:
    fields = set()

    @property
    def id(self):
        self.fields.add('id')
        return 'person.id'
</code>```

The idea is for this class to record which properties have been accessed. Now the problem comes when I need to start supporting: person.metadata.key where metadata is basically an HStore object or 1 level JSON, the key is arbitrary and the idea is for the class Person so record access to any of the keys in metadata. I tried something like this:

```<code>class CustomerBulkContext:

    fields = set()

    class PersonMetadata:
        def __getitem__(self, attr):
            fields.add(f'metadata.{attr}')
            return f'person.metadata.{attr}'

    metadata = CustomerMetadataContext()
</code>```

Now obviously the problem is that fields inside PersonMetadata is not a known variable at this point. How can I overcome this issue, I don't know if it's possible to do in Python without too much code.

答:
In order to track accesses like person.metadata.key you'd have to have person.metadata return an object which itself tracks how it was accessed. In order to track the whole chain, you'd pass the chain so far to the object.

Something like:

class AccessTracker:
    def __init__(self, path=()):
        self._path = path

    def __getattr__(self, name):
        print('Accessed %s in %s' % (name, self._path))
        return AccessTracker(self._path + (name,))
```

ContentLicense: CC BY-SA 4.0

Body:
I have a very simple class that defines properties like:

class Person:
    fields = set()

    @property
    def id(self):
        self.fields.add('id')
        return 'person.id'

The idea is for this class to record which properties have been accessed. Now the problem comes when I need to start supporting: person.metadata.key where metadata is basically an HStore object or 1 level JSON, the key is arbitrary and the idea is for the class Person so record access to any of the keys in metadata. I tried something like this:

class CustomerBulkContext:

    fields = set()

    class PersonMetadata:
        def __getitem__(self, attr):
            fields.add(f'metadata.{attr}')
            return f'person.metadata.{attr}'

    metadata = CustomerMetadataContext()

Now obviously the problem is that fields inside PersonMetadata is not a known variable at this point. How can I overcome this issue, I don't know if it's possible to do in Python without too much code.


问:
Alternate way to create List<MyObject> in @DynamoDBTable without using dynamodbmarshalling (deprecated)
I've followed here by creating the MyCustomMarshaller.

MyCustomMarshaller

```<code>public class MyCustomMarshaller implements DynamoDBMarshaller<List<DemoClass>> {

    private static final ObjectMapper mapper = new ObjectMapper();
    private static final ObjectWriter writer = mapper.writer();

    @Override
    public String marshall(List<DemoClass> obj) {

        try {
            return writer.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw failure(e,
                    "Unable to marshall the instance of " + obj.getClass()
                            + "into a string");
        }
    }

    @Override
    public List<DemoClass> unmarshall(Class<List<DemoClass>> clazz, String json) {
        final CollectionType
                type =
                mapper.getTypeFactory().constructCollectionType(List.class, DemoClass.class);
        try {
            return mapper.readValue(json, type);
        } catch (Exception e) {
            throw failure(e, "Unable to unmarshall the string " + json
                    + "into " + clazz);
        }
    }
}
</code>```

My dynamoDb class

```<code>@DynamoDBAttribute
@DynamoDBMarshalling(marshallerClass = MyCustomMarshaller.class)
List<DemoClass> Object;
</code>```

DemoClass

```<code>public class DemoClass {

    String name;

    int id;

}
</code>```

All the codes were working great.By the thing is

com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMarshalling is
  deprecated

So how can I change my code without using this dynamoDBmarshalling?

Thanks in Advance,

Jay

答:
Another approach that is easier to implement, and you let DynamoDB handle the conversion behind the curtain.

Annotate the field as @DynamoAttribute

```<code>@DynamoDBAttribute
private MyObjectClass myObject;
</code>```

And the, you annotate the "MyObjectClass" with @DynamoDBDocument

```<code>@DynamoDBDocument
public class MyObjectClass {
....
}
</code>```

And DynamoDB will convert and un-convert the "MyObjectClass myObject" to the JSON shape, even if it's a list / array of objects.

ContentLicense: CC BY-SA 3.0

Body:
I've followed here by creating the MyCustomMarshaller.

MyCustomMarshaller

public class MyCustomMarshaller implements DynamoDBMarshaller<List<DemoClass>> {

    private static final ObjectMapper mapper = new ObjectMapper();
    private static final ObjectWriter writer = mapper.writer();

    @Override
    public String marshall(List<DemoClass> obj) {

        try {
            return writer.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw failure(e,
                    "Unable to marshall the instance of " + obj.getClass()
                            + "into a string");
        }
    }

    @Override
    public List<DemoClass> unmarshall(Class<List<DemoClass>> clazz, String json) {
        final CollectionType
                type =
                mapper.getTypeFactory().constructCollectionType(List.class, DemoClass.class);
        try {
            return mapper.readValue(json, type);
        } catch (Exception e) {
            throw failure(e, "Unable to unmarshall the string " + json
                    + "into " + clazz);
        }
    }
}

My dynamoDb class

@DynamoDBAttribute
@DynamoDBMarshalling(marshallerClass = MyCustomMarshaller.class)
List<DemoClass> Object;

DemoClass

public class DemoClass {

    String name;

    int id;

}

All the codes were working great.By the thing is

com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMarshalling is
  deprecated

So how can I change my code without using this dynamoDBmarshalling?

Thanks in Advance,

Jay

Body:
Another approach that is easier to implement, and you let DynamoDB handle the conversion behind the curtain.

Annotate the field as @DynamoAttribute

@DynamoDBAttribute
private MyObjectClass myObject;

And the, you annotate the "MyObjectClass" with @DynamoDBDocument

@DynamoDBDocument
public class MyObjectClass {
....
}

And DynamoDB will convert and un-convert the "MyObjectClass myObject" to the JSON shape, even if it's a list / array of objects.


问:
npm ERR! code EINTEGRITY while npm install
When I try to make npm install, I got this error

```<code>  npm ERR! code EINTEGRITY
    npm ERR!
    sha512-boQj1WFgQH3v4clhu3mTNfP+vOBxorDlE8EKiMjUlLG3C4qAESnn9AxIOkFgTR2c9LtzNjPrjS60cT27ZKBhaA==
    integrity checksum failed when using sha512: wanted sha512-boQj1WFgQH3v4clhu3mTNfP+vOBxorDlE8EKiMjUlLG3C4qAESnn9AxIOkFgTR2c9LtzNjPrjS60cT27ZKBhaA== but got sha5
        12-jGhWI9FADblpQKmyQF4BghrHs6FLV3dYFHVWcvj0xIUzHuO41PPfUlZOUplwasz72FRE2Knsa0wWubWldC9Jpw==. (3240 bytes)
        npm WARN tar invalid entry
        npm WARN tar invalid entry
        npm WARN tar invalid entry
        npm WARN tar invalid entry
        npm WARN tar invalid entry
        npm WARN tar invalid entry
</code>```

I tried,

```<code>npm cache verify
npm cache clean --force
</code>```

I have already delete package-lock.json file,

Add proxy to .npmrc and other confs like strict-ssl=false,
NODE_TLS_REJECT_UNAUTHORIZED=0

versions :

```<code>npm version
{ npm: '6.11.3',
  ares: '1.15.0',
  brotli: '1.0.7',
  cldr: '35.1',
  http_parser: '2.8.0',
  icu: '64.2',
  modules: '64',
  napi: '4',
  nghttp2: '1.39.2',
  node: '10.16.3',
  openssl: '1.1.1c',
  tz: '2019a',
  unicode: '12.1',
  uv: '1.28.0',
  v8: '6.8.275.32-node.54',
  zlib: '1.2.11' }

node -v
v10.16.3
</code>```

答:
You deleted package-lock.json, so the following would probably be of no use for you. In my case it worked. But first make sure you understand what's going on. npm tells you that the checksum from https://registry.npm.org doesn't match the one from package-lock.json. Either it changed in the registry, or...

Consider a line from the output:

```<code>npm ERR!
  sha512-boQj1WFgQH3v4clhu3mTNfP+vOBxorDlE8EKiMjUlLG3C4qAESnn9AxIOkFgTR2c9LtzNjPrjS60cT27ZKBhaA==
integrity checksum failed when using sha512: wanted
  sha512-boQj1WFgQH3v4clhu3mTNfP+vOBxorDlE8EKiMjUlLG3C4qAESnn9AxIOkFgTR2c9LtzNjPrjS60cT27ZKBhaA==
but got
  sha512-jGhWI9FADblpQKmyQF4BghrHs6FLV3dYFHVWcvj0xIUzHuO41PPfUlZOUplwasz72FRE2Knsa0wWubWldC9Jpw==
. (3240 bytes)
</code>```

Find the package in package-lock.json by the first two integrity checksums (sha512-b...), and put the third one (sha512-j...) into its "integrity" field.

More on it here.

Body:
When I try to make npm install, I got this error

  npm ERR! code EINTEGRITY
    npm ERR!
    sha512-boQj1WFgQH3v4clhu3mTNfP+vOBxorDlE8EKiMjUlLG3C4qAESnn9AxIOkFgTR2c9LtzNjPrjS60cT27ZKBhaA==
    integrity checksum failed when using sha512: wanted sha512-boQj1WFgQH3v4clhu3mTNfP+vOBxorDlE8EKiMjUlLG3C4qAESnn9AxIOkFgTR2c9LtzNjPrjS60cT27ZKBhaA== but got sha5
        12-jGhWI9FADblpQKmyQF4BghrHs6FLV3dYFHVWcvj0xIUzHuO41PPfUlZOUplwasz72FRE2Knsa0wWubWldC9Jpw==. (3240 bytes)
        npm WARN tar invalid entry
        npm WARN tar invalid entry
        npm WARN tar invalid entry
        npm WARN tar invalid entry
        npm WARN tar invalid entry
        npm WARN tar invalid entry

I tried,

npm cache verify
npm cache clean --force

I have already delete package-lock.json file,

Add proxy to .npmrc and other confs like strict-ssl=false,
NODE_TLS_REJECT_UNAUTHORIZED=0

versions :

npm version
{ npm: '6.11.3',
  ares: '1.15.0',
  brotli: '1.0.7',
  cldr: '35.1',
  http_parser: '2.8.0',
  icu: '64.2',
  modules: '64',
  napi: '4',
  nghttp2: '1.39.2',
  node: '10.16.3',
  openssl: '1.1.1c',
  tz: '2019a',
  unicode: '12.1',
  uv: '1.28.0',
  v8: '6.8.275.32-node.54',
  zlib: '1.2.11' }

node -v
v10.16.3

Body:
You deleted package-lock.json, so the following would probably be of no use for you. In my case it worked. But first make sure you understand what's going on. npm tells you that the checksum from https://registry.npm.org doesn't match the one from package-lock.json. Either it changed in the registry, or...

Consider a line from the output:

npm ERR!
  sha512-boQj1WFgQH3v4clhu3mTNfP+vOBxorDlE8EKiMjUlLG3C4qAESnn9AxIOkFgTR2c9LtzNjPrjS60cT27ZKBhaA==
integrity checksum failed when using sha512: wanted
  sha512-boQj1WFgQH3v4clhu3mTNfP+vOBxorDlE8EKiMjUlLG3C4qAESnn9AxIOkFgTR2c9LtzNjPrjS60cT27ZKBhaA==
but got
  sha512-jGhWI9FADblpQKmyQF4BghrHs6FLV3dYFHVWcvj0xIUzHuO41PPfUlZOUplwasz72FRE2Knsa0wWubWldC9Jpw==
. (3240 bytes)

Find the package in package-lock.json by the first two integrity checksums (sha512-b...), and put the third one (sha512-j...) into its "integrity" field.

More on it here.


问:
Could someone please explain how the boolean in this code works?
This question is more to understand a portion of code I am working with.  The "valid" boolean in line 1 becomes a condition for the while statement in line 2.  When you put a boolean in a while condition, does that automatically change the boolean?  I don't understand how if valid is initialized to false, it would ever become true outside of the while loop -unless there is something about it being in the while condition?  I'm including a portion of the code so you can see what is happening.  This is part of a fraction calculator I'm trying to understand.

Thanks for your help!

```<code>boolean valid = false;
while (!valid) {
    System.out.println("Please enter a Fraction a/b or integer (a): ");
    firstFraction = scan.nextLine();
    valid = validFraction(firstFraction);
    if (valid) {
        int findSlash = firstFraction.indexOf("/");
        if (findSlash >= 0) {
            firstFractionNumerator = Integer.parseInt(firstFraction.substring(0, findSlash));
            firstFractionDenominator = Integer.parseInt(firstFraction.substring(findSlash + 1, firstFraction.length()));
        }
        else {
            firstFractionNumerator = Integer.parseInt(firstFraction.substring(0, firstFraction.length()));
            firstFractionDenominator = 1;
        }
    }
}
</code>```

答:
As per the code, it is not meant to be true outside the while loop. The concept of the loop is to work until it finds a valid firstFraction. In other words; code will keep asking for input until user gives valid one (valid per code rules in validFraction method).

Then it takes that valid input and processes it, what's in the if (valid) {} is irrelevant to the loop decision making and it's just for checking weather the input is a/b or an integer.
Then loop quits and code proceeds to what's implemented after the while loop.

In conclusion, the loop is good.

Body:
This question is more to understand a portion of code I am working with.  The "valid" boolean in line 1 becomes a condition for the while statement in line 2.  When you put a boolean in a while condition, does that automatically change the boolean?  I don't understand how if valid is initialized to false, it would ever become true outside of the while loop -unless there is something about it being in the while condition?  I'm including a portion of the code so you can see what is happening.  This is part of a fraction calculator I'm trying to understand.

Thanks for your help!

boolean valid = false;
while (!valid) {
    System.out.println("Please enter a Fraction a/b or integer (a): ");
    firstFraction = scan.nextLine();
    valid = validFraction(firstFraction);
    if (valid) {
        int findSlash = firstFraction.indexOf("/");
        if (findSlash >= 0) {
            firstFractionNumerator = Integer.parseInt(firstFraction.substring(0, findSlash));
            firstFractionDenominator = Integer.parseInt(firstFraction.substring(findSlash + 1, firstFraction.length()));
        }
        else {
            firstFractionNumerator = Integer.parseInt(firstFraction.substring(0, firstFraction.length()));
            firstFractionDenominator = 1;
        }
    }
}


问:
jquery how to figure out what the JSON Object contains
I'm using JQuery with CodeIgniter PHP to figure make AJAX calls and return data via JSON. I want to figure out what my JSON object has returned, but I'm not sure what the syntax might be. Is there a way to just alert or log all the contents of the JSON object somehow? This is my code:

```<code>$.ajax({
    type: "GET",
    url: groups_url,
    success: function(parent){
        alert (parent);
    }
});
</code>```

If I do this - I get an object, but I don't know what it contains.

答:
Log to your console and inspect it:</p>

```<code>$.ajax({
    type: "GET",
    url: groups_url,
    success: function(parent){
       console.log(parent);
    }
});
</code>```

Body:
I'm using JQuery with CodeIgniter PHP to figure make AJAX calls and return data via JSON. I want to figure out what my JSON object has returned, but I'm not sure what the syntax might be. Is there a way to just alert or log all the contents of the JSON object somehow? This is my code:

$.ajax({
    type: "GET",
    url: groups_url,
    success: function(parent){
        alert (parent);
    }
});

If I do this - I get an object, but I don't know what it contains.

Body:
Log to your console and inspect it:

$.ajax({
    type: "GET",
    url: groups_url,
    success: function(parent){
       console.log(parent);
    }
});


问:
pandas perform multiple transformations and creating a new data frame
I have a daframe where I want to perform multiple (independent) transformations, and they create a new data frame (with a multi-index), where each index correspond to one of the transformations.

More concretely:

```<code>df = pd.DataFrame([[1, "X", 'H', 100], [2, "Y", 'K', 100] ,[3, "X", 'H', 200], [4, "Y", 'H', 100]], columns=['id', 'XY', 'HK', 'A']).set_index("id")

    XY  HK  A
id
1   X   H   100
2   Y   K   100
3   X   H   200
4   Y   H   100
</code>```

I now want to know how many XY and how many HK have the same A. The final results should look like this (with multi-index):

```<code>     XY      HK
    X   Y   H   K
A
100 1.0 2.0 2.0 1.0
200 1.0 NaN 1.0 NaN
</code>```

This is what I was expecting to work:

```<code>df.groupby(['A', 'XY', 'HK']).count()
</code>```

but it only contains the multi index without the values.

What I was able to do is:

count the XY:

```<code>xy_count = df.groupby(['A', 'XY']).count().HK.unstack()
</code>```

count the HK:

```<code>hk_count = df.groupby(['A', 'HK']).count().XY.unstack()
</code>```

merge the results (?)

```<code>results = pd.DataFrame()
results['XY'] = xy_count
results['HK'] = hk_count
</code>```

but this last part does now work.

So my questions are:

Q1: There seems to be a better way I am missing
Q2: why does step 3 not work?

Not really a question, but also I find confusing that to get the HK, you have to call the XY column and vice versa.

答:
You can do:

```<code>groups = df.groupby('A')
pd.concat({col:groups[col].value_counts().unstack()
           for col in ['XY','HK']}, axis=1)
</code>```

Output:

```<code>      XY        HK
       X    Y    H    K
A
100  1.0  2.0  2.0  1.0
200  1.0  NaN  1.0  NaN
</code>```

Body:
I have a daframe where I want to perform multiple (independent) transformations, and they create a new data frame (with a multi-index), where each index correspond to one of the transformations.

More concretely:

df = pd.DataFrame([[1, "X", 'H', 100], [2, "Y", 'K', 100] ,[3, "X", 'H', 200], [4, "Y", 'H', 100]], columns=['id', 'XY', 'HK', 'A']).set_index("id")

    XY  HK  A
id
1   X   H   100
2   Y   K   100
3   X   H   200
4   Y   H   100

I now want to know how many XY and how many HK have the same A. The final results should look like this (with multi-index):

     XY      HK
    X   Y   H   K
A
100 1.0 2.0 2.0 1.0
200 1.0 NaN 1.0 NaN

This is what I was expecting to work:

df.groupby(['A', 'XY', 'HK']).count()

but it only contains the multi index without the values.

What I was able to do is:

count the XY:

xy_count = df.groupby(['A', 'XY']).count().HK.unstack()

count the HK:

hk_count = df.groupby(['A', 'HK']).count().XY.unstack()

merge the results (?)

results = pd.DataFrame()
results['XY'] = xy_count
results['HK'] = hk_count

but this last part does now work.

So my questions are:

Q1: There seems to be a better way I am missing
Q2: why does step 3 not work?

Not really a question, but also I find confusing that to get the HK, you have to call the XY column and vice versa.

Body:
You can do:

groups = df.groupby('A')
pd.concat({col:groups[col].value_counts().unstack()
           for col in ['XY','HK']}, axis=1)

Output:

      XY        HK
       X    Y    H    K
A
100  1.0  2.0  2.0  1.0
200  1.0  NaN  1.0  NaN


问:
How to trigger CodePipeline for GitHub pull requests being merged?
How can I configure CodePipeline to be triggered for Pull Requests being opened, edited or merged?

Here is a Terraform configuration:

```<code>resource "aws_codepipeline_webhook" "gh_to_codepipeline_integration" {
  name            = "gh_to_codepipeline_integration"
  authentication  = "GITHUB_HMAC"
  target_action   = "Source"
  target_pipeline = aws_codepipeline.mycodepipeline.name

  authentication_configuration {
    secret_token = var.github_webhook_secret
  }

  // accept pull requests
  // Is there a way to filter on the PR being closed and merged?  This isn't it...
  filter {
    json_path    = "$.action"
    match_equals = "closed"
  }

}
</code>```

CodePipeline is set to accept webhook events that have all of the conditions specified in the filters, which corresponds to Pull Request Events.

Note that the GitHub documentation states for the action field of a PullRequestEvent (my emphasis in bold):

The action that was performed. Can be one of assigned, unassigned,
  review_requested, review_request_removed, labeled, unlabeled, opened,
  edited, closed, ready_for_review, locked, unlocked, or reopened. If
  the action is closed and the merged key is false, the pull request was
  closed with unmerged commits. If the action is closed and the merged
  key is true, the pull request was merged. While webhooks are also
  triggered when a pull request is synchronized, Events API timelines
  don't include pull request events with the synchronize action.

It seems like I need to filter for both $.action==closed && $.pull_request_merged=true, but it doesn't look like I can do both.  If I just filter on $.action==closed then my pipeline will rebuild if PRs are closed without merging.  Is this an oversight on my part, or are CodePipelines not as flexible in their triggers as CodeBuild projects?

答:
For pull requests being opened/updated, because CodePipeline's Git integrations require a branch name, this is not natively supported as the branch name is variable, unless you open PRs on long running branches like dev, qa etc (e.g. if you are using a Gitflow-based workflow).

The way that we support PRs based from dynamic branches is use CodeBuild for the build/unit test stage of our workflow, and then package up the repository and build artefacts to S3.  From there we trigger Deployment pipelines for integration and acceptance environments using S3 artefact as the source.  Using CodePipeline for deployments is powerful as it automatically ensures only one stage can execute at a time, meaning only one change for a given application is going through a given environment at any one time.

This approach is however quite complex and requires quite a bit of Lambda magic mixed with SQS FIFO queues to deal with concurrent PRs (this is to overcome the superseding behaviour of CodePipeline), but it's quite a powerful pattern.  We also use GitHub reviews to do things like trigger acceptance stage, and auto-approve manual approval steps in CodePipeline.

Once you are ready to merge the PR, we just use normal CodePipeline triggered off master to deploy to production - one thing you also need to do is ensure you use the artefact that was built and tested on the PR.

Body:
How can I configure CodePipeline to be triggered for Pull Requests being opened, edited or merged?

Here is a Terraform configuration:

resource "aws_codepipeline_webhook" "gh_to_codepipeline_integration" {
  name            = "gh_to_codepipeline_integration"
  authentication  = "GITHUB_HMAC"
  target_action   = "Source"
  target_pipeline = aws_codepipeline.mycodepipeline.name

  authentication_configuration {
    secret_token = var.github_webhook_secret
  }

  // accept pull requests
  // Is there a way to filter on the PR being closed and merged?  This isn't it...
  filter {
    json_path    = "$.action"
    match_equals = "closed"
  }

}

CodePipeline is set to accept webhook events that have all of the conditions specified in the filters, which corresponds to Pull Request Events.

Note that the GitHub documentation states for the action field of a PullRequestEvent (my emphasis in bold):

The action that was performed. Can be one of assigned, unassigned,
  review_requested, review_request_removed, labeled, unlabeled, opened,
  edited, closed, ready_for_review, locked, unlocked, or reopened. If
  the action is closed and the merged key is false, the pull request was
  closed with unmerged commits. If the action is closed and the merged
  key is true, the pull request was merged. While webhooks are also
  triggered when a pull request is synchronized, Events API timelines
  don't include pull request events with the synchronize action.

It seems like I need to filter for both $.action==closed && $.pull_request_merged=true, but it doesn't look like I can do both.  If I just filter on $.action==closed then my pipeline will rebuild if PRs are closed without merging.  Is this an oversight on my part, or are CodePipelines not as flexible in their triggers as CodeBuild projects?


问:
best way to find substring using regex in python 3
I was trying to find out the best way to find the specific substring in key value pair using re for the following:

```<code>some_string-variable_length/some_no_variable_digit/some_no1_variable_digit/some_string1/some_string2
eg: aba/101/11111/cde/xyz or aaa/111/1119/cde/xzx or ada/21111/5/cxe/yyz
</code>```

here everything is variable and what I was looking for is something like below in key value pair:

```<code>`cde: 2` as there are two entries for cde

cxe: 1 as there is only one cxe
</code>```

Note: everything is variable here except /. ie cde or cxe or some string will be there exactly after two / in each case

```<code>input:aba/101/11111/cde/xyz/blabla
output: cde:xyz/blabla
input: aaa/111/1119/cde/xzx/blabla
output: cde:xzx/blabla
input: aahjdsga/11231/1119/gfts/sjhgdshg/blabla
output: gfts:sjhgdshg/blabla
</code>```

If you notice here, my key is always the first string after 3rd / and value is always the substring after key

答:
Here are a couple of solutions based on your description that "key is always the first string after 3rd / and value is always the substring after key". The first uses str.split with a maxsplit of 4 to collect everything after the fourth / into the value. The second uses regex to extract the two parts:

```<code>inp = ['aba/101/11111/cde/xyz/blabla',
        'aaa/111/1119/cde/xzx/blabla',
        'aahjdsga/11231/1119/gfts/sjhgdshg/blabla'
        ]

for s in inp:
    parts = s.split('/', 4)
    key = parts[3]
    value = parts[4]
    print(f'{key}:{value}')

import re

for s in inp:
    m = re.match(r'^(?:[^/]*/){3}([^/]*)/(.*)$', s)
    if m is not None:
        key = m.group(1)
        value = m.group(2)
        print(f'{key}:{value}')
</code>```

For both pieces of code the output is

```<code>cde:xyz/blabla
cde:xzx/blabla
gfts:sjhgdshg/blabla
</code>```

Body:
I was trying to find out the best way to find the specific substring in key value pair using re for the following:

some_string-variable_length/some_no_variable_digit/some_no1_variable_digit/some_string1/some_string2
eg: aba/101/11111/cde/xyz or aaa/111/1119/cde/xzx or ada/21111/5/cxe/yyz

here everything is variable and what I was looking for is something like below in key value pair:

`cde: 2` as there are two entries for cde

cxe: 1 as there is only one cxe

Note: everything is variable here except /. ie cde or cxe or some string will be there exactly after two / in each case

input:aba/101/11111/cde/xyz/blabla
output: cde:xyz/blabla
input: aaa/111/1119/cde/xzx/blabla
output: cde:xzx/blabla
input: aahjdsga/11231/1119/gfts/sjhgdshg/blabla
output: gfts:sjhgdshg/blabla

If you notice here, my key is always the first string after 3rd / and value is always the substring after key

Body:
Here are a couple of solutions based on your description that "key is always the first string after 3rd / and value is always the substring after key". The first uses str.split with a maxsplit of 4 to collect everything after the fourth / into the value. The second uses regex to extract the two parts:

inp = ['aba/101/11111/cde/xyz/blabla',
        'aaa/111/1119/cde/xzx/blabla',
        'aahjdsga/11231/1119/gfts/sjhgdshg/blabla'
        ]

for s in inp:
    parts = s.split('/', 4)
    key = parts[3]
    value = parts[4]
    print(f'{key}:{value}')

import re

for s in inp:
    m = re.match(r'^(?:[^/]*/){3}([^/]*)/(.*)$', s)
    if m is not None:
        key = m.group(1)
        value = m.group(2)
        print(f'{key}:{value}')

For both pieces of code the output is

cde:xyz/blabla
cde:xzx/blabla
gfts:sjhgdshg/blabla


问:
How can I make this while loop faster on a microcontroller button?
I am working with a micro controller that has a button A. When I press this button and hold it for 2 seconds, its value becomes 0 and the color turns either blue or green, when I release, its value goes back to 1 but the color stays the same unless it was clicked again and the color changes. The problem is, it shouldn't take someone 2 whole seconds to have to change the led light. What can I do to make the value (either 0 or 1) be read faster?

Here is a snippet of the code in the while loop.

```<code>
// here are the states for reference. Everything is either a 0 or a 1
const int BUTTON_PRESSED = 0;
const int BUTTON_UNPRESSED = 1;

const int GREEN_LED = 0;
const int BLUE_LED = 1;

    const struct timespec sleepTime = { 1, 0 };

    while (true) {
        Value_Type value;
        // this function get the input of button a when pressed
        GetValue(button_A_fd, &value);
        Log_Debug(
           "Button value (%d)\n", value);

        // Processing the button.

        //Turns LED ON; Button not pressed down
        if (value == BUTTON_UNPRESSED) {
            last_button_state = BUTTON_UNPRESSED;
        } else {

            // if last button state is 1 then now it is being pressed
            if (last_button_state == BUTTON_UNPRESSED) {
                // Flip LEDs
                if (active_led == BLUE_LED) {
                    active_led = GREEN_LED;
                }
                else if (active_led == GREEN_LED) {
                    active_led = BLUE_LED;
                }

                last_button_state = BUTTON_PRESSED;
                // sets the pointer to the 0 bit of the file to write
                lseek(fd_storage, 0, SEEK_SET);
                // write current active led to mutable storage and save
                write(fd_storage, &active_led, sizeof(active_led));
            }
        }
        // Blinking the active LED.
        // reading input only when pressed and turn off other led
        if (active_led == GREEN_LED) {
            // turn off blue led, then turn on green
            SetValue(blue_led_fd, Value_High);
            SetValue(green_led_fd, Value_Low);
            nanosleep(&sleepTime, NULL);
            SetValue(green_led_fd, Value_High);
            nanosleep(&sleepTime, NULL);
        }
        else if (active_led == BLUE_LED) {
            // turn off green led, then turn on blue
            SetValue(green_led_fd, Value_High);
            SetValue(blue_led_fd, Value_Low);
            nanosleep(&sleepTime, NULL);
            SetValue(blue_led_fd, Value_High);
            nanosleep(&sleepTime, NULL);
        }
    }
}

</code>```

I tried to put GetValue() in several parts of the code to see if it could maybe get a value faster but it did not work. How can I move from here? I hope I shared enough code to understand the problem. Thank you.

答:
Looks like your code reads the button which is fast, and then immediately sets outputs and sleeps 1 second, sets an output and sleeps another second before going up to check if the button is pressed again.

You should restructure the code to check the state of the button more frequently where you're going to sleep now.

Sleep for shorter periods and check to see if the button is pressed in a loop until your total sleep time has been met or the button state changes.

Body:
I am working with a micro controller that has a button A. When I press this button and hold it for 2 seconds, its value becomes 0 and the color turns either blue or green, when I release, its value goes back to 1 but the color stays the same unless it was clicked again and the color changes. The problem is, it shouldn't take someone 2 whole seconds to have to change the led light. What can I do to make the value (either 0 or 1) be read faster?

Here is a snippet of the code in the while loop.

// here are the states for reference. Everything is either a 0 or a 1
const int BUTTON_PRESSED = 0;
const int BUTTON_UNPRESSED = 1;

const int GREEN_LED = 0;
const int BLUE_LED = 1;

    const struct timespec sleepTime = { 1, 0 };

    while (true) {
        Value_Type value;
        // this function get the input of button a when pressed
        GetValue(button_A_fd, &value);
        Log_Debug(
           "Button value (%d)\n", value);

        // Processing the button.

        //Turns LED ON; Button not pressed down
        if (value == BUTTON_UNPRESSED) {
            last_button_state = BUTTON_UNPRESSED;
        } else {

            // if last button state is 1 then now it is being pressed
            if (last_button_state == BUTTON_UNPRESSED) {
                // Flip LEDs
                if (active_led == BLUE_LED) {
                    active_led = GREEN_LED;
                }
                else if (active_led == GREEN_LED) {
                    active_led = BLUE_LED;
                }

                last_button_state = BUTTON_PRESSED;
                // sets the pointer to the 0 bit of the file to write
                lseek(fd_storage, 0, SEEK_SET);
                // write current active led to mutable storage and save
                write(fd_storage, &active_led, sizeof(active_led));
            }
        }
        // Blinking the active LED.
        // reading input only when pressed and turn off other led
        if (active_led == GREEN_LED) {
            // turn off blue led, then turn on green
            SetValue(blue_led_fd, Value_High);
            SetValue(green_led_fd, Value_Low);
            nanosleep(&sleepTime, NULL);
            SetValue(green_led_fd, Value_High);
            nanosleep(&sleepTime, NULL);
        }
        else if (active_led == BLUE_LED) {
            // turn off green led, then turn on blue
            SetValue(green_led_fd, Value_High);
            SetValue(blue_led_fd, Value_Low);
            nanosleep(&sleepTime, NULL);
            SetValue(blue_led_fd, Value_High);
            nanosleep(&sleepTime, NULL);
        }
    }
}

I tried to put GetValue() in several parts of the code to see if it could maybe get a value faster but it did not work. How can I move from here? I hope I shared enough code to understand the problem. Thank you.


问:
Web Scraping Table into Pandas Dataframe
I'm a beginner when it comes to using Pandas. But I want to take the table of G-Sync Gaming Monitors in Nvidia's website here: https://www.nvidia.com/en-us/geforce/products/g-sync-monitors/specs/ and convert that to a data frame in Pandas for Python.

The first thing I tried to do was

```<code>import pandas as pd
df = pd.read_html('https://www.nvidia.com/en-us/geforce/products/g-sync-monitors/specs/')
</code>```

but that didn't seem to work. I got a ValueError: No tables found.

Then I tried to do

```<code>import requests
import lxml.html as lh
page = requests.get('https://www.nvidia.com/en-us/geforce/products/g-sync-monitors/specs/')
</code>```

but somehow I got ContentDecodingError: ('Received response with content-encoding: gzip, but failed to decode it.', error('Error -3 while decompressing data: incorrect header check')).

If someone could explain why the first two ways didn't work and how to actually get the table into a data frame, that would be very helpful. Thank you!

答:
The data is loaded dynamically via json request.

This script loads the json data into a dataframe and prints it:

```<code>import re
import json
import pandas as pd

url = 'https://www.nvidia.com/en-us/geforce/products/g-sync-monitors/specs/'
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0'}

html_txt = requests.get(url, headers=headers).text

json_url =  'https://www.nvidia.com' + re.search(r"'url': '(.*?)'", html_txt).group(1)

data = requests.get(json_url, headers=headers).json()

# uncomment this to print all data:
# print(json.dumps(data, indent=4))

def fn(x):
    out = []
    for v in x:
        if isinstance(v, dict):
            out.append(v['en'])
        else:
            out.append(v)
    return out

df = pd.json_normalize(data['data'], max_level=0).apply(fn)
print(df)
</code>```

Prints:

```<code>                  type manufacturer      model  hdr     size lcd type        resolution variable refresh rate range variable overdrive variable refresh input    driver needed
0      G-SYNC ULTIMATE         Acer    CP7271K  Yes       27      IPS    3840x2160 (4K)                     1-144Hz                Yes           Display Port              N/A
1      G-SYNC ULTIMATE         Acer        X27  Yes       27      IPS    3840x2160 (4K)                     1-144Hz                Yes           Display Port              N/A
2      G-SYNC ULTIMATE         Acer        X32  Yes       32      IPS    3840x2160 (4K)                     1-144Hz                Yes           Display Port              N/A
3      G-SYNC ULTIMATE         Acer        X35  Yes       35       VA  3440x1440 (WQHD)                     1-200Hz                Yes           Display Port              N/A
4      G-SYNC ULTIMATE         Asus       PG65  Yes       65       VA    3840x2160 (4K)                     1-144Hz                Yes           Display Port              N/A
..                 ...          ...        ...  ...      ...      ...               ...                         ...                ...                    ...              ...
159  G-SYNC Compatible           LG    2020 ZX  Yes   77, 88     OLED    7680x4320 (8K)                    40-120Hz                 No                   HDMI  445.51 or newer
160  G-SYNC Compatible          MSI   MAG251RX  Yes     24.5      IPS   1920x1080 (FHD)                    48-240Hz                 No           Display Port  441.66 or newer
161  G-SYNC Compatible        Razer  Raptor 27  Yes       27      IPS   2560x1440 (QHD)                    48-144Hz                 No           Display Port  431.60 or newer
162  G-SYNC Compatible      Samsung       CRG5   No       27       VA   1920x1080 (FHD)                    48-240Hz                 No           Display Port  430.86 or newer
163  G-SYNC Compatible    ViewSonic      XG270   No       27      IPS   1920x1080 (FHD)                    48-240Hz                 No           Display Port  441.41 or newer

[164 rows x 11 columns]
</code>```

Body:
I'm a beginner when it comes to using Pandas. But I want to take the table of G-Sync Gaming Monitors in Nvidia's website here: https://www.nvidia.com/en-us/geforce/products/g-sync-monitors/specs/ and convert that to a data frame in Pandas for Python.

The first thing I tried to do was

import pandas as pd
df = pd.read_html('https://www.nvidia.com/en-us/geforce/products/g-sync-monitors/specs/')

but that didn't seem to work. I got a ValueError: No tables found.

Then I tried to do

import requests
import lxml.html as lh
page = requests.get('https://www.nvidia.com/en-us/geforce/products/g-sync-monitors/specs/')

but somehow I got ContentDecodingError: ('Received response with content-encoding: gzip, but failed to decode it.', error('Error -3 while decompressing data: incorrect header check')).

If someone could explain why the first two ways didn't work and how to actually get the table into a data frame, that would be very helpful. Thank you!

Body:
The data is loaded dynamically via json request.

This script loads the json data into a dataframe and prints it:

import re
import json
import pandas as pd

url = 'https://www.nvidia.com/en-us/geforce/products/g-sync-monitors/specs/'
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0'}

html_txt = requests.get(url, headers=headers).text

json_url =  'https://www.nvidia.com' + re.search(r"'url': '(.*?)'", html_txt).group(1)

data = requests.get(json_url, headers=headers).json()

# uncomment this to print all data:
# print(json.dumps(data, indent=4))

def fn(x):
    out = []
    for v in x:
        if isinstance(v, dict):
            out.append(v['en'])
        else:
            out.append(v)
    return out

df = pd.json_normalize(data['data'], max_level=0).apply(fn)
print(df)

Prints:

                  type manufacturer      model  hdr     size lcd type        resolution variable refresh rate range variable overdrive variable refresh input    driver needed
0      G-SYNC ULTIMATE         Acer    CP7271K  Yes       27      IPS    3840x2160 (4K)                     1-144Hz                Yes           Display Port              N/A
1      G-SYNC ULTIMATE         Acer        X27  Yes       27      IPS    3840x2160 (4K)                     1-144Hz                Yes           Display Port              N/A
2      G-SYNC ULTIMATE         Acer        X32  Yes       32      IPS    3840x2160 (4K)                     1-144Hz                Yes           Display Port              N/A
3      G-SYNC ULTIMATE         Acer        X35  Yes       35       VA  3440x1440 (WQHD)                     1-200Hz                Yes           Display Port              N/A
4      G-SYNC ULTIMATE         Asus       PG65  Yes       65       VA    3840x2160 (4K)                     1-144Hz                Yes           Display Port              N/A
..                 ...          ...        ...  ...      ...      ...               ...                         ...                ...                    ...              ...
159  G-SYNC Compatible           LG    2020 ZX  Yes   77, 88     OLED    7680x4320 (8K)                    40-120Hz                 No                   HDMI  445.51 or newer
160  G-SYNC Compatible          MSI   MAG251RX  Yes     24.5      IPS   1920x1080 (FHD)                    48-240Hz                 No           Display Port  441.66 or newer
161  G-SYNC Compatible        Razer  Raptor 27  Yes       27      IPS   2560x1440 (QHD)                    48-144Hz                 No           Display Port  431.60 or newer
162  G-SYNC Compatible      Samsung       CRG5   No       27       VA   1920x1080 (FHD)                    48-240Hz                 No           Display Port  430.86 or newer
163  G-SYNC Compatible    ViewSonic      XG270   No       27      IPS   1920x1080 (FHD)                    48-240Hz                 No           Display Port  441.41 or newer

[164 rows x 11 columns]


问:
Google sheets, script to set multiple hyperlinks in one cell
My goal is to create a spreadsheet cell that has multiple hyperlinks from a Google script.

I can create a cell with multiple links selecting part of the cell text and then using Ctrl + K or the menu insert link. My cell had google and yahoo as an example, with two hyperlinks, one to each search engine.

I can read the hyperlinks in this cell in two different ways:

```<code> var range = SpreadsheetApp.getActiveSheet().getRange('A1');
 var richText = range.getRichTextValue();
 var allRuns = richText.getRuns();
 var firstLink = allRuns[0].getLinkUrl();
 var secondLink = allRuns[2].getLinkUrl();
 var gLink = richText.getLinkUrl(0, 5);
 var aLink = richText.getLinkUrl(11, 15);
</code>```

But there is no setLinkUrl method available. I couldn't find anything in the Google sheets API either.

I copied this cell and using xclip in Linux, the command

```<code>xclip -selection clipboard -o  -t text/html
</code>```

The result is

```<code><meta http-equiv="content-type" content="text/html; charset=utf-8">
<style type="text/css">
<!--
td {
    border: 1px solid #ccc;
}

br {
    mso-data-placement: same-cell;
}
-->
</style>
<span style="font-size: 10pt; font-family: Arial; font-style: normal;"
    data-sheets-value="{"1":2,"2":"google and yahoo"}"
    data-sheets-userformat="{"2":1049089,"3":{"1":0},"12":0,"23":1}"
    data-sheets-textstyleruns="{"1":0,"2":{"2":{"1":2,"2":1136076},"9":1}}{"1":6}{"1":11,"2":{"2":{"1":2,"2":1136076},"9":1}}"
    data-sheets-hyperlinkruns="{"1":0,"2":"https://www.google.com/"}{"1":6}{"1":11,"2":"https://www.yahoo.com/"}{"1":16}"><span
    style="font-size: 10pt; font-family: Arial; font-style: normal; text-decoration: underline; -webkit-text-decoration-skip: none; text-decoration-skip-ink: none; color: #1155cc;"><a
        class="in-cell-link" target="_blank" href="https://www.google.com/">google</a></span><span
    style="font-size: 10pt; font-family: Arial; font-style: normal;">
        and </span><span
    style="font-size: 10pt; font-family: Arial; font-style: normal; text-decoration: underline; -webkit-text-decoration-skip: none; text-decoration-skip-ink: none; color: #1155cc;"><a
        class="in-cell-link" target="_blank" href="https://www.yahoo.com/">yahoo</a></span></span>
</code>```

I'm not sure if this means that hyperlinks have their own runs, independent form text style runs? Any pointers are appreciated.

答:
```<code>function addMultipleUrlsToCell() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Sheet2');
  sh.getRange('A1').setValue('');
  var RichTextValue=SpreadsheetApp.newRichTextValue()
  .setText("Google,GASReference,SO")
  .setLinkUrl(0,6,"https://google.com/")
  .setLinkUrl(7,19,"https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet-app/")
  .setLinkUrl(20,22,"https://stackoverflow.com")
  .build();
  sh.getRange("A1").setRichTextValue(RichTextValue);
}

function retrieveMultipleUrls() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getSheetByName('Sheet2');
  const rg=sh.getRange(1,1);
  var rtv=rg.getRichTextValue().getRuns();
  var res=rtv.reduce(function(ar,e){
    var url=e.getLinkUrl();
    if(url)ar.push(url);
    return ar;
  },[]);
  console.log(res);
}
</code>```

Reference

Body:
My goal is to create a spreadsheet cell that has multiple hyperlinks from a Google script.

I can create a cell with multiple links selecting part of the cell text and then using Ctrl + K or the menu insert link. My cell had google and yahoo as an example, with two hyperlinks, one to each search engine.

I can read the hyperlinks in this cell in two different ways:

 var range = SpreadsheetApp.getActiveSheet().getRange('A1');
 var richText = range.getRichTextValue();
 var allRuns = richText.getRuns();
 var firstLink = allRuns[0].getLinkUrl();
 var secondLink = allRuns[2].getLinkUrl();
 var gLink = richText.getLinkUrl(0, 5);
 var aLink = richText.getLinkUrl(11, 15);

But there is no setLinkUrl method available. I couldn't find anything in the Google sheets API either.

I copied this cell and using xclip in Linux, the command

xclip -selection clipboard -o  -t text/html

The result is

<meta http-equiv="content-type" content="text/html; charset=utf-8">

<span style="font-size: 10pt; font-family: Arial; font-style: normal;"
    data-sheets-value="{"1":2,"2":"google and yahoo"}"
    data-sheets-userformat="{"2":1049089,"3":{"1":0},"12":0,"23":1}"
    data-sheets-textstyleruns="{"1":0,"2":{"2":{"1":2,"2":1136076},"9":1}}{"1":6}{"1":11,"2":{"2":{"1":2,"2":1136076},"9":1}}"
    data-sheets-hyperlinkruns="{"1":0,"2":"https://www.google.com/"}{"1":6}{"1":11,"2":"https://www.yahoo.com/"}{"1":16}">google
        and yahoo

I'm not sure if this means that hyperlinks have their own runs, independent form text style runs? Any pointers are appreciated.

Body:
function addMultipleUrlsToCell() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Sheet2');
  sh.getRange('A1').setValue('');
  var RichTextValue=SpreadsheetApp.newRichTextValue()
  .setText("Google,GASReference,SO")
  .setLinkUrl(0,6,"https://google.com/")
  .setLinkUrl(7,19,"https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet-app/")
  .setLinkUrl(20,22,"https://stackoverflow.com")
  .build();
  sh.getRange("A1").setRichTextValue(RichTextValue);
}

function retrieveMultipleUrls() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getSheetByName('Sheet2');
  const rg=sh.getRange(1,1);
  var rtv=rg.getRichTextValue().getRuns();
  var res=rtv.reduce(function(ar,e){
    var url=e.getLinkUrl();
    if(url)ar.push(url);
    return ar;
  },[]);
  console.log(res);
}

Reference


答:
Learn to love the Javascript console.  The console.log method covers almost every eventuality -- giving you a nicely formatted summary of the object (or array, string, number, or boolean) that you're concerned with.

```<code>console.log(parent);
</code>```

You can see the log by a console built into your browser (e.g. Chrome console, the Firefox 4 web console, IE developer tools) or by using a plugin (e.g. Firebug for Firefox <4).

Title: jquery how to figure out what the JSON Object contains

Body:
Learn to love the Javascript console.  The console.log method covers almost every eventuality -- giving you a nicely formatted summary of the object (or array, string, number, or boolean) that you're concerned with.

console.log(parent);

You can see the log by a console built into your browser (e.g. Chrome console, the Firefox 4 web console, IE developer tools) or by using a plugin (e.g. Firebug for Firefox <4).


问:
adding custom header in JSON
I am trying to put Custom Header in my JSON file. Below are the header that the service provider is asking me

Accept:application/json
Content-Type:application/json
hmac-signature:

Below is my partial  code tin include the custom header:

```<code>  var httpRequestMessage = new HttpRequestMessage
            {
                Method = HttpMethod.Post,
                RequestUri = new Uri("http://testingwebsite"),
                Headers = {
                            { HttpRequestHeader.Authorization.ToString(), SHA1Key },
                            { HttpRequestHeader.Accept.ToString(), "application/json" }

                        }
</code>```

when I tried to add the below line, I got an exception misused header name

```<code> { HttpRequestHeader.ContentType.ToString(), "application/json" }
</code>```

any help will be apprecaited.

答:
I don't think using .ToString() on those Types is the right way to go. For example, ContentType.ToString() is likely "ContentType". That is just not a valid http header. I'd trying just using the string "Content-Type".</p>

```<code>    { "Content-Type", "application/json" }
</code>```

Title: adding custom header in JSON

Body:
I am trying to put Custom Header in my JSON file. Below are the header that the service provider is asking me

Accept:application/json
Content-Type:application/json
hmac-signature:

Below is my partial  code tin include the custom header:

  var httpRequestMessage = new HttpRequestMessage
            {
                Method = HttpMethod.Post,
                RequestUri = new Uri("http://testingwebsite"),
                Headers = {
                            { HttpRequestHeader.Authorization.ToString(), SHA1Key },
                            { HttpRequestHeader.Accept.ToString(), "application/json" }

                        }

when I tried to add the below line, I got an exception misused header name

 { HttpRequestHeader.ContentType.ToString(), "application/json" }

any help will be apprecaited.

Body:
I don't think using .ToString() on those Types is the right way to go. For example, ContentType.ToString() is likely "ContentType". That is just not a valid http header. I'd trying just using the string "Content-Type".

    { "Content-Type", "application/json" }


问:
How to get bitset OR with different bitset sizes
When I use,

```<code>  std::bitset<5> op1 (std::string("01001"));
  std::bitset<5> op2 (std::string("10011"));

  std::cout << (op1|=op2) << std::endl;
</code>```

everything is fine obviously.

But my question is, how can I use OR operation using two different sized 'std::bitset's?
Such as,

```<code>  std::bitset<11> op1 (std::string("101110011"));
  std::bitset<5> op2 (std::string("01001"));

  std::cout << (op1|=op2) << std::endl;
</code>```

I can't compile this code in VS 2012. What have I missed here? Can't I use different sized bitsets for OR operations (and XOR as well)? Is this a platform specific problem?

答:
```<code>using namespace std;

template <size_t startN, size_t endN>
bitset<endN> convert(bitset<startN> start)
{
    const size_t minBits = (startN < endN) ? startN : endN;
    const size_t min64Bits = (minBits - 1) / 64 + 1;
    bitset<endN> result;
    for (size_t n = 0; n < min64Bits; n++)
    {
        result <<= 64;
        result |= start.to_ullong();
        start >>= 64;
    }
    return result;
}

int main()
{
    std::bitset<11> op1 (std::string("101110011"));
    std::bitset<5> op2 (std::string("01001"));
    std::cout << (op1|=convert<5, 11>(op2));
}
</code>```

You could use this function to convert if you may have more than 64 bits in your bitsets.

Body:
When I use,

  std::bitset<5> op1 (std::string("01001"));
  std::bitset<5> op2 (std::string("10011"));

  std::cout << (op1|=op2) << std::endl;

everything is fine obviously.

But my question is, how can I use OR operation using two different sized 'std::bitset's?
Such as,

  std::bitset<11> op1 (std::string("101110011"));
  std::bitset<5> op2 (std::string("01001"));

  std::cout << (op1|=op2) << std::endl;

I can't compile this code in VS 2012. What have I missed here? Can't I use different sized bitsets for OR operations (and XOR as well)? Is this a platform specific problem?

Body:
using namespace std;

template <size_t startN, size_t endN>
bitset<endN> convert(bitset<startN> start)
{
    const size_t minBits = (startN < endN) ? startN : endN;
    const size_t min64Bits = (minBits - 1) / 64 + 1;
    bitset<endN> result;
    for (size_t n = 0; n < min64Bits; n++)
    {
        result <<= 64;
        result |= start.to_ullong();
        start >>= 64;
    }
    return result;
}

int main()
{
    std::bitset<11> op1 (std::string("101110011"));
    std::bitset<5> op2 (std::string("01001"));
    std::cout << (op1|=convert<5, 11>(op2));
}

You could use this function to convert if you may have more than 64 bits in your bitsets.


问:
Sequence of numbers, loop does not work with the chosen input
I have to print the same number of times that I enter (var number) example: if I put 21 it has to give me 21 numbers to print.

Currently if I put 20 it gives me exactly 20 (all good) but if I put 21 it gives me 3 more not 1 (which is what it should give me) if I put 23 it doesn't give me anything.

1º = 10
2º = 8

3º Sum of the 2 previous elements: (10 + 8 = 18)

4º The element twice before (8) is multiplied by 3 and divided by 2 and the whole part is taken: (8 * 3/2 = 12)

5º The element 2 times before is divided by 2 and the whole part is taken. (2/18 = 9)

and the process is repeated from the 3rd element.
y se vuelve a repetir el proceso desde el elemento 3º.
This is an image of the solved exercise

What i have

```<code>for(i = 1; i <= numero/3; i++){
            zenb3 = parseInt(zenb1+zenb2);
            txt = txt + zenb3 + " ; ";
      zenb4 = parseInt((zenb2*3)/2);
            txt = txt + zenb4 + " ; ";
      zenb5 = parseInt(zenb3/2);
            txt = txt + zenb5 + " ; ";
            zenb1 = zenb4;
      zenb2 = zenb5;

        }
</code>```

Complete code

     <!DOCTYPE html>

          <meta http-equiv="content-type" content="text/html;charset=utf-8">
          <title>Serie</title>

Serie

          <fieldset>
            <legend>Serie</legend>
          <form action="" method="get" name="finfo">

Ingrese el numero de elementos:

<input type="text" id="zenbakia" name="tope" size="10" maxlength="50">
                    <input type="button" value="Erakutsi" onclick="creaMensaje()"/>
                    <input type="reset" value="Garbitu" onclick="iniciar()"/>

          </form>
        </fieldset>

        ```

答:
I made an adaptation in your code and explained the problem in the comments:

function creaMensaje() {

        var txt = "";
        // var zenb1 = 10;
        // var zenb2 = 8;
        var zenbs = [10, 8]
        var numero = document.getElementById("zenbakia").value;

        if (numero != parseInt(numero)){
            txt = "Debe ser un numero entre 20 y 40";
        }else if (numero < 20 || numero > 40 ){
            txt = "Debe ser un numero entre 20 y 40";
        }else{

            txt = zenbs[0] + " ; " + zenbs[1] + " ; " ;

            for(let i = 2; i < numero; i++) {
               if((i + 1) % 3 == 0) {
                   zenbs[i] = zenbs[i - 1] + zenbs[i - 2]
               }
               else if((i + 1) % 3 == 1) {
                   zenbs[i] = Math.floor(zenbs[i - 2] * 3/2)
               }
               else if((i + 1) % 3 == 2) {
                   zenbs[i] = Math.floor(zenbs[i - 2]/2)
               }

               txt += zenbs[i] + ' ; '

            }

        }

        document.getElementById("mensaje").innerHTML = txt;
    }

    function iniciar()
    {
        document.getElementById("mensaje").innerHTML ='';

    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Serie</h1>
      <fieldset>
        <legend>Serie</legend>
      <form action="" method="get" name="finfo">
        <table>
            <tr><td><label>Ingrese el numero de elementos:</label></td></tr>
            <tr><td><input type="text" id="zenbakia" name="tope" size="10" maxlength="50">
                <input type="button" value="Erakutsi" onclick="creaMensaje()"/>
                <input type="reset" value="Garbitu" onclick="iniciar()"/></td>
            </tr>
        </table>

      </form>
    </fieldset>

      <p id="mensaje"></p></code>```

Summing up:

I removed the two initial variables (zenb1 and zenb2) and created an array with these two values (zenbs), then redid its loop, basically it starts from the number 2 to create numbers that are the sum of the previous 2 and then it add this new number to the txt variable

Body:
I have to print the same number of times that I enter (var number) example: if I put 21 it has to give me 21 numbers to print.

Currently if I put 20 it gives me exactly 20 (all good) but if I put 21 it gives me 3 more not 1 (which is what it should give me) if I put 23 it doesn't give me anything.

1º = 10
2º = 8

3º Sum of the 2 previous elements: (10 + 8 = 18)

4º The element twice before (8) is multiplied by 3 and divided by 2 and the whole part is taken: (8 * 3/2 = 12)

5º The element 2 times before is divided by 2 and the whole part is taken. (2/18 = 9)

and the process is repeated from the 3rd element.
y se vuelve a repetir el proceso desde el elemento 3º.
This is an image of the solved exercise

What i have

for(i = 1; i <= numero/3; i++){
            zenb3 = parseInt(zenb1+zenb2);
            txt = txt + zenb3 + " ; ";
      zenb4 = parseInt((zenb2*3)/2);
            txt = txt + zenb4 + " ; ";
      zenb5 = parseInt(zenb3/2);
            txt = txt + zenb5 + " ; ";
            zenb1 = zenb4;
      zenb2 = zenb5;

        }

Complete code

     <!DOCTYPE html>

          <meta http-equiv="content-type" content="text/html;charset=utf-8">
          <title>Serie</title>

Serie

          <fieldset>
            <legend>Serie</legend>
          <form action="" method="get" name="finfo">

Ingrese el numero de elementos:

<input type="text" id="zenbakia" name="tope" size="10" maxlength="50">
                    <input type="button" value="Erakutsi" onclick="creaMensaje()"/>
                    <input type="reset" value="Garbitu" onclick="iniciar()"/>

          </form>
        </fieldset>

Body:
I made an adaptation in your code and explained the problem in the comments:

function creaMensaje() {

        var txt = "";
        // var zenb1 = 10;
        // var zenb2 = 8;
        var zenbs = [10, 8]
        var numero = document.getElementById("zenbakia").value;

        if (numero != parseInt(numero)){
            txt = "Debe ser un numero entre 20 y 40";
        }else if (numero < 20 || numero > 40 ){
            txt = "Debe ser un numero entre 20 y 40";
        }else{

            txt = zenbs[0] + " ; " + zenbs[1] + " ; " ;

            for(let i = 2; i < numero; i++) {
               if((i + 1) % 3 == 0) {
                   zenbs[i] = zenbs[i - 1] + zenbs[i - 2]
               }
               else if((i + 1) % 3 == 1) {
                   zenbs[i] = Math.floor(zenbs[i - 2] * 3/2)
               }
               else if((i + 1) % 3 == 2) {
                   zenbs[i] = Math.floor(zenbs[i - 2]/2)
               }

               txt += zenbs[i] + ' ; '

            }

        }

        document.getElementById("mensaje").innerHTML = txt;
    }

    function iniciar()
    {
        document.getElementById("mensaje").innerHTML ='';

    }

<h1>Serie</h1>
      <fieldset>
        <legend>Serie</legend>
      <form action="" method="get" name="finfo">
        <table>
            <tr><td><label>Ingrese el numero de elementos:</label></td></tr>
            <tr><td><input type="text" id="zenbakia" name="tope" size="10" maxlength="50">
                <input type="button" value="Erakutsi" onclick="creaMensaje()"/>
                <input type="reset" value="Garbitu" onclick="iniciar()"/></td>
            </tr>
        </table>

      </form>
    </fieldset>

      <p id="mensaje"></p>

Summing up:

I removed the two initial variables (zenb1 and zenb2) and created an array with these two values (zenbs), then redid its loop, basically it starts from the number 2 to create numbers that are the sum of the previous 2 and then it add this new number to the txt variable


问:
Can I use Firebase Free Spark Plan for Commercial Use?
Can I use Firebase Free Spark Plan for Commercial Use as long as it works for me? If I earn like $25 a month via ads on my website, can I use the Free Spark Plan?</p>

答: Currently there is no restriction. </p>

Body: Currently there is no restriction.


问:
Twitter Bootstrap Tooltip: flickers when placed on top of button, but works fine when placed at the left/right/bottom
I am dealing with some weird behavior for an instance of bootstrap's tooltip.

The page I am working with has several buttons that, when hovered over, display tooltips with the description for the buttons' functionality. The tooltips are all displayed on top of the buttons, and, with the exception of one button, everything works fine. This one button displays the tooltip with a continuous flickering, the tooltip itself covers part of the button (instead of being completely on top of the button), and prevents the button from being properly clicked. If the "data-placement" for the tooltip is changed from "top" to "left"/"right"/"bottom", the tooltip is displayed correctly.

Additionally, the button that gives me problems is wrapped in a div that has "float: right;" assigned in the css. I am mentioning this because I noticed that if I remove the float, the tooltip works fine. Unfortunately, if I remove the float, the button itself loses its correct positioning.

While I could give up the "top" positioning for the tooltip, I was hoping that there might be an easy trick to this problem. Does anyone have any suggestions?

Thank you.

Update:

This StackOverflow question presents the same problem as the one I was encountering. I found the answer useful.

答:
Read The Docs

The docs on Bootstrap 4 explicitly address this issue and also provide a solution:

Overflow auto and scroll

Tooltip position attempts to automatically change when a parent container has overflow: auto or overflow: scroll like our .table-responsive, but still keeps the original placement’s positioning. To resolve, set the boundary option to anything other than default value, 'scrollParent', such as 'window':

$('#example').tooltip({ boundary: 'window' })

So we have to set the boundary option to 'window'.

From the docs on the boundary option:

Overflow constraint boundary of the tooltip. Accepts the values of 'viewport', 'window', 'scrollParent', or an HTMLElement reference (JavaScript only). For more information refer to Popper.js's preventOverflow docs.

Best Practice

That being said, the preferred way of initializing tooltips everywhere is to use '[data-toggle="tooltip"]' as selector:

```<code>$('[data-toggle="tooltip"]').tooltip({ boundary: 'window' })
</code>```

Once And For All

Now if you are dynamically adding or removing elements (with tooltips) to the DOM or are even replacing the whole page without reloading it (i.e. by using a pushState library like PJAX) - or if you are just using modals (with tooltips) - you have to initialize those tooltips (again).

Fixing Tooltips On Elements

That's where the following function comes in handy, which destroys and recreates all tooltips. Call this function after you've added / removed an element to / from the DOM that has / had a tooltip attached.

```<code>function recreateTooltips() {
    $('[data-toggle="tooltip"]').tooltip('dispose').tooltip({boundary: 'window'});
}
</code>```

This might seem expensive (and certainly is), but I've never noticed any performance impact even with dozens of tooltips on the same page.

Fixing Tooltips In Modals

To fix tooltips in modals, you simply bind the function from above to the 'shown.bs.modal' event, which fires after a modal is fully shown to the user.

```<code>/** Recreate tooltips upon showing modal */
$(document).on('shown.bs.modal', '*', function () {
    recreateTooltips();
});
</code>```

Body:
Read The Docs

The docs on Bootstrap 4 explicitly address this issue and also provide a solution:

Overflow auto and scroll

Tooltip position attempts to automatically change when a parent container has overflow: auto or overflow: scroll like our .table-responsive, but still keeps the original placement’s positioning. To resolve, set the boundary option to anything other than default value, 'scrollParent', such as 'window':

$('#example').tooltip({ boundary: 'window' })

So we have to set the boundary option to 'window'.

From the docs on the boundary option:

Overflow constraint boundary of the tooltip. Accepts the values of 'viewport', 'window', 'scrollParent', or an HTMLElement reference (JavaScript only). For more information refer to Popper.js's preventOverflow docs.

Best Practice

That being said, the preferred way of initializing tooltips everywhere is to use '[data-toggle="tooltip"]' as selector:

$('[data-toggle="tooltip"]').tooltip({ boundary: 'window' })

Once And For All

Now if you are dynamically adding or removing elements (with tooltips) to the DOM or are even replacing the whole page without reloading it (i.e. by using a pushState library like PJAX) - or if you are just using modals (with tooltips) - you have to initialize those tooltips (again).

Fixing Tooltips On Elements

That's where the following function comes in handy, which destroys and recreates all tooltips. Call this function after you've added / removed an element to / from the DOM that has / had a tooltip attached.

function recreateTooltips() {
    $('[data-toggle="tooltip"]').tooltip('dispose').tooltip({boundary: 'window'});
}

This might seem expensive (and certainly is), but I've never noticed any performance impact even with dozens of tooltips on the same page.

Fixing Tooltips In Modals

To fix tooltips in modals, you simply bind the function from above to the 'shown.bs.modal' event, which fires after a modal is fully shown to the user.

/** Recreate tooltips upon showing modal */
$(document).on('shown.bs.modal', '*', function () {
    recreateTooltips();
});


问:
what's wrong in where condition statement
```<code>SqlConnection con =
   new SqlConnection
     (@"Data Source=SAMA-PC\SQLEXPRESS;Initial Catalog=advCenter;
          Integrated Security=True");
SqlCommand com1 = new SqlCommand(
     "select visited_link
      from links
      where [user_email]=@ue and [visited_link]=@vl",con);
com1.Parameters.AddWithValue("@ue",Convert.ToString(Session["mail"]));
com1.Parameters.AddWithValue("@vl", ImageButton1.ID);
con.Open();
SqlDataReader dr;
dr = com1.ExecuteReader();
if (dr.HasRows)
{
    Label2.Text = "wrong";
}
</code>```

答:
I guess you can try

```<code>command.Parameters.Add("@ue", SqlDbType.NText)
command.Parameters("@ue").Value = Convert.ToString(Session["mail"]);
</code>```

to explicitly specify the column data type.

Body:
I guess you can try

command.Parameters.Add("@ue", SqlDbType.NText)
command.Parameters("@ue").Value = Convert.ToString(Session["mail"]);

to explicitly specify the column data type.


问:
How to avoid initializing a Hibernate proxy when only the entity id is needed
For a @ManyToOne relation in JPA entity I'm only interested in the actual id reference, not to fetch the whole model associated with the relation.

Take for example these Kotlin JPA entities:

```<code>@Entity
class Continent(
        @Id
        var id: String,
        var code: String,
        var name: String
) : Comparable<Continent> {

    companion object {
        private val COMPARATOR = compareBy<Continent> { it.id }
    }

    override fun compareTo(other: Continent): Int {
        return COMPARATOR.compare(this, other)
    }
}

@Entity
class Country(
        @Id
        var id: String,
        var alpha2Code: String,
        var alpha3Code: String,
        var name: String,
        @ManyToOne(fetch = FetchType.LAZY)
        @JoinColumn(name = "continent_id")
        var continent: Continent

) : Comparable<Country> {

    companion object {
        private val COMPARATOR = compareBy<Country> { it.id }
    }

    override fun compareTo(other: Country): Int {
        return COMPARATOR.compare(this, other)
    }
}
</code>```

Now when I access country.continent.id from my Kotlin code the full Continent is actually queried from the database.
This is overkill as I'm only interested in the Continent.id.

I've tried adding @Access(AccessType.PROPERTY) like:

```<code>@Entity
class Continent(
        @Id
        @Access(AccessType.PROPERTY)
        var id: String,
</code>```

but it doesn't make a difference. The whole Continent is still queried from the database.

I tried the @Access(AccessType.PROPERTY) as it was mentioned in other posts (like Hibernate one-to-one: getId() without fetching entire object), but I already noticed mixed feedback about this.

I'm using Hibernate 5.3.7.Final with Kotlin 1.3.0.

I wonder if 1) the @Access(AccessType.PROPERTY) approach is correct and 2) should this also be working with Kotlin? Maybe the way Kotlin generated the Java code is causing an issue?

UPDATE

I created a simple test project proving the continent is being queried.
https://github.com/marceloverdijk/hibernate-proxy-id

The project contains a simple test retrieving country.continent.id and SQL logging is enabled. From logging can be seen the continent is queried.

UPDATE 2

I've created https://youtrack.jetbrains.net/issue/KT-28525 for this.

答:
As Adrien Dos Reis mentioned, Hibernate requires all classes annotated with @Entity must be open (ie, not final). Instead of having all the tedious work of manually making classes and properties open, just add the all-open plugin to kotlin-maven-plugin as follows:

<plugin>
    <groupId>org.jetbrains.kotlin</groupId>
    <artifactId>kotlin-maven-plugin</artifactId>

    <configuration>
        <args>
            <arg>-Xjsr305=strict</arg>
        </args>

        <compilerPlugins>
            <plugin>all-open</plugin>
            <plugin>jpa</plugin>
        </compilerPlugins>

        <pluginOptions>
            <option>all-open:annotation=javax.persistence.Entity</option>
        </pluginOptions>
    </configuration>

    <dependencies>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-maven-allopen</artifactId>
            <version>${kotlin.version}</version>
        </dependency>

        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-maven-noarg</artifactId>
            <version>${kotlin.version}</version>
        </dependency>
    </dependencies>
</plugin>
```

Notice that option all-open:annotation=javax.persistence.Entity has been added to all-open plugin. This causes all classes annotated with @Entity to be open by default. For detailed information, refer to https://kotlinlang.org/docs/reference/compiler-plugins.html#all-open-compiler-plugin

Body:
For a @ManyToOne relation in JPA entity I'm only interested in the actual id reference, not to fetch the whole model associated with the relation.

Take for example these Kotlin JPA entities:

@Entity
class Continent(
        @Id
        var id: String,
        var code: String,
        var name: String
) : Comparable<Continent> {

    companion object {
        private val COMPARATOR = compareBy<Continent> { it.id }
    }

    override fun compareTo(other: Continent): Int {
        return COMPARATOR.compare(this, other)
    }
}

@Entity
class Country(
        @Id
        var id: String,
        var alpha2Code: String,
        var alpha3Code: String,
        var name: String,
        @ManyToOne(fetch = FetchType.LAZY)
        @JoinColumn(name = "continent_id")
        var continent: Continent

) : Comparable<Country> {

    companion object {
        private val COMPARATOR = compareBy<Country> { it.id }
    }

    override fun compareTo(other: Country): Int {
        return COMPARATOR.compare(this, other)
    }
}

Now when I access country.continent.id from my Kotlin code the full Continent is actually queried from the database.
This is overkill as I'm only interested in the Continent.id.

I've tried adding @Access(AccessType.PROPERTY) like:

@Entity
class Continent(
        @Id
        @Access(AccessType.PROPERTY)
        var id: String,

but it doesn't make a difference. The whole Continent is still queried from the database.

I tried the @Access(AccessType.PROPERTY) as it was mentioned in other posts (like Hibernate one-to-one: getId() without fetching entire object), but I already noticed mixed feedback about this.

I'm using Hibernate 5.3.7.Final with Kotlin 1.3.0.

I wonder if 1) the @Access(AccessType.PROPERTY) approach is correct and 2) should this also be working with Kotlin? Maybe the way Kotlin generated the Java code is causing an issue?

UPDATE

I created a simple test project proving the continent is being queried.
https://github.com/marceloverdijk/hibernate-proxy-id

The project contains a simple test retrieving country.continent.id and SQL logging is enabled. From logging can be seen the continent is queried.

UPDATE 2

I've created https://youtrack.jetbrains.net/issue/KT-28525 for this.

Body:
As Adrien Dos Reis mentioned, Hibernate requires all classes annotated with @Entity must be open (ie, not final). Instead of having all the tedious work of manually making classes and properties open, just add the all-open plugin to kotlin-maven-plugin as follows:

<plugin>
    <groupId>org.jetbrains.kotlin</groupId>
    <artifactId>kotlin-maven-plugin</artifactId>

    <configuration>
        <args>
            <arg>-Xjsr305=strict</arg>
        </args>

        <compilerPlugins>
            <plugin>all-open</plugin>
            <plugin>jpa</plugin>
        </compilerPlugins>

        <pluginOptions>
            <option>all-open:annotation=javax.persistence.Entity</option>
        </pluginOptions>
    </configuration>

    <dependencies>
        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-maven-allopen</artifactId>
            <version>${kotlin.version}</version>
        </dependency>

        <dependency>
            <groupId>org.jetbrains.kotlin</groupId>
            <artifactId>kotlin-maven-noarg</artifactId>
            <version>${kotlin.version}</version>
        </dependency>
    </dependencies>
</plugin>

Notice that option all-open:annotation=javax.persistence.Entity has been added to all-open plugin. This causes all classes annotated with @Entity to be open by default. For detailed information, refer to https://kotlinlang.org/docs/reference/compiler-plugins.html#all-open-compiler-plugin


问:
how to make file path as a global variable in python?
I've been getting this error NameError: name 'filep' is not defined i need to make filep as a file path. but every time i run my code i always get this error.

i need to make the filep as a module variable instead of a parameter as well as menulist.

```<code>import csv

filep= # filepath
menulist = [] #global scope

def menu_List():

    global menulist
    menulist = []  # store items
    try:
        with open(filep) as f:  # read file
            reader = f.readlines()
            next(reader, None) #skip the header

            for row in reader:
                row[2] = int(row[2].strip()) #convert string to int
                row[1] = float(row[1].strip()) #convert string to float
                if row[2] > 100 and row[2] < 200:
                    menulist.append(row)
    except NameError:
        raise ValueError("Variable not set")

    menulist.sort(key=lambda x: x[-1])

menu_List()
</code>```

答:
The answer above (which use args for fliep) is the best solution, but if you determined to not use args:

filep= 'file path you want'# filepath
menulist = [] #global scope

def menu_List():
    global filep #just add one more global will make it work
    global menulist
    menulist = []  # store items
    try:
        with open(filep) as f:  # read file
            reader = f.readlines()
            next(reader, None) #skip the header

            for row in reader:
                row[2] = int(row[2].strip()) #convert string to int
                row[1] = float(row[1].strip()) #convert string to float
                if row[2] > 100 and row[2] < 200:
                    menulist.append(row)
    except NameError:
        raise ValueError("Variable not set")

    menulist.sort(key=lambda x: x[-1])

menu_List()
```

Extra little tip: Try prevent using global var if you can, global var slow down program's speed and eats memory, also sometime causing messy var naming.

Body:
I've been getting this error NameError: name 'filep' is not defined i need to make filep as a file path. but every time i run my code i always get this error.

i need to make the filep as a module variable instead of a parameter as well as menulist.

import csv

filep= # filepath
menulist = [] #global scope

def menu_List():

    global menulist
    menulist = []  # store items
    try:
        with open(filep) as f:  # read file
            reader = f.readlines()
            next(reader, None) #skip the header

            for row in reader:
                row[2] = int(row[2].strip()) #convert string to int
                row[1] = float(row[1].strip()) #convert string to float
                if row[2] > 100 and row[2] < 200:
                    menulist.append(row)
    except NameError:
        raise ValueError("Variable not set")

    menulist.sort(key=lambda x: x[-1])

menu_List()

Body:
The answer above (which use args for fliep) is the best solution, but if you determined to not use args:

filep= 'file path you want'# filepath
menulist = [] #global scope

def menu_List():
    global filep #just add one more global will make it work
    global menulist
    menulist = []  # store items
    try:
        with open(filep) as f:  # read file
            reader = f.readlines()
            next(reader, None) #skip the header

            for row in reader:
                row[2] = int(row[2].strip()) #convert string to int
                row[1] = float(row[1].strip()) #convert string to float
                if row[2] > 100 and row[2] < 200:
                    menulist.append(row)
    except NameError:
        raise ValueError("Variable not set")

    menulist.sort(key=lambda x: x[-1])

menu_List()

Extra little tip: Try prevent using global var if you can, global var slow down program's speed and eats memory, also sometime causing messy var naming.


问:
How to count chars in a word?
Basically i'm trying to write function that takes GGHTTYYYD and returns 2GH2T3YD. Notice that numbers going first. I'm trying to write it in javascrript. How this can be done?
Basically here i s my code:

```<code>let s = 'GGHTTYYYD';

const count = (str) => {
  let hash = {};
  str.split('').forEach((char) => {
    hash[char] = hash[char] ? (hash[char] += 1) : 1;
  });
  return hash
};
</code>```

now i stuck at converting object named hash to string and filter all "1"

答:
Using a JavaScript object as a map, then converting it to a string:</p>

```<code>let inputStr="GGHTTYYYD"

const freqCount = (str) =>{

    const map={};

    //create a frequency map using a Javascript Object
    for(let c of str){
        map[c] = map[c] ? map[c]+1 : 1;
    }

    let outputStr="";

    for(let key in map){
        //add an if so we don't log 1's, print out the frequency
        if(map[key]!==1){outputStr+=map[key];}
        //add the letter no matter what
        outputStr+=key;
    }

    return outputStr;
}

console.log(freqCount(inputStr));
//2GH2T3YD
</code>```

Title: How to count chars in a word?

Body:
Basically i'm trying to write function that takes GGHTTYYYD and returns 2GH2T3YD. Notice that numbers going first. I'm trying to write it in javascrript. How this can be done?
Basically here i s my code:

let s = 'GGHTTYYYD';

const count = (str) => {
  let hash = {};
  str.split('').forEach((char) => {
    hash[char] = hash[char] ? (hash[char] += 1) : 1;
  });
  return hash
};

now i stuck at converting object named hash to string and filter all "1"

Body:
Using a JavaScript object as a map, then converting it to a string:

let inputStr="GGHTTYYYD"

const freqCount = (str) =>{

    const map={};

    //create a frequency map using a Javascript Object
    for(let c of str){
        map[c] = map[c] ? map[c]+1 : 1;
    }

    let outputStr="";

    for(let key in map){
        //add an if so we don't log 1's, print out the frequency
        if(map[key]!==1){outputStr+=map[key];}
        //add the letter no matter what
        outputStr+=key;
    }

    return outputStr;
}

console.log(freqCount(inputStr));
//2GH2T3YD