问:
Is there a way to use JSON to add an internal comment within Jira?
I am working on my company's Jira Service Desk project and we are having some trouble with some of our workflow automation. Currently to move an issue through the workflow from Step 1 (Waiting for support) -> Step 2 (In Progress) a comment is required to be entered by the user after clicking on the "In Progress" button to successfully move the issue to the next step.

This is working as intended but we wanted to utilize an automation rule as well that will automatically transition the issues from Step 1 to Step 2 if a comment added to an issue. The problem occurs due to the workflow validator requiring that a comment be added during the transition for the issue to move to the next status.

The good thing is that our automation plugin (Automation for Jira) does allow you to add JSON configurations to the steps within the rule. For example, I am able to add the JSON to add a comment to the rule during the transition, which is exactly what we want. But the problem here is that the comment is an external comment that is sent to the customer. We would need this comment to be an internal comment so the customer is not sent any unnecessary information when we already have users reaching out to them.

What we are trying to achieve is to have an issue in the “Waiting for Support” status, then when an internal user comments on that issue it is transitioned automatically to the next status (In Progress) using the automation rule. But due to our workflow requirements we are also needing to add an additional internal comment during that transition for the transition to be valid. Our workflow requires us to add a comment during the transition from one status to another before it will allow the status to be changed.

So far I have tried a few different things with the JSON code but I am not familiar at all with JSON and have not been able to get it figured out in how to differentiate between a public/external comment and a private/internal comment. I have gotten it to where the comment is added during the transition and then the automation runs successfully, but the problem is this comment becomes an external comment when we would need it to be internal and visible to only our service desk users.

```<code>   {
        "update": {

        "comment": [
    {
        "add": {
        "body": "Issue issue.key has been transitioned to the In Progress
        status per automation guidelines."

    }

    }
    ]
    }
    }

This is the JSON code that is added at the status transition step that works. Just not 100% the right way. I am trying to somehow figure out a way to have the comment that is added be internal as opposed to external.
</code>```

I was able to use the "Comment on issue" action and mimic my rule plus the additional internal comment with the "comment on issue" action. After exporting the JSON this is what I got:

I was able to create my rule with the "comment on issue" action and leave it as an internal comment. After that I exported the JSON to see what it looked like and this is what I got:

```<code>    "cloud":true,
"rules":[
{
"id":188601,
"clientKey":"jira:12205936",
"name":"Incident Comment Transition ",
"state":"ENABLED",
"description":null,
"canOtherRuleTrigger":false,
"notifyOnError":"FIRSTERROR",
"authorAccountId":"5a328efd101d3439bb11039c",
"actorAccountId":"557058:f58131cb-b67d-43c7-b30d-6b58d40bd077",
"created":1559219471531,
"updated":1559221244585,
"trigger":{
"id":"3628751",
"component":"TRIGGER",
"parentId":null,
"conditionParentId":null,
"schemaVersion":1,
"type":"jira.issue.event.trigger:commented",
"value":{
"synchronous":false,
"eventKey":"jira:issue_updated",
"issueEvent":"issue_commented"
},
"children":[
],
"conditions":[
]
},
"components":[
{
"id":"3628752",
"component":"CONDITION",
"parentId":null,
"conditionParentId":null,
"schemaVersion":1,
"type":"jira.jql.condition",
"value":"assignee != empty and resolution = unresolved and status = \"waiting for support\" and issuetype=\"incident\"",
"children":[
],
"conditions":[
]
},
{
"id":"3628753",
"component":"ACTION",
"parentId":null,
"conditionParentId":null,
"schemaVersion":6,
"type":"jira.issue.transition",
"value":{
"operations":[
],
"advancedFields":"",
"sendNotifications":true,
"useLegacyRendering":false,
"transitionMode":"status",
"destinationStatus":{
"type":"ID",
"value":"3"
},
"transitionMatch":"",
"transition":null,
"ignoreConditions":false
},
"children":[
],
"conditions":[
]
},
{
"id":"3628754",
"component":"ACTION",
"parentId":null,
"conditionParentId":null,
"schemaVersion":1,
"type":"jira.issue.comment",
"value":{
"comment":"Issue {{issue.key}} has been moved to the In Progress status per automation guidelines.",
"publicComment":false,
"commentVisibility":null,
"sendNotifications":true,
"addCommentOnce":true,
"useLegacyRendering":false
},
"children":[
],
"conditions":[
]
}
],
"projects":[
{
"projectId":"10610",
"projectTypeKey":"service_desk"
}
],
"labels":[
]
}
    ]
</code>```

Would you be able to tell me which part of this is the section that will add the internal comment? I was thinking maybe if I could just use that JSON in the "transition issue" step of the rule this may accomplish what I am trying to do.

Thanks!

答:
I'm not sure how to do it with JSON, but you should be able to do it within their GUI.

Within the Comment on issue action, Under More options -> Service Desk you should see a check box for Share with customer.

Ref : Rule Playground

You can just create a dummy rule and export the rule to get the JSON.

PS : Their support is supposed to be very good as well.

Body:
I am working on my company's Jira Service Desk project and we are having some trouble with some of our workflow automation. Currently to move an issue through the workflow from Step 1 (Waiting for support) -> Step 2 (In Progress) a comment is required to be entered by the user after clicking on the "In Progress" button to successfully move the issue to the next step.

This is working as intended but we wanted to utilize an automation rule as well that will automatically transition the issues from Step 1 to Step 2 if a comment added to an issue. The problem occurs due to the workflow validator requiring that a comment be added during the transition for the issue to move to the next status.

The good thing is that our automation plugin (Automation for Jira) does allow you to add JSON configurations to the steps within the rule. For example, I am able to add the JSON to add a comment to the rule during the transition, which is exactly what we want. But the problem here is that the comment is an external comment that is sent to the customer. We would need this comment to be an internal comment so the customer is not sent any unnecessary information when we already have users reaching out to them.

What we are trying to achieve is to have an issue in the “Waiting for Support” status, then when an internal user comments on that issue it is transitioned automatically to the next status (In Progress) using the automation rule. But due to our workflow requirements we are also needing to add an additional internal comment during that transition for the transition to be valid. Our workflow requires us to add a comment during the transition from one status to another before it will allow the status to be changed.

So far I have tried a few different things with the JSON code but I am not familiar at all with JSON and have not been able to get it figured out in how to differentiate between a public/external comment and a private/internal comment. I have gotten it to where the comment is added during the transition and then the automation runs successfully, but the problem is this comment becomes an external comment when we would need it to be internal and visible to only our service desk users.

   {
        "update": {

        "comment": [
    {
        "add": {
        "body": "Issue issue.key has been transitioned to the In Progress
        status per automation guidelines."

    }

    }
    ]
    }
    }

This is the JSON code that is added at the status transition step that works. Just not 100% the right way. I am trying to somehow figure out a way to have the comment that is added be internal as opposed to external.

I was able to use the "Comment on issue" action and mimic my rule plus the additional internal comment with the "comment on issue" action. After exporting the JSON this is what I got:

I was able to create my rule with the "comment on issue" action and leave it as an internal comment. After that I exported the JSON to see what it looked like and this is what I got:

    "cloud":true,
"rules":[
{
"id":188601,
"clientKey":"jira:12205936",
"name":"Incident Comment Transition ",
"state":"ENABLED",
"description":null,
"canOtherRuleTrigger":false,
"notifyOnError":"FIRSTERROR",
"authorAccountId":"5a328efd101d3439bb11039c",
"actorAccountId":"557058:f58131cb-b67d-43c7-b30d-6b58d40bd077",
"created":1559219471531,
"updated":1559221244585,
"trigger":{
"id":"3628751",
"component":"TRIGGER",
"parentId":null,
"conditionParentId":null,
"schemaVersion":1,
"type":"jira.issue.event.trigger:commented",
"value":{
"synchronous":false,
"eventKey":"jira:issue_updated",
"issueEvent":"issue_commented"
},
"children":[
],
"conditions":[
]
},
"components":[
{
"id":"3628752",
"component":"CONDITION",
"parentId":null,
"conditionParentId":null,
"schemaVersion":1,
"type":"jira.jql.condition",
"value":"assignee != empty and resolution = unresolved and status = \"waiting for support\" and issuetype=\"incident\"",
"children":[
],
"conditions":[
]
},
{
"id":"3628753",
"component":"ACTION",
"parentId":null,
"conditionParentId":null,
"schemaVersion":6,
"type":"jira.issue.transition",
"value":{
"operations":[
],
"advancedFields":"",
"sendNotifications":true,
"useLegacyRendering":false,
"transitionMode":"status",
"destinationStatus":{
"type":"ID",
"value":"3"
},
"transitionMatch":"",
"transition":null,
"ignoreConditions":false
},
"children":[
],
"conditions":[
]
},
{
"id":"3628754",
"component":"ACTION",
"parentId":null,
"conditionParentId":null,
"schemaVersion":1,
"type":"jira.issue.comment",
"value":{
"comment":"Issue {{issue.key}} has been moved to the In Progress status per automation guidelines.",
"publicComment":false,
"commentVisibility":null,
"sendNotifications":true,
"addCommentOnce":true,
"useLegacyRendering":false
},
"children":[
],
"conditions":[
]
}
],
"projects":[
{
"projectId":"10610",
"projectTypeKey":"service_desk"
}
],
"labels":[
]
}
    ]

Would you be able to tell me which part of this is the section that will add the internal comment? I was thinking maybe if I could just use that JSON in the "transition issue" step of the rule this may accomplish what I am trying to do.

Thanks!


来源: stackexchange

问:
JavaScript merging objects by id
What's the correct way to merge two arrays in Javascript?

I've got two arrays (for example):

```<code>var a1 = [{ id : 1, name : "test"}, { id : 2, name : "test2"}]
var a2 = [{ id : 1, count : "1"}, {id : 2, count : "2"}]
</code>```

I want to be able to end up with something like:

```<code>var a3 = [{ id : 1, name : "test", count : "1"},
          { id : 2, name : "test2", count : "2"}]
</code>```

Where the two arrays are being joined based on the 'id' field and extra data is simply being added.

I tried to use _.union to do this, but it simply overwrites the values from the second array into the first one

答:
A working TypeScript version:

export default class Merge {
  static byKey(a1: any[], a2: any[], key: string) {
    const res = a1.concat(a2).reduce((acc, x) => {
      acc[x[key]] = Object.assign(acc[x[key]] || {}, x);
      return acc;
    }, {});

    return Object.entries(res).map(pair => {
      const [, value] = pair;
      return value;
    });
  }
}

test("Merge", async () => {
  const a1 = [{ id: "1", value: "1" }, { id: "2", value: "2" }];
  const a2 = [{ id: "2", value: "3" }];

  expect(Merge.byKey(a1, a2, "id")).toStrictEqual([
    {
      id: "1",
      value: "1"
    },
    { id: "2", value: "3" }
  ]);
});

```

ContentLicense: CC BY-SA 3.0

Title: JavaScript merging objects by id

Body:
What's the correct way to merge two arrays in Javascript?

I've got two arrays (for example):

var a1 = [{ id : 1, name : "test"}, { id : 2, name : "test2"}]
var a2 = [{ id : 1, count : "1"}, {id : 2, count : "2"}]

I want to be able to end up with something like:

var a3 = [{ id : 1, name : "test", count : "1"},
          { id : 2, name : "test2", count : "2"}]

Where the two arrays are being joined based on the 'id' field and extra data is simply being added.

I tried to use _.union to do this, but it simply overwrites the values from the second array into the first one

ContentLicense: CC BY-SA 4.0


问:
How do you produce a random 0 or 1 with random.rand
I'm trying to produce a 0 or 1 with numpy's random.rand.

np.random.rand() produces a random float between 0 and 1 but not just a 0 or a 1.

Thank you.

答:
You can use numpy.random.random_integers

```<code>random_int= np.random.random_integers(0,1)
print (random_int)
</code>```

Body:
You can use numpy.random.random_integers

random_int= np.random.random_integers(0,1)
print (random_int)


问:
How can LiveDocx in PHP be used to read .doc & .docx files and read text inside it and save to HTML?
Let's say we have a .doc & .docx files. I want to use LiveDocx in PHP to load the files, read it's content and strip the text from inside it. Then save it to an HTML string.

Can this be done?

I've searched the documentation, and it seams that LiveDocx only loads .doc & .docx template files only!

答:
I think you can use TextControl that improves phpLiveDocx TextControl link

Using this you can also import pdf doc and docx

ContentLicense: CC BY-SA 2.5


问:
Is there a type-safe way to filter out instances of a given variant from a list of objects of a discriminated union type?
I have a bunch of type families that involve mostly shared properties, with each "subtype" adding maybe one or two properties. (Say you're ordering food online, an order item for a pizza lets you add ingredients, other items don't.)

Most of the code doesn't care to distinguish these and just passes the values through, but for presentation I need to handle the subtypes separately.

So I want a function that lets me pluck items of a given variant from an array of objects of the union type. The closest I got is:

```<code>type ThingVariant = "foo" | "bar";

interface IThingBase<TVariant extends ThingVariant> {
    variant: TVariant;
}

interface IFoo extends IThingBase<'foo'> {
    foo: number;
}

interface IBar extends IThingBase<'bar'> {
    bar: number;
}

type Thing = IFoo | IBar;

const things: Thing[] = [
    { variant: 'foo', foo: 1 },
    { variant: 'bar', bar: 2 },
    { variant: 'foo', foo: 1 },
    { variant: 'bar', bar: 2 },
]

function getThingsOfVariant<TVariant extends ThingVariant,
    TThing extends IThingBase<TVariant>&Thing>(variant: TVariant): TThing[] {
    return things.filter((it): it is TThing => it.variant === variant);
}

function getFoos(): IFoo[] {
    return getThingsOfVariant<'foo', IFoo>('foo');
}
</code>```

My problem with the above code is that getThingsOfVariant<'foo', IFoo>('foo') is a rather redundant mouthful. Especially considering TypeScript can handle this type narrowing automatically when using if or switch over a discriminator. Another annoyance is that because of the explicit type guard signature on the predicate to filter(), that part itself bypasses type-checking; i.e. returning true from it would be legal but incorrect.

Is there a way to implement this sort of thing "cleanly", actually leveraging the type checker and ideally type inference?

答:
type Thing = { variant: 'foo', foo: number } | { variant: 'bar', bar: number };

const things: Thing[] = [
    { variant: 'foo', foo: 1 },
    { variant: 'bar', bar: 2 },
    { variant: 'foo', foo: 1 },
    { variant: 'bar', bar: 2 },
];

const foos = things.flatMap(x => x.variant === "foo" ? [x] : []);
```

Body:
I have a bunch of type families that involve mostly shared properties, with each "subtype" adding maybe one or two properties. (Say you're ordering food online, an order item for a pizza lets you add ingredients, other items don't.)

Most of the code doesn't care to distinguish these and just passes the values through, but for presentation I need to handle the subtypes separately.

So I want a function that lets me pluck items of a given variant from an array of objects of the union type. The closest I got is:

type ThingVariant = "foo" | "bar";

interface IThingBase<TVariant extends ThingVariant> {
    variant: TVariant;
}

interface IFoo extends IThingBase<'foo'> {
    foo: number;
}

interface IBar extends IThingBase<'bar'> {
    bar: number;
}

type Thing = IFoo | IBar;

const things: Thing[] = [
    { variant: 'foo', foo: 1 },
    { variant: 'bar', bar: 2 },
    { variant: 'foo', foo: 1 },
    { variant: 'bar', bar: 2 },
]

function getThingsOfVariant<TVariant extends ThingVariant,
    TThing extends IThingBase<TVariant>&Thing>(variant: TVariant): TThing[] {
    return things.filter((it): it is TThing => it.variant === variant);
}

function getFoos(): IFoo[] {
    return getThingsOfVariant<'foo', IFoo>('foo');
}

My problem with the above code is that getThingsOfVariant<'foo', IFoo>('foo') is a rather redundant mouthful. Especially considering TypeScript can handle this type narrowing automatically when using if or switch over a discriminator. Another annoyance is that because of the explicit type guard signature on the predicate to filter(), that part itself bypasses type-checking; i.e. returning true from it would be legal but incorrect.

Is there a way to implement this sort of thing "cleanly", actually leveraging the type checker and ideally type inference?


问:
Linux + Wordpress: how to fired a function from a Linux Cron job?
I created a Linux Cron Job like:

```<code>0 0 * * * home/www/wp-content/themes/my_theme/functions.php
</code>```

The file wp-content/themes/my_theme/functions.php has the function I need to call from the cron job: do_something().

As you can see the command is: home/www/wp-content/themes/my_theme/functions.php is wrong, since I need to specify my function: do_something().

My question is: how do chage the job command to execute the function  do_something().

答:
(1) Do not call functions.php file directly for cron job if you have wordpress specific function to use but setup wordpress environment first with two commands I mentioned in the previous question you had posted.

```<code><?php
define('WP_USE_THEMES', false);
require('./wp-blog-header.php');
//ensure correct *path* for your wp-blog-header.php file
//now you can use function you want from functions.php file directly
do_something();
?>
</code>```

(2) If your do_something() function is not for any wordpress related task, just copy that function and use it in your cron file, say mycron.php

(3) You had asked where to put this suggested code. Put suggested code at the top of your mycron.php file.

Body:
I created a Linux Cron Job like:

0 0 * * * home/www/wp-content/themes/my_theme/functions.php

The file wp-content/themes/my_theme/functions.php has the function I need to call from the cron job: do_something().

As you can see the command is: home/www/wp-content/themes/my_theme/functions.php is wrong, since I need to specify my function: do_something().

My question is: how do chage the job command to execute the function  do_something().

Body:
(1) Do not call functions.php file directly for cron job if you have wordpress specific function to use but setup wordpress environment first with two commands I mentioned in the previous question you had posted.

<?php
define('WP_USE_THEMES', false);
require('./wp-blog-header.php');
//ensure correct *path* for your wp-blog-header.php file
//now you can use function you want from functions.php file directly
do_something();
?>

(2) If your do_something() function is not for any wordpress related task, just copy that function and use it in your cron file, say mycron.php

(3) You had asked where to put this suggested code. Put suggested code at the top of your mycron.php file.


问:
How to insert items into existing array
Assume I have two arrays as below

```<code>array:2 [
  0 => {#1995
    +"id": 6
    +"sales_target_amount": "30000.00"
  }
  1 => {#1996
    +"id": 10
    +"sales_target_amount": "1000.00"
  }
]
</code>```

second array

```<code>array:2 [
  0 => {#1994
    +"sales_total": "4165.80"
    +"staff_id": 6
  }
  1 => {#1513
    +"sales_total": "1335.60"
    +"staff_id": 10
  }
]
</code>```

I'm trying to insert the first array sales_target_amount into the second array if the id is matched to the staff_id.

code

```<code>  $sum = array_merge($second_array[],$firs_array);
</code>```

The code above will merge the two array together but not insert the items based on the id.

Expected Result

```<code>array:2 [
      0 => {#1994
        +"sales_total": "4165.80"
        +"staff_id": 6
        +"sales_target_amount": "30000.00"
      }
      1 => {#1513
        +"sales_total": "1335.60"
        +"staff_id": 10
        +"sales_target_amount": "1000.00"
      }
    ]
</code>```

答:
Sort answer using this library

$array = array_merge_recursive(
  Arr::flattenSingle(Arr::group($array1, 'id')),
  Arr::flattenSingle(Arr::group($array2, 'staff_id'))
);
```

<p>What it does underneath is to first group your arrays by column you want them merged by. Then because every element in group will have only one corresponding array (cause they are grouped by unique id) flatten those groups to build array with elements like <code>id => array_with_that_id</code>. And then merge those flattened groups by keys which in these case are ids. </p>

<p>Overall this will produce</p>

<pre class="lang-php prettyprint-override"><code>Array (
  [6] => Array (
    [id] => 6
    [sales_total] => 4165.8
    [staff_id] => 6
    [sales_target_amount] => 30000
  )
  [10] => Array (
    [id] => 10
    [sales_total] => 1335.6
    [staff_id] => 10
    [sales_target_amount] => 1000
  )
)
</code>```

Title: How to insert items into existing array

Body:
Assume I have two arrays as below

array:2 [
  0 => {#1995
    +"id": 6
    +"sales_target_amount": "30000.00"
  }
  1 => {#1996
    +"id": 10
    +"sales_target_amount": "1000.00"
  }
]

second array

array:2 [
  0 => {#1994
    +"sales_total": "4165.80"
    +"staff_id": 6
  }
  1 => {#1513
    +"sales_total": "1335.60"
    +"staff_id": 10
  }
]

I'm trying to insert the first array sales_target_amount into the second array if the id is matched to the staff_id.

code

  $sum = array_merge($second_array[],$firs_array);

The code above will merge the two array together but not insert the items based on the id.

Expected Result

array:2 [
      0 => {#1994
        +"sales_total": "4165.80"
        +"staff_id": 6
        +"sales_target_amount": "30000.00"
      }
      1 => {#1513
        +"sales_total": "1335.60"
        +"staff_id": 10
        +"sales_target_amount": "1000.00"
      }
    ]

Body:
Sort answer using this library

$array = array_merge_recursive(
  Arr::flattenSingle(Arr::group($array1, 'id')),
  Arr::flattenSingle(Arr::group($array2, 'staff_id'))
);

What it does underneath is to first group your arrays by column you want them merged by. Then because every element in group will have only one corresponding array (cause they are grouped by unique id) flatten those groups to build array with elements like id => array_with_that_id. And then merge those flattened groups by keys which in these case are ids.

Overall this will produce

Array (
  [6] => Array (
    [id] => 6
    [sales_total] => 4165.8
    [staff_id] => 6
    [sales_target_amount] => 30000
  )
  [10] => Array (
    [id] => 10
    [sales_total] => 1335.6
    [staff_id] => 10
    [sales_target_amount] => 1000
  )
)


问:
JSON Object to POJO dynamically
I want to store an array of JSON Object into POJO class dynamically how can I do this particular thing in java.</p>

```<code>[
{
"history":"L",
"loan":"12345"
"status":1
.
.
},
{
"History":"L",
"loan":"67890"
"status":1
.
.
},
....
]
</code>```

答:
You need to have a model calss.
lets say your json-string is like this :

```<code>String temp_json_string = "{ \"history\":\"L\", \"loan\":\"12345\", \"status\":\"1\"}";
</code>```

Go to this or similar site and generate a class for your temp_json_string by pasting json string in that link and get class, choose getters and setters if you need.

http://www.jsonschema2pojo.org/

Create a new gson/jackson object (import that library either maven or build jre system path), convert the string to this "BankLoanDetails" class.

```<code>    Gson gson = new Gson();
    BankLoanDetails my_loan_pojo = gson.fromJson(temp_json_string,
                                                   BankLoanDetails.class);
</code>```

your my_loan_pojo is pojo representing your json string.

Did you check at Safely turning a JSON string into an object

Title: JSON Object to POJO dynamically

Body:
I want to store an array of JSON Object into POJO class dynamically how can I do this particular thing in java.

[
{
"history":"L",
"loan":"12345"
"status":1
.
.
},
{
"History":"L",
"loan":"67890"
"status":1
.
.
},
....
]

Body:
You need to have a model calss.
lets say your json-string is like this :

String temp_json_string = "{ \"history\":\"L\", \"loan\":\"12345\", \"status\":\"1\"}";

Go to this or similar site and generate a class for your temp_json_string by pasting json string in that link and get class, choose getters and setters if you need.

http://www.jsonschema2pojo.org/

Create a new gson/jackson object (import that library either maven or build jre system path), convert the string to this "BankLoanDetails" class.

    Gson gson = new Gson();
    BankLoanDetails my_loan_pojo = gson.fromJson(temp_json_string,
                                                   BankLoanDetails.class);

your my_loan_pojo is pojo representing your json string.

Did you check at Safely turning a JSON string into an object


问:
jQuery ul event target - can i find the li that actually is event target?
```<code>$("#slider ul").hover(function(){
  //do something
});
</code>```

Is there a way to find out which child (li) was actually hovered on to make this function work?

This is a long function that when originally written as $("#slider ul li") etc, worked, but only when completely leaving the slider ul area. I need it to work when moving from one li directly to neighboring li, etc.

答:
It sounds like you are trying to do 2 separate things... one thing on ul hover, and then one again on the li hover

You should probably split out the event handlers:

```<code>var slider = $('#slider ul');

slider.hover(function(){ /* do something*/ });
slider.find('li').hover(function(){ /* do something else with $(this) */ });
</code>```

Body:
$("#slider ul").hover(function(){
  //do something
});

Is there a way to find out which child (li) was actually hovered on to make this function work?

This is a long function that when originally written as $("#slider ul li") etc, worked, but only when completely leaving the slider ul area. I need it to work when moving from one li directly to neighboring li, etc.

Body:
It sounds like you are trying to do 2 separate things... one thing on ul hover, and then one again on the li hover

You should probably split out the event handlers:

var slider = $('#slider ul');

slider.hover(function(){ /* do something*/ });
slider.find('li').hover(function(){ /* do something else with $(this) */ });


问:
Kittens - ambiguous imports (again)
This answer https://stackoverflow.com/a/56366311/2682459 shows how it is possible to use an object to provide a custom implementation of a typeclass when using Kitten. Applying the same principle to the following code though doesn't work:

```<code>package com.xxx.yyy.zzz

import cats._, cats.derived._, cats.implicits._

object Test extends App {

  case class Inner(double: Double)

  case class Outer(inner: Inner, s: String)

  implicit object doubleEq extends Eq[Double] {
    override def eqv(x: Double, y: Double): Boolean = Math.abs(x - y) < 0.1
  }

  implicit val outerEq: Eq[Outer] = {
    import derived.auto.eq._
    derived.semi.eq[Outer]
  }

  implicitly[Eq[Double]]

  val testCC1 = Outer(Inner(1.01d), "BlahBlahBlah")
  val testCC2 = Outer(Inner(1.00d), "BlahBlahBlah")

  println(testCC1 === testCC2)

}
</code>```

The implicitly[Eq[Double]] shows that once again I have ambiguous implicits:

```<code>Error:(20, 13) ambiguous implicit values:
 both value catsKernelStdOrderForDouble in trait DoubleInstances of type => cats.kernel.Order[Double] with cats.kernel.Hash[Double]
 and object doubleEq in object Test of type com.xxx.yyy.zzz.Test.doubleEq.type
 match expected type cats.Eq[Double]
  implicitly[Eq[Double]]
</code>```

How do I work round this one? I really don't want to have to cherry pick the cats implicits I import as this isn't very scalable!

答:
Change your imports. Don't import cats.instances.double._

```<code>import cats._, cats.derived._
import cats.instances.string._ // Outer uses Double and String
import cats.syntax.eq._ // for ===
</code>```

Both

```<code>implicit val doubleEq: Eq[Double] = new Eq[Double] {
  override def eqv(x: Double, y: Double): Boolean = Math.abs(x - y) < 0.1
}
</code>```

and

```<code>implicit object doubleEq extends Eq[Double] {
  override def eqv(x: Double, y: Double): Boolean = Math.abs(x - y) < 0.1
}
</code>```

work.

http://eed3si9n.com/herding-cats/import-guide.html

https://blog.softwaremill.com/9-tips-about-using-cats-in-scala-you-might-want-to-know-e1bafd365f88 advice 2)

Title: Kittens - ambiguous imports (again)

Body:
This answer https://stackoverflow.com/a/56366311/2682459 shows how it is possible to use an object to provide a custom implementation of a typeclass when using Kitten. Applying the same principle to the following code though doesn't work:

package com.xxx.yyy.zzz

import cats._, cats.derived._, cats.implicits._

object Test extends App {

  case class Inner(double: Double)

  case class Outer(inner: Inner, s: String)

  implicit object doubleEq extends Eq[Double] {
    override def eqv(x: Double, y: Double): Boolean = Math.abs(x - y) < 0.1
  }

  implicit val outerEq: Eq[Outer] = {
    import derived.auto.eq._
    derived.semi.eq[Outer]
  }

  implicitly[Eq[Double]]

  val testCC1 = Outer(Inner(1.01d), "BlahBlahBlah")
  val testCC2 = Outer(Inner(1.00d), "BlahBlahBlah")

  println(testCC1 === testCC2)

}

The implicitly[Eq[Double]] shows that once again I have ambiguous implicits:

Error:(20, 13) ambiguous implicit values:
 both value catsKernelStdOrderForDouble in trait DoubleInstances of type => cats.kernel.Order[Double] with cats.kernel.Hash[Double]
 and object doubleEq in object Test of type com.xxx.yyy.zzz.Test.doubleEq.type
 match expected type cats.Eq[Double]
  implicitly[Eq[Double]]

How do I work round this one? I really don't want to have to cherry pick the cats implicits I import as this isn't very scalable!

Body:
Change your imports. Don't import cats.instances.double._

import cats._, cats.derived._
import cats.instances.string._ // Outer uses Double and String
import cats.syntax.eq._ // for ===

Both

implicit val doubleEq: Eq[Double] = new Eq[Double] {
  override def eqv(x: Double, y: Double): Boolean = Math.abs(x - y) < 0.1
}

and

implicit object doubleEq extends Eq[Double] {
  override def eqv(x: Double, y: Double): Boolean = Math.abs(x - y) < 0.1
}

work.

http://eed3si9n.com/herding-cats/import-guide.html

https://blog.softwaremill.com/9-tips-about-using-cats-in-scala-you-might-want-to-know-e1bafd365f88 advice 2)


问:
How do I add parameter as a value in JPQL for INTERVAL from property file?
I want to send parameter from property file in JPQL using @Query

Suppose I have a query,

```<code>@Query(value= "Select * from myTable where id = ?1 AND last_modified_date between DATE_SUB(NOW(), INTERVAL ?2) AND NOW()", nativeQuery = true)
List<MyTableClass> getAllData(Long id, String stringSetFromPropertyFile);
</code>```

Here the "stringSetFromPropertyFile" is sent from the Service class.

When I do the above thing it gives a query error where ?2 as a parameter is not set blank.

答:
try </p>

```<code>@Query(value= "Select * from myTable where id = ?1 AND last_modified_date between DATE_SUB(NOW(), INTERVAL ?2) AND NOW()",nativeQuery = true)
List<MyTableClass> getAllData(Long id, String stringSetFromPropertyFile);
</code>```

Body:
I want to send parameter from property file in JPQL using @Query

Suppose I have a query,

@Query(value= "Select * from myTable where id = ?1 AND last_modified_date between DATE_SUB(NOW(), INTERVAL ?2) AND NOW()", nativeQuery = true)
List<MyTableClass> getAllData(Long id, String stringSetFromPropertyFile);

Here the "stringSetFromPropertyFile" is sent from the Service class.

When I do the above thing it gives a query error where ?2 as a parameter is not set blank.

Body:
try

@Query(value= "Select * from myTable where id = ?1 AND last_modified_date between DATE_SUB(NOW(), INTERVAL ?2) AND NOW()",nativeQuery = true)
List<MyTableClass> getAllData(Long id, String stringSetFromPropertyFile);


问:
How to use updated Twitter API with node.js, "event: field is required"
I keep getting the following error when trying to use the Twitter API to send direct messages.

```<code>message: 'event: field is required',
  code: 214,
  allErrors: [ { code: 214, message: 'event: field is required' } ],
  twitterReply: { errors: [ [Object] ] },
  statusCode: 400 }
{ errors: [ { code: 214, message: 'event: field is required' } ] }
</code>```

Twitter recently updated their api (im told) so to send direct messages the url 'direct_messages/events/new' is now used. I'm using the 'twit' module to access the api.

```<code>export async function messageTwitter(message, recipient){
    client.post('direct_messages/events/new',{
        screen_name: recipient,
        text: message
    }, (event, error)=>{
            console.log(event)
            console.log(error)
    })
}
</code>```

I want the post request to be properly formatted, i cannot find any info in the documentation that explains how 'event' should be defined.

答:
After messing around based off of the errors I was getting I figured out how to format the object. Sorry I know this was sort of a dumb, poorly asked question. Here is my updated code: </p>

```<code>export async function messageTwitter(message, recipient){
    client.post('direct_messages/events/new', {
        event: {
            type: "message_create",
            message_create: {
                target: {
                    recipient_id: recipient
                },
                message_data: {
                    text: message
                }
            }
        }
    }, (error, event)=>{
            if(error){
              console.log(error)
            }
            else{
               console.log(event);
             }
    })
}
</code>```

Body:
I keep getting the following error when trying to use the Twitter API to send direct messages.

message: 'event: field is required',
  code: 214,
  allErrors: [ { code: 214, message: 'event: field is required' } ],
  twitterReply: { errors: [ [Object] ] },
  statusCode: 400 }
{ errors: [ { code: 214, message: 'event: field is required' } ] }

Twitter recently updated their api (im told) so to send direct messages the url 'direct_messages/events/new' is now used. I'm using the 'twit' module to access the api.

export async function messageTwitter(message, recipient){
    client.post('direct_messages/events/new',{
        screen_name: recipient,
        text: message
    }, (event, error)=>{
            console.log(event)
            console.log(error)
    })
}

I want the post request to be properly formatted, i cannot find any info in the documentation that explains how 'event' should be defined.

Body:
After messing around based off of the errors I was getting I figured out how to format the object. Sorry I know this was sort of a dumb, poorly asked question. Here is my updated code:

export async function messageTwitter(message, recipient){
    client.post('direct_messages/events/new', {
        event: {
            type: "message_create",
            message_create: {
                target: {
                    recipient_id: recipient
                },
                message_data: {
                    text: message
                }
            }
        }
    }, (error, event)=>{
            if(error){
              console.log(error)
            }
            else{
               console.log(event);
             }
    })
}


问:
Get all matched row using SQL query
I have the posts table with the following data /structure:

```<code>posts_id   post_message   u_id  like_count  created
===================================================
1         content.......  1     25          1559041633
2         content.......  2     25          1559041633
</code>```

and posts_like table with the following data/structure:

```<code>like_id    posts_id   u_id   r_id    created
=============================================
22         2          1      2       1559041633
27         2          2      4       1559041633
30         1          2      7       1559041633
</code>```

Note: u_id means the user id, r_id means reaction id, posts_id means posts id.

Now, I want to get all posts from the posts table along with the full name from the users table and all u_id and r_id under each post.

For example, you can see that under posts_id = 2 I have u_id 1 and 2 and r_id 2 and 4.

Desire Output:

```<code>first post content
user full Name
u_id: 2
r_id: 7

second post content
user full Name
u_id: 1, 2
r_id: 2, 4
</code>```

Current I am using this SQL query

```<code>$query = $this->_db->_pdo->prepare("
SELECT p.posts_id, p.post_message, p.like_count, p.created, u.full_name,
 u.u_id, pl.r_id FROM posts AS p LEFT JOIN users AS u ON u.u_id = p.u_id
LEFT JOIN posts_like AS pl ON pl.posts_id = p.posts_id GROUP BY
p.posts_id ORDER BY p.posts_id DESC ");
</code>```

This above query does not get the all u_id and r_id under each post.

答:
You need to use a GROUP_CONCAT on your u_id and r_id fields to get a list of all the reactions. Note that you need to use pl.u_id, not u.u_id as u.u_id refers to the post creator, not the person who has reacted to the post.

```<code>SELECT p.posts_id, p.post_message, p.like_count, p.created,
       u.full_name,
       GROUP_CONCAT(pl.u_id ORDER BY pl.u_id) AS u_id,
       GROUP_CONCAT(pl.r_id ORDER BY pl.u_id) AS r_id
FROM posts AS p
LEFT JOIN users AS u ON u.u_id = p.u_id
LEFT JOIN posts_like AS pl ON pl.posts_id = p.posts_id
GROUP BY p.posts_id
ORDER BY p.posts_id DESC
</code>```

Output:

```<code>posts_id    post_message    like_count  created     full_name   u_id    r_id
2           content.......  25          1559041633  Mary Brown  1,2     2,4
1           content.......  25          1559041633  John Smith  2       7
</code>```

Demo on dbfiddle

Title: Get all matched row using SQL query

Body:
I have the posts table with the following data /structure:

posts_id   post_message   u_id  like_count  created
===================================================
1         content.......  1     25          1559041633
2         content.......  2     25          1559041633

and posts_like table with the following data/structure:

like_id    posts_id   u_id   r_id    created
=============================================
22         2          1      2       1559041633
27         2          2      4       1559041633
30         1          2      7       1559041633

Note: u_id means the user id, r_id means reaction id, posts_id means posts id.

Now, I want to get all posts from the posts table along with the full name from the users table and all u_id and r_id under each post.

For example, you can see that under posts_id = 2 I have u_id 1 and 2 and r_id 2 and 4.

Desire Output:

first post content
user full Name
u_id: 2
r_id: 7

second post content
user full Name
u_id: 1, 2
r_id: 2, 4

Current I am using this SQL query

$query = $this->_db->_pdo->prepare("
SELECT p.posts_id, p.post_message, p.like_count, p.created, u.full_name,
 u.u_id, pl.r_id FROM posts AS p LEFT JOIN users AS u ON u.u_id = p.u_id
LEFT JOIN posts_like AS pl ON pl.posts_id = p.posts_id GROUP BY
p.posts_id ORDER BY p.posts_id DESC ");

This above query does not get the all u_id and r_id under each post.

Body:
You need to use a GROUP_CONCAT on your u_id and r_id fields to get a list of all the reactions. Note that you need to use pl.u_id, not u.u_id as u.u_id refers to the post creator, not the person who has reacted to the post.

SELECT p.posts_id, p.post_message, p.like_count, p.created,
       u.full_name,
       GROUP_CONCAT(pl.u_id ORDER BY pl.u_id) AS u_id,
       GROUP_CONCAT(pl.r_id ORDER BY pl.u_id) AS r_id
FROM posts AS p
LEFT JOIN users AS u ON u.u_id = p.u_id
LEFT JOIN posts_like AS pl ON pl.posts_id = p.posts_id
GROUP BY p.posts_id
ORDER BY p.posts_id DESC

Output:

posts_id    post_message    like_count  created     full_name   u_id    r_id
2           content.......  25          1559041633  Mary Brown  1,2     2,4
1           content.......  25          1559041633  John Smith  2       7

Demo on dbfiddle


问:
ImportError: No module named IPython.paths when running jupyter notebook?
I installed jupyter via: /usr/local/opt/python/bin/python2.7 -m pip install jupyter

this install ipython version 4.1.2. However, when I run jupyter notebook, I get:

```<code>Traceback (most recent call last):
  File "/usr/local/bin/jupyter-notebook", line 7, in <module>
    from notebook.notebookapp import main
  File "/Library/Python/2.7/site-packages/notebook/notebookapp.py", line 83, in <module>
    from IPython.paths import get_ipython_dir
ImportError: No module named IPython.paths
</code>```

yet, when I run from IPython.paths import get_ipython_dir in the ipython shell directly it works fine. Also when I run /usr/local/opt/python/bin/python2.7 and then the same thing, it runs successfully. Additionally, when I check the sys.executable path in python I get /usr/local/opt/python/bin/python2.7

This doesn't make sense to me. How can Ipython and my normal python (both using /usr/local/opt/python/bin/python2.7) both run this successfully, but my jupyter, installed with that specific python, cannot run the command. Any suggestions?

答:
Upgrade ipython:

```<code>pip install ipython==5.3.0
</code>```

If you cannot uninstall ipython, try this:

```<code>sudo -H pip install --ignore-installed -U ipython==5.3.0
</code>```

Body:
I installed jupyter via: /usr/local/opt/python/bin/python2.7 -m pip install jupyter

this install ipython version 4.1.2. However, when I run jupyter notebook, I get:

Traceback (most recent call last):
  File "/usr/local/bin/jupyter-notebook", line 7, in <module>
    from notebook.notebookapp import main
  File "/Library/Python/2.7/site-packages/notebook/notebookapp.py", line 83, in <module>
    from IPython.paths import get_ipython_dir
ImportError: No module named IPython.paths

yet, when I run from IPython.paths import get_ipython_dir in the ipython shell directly it works fine. Also when I run /usr/local/opt/python/bin/python2.7 and then the same thing, it runs successfully. Additionally, when I check the sys.executable path in python I get /usr/local/opt/python/bin/python2.7

This doesn't make sense to me. How can Ipython and my normal python (both using /usr/local/opt/python/bin/python2.7) both run this successfully, but my jupyter, installed with that specific python, cannot run the command. Any suggestions?

Body:
Upgrade ipython:

pip install ipython==5.3.0

If you cannot uninstall ipython, try this:

sudo -H pip install --ignore-installed -U ipython==5.3.0


问:
UIDeviceOrientationUnknown in landscape mode
I am trying to figure out what orientation the iphone has in the simulator and instead of giving it to me using the UIDevice orientation property I just get UIDeviceOrientationUnknown.

Does this property not work in the simulator?  What could be the possible reason for this happening?

I am using opengl es

答:
You can also use:

```<code>UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
</code>```

which works even without calling beginGeneratingDeviceOrientationNotifications.

Body:
You can also use:

UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];

which works even without calling beginGeneratingDeviceOrientationNotifications.


问:
How to upload the a file(image) through Web-API and update the data with jQuery?
I am trying to upload a image as Avatar photo to the server through the Web-API.

Anyone can explain how to insert the image URL into the data by current user id has token?

I have already done $.getJSON (url,... I can read and append them wherever I wanted.

I have something like this:

user_id=1

/api/images/upload_form/avatar

/api/users/update_user_info

1. How can I attach the image file and post it through Web-API with jQuery?

2. And How can I re-upload(update) the file?

```<code> $(document).ready(function (e) {
     $('#upload').on('click', function () {
     var file_data = $('#file').prop('files')[0];
     var form_data = new FormData();
     form_data.append('file', file_data);
     $.ajax({
             url: 'https://myurl/api/images/upload_form/avatar', // point to server-side controller method
             dataType: 'text', // what to expect back from the server
             cache: false,
             contentType: false,
             processData: false,
             data: form_data,
             type: 'post',
             success: function (response) {
                 $('#msg').html(response); // display success response from the server
                 },
             error: function (response) {
                 $('#msg').html(response); // display error response from the server
                 }
           });
     });
});
</code>```

user_id=1 << I need to add this key and value to the post url, but how?

Any help will be appreciate.

Thanks

答:
For those new guys who still struggling like I was:

1. How can I attach the image file and post it through Web-API with jQuery?

Uploading the image but response: { 'user_id' of undefined } ?

Before you post the your request, you have to grab parameters form the URL.

```<code>var urlParams = new URLSearchParams(window.location.search); // current URL

console.log(urlParams.get('user_id')); // return token id or user id

</code>```

and all you have to do is put this:

```<code>...
var user_data = urlParams.get('user_id'); // or token
form_data.append('user_id', user_data);
$.ajax({
        url: 'https://myurl/api/images/upload_form/avatar',
        dataType: 'text',
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,
        ...
</code>```

2. And How can I re-upload(update) the file?

Just upload another file!

Might not be the right way to do that, but works!

Body:
I am trying to upload a image as Avatar photo to the server through the Web-API.

Anyone can explain how to insert the image URL into the data by current user id has token?

I have already done $.getJSON (url,... I can read and append them wherever I wanted.

I have something like this:

user_id=1

/api/images/upload_form/avatar

/api/users/update_user_info

1. How can I attach the image file and post it through Web-API with jQuery?

2. And How can I re-upload(update) the file?

 $(document).ready(function (e) {
     $('#upload').on('click', function () {
     var file_data = $('#file').prop('files')[0];
     var form_data = new FormData();
     form_data.append('file', file_data);
     $.ajax({
             url: 'https://myurl/api/images/upload_form/avatar', // point to server-side controller method
             dataType: 'text', // what to expect back from the server
             cache: false,
             contentType: false,
             processData: false,
             data: form_data,
             type: 'post',
             success: function (response) {
                 $('#msg').html(response); // display success response from the server
                 },
             error: function (response) {
                 $('#msg').html(response); // display error response from the server
                 }
           });
     });
});

user_id=1 << I need to add this key and value to the post url, but how?

Any help will be appreciate.

Thanks

Body:
For those new guys who still struggling like I was:

1. How can I attach the image file and post it through Web-API with jQuery?

Uploading the image but response: { 'user_id' of undefined } ?

Before you post the your request, you have to grab parameters form the URL.

var urlParams = new URLSearchParams(window.location.search); // current URL

console.log(urlParams.get('user_id')); // return token id or user id

and all you have to do is put this:

...
var user_data = urlParams.get('user_id'); // or token
form_data.append('user_id', user_data);
$.ajax({
        url: 'https://myurl/api/images/upload_form/avatar',
        dataType: 'text',
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,
        ...

2. And How can I re-upload(update) the file?

Just upload another file!

Might not be the right way to do that, but works!


问:
Moving method out of the Class
I'd like to re-factor Cache class purely for academic reason.

However, I'm having a tough time figuring out how I can move getMap out of the Cache class and have it as a regular function.

```<code>function isObject(arg) {
  const typeOfObj = typeof arg;
  return (typeOfObj === 'object' || typeOfObj === 'function') && arg !== null;
}

class Cache {
  constructor() {
    this.map = new Map();
    this.weakmap = new WeakMap();
  }
  // return a Cache's value at a key
  getMap(key) {
    // console.log(this);
    const map = this[isObject(key) ? 'weakmap' : 'map'];
    // console.log(map);
    this.setKeyIfNeeded(map, key);
    let valueMap = map.get(key);
    return valueMap;
  }
  // create a Cache's key, if needed

  setKeyIfNeeded(map, key) {
    if (!map.has(key)) {
      map.set(key, new Cache());
    }
  }
}

const getNestedMap = (keys, initialCache) =>
  keys.reduce((cache, key) => cache.getMap(key), initialCache);

function memoize(fn) {
  const cache = new Cache();
  return (...args) => {
    // get (or create) a cache item

    const item = getNestedMap(args, cache);

    if (Reflect.has(item, 'value')) {
      return item.value;
    }
    return (item.value = fn(args));
  };
}

let counter = 1;
function foo() {
  counter += 1;
  return counter;
}

const id1 = Symbol('id');
const id2 = Symbol('id');

const memoizedFoo = memoize(foo);

console.log(memoizedFoo(3, 4, 5, 6)); //2
console.log(memoizedFoo(3, 4, 5, 6)); //2
console.log(memoizedFoo(3, 4, 6)); //3
console.log(memoizedFoo(3, 4, 6)); //3
</code>```

答:
SOLUTION

```<code>function isObject(arg) {
  const typeOfObj = typeof arg;
  return (typeOfObj === 'object' || typeOfObj === 'function') && arg !== null;
}

class Cache {
  constructor() {
    this.map = new Map();
    this.weakmap = new WeakMap();
  }

  static setKey(key, map) {
    return map.set(key, new Cache());
  }
}

function getCache(args, cache) {
  for (const key of args) {
    const map = cache[isObject(key) ? 'weakmap' : 'map'];
    cache = map.get(key) || Cache.setKey(key, map).get(key);
  }
  return cache;
}

function memoize(fn) {
  const cache = new Cache();
  return (...args) => {
    const item = getCache(args, cache);
    if (Reflect.has(item, 'value')) {
      return item.value;
    }
    return (item.value = fn(args));
  };
}

let counter = 1;
function foo() {
  counter += 1;
  return counter;
}
</code>```

Title: Moving method out of the Class

Body:
I'd like to re-factor Cache class purely for academic reason.

However, I'm having a tough time figuring out how I can move getMap out of the Cache class and have it as a regular function.

function isObject(arg) {
  const typeOfObj = typeof arg;
  return (typeOfObj === 'object' || typeOfObj === 'function') && arg !== null;
}

class Cache {
  constructor() {
    this.map = new Map();
    this.weakmap = new WeakMap();
  }
  // return a Cache's value at a key
  getMap(key) {
    // console.log(this);
    const map = this[isObject(key) ? 'weakmap' : 'map'];
    // console.log(map);
    this.setKeyIfNeeded(map, key);
    let valueMap = map.get(key);
    return valueMap;
  }
  // create a Cache's key, if needed

  setKeyIfNeeded(map, key) {
    if (!map.has(key)) {
      map.set(key, new Cache());
    }
  }
}

const getNestedMap = (keys, initialCache) =>
  keys.reduce((cache, key) => cache.getMap(key), initialCache);

function memoize(fn) {
  const cache = new Cache();
  return (...args) => {
    // get (or create) a cache item

    const item = getNestedMap(args, cache);

    if (Reflect.has(item, 'value')) {
      return item.value;
    }
    return (item.value = fn(args));
  };
}

let counter = 1;
function foo() {
  counter += 1;
  return counter;
}

const id1 = Symbol('id');
const id2 = Symbol('id');

const memoizedFoo = memoize(foo);

console.log(memoizedFoo(3, 4, 5, 6)); //2
console.log(memoizedFoo(3, 4, 5, 6)); //2
console.log(memoizedFoo(3, 4, 6)); //3
console.log(memoizedFoo(3, 4, 6)); //3

Body:
SOLUTION

function isObject(arg) {
  const typeOfObj = typeof arg;
  return (typeOfObj === 'object' || typeOfObj === 'function') && arg !== null;
}

class Cache {
  constructor() {
    this.map = new Map();
    this.weakmap = new WeakMap();
  }

  static setKey(key, map) {
    return map.set(key, new Cache());
  }
}

function getCache(args, cache) {
  for (const key of args) {
    const map = cache[isObject(key) ? 'weakmap' : 'map'];
    cache = map.get(key) || Cache.setKey(key, map).get(key);
  }
  return cache;
}

function memoize(fn) {
  const cache = new Cache();
  return (...args) => {
    const item = getCache(args, cache);
    if (Reflect.has(item, 'value')) {
      return item.value;
    }
    return (item.value = fn(args));
  };
}

let counter = 1;
function foo() {
  counter += 1;
  return counter;
}


答:
The blow codes work and gives exactly the same output.

```<code>library(data.tree)

SubjectID <- c('101','102','103','103')
parent <- c(1387, 986,1623,1191)
child1 <-c(1620,1015,1385,1450)
child2 <- c(1743,'','',1623)
child3 <- c(1859,'','','')
df<-data.frame(SubjectID, parent,child1,child2,child3)

df$pathString<- paste("study",df$SubjectID, df$parent, df$child1,df$child2,df$child3, sep="/")

as.Node(df)
</code>```

Update:
An update based on your comments to include data transformation.
There might be a better way to transform the data. If conditions change, the code can be updated accordingly.

```<code>SubjectID <- c('101','101','101','102','103','103','103')
parent <-    c(1387,  1620, 1743, 986,  1623, 1191, 1450)
child<-      c(1620,  1743, 1859 ,1015, 1385, 1450, 1623)

nchild <- 10
nc <- 1
child_new <- rep(list(c()),nchild)
SID <- SubjectID[nc]
parentn <- parent[nc]
child_new[[nc]] <- child[nc]

for (s in 2:length(SubjectID)) {

  if (SubjectID[s]!=SubjectID[s-1]){
    nc <- 1
    SID <- c(SID,SubjectID[s])
    parentn <- c(parentn,parent[s])
    child_new[[1]] <- c(child_new[[1]],child[s])
    for (ic in 2:length(child_new))  child_new[[ic]] <- c(child_new[[ic]],"")
  } else {
    if(parent[s]==child[s-1]) {
      nc <- nc+1
      child_new[[nc]] <- c(child_new[[nc]],child[s])
    }
    if(parent[s]!=child[s-1]) {
      SID <- c(SID,SubjectID[s])
      parentn <- c(parentn,parent[s])
      child_new[[nc]] <- c(child_new[[nc]],child[s])
    }
  }
}

for (i in 1:length(child_new)){
  len_child <- length(child_new[[i]])
  if (len_child<length(SID)) child_new[[i]] <- c(child_new[[i]],rep("",length(SID)-len_child))
}

library(data.tree)
df <- data.frame(t(matrix(unlist(child_new), nrow=nchild, byrow=T)))
df <- cbind(SID, parentn, df)
df$pathString<- paste("study",do.call(paste, c(df[colnames(df)], sep="/")),sep="/")

as.Node(df)
</code>```

Title: How to get tree nodes to nest properly in tree.map

Body:
I am having trouble building a tree.map from parent/child grouped pairs. Here's my sample data:

SubjectID <- c('101','101','101','102','103','103','103')
parent <- c(1387, 1620, 1743,986,1623,1191,1450)
child <- c(1620,1743,1859 ,1015,1385,1450,1623)
df <- data.frame(SubjectID, parent,child)

I've tried building the tree with tree.map:

df$pathString <- paste("study",df$SubjectID, df$parent, df$child, sep="/")
as.Node(df)

The result is:

1  study
2   ¦--101
3   ¦   ¦--1387
4   ¦   ¦   °--1620
5   ¦   ¦--1620
6   ¦   ¦   °--1743
7   ¦   °--1743
8   ¦       °--1859
9   ¦--102
10  ¦   °--986
11  ¦       °--1015
12  °--103
13      ¦--1623
14      ¦   °--1385
15      ¦--1191
16      ¦   °--1450
17      °--1450
18          °--1623

I would like the result to link the parent with child like this:

1  study
2   ¦--101
3   ¦   ¦--1387
4   ¦   ¦   °--1620
5   ¦   ¦      °--1743
6   ¦   ¦         °--1859
9   ¦--102
7   ¦   °--986
8   ¦       °--1015
9   °--103
10      ¦--1623
11      ¦   °--1385
12      ¦--1191
13      ¦   °--1450
14      ¦      °--1623

Body:
The blow codes work and gives exactly the same output.

library(data.tree)

SubjectID <- c('101','102','103','103')
parent <- c(1387, 986,1623,1191)
child1 <-c(1620,1015,1385,1450)
child2 <- c(1743,'','',1623)
child3 <- c(1859,'','','')
df<-data.frame(SubjectID, parent,child1,child2,child3)

df$pathString<- paste("study",df$SubjectID, df$parent, df$child1,df$child2,df$child3, sep="/")

as.Node(df)

Update:
An update based on your comments to include data transformation.
There might be a better way to transform the data. If conditions change, the code can be updated accordingly.

SubjectID <- c('101','101','101','102','103','103','103')
parent <-    c(1387,  1620, 1743, 986,  1623, 1191, 1450)
child<-      c(1620,  1743, 1859 ,1015, 1385, 1450, 1623)

nchild <- 10
nc <- 1
child_new <- rep(list(c()),nchild)
SID <- SubjectID[nc]
parentn <- parent[nc]
child_new[[nc]] <- child[nc]

for (s in 2:length(SubjectID)) {

  if (SubjectID[s]!=SubjectID[s-1]){
    nc <- 1
    SID <- c(SID,SubjectID[s])
    parentn <- c(parentn,parent[s])
    child_new[[1]] <- c(child_new[[1]],child[s])
    for (ic in 2:length(child_new))  child_new[[ic]] <- c(child_new[[ic]],"")
  } else {
    if(parent[s]==child[s-1]) {
      nc <- nc+1
      child_new[[nc]] <- c(child_new[[nc]],child[s])
    }
    if(parent[s]!=child[s-1]) {
      SID <- c(SID,SubjectID[s])
      parentn <- c(parentn,parent[s])
      child_new[[nc]] <- c(child_new[[nc]],child[s])
    }
  }
}

for (i in 1:length(child_new)){
  len_child <- length(child_new[[i]])
  if (len_child<length(SID)) child_new[[i]] <- c(child_new[[i]],rep("",length(SID)-len_child))
}

library(data.tree)
df <- data.frame(t(matrix(unlist(child_new), nrow=nchild, byrow=T)))
df <- cbind(SID, parentn, df)
df$pathString<- paste("study",do.call(paste, c(df[colnames(df)], sep="/")),sep="/")

as.Node(df)


问:
How to customize data provider request call?
I'm new to react and react-admin.

I'm, using jsonServerProvider (in my App.js I have the following):

```<code>import jsonServerProvider from 'ra-data-json-server';
</code>```

I'd like to create a custom bulk action. In a list, select many items and click a button to "connect" them. I tried to use UPDATE_MANY, but this calls my endpoint multiple times, so it's not suitable. Ideally I need the request to call my endpoint like so: url.to.myendpoint?ids=1,2,3 or even better pass an array of IDs in the body and use a PUT request.

Just to understand how things work and debug network calls, I tried also the GET_MANY, in the dataproviders page, the request seems to get the IDs like so: { ids: {mixed[]}, data: {Object} }

But the request is sent to the server like so: url.to.myendpoint?id=1&id=2&id=3 which in my python/flask backend is not nice to parse.

I've spent a bunch of time reading the docs, e.g.:

https://github.com/marmelab/react-admin/blob/master/docs/Actions.md

https://react-admin.com/docs/en/actions.html

https://marmelab.com/react-admin/Actions.html

I tried different approaches and I could not achieve what I want. So again please help me to make my custom bulk button work.

My bulk button is called ConnectItemsButton and the code looks like this:

```<code>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Button, crudUpdateMany } from 'react-admin';
import { showNotification, GET_MANY } from 'react-admin';
import dataProvider from './dataProvider';

class ConnectItemsButton extends Component {
  handleClick = () => {
    const { selectedIds } = this.props;
    dataProvider(GET_MANY, 'items/connect', { ids: selectedIds })
      .then(() => {
        showNotification('Connected!');
      })
      .catch((e) => {
        showNotification('Error.', 'warning')
      });
  };

  render() {
    return (
      <Button label="Associate" onClick={this.handleClick} />
    );
  }
}

export default connect(undefined, { crudUpdateMany })(ConnectItemsButton);

</code>```

Note that the contents of ./dataProvider (it's the same provider used in the App.js file and passed to the <Admin> in the props):

```<code>import jsonServerProvider from 'ra-data-json-server';
export default jsonServerProvider('http://127.0.0.1:5000/api');
</code>```

In my list I created it, the button is displayed properly, so here I share the code snippet:

```<code>const PostBulkActionButtons = props => (
  <Fragment>
    <ConnectItemsButton {...props} />
  </Fragment>
);

...

export const ItemsList = props => (
  <List {...props} bulkActionButtons={<PostBulkActionButtons />}>

...

</code>```

In my backend endpoint items/connect I simply need to get a comma separated list of IDs to parse, that's it.

A simple working solution would be awesome, or at least point me in the right direction. Thanks for your help.

答: I think using Promise.all will solve the issue, see this link for reference https://github.com/marmelab/react-admin/blob/master/packages/ra-data-simple-rest/src/index.js#L140</p>

Body:
I'm new to react and react-admin.

I'm, using jsonServerProvider (in my App.js I have the following):

import jsonServerProvider from 'ra-data-json-server';

I'd like to create a custom bulk action. In a list, select many items and click a button to "connect" them. I tried to use UPDATE_MANY, but this calls my endpoint multiple times, so it's not suitable. Ideally I need the request to call my endpoint like so: url.to.myendpoint?ids=1,2,3 or even better pass an array of IDs in the body and use a PUT request.

Just to understand how things work and debug network calls, I tried also the GET_MANY, in the dataproviders page, the request seems to get the IDs like so: { ids: {mixed[]}, data: {Object} }

But the request is sent to the server like so: url.to.myendpoint?id=1&id=2&id=3 which in my python/flask backend is not nice to parse.

I've spent a bunch of time reading the docs, e.g.:

https://github.com/marmelab/react-admin/blob/master/docs/Actions.md

https://react-admin.com/docs/en/actions.html

https://marmelab.com/react-admin/Actions.html

I tried different approaches and I could not achieve what I want. So again please help me to make my custom bulk button work.

My bulk button is called ConnectItemsButton and the code looks like this:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Button, crudUpdateMany } from 'react-admin';
import { showNotification, GET_MANY } from 'react-admin';
import dataProvider from './dataProvider';

class ConnectItemsButton extends Component {
  handleClick = () => {
    const { selectedIds } = this.props;
    dataProvider(GET_MANY, 'items/connect', { ids: selectedIds })
      .then(() => {
        showNotification('Connected!');
      })
      .catch((e) => {
        showNotification('Error.', 'warning')
      });
  };

  render() {
    return (
      <Button label="Associate" onClick={this.handleClick} />
    );
  }
}

export default connect(undefined, { crudUpdateMany })(ConnectItemsButton);

Note that the contents of ./dataProvider (it's the same provider used in the App.js file and passed to the <Admin> in the props):

import jsonServerProvider from 'ra-data-json-server';
export default jsonServerProvider('http://127.0.0.1:5000/api');

In my list I created it, the button is displayed properly, so here I share the code snippet:

const PostBulkActionButtons = props => (
  <Fragment>
    <ConnectItemsButton {...props} />
  </Fragment>
);

...

export const ItemsList = props => (
  <List {...props} bulkActionButtons={<PostBulkActionButtons />}>

...

In my backend endpoint items/connect I simply need to get a comma separated list of IDs to parse, that's it.

A simple working solution would be awesome, or at least point me in the right direction. Thanks for your help.


问:
How to add shadow and remove bottom line in NavigationBar globally?
So I'm looking for how can I add shadow to NavigationBar and remove the bottom black line from NavigationBar? Also if I have searchBar in NavigationBar then shadow should go below to search bar. I want to make a change globally without making a change in every viewController.

https://imgur.com/a/8ogGRaf.jpg

So I already archive these changes except add a shadow below to search controller.

For Shadow:

```<code>self.navigationController?.navigationBar.isTranslucent = false
self.navigationController?.navigationBar.layer.shadowColor = UIColor.black.cgColor
self.navigationController?.navigationBar.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
self.navigationController?.navigationBar.layer.shadowRadius = 7.0
self.navigationController?.navigationBar.layer.shadowOpacity = 0.2
</code>```

For Remove a Bottom Bar:

```<code>UINavigationBar.appearance().backIndicatorImage = UIImage(named:"normal")
UINavigationBar.appearance().backIndicatorTransitionMaskImage = UIImage(named:"normal")
</code>```

This is What issue I'm getting with search Bar

https://imgur.com/a/QQ9yrbE

答:
2.hide bottom line</p>

```<code>public extension UINavigationBar {

    /// Hide line under navigation bar
    public func hideBottomHairline() {
        let navigationBarImageView = hairlineImageViewInNavigationBar(self)
        navigationBarImageView!.isHidden = true
    }

    ///  Show line under navigation bar
    public func showBottomHairline() {
        let navigationBarImageView = hairlineImageViewInNavigationBar(self)
        navigationBarImageView!.isHidden = false
    }

    fileprivate func hairlineImageViewInNavigationBar(_ view: UIView) -> UIImageView? {
        if view.isKind(of: UIImageView.self) && view.bounds.height <= 1.0 {
            return (view as! UIImageView)
        }
        let subviews = (view.subviews as [UIView])
        for subview: UIView in subviews {
            if let imageView: UIImageView = hairlineImageViewInNavigationBar(subview) {
                return imageView
            }
        }
        return nil
    }
}
</code>```

Body:
So I'm looking for how can I add shadow to NavigationBar and remove the bottom black line from NavigationBar? Also if I have searchBar in NavigationBar then shadow should go below to search bar. I want to make a change globally without making a change in every viewController.

https://imgur.com/a/8ogGRaf.jpg

So I already archive these changes except add a shadow below to search controller.

For Shadow:

self.navigationController?.navigationBar.isTranslucent = false
self.navigationController?.navigationBar.layer.shadowColor = UIColor.black.cgColor
self.navigationController?.navigationBar.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
self.navigationController?.navigationBar.layer.shadowRadius = 7.0
self.navigationController?.navigationBar.layer.shadowOpacity = 0.2

For Remove a Bottom Bar:

UINavigationBar.appearance().backIndicatorImage = UIImage(named:"normal")
UINavigationBar.appearance().backIndicatorTransitionMaskImage = UIImage(named:"normal")

This is What issue I'm getting with search Bar

https://imgur.com/a/QQ9yrbE

Body:
2.hide bottom line

public extension UINavigationBar {

    /// Hide line under navigation bar
    public func hideBottomHairline() {
        let navigationBarImageView = hairlineImageViewInNavigationBar(self)
        navigationBarImageView!.isHidden = true
    }

    ///  Show line under navigation bar
    public func showBottomHairline() {
        let navigationBarImageView = hairlineImageViewInNavigationBar(self)
        navigationBarImageView!.isHidden = false
    }

    fileprivate func hairlineImageViewInNavigationBar(_ view: UIView) -> UIImageView? {
        if view.isKind(of: UIImageView.self) && view.bounds.height <= 1.0 {
            return (view as! UIImageView)
        }
        let subviews = (view.subviews as [UIView])
        for subview: UIView in subviews {
            if let imageView: UIImageView = hairlineImageViewInNavigationBar(subview) {
                return imageView
            }
        }
        return nil
    }
}


问:
Airflow: Creating a DAG in airflow via UI
Airflow veterans please help,

I was looking for a cron replacement and came across apache airflow.

We have a setup where multiple users should be able to create their own DAGs and schedule their jobs.

Our users are a mix of people who may not know how to write the DAG python file. Also, they may not have access to the server where airflow is running.

Is it possible to create an airflow DAG via UI. I could not find any reference to the same. All examples speak about creating a python file and uploading it to the $AIRFLOW_HOME/dag/ directory. Users will not have access to this directory.

Rundeck for example allows user to add workflows and task dependencies via UI. Is there a plugin/functionality similar to this in airflow.

PS: I really like the way airflow shows the dependency graphs and want to try it out. But If creating a DAG is so complicated, then it will be a major problem for lots of my end users.

答:
Use Airflow Variable model, it could do it.

Step 1, define you biz model with user inputs
Step 2, write in as dag file in python, the user input could be read by airflow variable model.(key/value mode)
step 3. exchange tasks info by airflow xcom model.

in production mode, user input their parameter in airflow web ui->admin->variable for certain DAG.(key value mode)

then it done.

Recently, I use airflow and dag with user viable to do a lot of different kinds of outlier detection dag for different scenarios.  work smoothly.

hope above experience could help you.


问:
How to use multiple tables using specific condition
I have two table TableA and TableB for these tables data will be populated based on certain process (means TableA will be like temp table if value finialised then data will be moved to TableB)

based on that X condition
I will select the value from TableA else from TableB

```<code>If X=10 condition
select col1,col2,col3,col4 from TableA
else
select col1,col2,col3,col4 from TableB
</code>```

Both tables TableA and TableB will have same table structure,So here i dont want use the same code statement again in else by changing the table name alone.Is any other way that can be used without repeating the select statement again by changing the table.

答:
I think you want this:</p>

```<code>DECLARE @tableName varchar(20)
IF 1=1
set @tableName = 'table1'
ELSE
set @tableName = 'table2'

EXEC ('SELECT * FROM ' + @tableName)
</code>```

Body:
I have two table TableA and TableB for these tables data will be populated based on certain process (means TableA will be like temp table if value finialised then data will be moved to TableB)

based on that X condition
I will select the value from TableA else from TableB

If X=10 condition
select col1,col2,col3,col4 from TableA
else
select col1,col2,col3,col4 from TableB

Both tables TableA and TableB will have same table structure,So here i dont want use the same code statement again in else by changing the table name alone.Is any other way that can be used without repeating the select statement again by changing the table.

Body:
I think you want this:

DECLARE @tableName varchar(20)
IF 1=1
set @tableName = 'table1'
ELSE
set @tableName = 'table2'

EXEC ('SELECT * FROM ' + @tableName)


问:
How to create Custom UITableViewCell with dynamic number of labels
each custom cell in tableview can either have one or two or three or more labels depending on the number of data return from api.

I've tried creating dynamic number of labels into cell in cellForRowAtIndexPath method. But every time I scroll, all these labels overlap each other..Is there any other way to create a dynamic number of labels into a cell?

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "PracLabelCell", for: indexPath) as! PracLabelCell

    let w : CGFloat = CGFloat(self.tableview.frame.size.width/3)
    var x : CGFloat = 0

    for index in 0...2
    {
        let label = UILabel(frame: CGRect(x: x, y: cell.frame.origin.y, width: w , height: cell.frame.size.height))
        let str = String(index)
        print(str)
        label.text = str
        cell.contentView.addSubview(label)
        print("x is" , x)
        x += w

    }

    return cell
}
</code>```

答:
you need to create inner tableview inside cell its more better than loop and create label manually.
  you just need to create tableview inside your main cell. for inner tableview create cell with label thats it now you can return number of cells as you want.
  hope this helps you.

Body:
each custom cell in tableview can either have one or two or three or more labels depending on the number of data return from api.

I've tried creating dynamic number of labels into cell in cellForRowAtIndexPath method. But every time I scroll, all these labels overlap each other..Is there any other way to create a dynamic number of labels into a cell?

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "PracLabelCell", for: indexPath) as! PracLabelCell

    let w : CGFloat = CGFloat(self.tableview.frame.size.width/3)
    var x : CGFloat = 0

    for index in 0...2
    {
        let label = UILabel(frame: CGRect(x: x, y: cell.frame.origin.y, width: w , height: cell.frame.size.height))
        let str = String(index)
        print(str)
        label.text = str
        cell.contentView.addSubview(label)
        print("x is" , x)
        x += w

    }

    return cell
}


问:
Mongoose: How to avoid inserting duplicate records?
I have written the following mongoose function to create new document in mongodb

```<code>createdata: (body) => {
    let sEntry = new SData(Object.assign({}, {
        dataId: body.DataId
    }));
    return sEntry.save();
}
</code>```

I want to modify the above logic so that it doesn't insert two rows with same dataId

In other words, if a particular value of dataId is already existing in mongo then it should not create another entry with same dataId

答:
You need to first install this mongoose-unique-validator for that. Then after you can define  unique: true in

In the second step, you need to define the unique: true in your schema. and also you have to handle the error response.

```<code>var SData = mongoose.Schema({
    dataId: { type: String, index: true, unique: true, required: true },
});

createdata: (body) => {
    let sEntry = new SData(Object.assign({}, {
        dataId: body.DataId
    }));
    return sEntry.save(function() {
        console.log(error)
    });
}
</code>```

Body:
I have written the following mongoose function to create new document in mongodb

createdata: (body) => {
    let sEntry = new SData(Object.assign({}, {
        dataId: body.DataId
    }));
    return sEntry.save();
}

I want to modify the above logic so that it doesn't insert two rows with same dataId

In other words, if a particular value of dataId is already existing in mongo then it should not create another entry with same dataId

Body:
You need to first install this mongoose-unique-validator for that. Then after you can define  unique: true in

In the second step, you need to define the unique: true in your schema. and also you have to handle the error response.

var SData = mongoose.Schema({
    dataId: { type: String, index: true, unique: true, required: true },
});

createdata: (body) => {
    let sEntry = new SData(Object.assign({}, {
        dataId: body.DataId
    }));
    return sEntry.save(function() {
        console.log(error)
    });
}


问:
Drop-down menu not showing values using Thymeleaf
I am creating a Spring Boot application using Maven and Thymeleaf.
I have a class Sessi0n, and another one Module. Sessi0n contains a list of Module (modules).

What I need to do, is to display in a template (using Thymeleaf) my Sessi0n(s), and populate a drop-down list with the module(s) affected to each sessi0n.

Here is my code:

```<code>    <select>
      <th:block th:each="module : ${sessi0n.modules}">
        <p th:text="${module.libelleModule}"></p>
     </th:block>
    </select>
</code>```

I already searched on sites, read the documentation and looked throughout the solutions proposed by Stackoverflow. Even if there are some suggestions that may be suitable for my situation, I still can not figure it out, how to do, in order to make my code work (for each sessi0n that I choose, show me a drop-down menu with all the modules related for this sessi0n).

Many thanks guys, I am new to Thymeleaf, your help would be greatly appreciated.

```<code>    @Entity
    public class Module {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String libelleModule;
    private int duree;
    //getters //setters

    @Entity
    public class Sessi0n {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String libelle;
    private Date dateDebut;
    private Date dateFin;
    @OneToMany (cascade = CascadeType.ALL);
    private List<Module> modules;
    //getter //setter
</code>```

答:
Your select code should be something like this -

```<code><select id="someId">
    <option selected="selected" value="">Choose one...</option>
    <option th:each="object : ${objectList}"
            th:value="${object.id}" th:text="${object.name}">Options</option>
</select>
</code>```

Select component works with option inside it.

Body:
I am creating a Spring Boot application using Maven and Thymeleaf.
I have a class Sessi0n, and another one Module. Sessi0n contains a list of Module (modules).

What I need to do, is to display in a template (using Thymeleaf) my Sessi0n(s), and populate a drop-down list with the module(s) affected to each sessi0n.

Here is my code:

    <select>

    </select>

I already searched on sites, read the documentation and looked throughout the solutions proposed by Stackoverflow. Even if there are some suggestions that may be suitable for my situation, I still can not figure it out, how to do, in order to make my code work (for each sessi0n that I choose, show me a drop-down menu with all the modules related for this sessi0n).

Many thanks guys, I am new to Thymeleaf, your help would be greatly appreciated.

    @Entity
    public class Module {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String libelleModule;
    private int duree;
    //getters //setters

    @Entity
    public class Sessi0n {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String libelle;
    private Date dateDebut;
    private Date dateFin;
    @OneToMany (cascade = CascadeType.ALL);
    private List<Module> modules;
    //getter //setter

Body:
Your select code should be something like this -

<select id="someId">
    <option selected="selected" value="">Choose one...</option>
    <option th:each="object : ${objectList}"
            th:value="${object.id}" th:text="${object.name}">Options</option>
</select>

Select component works with option inside it.


问:
JSON Object to POJO dynamically
I want to store an array of JSON Object into POJO class dynamically how can I do this particular thing in java.</p>

```<code>[
{
"history":"L",
"loan":"12345"
"status":1
.
.
},
{
"History":"L",
"loan":"67890"
"status":1
.
.
},
....
]
</code>```

答:
I am extending Akash's answer.

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;

---

ObjectMapper mapper = new ObjectMapper();

List<DTO> list = mapper.readValue(JSONString, TypeFactory.collectionType(List.class, DTO.class));
```

Title: JSON Object to POJO dynamically

Body:
I want to store an array of JSON Object into POJO class dynamically how can I do this particular thing in java.

[
{
"history":"L",
"loan":"12345"
"status":1
.
.
},
{
"History":"L",
"loan":"67890"
"status":1
.
.
},
....
]


答:
The problem is that most of the nn.Linear layers in the "generalized" version are stored in a regular pythonic list (self.fcLayers). pytorch does not know to look for nn.Paramters inside regular pythonic members of nn.Module.

Solution:

If you wish to store nn.Modules in a way that pytorch can manage them, you need to use specialized pytorch containers.

For instance, if you use nn.ModuleList instead of a regular pythonic list:

```<code>self.fcLayers = nn.ModuleList([])
</code>```

your example should work fine.

BTW,

you need pytorch to know that members of your nn.Module are modules themselves not only to get their parameters, but also for other functions, such as moving them to gpu/cpu, setting their mode to eval/training etc.

Title: Pytorch nn Module generalization

Body:
Let us take a look at the simple class:

class Temp1(nn.Module):

    def __init__(self, stateSize, actionSize, layers=[10, 5], activations=[F.tanh, F.tanh] ):

        super(Temp1, self).__init__()
        self.layer1 = nn.Linear(stateSize, layers[0])
        self.layer2 = nn.Linear(layers[0], layers[1])
        self.fcFinal = nn.Linear( layers[1], actionSize )
        return

This is a fairly straight forward pytorch module. It creates a simple sequential dense network. If we check its hidden parameters, we see the following:

t1 = Temp1(2, 2)
list(t1.parameters())

This is the expected result ...

[Parameter containing:
 tensor([[-0.0311, -0.5513],
         [-0.0634, -0.3783],
         [-0.2514,  0.6139],
         [ 0.4711, -0.0241],
         [-0.1739,  0.2208],
         [-0.1533,  0.3838],
         [-0.6490, -0.5784],
         [ 0.5312,  0.6703],
         [ 0.3506,  0.3652],
         [ 0.1768, -0.4158]], requires_grad=True), Parameter containing:
 tensor([-0.3199, -0.4154, -0.5530, -0.6738, -0.4411,  0.2641, -0.3576,  0.0447,
          0.0254,  0.0965], requires_grad=True), Parameter containing:
 tensor([[-2.8257e-01,  6.7583e-02,  9.0356e-02,  1.0868e-01,  4.0876e-02,
           4.0616e-02,  4.4419e-02, -8.1544e-02,  2.5244e-01,  3.8777e-03],
         [-8.0950e-03, -1.4175e-01, -2.9492e-01,  3.1439e-01, -2.3065e-01,
          -6.6631e-02,  3.0047e-01,  2.8353e-01,  2.3457e-01, -3.1399e-03],
         [-5.2522e-02, -2.2183e-01, -1.5485e-01,  2.6317e-01,  2.8273e-01,
          -7.4823e-02, -5.3704e-02,  9.3526e-02, -1.7916e-01, -3.1132e-04],
         [ 8.9063e-02,  2.9263e-01, -1.0052e-01,  8.7005e-02, -1.1246e-01,
          -2.7968e-01,  4.1411e-02, -1.6776e-01,  1.2363e-01, -2.2808e-01],
         [ 2.9244e-02,  5.8296e-02, -2.9729e-01, -3.1437e-01, -9.3182e-02,
          -7.5236e-03,  5.6159e-02, -2.2075e-02,  1.0337e-01,  8.1123e-02]],
        requires_grad=True), Parameter containing:
 tensor([ 0.2240,  0.0997, -0.0047, -0.1784, -0.0369], requires_grad=True), Parameter containing:
 tensor([[ 0.3546, -0.2180,  0.1723, -0.0463,  0.2572],
         [-0.1669, -0.1364, -0.0398,  0.2233, -0.1805]], requires_grad=True), Parameter containing:
 tensor([ 0.0871, -0.1698], requires_grad=True)]

Now, let us try to generalize this a bit:

class Temp(nn.Module):

    def __init__(self, stateSize, actionSize, layers=[10, 5], activations=[F.tanh, F.tanh] ):

        super(Temp, self).__init__()

        # Generate the fullly connected layer functions
        self.fcLayers = []

        oldN = stateSize
        for i, layer in enumerate(layers):
            self.fcLayers.append( nn.Linear(oldN, layer) )
            oldN = layer
        self.fcFinal = nn.Linear( oldN, actionSize )
        return

It turns out that the number of parameters within this module is no longer the same ...

t = Temp(2, 3)
list(t.parameters())

[Parameter containing:
 tensor([[-0.3342,  0.4111,  0.0418,  0.4457,  0.0648],
         [ 0.4364, -0.0360, -0.2239,  0.4025,  0.1661],
         [ 0.1932, -0.0896,  0.3269, -0.2179,  0.1035]], requires_grad=True),
 Parameter containing:
 tensor([-0.2867, -0.1354, -0.0026], requires_grad=True)]

I believe understand why this is happening. The bigger question is, how do we overcome this problem? The second, generalized method for example will not be sent to the GPU properly, and will not be trained by an optimizer.

Body:
The problem is that most of the nn.Linear layers in the "generalized" version are stored in a regular pythonic list (self.fcLayers). pytorch does not know to look for nn.Paramters inside regular pythonic members of nn.Module.

Solution:

If you wish to store nn.Modules in a way that pytorch can manage them, you need to use specialized pytorch containers.

For instance, if you use nn.ModuleList instead of a regular pythonic list:

self.fcLayers = nn.ModuleList([])

your example should work fine.

BTW,

you need pytorch to know that members of your nn.Module are modules themselves not only to get their parameters, but also for other functions, such as moving them to gpu/cpu, setting their mode to eval/training etc.


问:
How to get all legends from a plot?
I have a Plot with 2 or more legends.
How can I "get" all the legends to change (for example) the color and linestyle in the legend?

handles, labels = ax.get_legend_handles_labels() only gives me the "first" legend, which I added to the plot with plt.legend(). But I want the others legends too, which I added with plt.gca().add_artist(leg2)
How can I do that?

答:
Solution

An alternative: ax.get_legend()

legends = ax.get_legends()
```
<p>To access the properties of the legends:</p>
<pre class="lang-py prettyprint-override"><code>legends = ax.get_legend()
dict_legends = {'Legends': dict()}
if not isinstance(legends, list):
    legends = [legends]
for i, legend in enumerate(legends):
    dict_legend = dict()
    for j, obj in enumerate(lgnd.get_texts()):
        dict_obj = dict()
        dict_fp = dict()
        text = obj.get_text()
        position = obj.get_position()
        color = obj.get_color()
        dict_obj.update({'Text': text,
                         'Position': tuple(position),
                         'Color': color})
        obj_fp = obj.get_font_properties()
        dict_fp.update({'Font_Name': obj_fp.get_name()})
        fontconfig_pattern = obj_fp.get_fontconfig_pattern()
        font_properties = str.split(fontconfig_pattern,":")
        for fp in font_properties:
            if not (fp.strip()==''):
                key, value = fp.split("=")
                dict_fp.update({str.title(key): value})
        dict_fp.update({'fontconfig_pattern': fontconfig_pattern})
        dict_obj.update({'Font_Properties': dict_fp})
        dict_legend.update({'Text_Object_{}'.format(j+1): dict_obj})
    dict_legends['Legends'].update({'Legend_{}'.format(i): {'Legend_Object': legend,
                                                            'Contents': dict_legend}})

print(dict_legends)
</code>```

Configuration:

```<code>#  Windows: 10
#  Python: 3.6
#  Matplotlib: 2.2.2
</code>```

Title: How to get all legends from a plot?

Body:
Solution

An alternative: ax.get_legend()

legends = ax.get_legends()

To access the properties of the legends:

legends = ax.get_legend()
dict_legends = {'Legends': dict()}
if not isinstance(legends, list):
    legends = [legends]
for i, legend in enumerate(legends):
    dict_legend = dict()
    for j, obj in enumerate(lgnd.get_texts()):
        dict_obj = dict()
        dict_fp = dict()
        text = obj.get_text()
        position = obj.get_position()
        color = obj.get_color()
        dict_obj.update({'Text': text,
                         'Position': tuple(position),
                         'Color': color})
        obj_fp = obj.get_font_properties()
        dict_fp.update({'Font_Name': obj_fp.get_name()})
        fontconfig_pattern = obj_fp.get_fontconfig_pattern()
        font_properties = str.split(fontconfig_pattern,":")
        for fp in font_properties:
            if not (fp.strip()==''):
                key, value = fp.split("=")
                dict_fp.update({str.title(key): value})
        dict_fp.update({'fontconfig_pattern': fontconfig_pattern})
        dict_obj.update({'Font_Properties': dict_fp})
        dict_legend.update({'Text_Object_{}'.format(j+1): dict_obj})
    dict_legends['Legends'].update({'Legend_{}'.format(i): {'Legend_Object': legend,
                                                            'Contents': dict_legend}})

print(dict_legends)

Configuration:

#  Windows: 10
#  Python: 3.6
#  Matplotlib: 2.2.2


问:
Send element tr created dynamically to a function and in it, get the values of the input in the td
I have a table to which I am adding records as follows

```<code>    var rowCount = document.getElementById('tblParteDiario').rows.length;

var row = '<tr>' +
    '   <td class="div-table-cell" style="width:8%;text-align:left; font-size=small">' + //0 = Chofer
    '       <input style="width:100%" class="form-control txtChoferAutocomplete' + rowCount + ' " placeholder = "Búsqueda" /> ' +
    '       <input class="txtChoferlID' + rowCount + ' " type="hidden" /> ' +
    '   </td> ' +
    '   <td class="div-table-cell" style="width:5%;text-align:left; font-size=small">' + //1 = Desde
    '        <input type="text"  id="horaDesde" class="timepickerD form-control txtDesde' + rowCount +'"/> ' +
    '   </td> ' +
    '   <td class="div-table-cell" style="width:5%;text-align:left; font-size=small">' + //2 = Hasta
    '        <input type="text" id="horaHasta" onBlur="testFunction(this.parentNode.parentNode);" class="timepickerH form-control txtHasta' + rowCount + '"/> ' +
    '   </td> ' +
    '   <td class="div-table-cell" style="width:3%;text-align:left; font-size=small">' + //3 = TiempoTranscurrido
    '        <input type="text" class="form-control txtTranscurrido' + rowCount + '"/> ' +
    '   </td> ' +
    '   <td class="div-table-cell" style="width:8%;text-align:left; font-size=small">' + //4 = Pozo
    '       <input style="width:100%" class="form-control txtPozoAutocomplete' + rowCount + ' " placeholder = "Búsqueda" /> ' +
    '       <input class="txtPozolID' + rowCount + ' " type="hidden" /> ' +
    '   </td> ' +
    '</tr>';

$("#tblParteDiario").append(row);
</code>```

In the input of the column "2 = Hasta" I have specified that in the onBlur call a function and it receives the element tr, well, that works. How do I get the value of the inputs that are in the td 1 and 3, for example and in the case of the column "4 = Pozo" how do I get the value of the first input within the td

I leave the function that receives the tr with one of the many attempts that made to achieve the objective. In this case, the log tells me that .find is not a valid function

```<code>function testFunction(element) {
element.find('td:eq(3) input').each(function () {
    task = this.value;
    console.log(task);
});}
</code>```

答:
You can easily do that with jquery. All you have to do is find the input with the class name that you have. for example for first td and first input we say in the function for the element that we have sent to find the input with class name txtChoferAutocomplete and then get the value for it.

Below is an example of every input. you can delete the ones that you dont want.

function testFunction(element) {
  var txtChoferAutocomplete = $(element).find(".txtChoferAutocomplete").val();
  var txtChoferlID = $(element).find(".txtChoferlID").val();
  var txtDesde = $(element).find(".txtDesde").val();
  var txtHasta = $(element).find(".txtHasta").val();
  var txtTranscurrido = $(element).find(".txtTranscurrido").val();
  var txtPozoAutocomplete = $(element).find(".txtPozoAutocomplete").val();
  var txtPozolID = $(element).find(".txtPozolID").val();

  console.log(txtChoferAutocomplete)
  console.log(txtChoferlID)
  console.log(txtDesde)
  console.log(txtHasta)
  console.log(txtTranscurrido)
  console.log(txtPozoAutocomplete)
  console.log(txtPozolID)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
  <tr>
    <td class="div-table-cell">
      <input class="form-control txtChoferAutocomplete 10" placeholder="Búsqueda" />
      <input class="txtChoferlID 10" type="hidden" />
    </td>
    <td class="div-table-cell">
      <input type="text"  id="horaDesde" class="timepickerD form-control txtDesde 10"/>
    </td>
    <td class="div-table-cell">
      <input type="text" id="horaHasta" onblur="testFunction(this.parentNode.parentNode);" class="timepickerH form-control txtHasta 10"/>
    </td>
    <td class="div-table-cell">
      <input type="text" class="form-control txtTranscurrido 10"/>
    </td>
    <td class="div-table-cell">
      <input class="form-control txtPozoAutocomplete 10" placeholder="Búsqueda" />
      <input class="txtPozolID 10" type="hidden" />
    </td>
  </tr>
</table></code>```

Body:
I have a table to which I am adding records as follows

    var rowCount = document.getElementById('tblParteDiario').rows.length;

var row = '
' +
    '   ' + //0 = Chofer
    '       <input style="width:100%" class="form-control txtChoferAutocomplete' + rowCount + ' " placeholder = "Búsqueda" /> ' +
    '       <input class="txtChoferlID' + rowCount + ' " type="hidden" /> ' +
    '   	 ' +
    '   ' + //1 = Desde
    '        <input type="text"  id="horaDesde" class="timepickerD form-control txtDesde' + rowCount +'"/> ' +
    '   	 ' +
    '   ' + //2 = Hasta
    '        <input type="text" id="horaHasta" onBlur="testFunction(this.parentNode.parentNode);" class="timepickerH form-control txtHasta' + rowCount + '"/> ' +
    '   	 ' +
    '   ' + //3 = TiempoTranscurrido
    '        <input type="text" class="form-control txtTranscurrido' + rowCount + '"/> ' +
    '   	 ' +
    '   ' + //4 = Pozo
    '       <input style="width:100%" class="form-control txtPozoAutocomplete' + rowCount + ' " placeholder = "Búsqueda" /> ' +
    '       <input class="txtPozolID' + rowCount + ' " type="hidden" /> ' +
    '   	 ' +
    '
';

$("#tblParteDiario").append(row);

In the input of the column "2 = Hasta" I have specified that in the onBlur call a function and it receives the element tr, well, that works. How do I get the value of the inputs that are in the td 1 and 3, for example and in the case of the column "4 = Pozo" how do I get the value of the first input within the td

I leave the function that receives the tr with one of the many attempts that made to achieve the objective. In this case, the log tells me that .find is not a valid function

function testFunction(element) {
element.find('td:eq(3) input').each(function () {
    task = this.value;
    console.log(task);
});}

Body:
You can easily do that with jquery. All you have to do is find the input with the class name that you have. for example for first td and first input we say in the function for the element that we have sent to find the input with class name txtChoferAutocomplete and then get the value for it.

Below is an example of every input. you can delete the ones that you dont want.

function testFunction(element) {
  var txtChoferAutocomplete = $(element).find(".txtChoferAutocomplete").val();
  var txtChoferlID = $(element).find(".txtChoferlID").val();
  var txtDesde = $(element).find(".txtDesde").val();
  var txtHasta = $(element).find(".txtHasta").val();
  var txtTranscurrido = $(element).find(".txtTranscurrido").val();
  var txtPozoAutocomplete = $(element).find(".txtPozoAutocomplete").val();
  var txtPozolID = $(element).find(".txtPozolID").val();

  console.log(txtChoferAutocomplete)
  console.log(txtChoferlID)
  console.log(txtDesde)
  console.log(txtHasta)
  console.log(txtTranscurrido)
  console.log(txtPozoAutocomplete)
  console.log(txtPozolID)
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
  <tr>
    <td class="div-table-cell">
      <input class="form-control txtChoferAutocomplete 10" placeholder="Búsqueda" />
      <input class="txtChoferlID 10" type="hidden" />
    </td>
    <td class="div-table-cell">
      <input type="text"  id="horaDesde" class="timepickerD form-control txtDesde 10"/>
    </td>
    <td class="div-table-cell">
      <input type="text" id="horaHasta" onblur="testFunction(this.parentNode.parentNode);" class="timepickerH form-control txtHasta 10"/>
    </td>
    <td class="div-table-cell">
      <input type="text" class="form-control txtTranscurrido 10"/>
    </td>
    <td class="div-table-cell">
      <input class="form-control txtPozoAutocomplete 10" placeholder="Búsqueda" />
      <input class="txtPozolID 10" type="hidden" />
    </td>
  </tr>
</table>