问:
I am looking for a solution to group objects by a unique key together
I currently have an array something like this, there is a unique key in each object I can use (example: "_key": "qpfPdAZdFk"), I want to be able to group them into their own arrays

```<code>[
 {
    "node": {
        "entity_as_json": {
        "_key": "qpfPdAZdFk"
    },
    1:1

},
{

    "node": {
        "entity_as_json": {
        "_key": "qpfPdabcd",
    },
    2:2
},
{

    "node": {
        "entity_as_json": {
        "_key": "qpfPdAZdFk"
    }
    3:3
},
{
    "node": {
        "entity_as_json": {
        "_key": "qpfPdAZdFk"
    },
    4:4

},
{
    "node": {
        "entity_as_json": {
        "_key": "qpfPdabcd",
    },
    5:5
},
{
    "node": {
        "entity_as_json": {
        "_key": "qpfPdabcd",
    },
    6:6
},
]
</code>```

I want to be able return a grouped together array's like this

```<code>[
[
    {
        "node": {
            "entity_as_json": {
            "_key": "qpfPdAZdFk"
        },
        1:1

    },
    {

        "node": {
              "entity_as_json": {
            "_key": "qpfPdAZdFk"
        }
        3:3
    },
    {
        "node": {
              "entity_as_json": {
            "_key": "qpfPdAZdFk"
        },
        4:4

    },
],

[
    {

        "node": {
              "entity_as_json": {
            "_key": "qpfPdabcd",
        },
        2:2
    },
    {
        "node": {
              "entity_as_json": {
            "_key": "qpfPdabcd",
        },
        5:5
    },
    {
        "node": {
              "entity_as_json": {
            "_key": "qpfPdabcd",
        },
        6:6
    },
 ]
]
</code>```

I have been trying to think of a solution but I cant seem to get it working, is there some kind of way in JavaScript to identify by unique? I can use Lodash if that would work.

Any help much appreciated

答:
Lodash is prefect for situations like this. Lodash has a groupBy function https://lodash.com/docs/4.17.15#groupBy which you can use like this

```<code>import _ from 'lodash'

const groupedCollection = _.groupBy(collection, 'node._key')
</code>```

Body:
I currently have an array something like this, there is a unique key in each object I can use (example: "_key": "qpfPdAZdFk"), I want to be able to group them into their own arrays

[
 {
    "node": {
        "entity_as_json": {
        "_key": "qpfPdAZdFk"
    },
    1:1

},
{

    "node": {
        "entity_as_json": {
        "_key": "qpfPdabcd",
    },
    2:2
},
{

    "node": {
        "entity_as_json": {
        "_key": "qpfPdAZdFk"
    }
    3:3
},
{
    "node": {
        "entity_as_json": {
        "_key": "qpfPdAZdFk"
    },
    4:4

},
{
    "node": {
        "entity_as_json": {
        "_key": "qpfPdabcd",
    },
    5:5
},
{
    "node": {
        "entity_as_json": {
        "_key": "qpfPdabcd",
    },
    6:6
},
]

I want to be able return a grouped together array's like this

[
[
    {
        "node": {
            "entity_as_json": {
            "_key": "qpfPdAZdFk"
        },
        1:1

    },
    {

        "node": {
              "entity_as_json": {
            "_key": "qpfPdAZdFk"
        }
        3:3
    },
    {
        "node": {
              "entity_as_json": {
            "_key": "qpfPdAZdFk"
        },
        4:4

    },
],

[
    {

        "node": {
              "entity_as_json": {
            "_key": "qpfPdabcd",
        },
        2:2
    },
    {
        "node": {
              "entity_as_json": {
            "_key": "qpfPdabcd",
        },
        5:5
    },
    {
        "node": {
              "entity_as_json": {
            "_key": "qpfPdabcd",
        },
        6:6
    },
 ]
]

I have been trying to think of a solution but I cant seem to get it working, is there some kind of way in JavaScript to identify by unique? I can use Lodash if that would work.

Any help much appreciated

Body:
Lodash is prefect for situations like this. Lodash has a groupBy function https://lodash.com/docs/4.17.15#groupBy which you can use like this

import _ from 'lodash'

const groupedCollection = _.groupBy(collection, 'node._key')


来源: stackexchange

问:
Database calls in Custom Authorization Handler returning a NullReference Error in Blazor Server
I'm currently creating a Blazor Server application that uses Azure AD for Authentication. The authentication works perfectly but I want to set up some AuthorisedView's within the application.

I've created a custom Authorization Handler whereby I take the user's email and find what user group they belong to within my own sql server. For the database calls I'm using Dapper with some table models. When I make a database call within the HandleRequirementAsync function it returns a NullReference exception. I cannot see where there could be an error within the code, am I missing something obvious?

The users list should return the user in the database and then groups list should return the group that user is assigned to based on an ID. Both of these calls work perfectly throughout the rest of the application, it only causes errors within this section below.

GroupHandler.cs

```<code>public class GroupHandler : AuthorizationHandler<GroupRequirement>
{
    public IUserData _dbUser;
    public IGroupData _dbGroup;

    protected async override Task<Task> HandleRequirement(AuthorizationHandlerContect context, GroupRequirement requirement)
    {
        var emailAddress = context.User.Identity.Name;

        List<UserModel> users = await _dbUser.GetUserByEmail(emailAddress);
        List<GroupModel> groups = await _dbGroup.GetGroupByID(users[0].Group_ID.ToString());

        if(groups[0].Group.Contains(requirement.Group))
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }
}
</code>```

GroupRequirement.cs

```<code>public class GroupRequirement : IAuthorizationRequirement
{
    public string Group { get; }

    public GroupRequirement(string group)
    {
        Group = group;
    }
}
</code>```

Startup.cs

```<code>services.AddAuthorization(config =>
{
    config.AddPolicy("IsAdmin", policy =>
        policy.Requirements.Add(new GroupRequirement("Admin")));
});
</code>```

Error

```<code>NullReferenceException: Object reference not set an instance of an object

GroupHandler.HandleRequirementAsync(AuthorizationHandlerContext context, GroupRequirement requirement) in GroupHandler.cs, line 30

List<UserModel> users = await _dbUser.GetUserByEmail(emailAddress);
</code>```

答:
It looks like you never assign the _dbGroup Field in your GroupHandler class.

Depending on your Setup you may be able to inject a IUserData via a constructor.

ContentLicense: CC BY-SA 4.0

Body:
I'm currently creating a Blazor Server application that uses Azure AD for Authentication. The authentication works perfectly but I want to set up some AuthorisedView's within the application.

I've created a custom Authorization Handler whereby I take the user's email and find what user group they belong to within my own sql server. For the database calls I'm using Dapper with some table models. When I make a database call within the HandleRequirementAsync function it returns a NullReference exception. I cannot see where there could be an error within the code, am I missing something obvious?

The users list should return the user in the database and then groups list should return the group that user is assigned to based on an ID. Both of these calls work perfectly throughout the rest of the application, it only causes errors within this section below.

GroupHandler.cs

public class GroupHandler : AuthorizationHandler<GroupRequirement>
{
    public IUserData _dbUser;
    public IGroupData _dbGroup;

    protected async override Task<Task> HandleRequirement(AuthorizationHandlerContect context, GroupRequirement requirement)
    {
        var emailAddress = context.User.Identity.Name;

        List<UserModel> users = await _dbUser.GetUserByEmail(emailAddress);
        List<GroupModel> groups = await _dbGroup.GetGroupByID(users[0].Group_ID.ToString());

        if(groups[0].Group.Contains(requirement.Group))
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }
}

GroupRequirement.cs

public class GroupRequirement : IAuthorizationRequirement
{
    public string Group { get; }

    public GroupRequirement(string group)
    {
        Group = group;
    }
}

Startup.cs

services.AddAuthorization(config =>
{
    config.AddPolicy("IsAdmin", policy =>
        policy.Requirements.Add(new GroupRequirement("Admin")));
});

Error

NullReferenceException: Object reference not set an instance of an object

GroupHandler.HandleRequirementAsync(AuthorizationHandlerContext context, GroupRequirement requirement) in GroupHandler.cs, line 30

List<UserModel> users = await _dbUser.GetUserByEmail(emailAddress);


问:
In Python Creating dictionary from the group-by result and making list for the unique elements
I have this dataset:

```<code>pd.DataFrame({'pid' : ['12A', '12A', '12A', '10B', '10B', '10B', '10B'],
                'wips' : ['Aa', 'Aa', 'Aa', 'Dd', 'Dd', 'Dd', 'Dd'],
                'be':['charlie','charlie','charlie','hanami','hanami','hanami','hanami'],
                'rownum':[1,2,3,1,2,3,4]})
</code>```
```<code>   pid wips       be  rownum
0  12A   Aa  charlie       1
1  12A   Aa  charlie       2
2  12A   Aa  charlie       3
3  10B   Dd   hanami       1
4  10B   Dd   hanami       2
5  10B   Dd   hanami       3
6  10B   Dd   hanami       4
</code>```

I need to convert this df into a dictionary, like this -

```<code>[{'pid':'12A','wips':'Aa','be':'charlie','rownum':[1,2,3]},{'pid':'10B','wips':'Dd','be':'hanami','rownum':[1,2,3,4]}]
</code>```

Please help me with a piece of code to get this result. Thank you.

答:
we can first groupby with list then to_dict

```<code>out = df.groupby(['pid','wips','be'])['rownum'].agg(list).reset_index().to_dict('records')
Out[16]:
[{'pid': '10B', 'wips': 'Dd', 'be': 'hanami', 'rownum': [1, 2, 3, 4]},
 {'pid': '12A', 'wips': 'Aa', 'be': 'charlie', 'rownum': [1, 2, 3]}]
</code>```

Body:
I have this dataset:

pd.DataFrame({'pid' : ['12A', '12A', '12A', '10B', '10B', '10B', '10B'],
                'wips' : ['Aa', 'Aa', 'Aa', 'Dd', 'Dd', 'Dd', 'Dd'],
                'be':['charlie','charlie','charlie','hanami','hanami','hanami','hanami'],
                'rownum':[1,2,3,1,2,3,4]})

   pid wips       be  rownum
0  12A   Aa  charlie       1
1  12A   Aa  charlie       2
2  12A   Aa  charlie       3
3  10B   Dd   hanami       1
4  10B   Dd   hanami       2
5  10B   Dd   hanami       3
6  10B   Dd   hanami       4

I need to convert this df into a dictionary, like this -

[{'pid':'12A','wips':'Aa','be':'charlie','rownum':[1,2,3]},{'pid':'10B','wips':'Dd','be':'hanami','rownum':[1,2,3,4]}]

Please help me with a piece of code to get this result. Thank you.

Body:
we can first groupby with list then to_dict

out = df.groupby(['pid','wips','be'])['rownum'].agg(list).reset_index().to_dict('records')
Out[16]:
[{'pid': '10B', 'wips': 'Dd', 'be': 'hanami', 'rownum': [1, 2, 3, 4]},
 {'pid': '12A', 'wips': 'Aa', 'be': 'charlie', 'rownum': [1, 2, 3]}]


答:
Group, apply list, turn into dict.</p>
```<code>result = df.groupby(['pid', 'wips', 'be'])['rownum'].apply(list).reset_index().to_dict(orient='records')
</code>```

Title: In Python Creating dictionary from the group-by result and making list for the unique elements

Body:
Group, apply list, turn into dict.

result = df.groupby(['pid', 'wips', 'be'])['rownum'].apply(list).reset_index().to_dict(orient='records')


问:
Rails: Reset a model attribute at specific time each day
I have a rails app with a Location model, which has a rating, and a rating_count field. Now, I need to reset every Location's rating and rating_countattributes to 0 at a specific time everyday, lets say 12:00:00 UTC.

How would I accomplish this? I'm using the default sqlite3 databases.

答: The best option is to use cron. You can find tons of documentation out there!Although if you are running a Rails app you should check out whenever a pretty neat gem for managing cron jobs for your app!</p>

ContentLicense: CC BY-SA 3.0


问:
Laravel: Search by similar string
I'm trying to make a search feature on laravel. now I'm using this query:

```<code>$products = Product::with(['category', 'store'])
            ->when($keywords, function ($query) use ($keywords) {
                $query->where('name', 'LIKE', '%' . $keywords . "%")
                    ->orWhere('description', 'LIKE', '%' . $keywords . '%');
            })->get()
</code>```

The problem is, say on the database i've a product with the name corrupti, If i searched by the exact name or removed a character from beginning or end it works fine, but if I changed a single character it returns an empty list.

Users are likely to make typos, so I want to be able to find the product is the user typed corrupta, corrupi instead of corrupti.

I know this is not a simple task to achive, I googled many things but I didn't find a solution.

One thing I've came accross is the php similar_text funciton, it may be useful but I didn't find a way to include it in the database query.

答:
try this:</p>
```<code>$query = Product::query();
    $searches = explode(' ', $request->query('q'));

                if (isset($searches)) {
                    foreach ($searches as $search) {
                        $query->where(function ($q) use ($search) {
                            $q->where('code', 'ilike', '%' . $search . '%')
                                ->orWhere('name', 'ilike', '%' . $search . '%');
                        });
                    }
                }

                $data = $query->get();

                return ([
                    'success'   => true,
                    'response'  => $data,
                    'message'   => 'Your message here'
                ]);
</code>```

Title: Laravel: Search by similar string

Body:
I'm trying to make a search feature on laravel. now I'm using this query:

$products = Product::with(['category', 'store'])
            ->when($keywords, function ($query) use ($keywords) {
                $query->where('name', 'LIKE', '%' . $keywords . "%")
                    ->orWhere('description', 'LIKE', '%' . $keywords . '%');
            })->get()

The problem is, say on the database i've a product with the name corrupti, If i searched by the exact name or removed a character from beginning or end it works fine, but if I changed a single character it returns an empty list.

Users are likely to make typos, so I want to be able to find the product is the user typed corrupta, corrupi instead of corrupti.

I know this is not a simple task to achive, I googled many things but I didn't find a solution.

One thing I've came accross is the php similar_text funciton, it may be useful but I didn't find a way to include it in the database query.

Body:
try this:

$query = Product::query();
    $searches = explode(' ', $request->query('q'));

                if (isset($searches)) {
                    foreach ($searches as $search) {
                        $query->where(function ($q) use ($search) {
                            $q->where('code', 'ilike', '%' . $search . '%')
                                ->orWhere('name', 'ilike', '%' . $search . '%');
                        });
                    }
                }

                $data = $query->get();

                return ([
                    'success'   => true,
                    'response'  => $data,
                    'message'   => 'Your message here'
                ]);


问:
Converting binary search tree to linked list
I am trying to convert a binary search tree to a linked list. The linked list should have the smaller numbers in the front and the larger numbers in the back (smallest to largest). I need to create a function that takes in a binary search tree tree and outputs a linked list.

```<code>        4
      /   \
     2     6
   /  \   / \
  1   3  5   7
</code>```

Here's my binary search tree. I need to make the linked list this way: 1, 2, 3, 4, 5, 6, 7. Here's my current code:

```<code>node<int>* makeLinkedList(binary_tree_node<int>* root_ptr);

int main()
{
    binary_tree_node<int> *s1 = sample1();  //Creates the tree

    node<int>* node1 = makeLinkedList(s1);  //invokes function to make a linked list

    //Loop to print out the values of the linked list
    for (node1; node1 != NULL; node1 = node1->link()){
        cout<<node1->data()<<endl;
    }
}

node<int>* makeLinkedList(binary_tree_node<int>* root_ptr){
    node<int>* left;

    if (root_ptr == NULL) {
            return NULL;
    }

    else{

        left = makeLinkedList(root_ptr->left());
        list_head_insert(left, root_ptr->data());  //list_head_insert inserts a new entry at the head of the linked list
        return left;
    }
}
</code>```

When I run my code, the output is 4, 2, 1. I just don't understand how I can convert this binary search tree into a linked list from smallest to largest. I've tried putting list_head_insert function on top of the recursive call, but the output is nothing and the list is empty.

答:
```<code>
class HeadAndTail<T> {
    LinkedListNode<T> head;
    LinkedListNode<T> tail;

    public HeadAndTail() {
        this.head = null;
        this.tail = null;
    }

}

public class Solution {

     public static LinkedListNode<Integer> constructLinkedList(BinaryTreeNode<Integer> root) {
        return construct(root).head;
    }

    public static HeadAndTail<Integer> construct(BinaryTreeNode<Integer> root) {

        if(root == null) {
            return new HeadAndTail<>();
        }

        if(isLeafNode(root)) {
            LinkedListNode<Integer> node = new LinkedListNode<>(root.data);
            HeadAndTail<Integer> headAndTail = new HeadAndTail<>();
            headAndTail.head = node;
            headAndTail.tail = node;
            return headAndTail;
        }

        LinkedListNode<Integer> node = new LinkedListNode<>(root.data);
        HeadAndTail<Integer> forLeftPart = construct(root.left);
        HeadAndTail<Integer> forRightPart = construct(root.right);

        node.next = forRightPart.head;
        HeadAndTail<Integer> headAndTail = new HeadAndTail<>();

        //if left part is null
        if(forLeftPart.tail != null) {
            forLeftPart.tail.next = node;
            headAndTail.head = forLeftPart.head;
        } else{
            headAndTail.head = node;
        }

        //if right part is null
        if(forRightPart.tail != null) {
            headAndTail.tail = forRightPart.tail;
        } else {
            headAndTail.tail = node;
        }

        return headAndTail;
    }

}
</code>```

Body:
I am trying to convert a binary search tree to a linked list. The linked list should have the smaller numbers in the front and the larger numbers in the back (smallest to largest). I need to create a function that takes in a binary search tree tree and outputs a linked list.

        4
      /   \
     2     6
   /  \   / \
  1   3  5   7

Here's my binary search tree. I need to make the linked list this way: 1, 2, 3, 4, 5, 6, 7. Here's my current code:

node<int>* makeLinkedList(binary_tree_node<int>* root_ptr);

int main()
{
    binary_tree_node<int> *s1 = sample1();  //Creates the tree

    node<int>* node1 = makeLinkedList(s1);  //invokes function to make a linked list

    //Loop to print out the values of the linked list
    for (node1; node1 != NULL; node1 = node1->link()){
        cout<<node1->data()<<endl;
    }
}

node<int>* makeLinkedList(binary_tree_node<int>* root_ptr){
    node<int>* left;

    if (root_ptr == NULL) {
            return NULL;
    }

    else{

        left = makeLinkedList(root_ptr->left());
        list_head_insert(left, root_ptr->data());  //list_head_insert inserts a new entry at the head of the linked list
        return left;
    }
}

When I run my code, the output is 4, 2, 1. I just don't understand how I can convert this binary search tree into a linked list from smallest to largest. I've tried putting list_head_insert function on top of the recursive call, but the output is nothing and the list is empty.


问:
Distributed Systems - Events Consumption | Sync Problem
In one of the interviews, I was asked to build a payment ecosystem, which had 2 services - Activity Service and Credit Service. Activity Service is responsible for providing user activity information to the customer. Credit Service is responsible for providing credit related data.

Both these services listen to the same PAYMENT event from a kafka topic. Function of Activity service is listen to the PAYMENT event and make an API call to credit service to fetch credit data and store this aggregated view of PAYMENT event plus credit data into the Activity Database.

Whereas Credit Service also listens to the PAYMENT event and it updates its database based on this event.

One of the problem that is currently faced by the system is that, by the time Activities Service make an API call to Credit Service on consumption of PAYMENT event, the information provided by the Credit Service is not the updated, reason being Credit Service hasn't updated it's database based on the same PAYMENT event.

This looks like classic distributed systems problem. Any insights into how to solve this problem will be highly helpful.

答:
Since it's useful for at least one other service to have both a payment event and the updates from the credit service arising from that event, one reasonable solution might be to have the credit service publish an event which is just the original payment event enriched with the updates the credit service made to its model (or possibly, if consumers are expected to query the credit service, just the fact that it has updated the model).

Then the activity service can subscribe to those enriched events and either:

know that the credit service has processed the corresponding payment event so therefore the credit service's data model has seen the payment event

not have to query the credit service since it has a view of the changes the credit service made to its model

Note that the latter option (not querying, just depending on the enriched view) decouples the two services.

The former option does allow the activity service to see state which was modified based on payment events after the enriched event's payment event: this may or may not be desirable.


问:
Convert decimal mark when reading numbers as input
I have a CSV file with data reading that I want to read into Python. I get lists that contain strings like "2,5". Now doing float("2,5") does not work, because it has the wrong decimal mark.

How do I read this into Python as 2.5?

答:
using a regex  will be more reliable

```<code>import re

decmark_reg = re.compile('(?<=\d),(?=\d)')

ss = 'abc , 2,5 def ,5,88 or (2,5, 8,12, 8945,3 )'

print ss
print decmark_reg.sub('.',ss)
</code>```

result

```<code>abc , 2,5 def ,5,88 or (2,5, 8,12, 8945,3 )
abc , 2.5 def ,5.88 or (2.5, 8.12, 8945.3 )
</code>```

If you want to treat more complex cases (numbers with no digit before the decimal mark for exemple) the regex I crafted to detect all types of numbers in the following thread may be of interest for you:

stackoverflow.com/questions/5917082/regular-expression-to-match-numbers-with-or-without-commas-and-decimals-in-text/5929469

Body:
using a regex  will be more reliable

import re

decmark_reg = re.compile('(?<=\d),(?=\d)')

ss = 'abc , 2,5 def ,5,88 or (2,5, 8,12, 8945,3 )'

print ss
print decmark_reg.sub('.',ss)

result

abc , 2,5 def ,5,88 or (2,5, 8,12, 8945,3 )
abc , 2.5 def ,5.88 or (2.5, 8.12, 8945.3 )

If you want to treat more complex cases (numbers with no digit before the decimal mark for exemple) the regex I crafted to detect all types of numbers in the following thread may be of interest for you:

stackoverflow.com/questions/5917082/regular-expression-to-match-numbers-with-or-without-commas-and-decimals-in-text/5929469


问:
Functional recursive function with reduce
I'm given a sequence tuple(range(1,5)) and I am supposed to write a recursive function with reduce to calculate the product 1*2*3*4*5 = 24.

I don't know how to do this recursively, I've tried looking here https://www.burgaud.com/foldl-foldr-python/ and understand reduce is left-fold. My none recursive implementation is simply:

def red(func, seq):
    return reduce(func, seq)

red(lambda x, y: x*y, tuple(range(1,5)))
```

As reduce is left fold, how can I achieve this?

答:
To make a function recusive, you need to add a case for termination (only one element left) and the recusive call in which you make the problem smaller (go one step ahead in the sequence)

```<code>def reduce(func, seq):
    if len(seq) == 1:
        return seq[0]
    return func(seq[0], reduce(func, seq[1:]))

print(reduce(lambda x, y: x * y, tuple(range(1, 5))))
</code>```

Output:

```<code>24
</code>```

If you're using python 3.10+, you should look into pattern matching for a more functional style in python.

Body:
I'm given a sequence tuple(range(1,5)) and I am supposed to write a recursive function with reduce to calculate the product 1*2*3*4*5 = 24.

I don't know how to do this recursively, I've tried looking here https://www.burgaud.com/foldl-foldr-python/ and understand reduce is left-fold. My none recursive implementation is simply:

def red(func, seq):
    return reduce(func, seq)

red(lambda x, y: x*y, tuple(range(1,5)))

As reduce is left fold, how can I achieve this?

Body:
To make a function recusive, you need to add a case for termination (only one element left) and the recusive call in which you make the problem smaller (go one step ahead in the sequence)

def reduce(func, seq):
    if len(seq) == 1:
        return seq[0]
    return func(seq[0], reduce(func, seq[1:]))

print(reduce(lambda x, y: x * y, tuple(range(1, 5))))

Output:

24

If you're using python 3.10+, you should look into pattern matching for a more functional style in python.


问:
How do I place my terminal in the left side at visual studio code? Version 1.64.1 (2022)
I used to position my terminal at the left side of my visual studio code (as presented on the first image) but now the option to do that is gone, i think some recently update removed it (which seems strange, why would they remove a feature?).

After some googling, i found this How do I move the panel in Visual Studio Code to the right side?
But it doest help me, as my problem is different

Someone knows how i can achieve the same result nowadays?

What i already tried:

Tried to add this command at settings.json "workbench.panel.defaultLocation": "left" but it says it has been deprecated

Right click at terminal header does not show the "Move to Left" option anymore, instead there's only a Move Views to side panel, which results in a right-side placement, not left

View > Appearence does not have the desired option anymore

答:
v1.64.2 is out 02/10/2022 and this can now be done in that release.

Use the command:

View: Move Panel Left from the Command Palette.


问:
Blurred borders in Cairo
What is proper way to draw a blurred rectangular border using the Cairo API? I am writing a patch for Shotwell to add a blurred shadow to the thumbnails in the thumbnail view.

For now I am experimenting with manual blurring.

答:
I ended up drawing the border with linear and radial gradients.

Here is a small visualization. The lines symbolize the linear grandients and the 0 the radial gradients.

```<code>        0
        |
        |
 0------0
</code>```

Title: Blurred borders in Cairo

Body:
I ended up drawing the border with linear and radial gradients.

Here is a small visualization. The lines symbolize the linear grandients and the 0 the radial gradients.

        0
        |
        |
 0------0


问:
How to assign GameObject to child for serialization
I want to assign each item I create with a GameObject of some sort and then when I create a new object (called Item) it will have the assigned GameObject as a child.

For that I have a class of a scriptable object which holds a public GameObject called "gameObj" within it:

```<code>public abstract class ItemObject : ScriptableObject
{
    public int id;
    public GameObject gameObj;
}
</code>```

Then, in another class I want to have something of this sort:

```<code>public class GroundItem : MonoBehaviour, ISerializationCallbackReceiver
{
    public ItemObject item;

    public void OnBeforeSerialize()
    {
        this.gameObject.transform.GetChild(0) = item.gameObj; //WRONG CODE, NEED HELP HERE
    }
}
</code>```

The purpose is to set the gameObj from the given ItemObject.item as the GameObject for the GroundItem.

The purpose is in the end to have lots of scriptable items of all sorts (like bread, sword, stone etc) and each one will have a GameObject assigned to it, and once I create a new GroundItem game object I will simply assign the scriptable object item and its child will have the game object itself (which includes all the visuals, special scripts etc).

For reference, in the following link the person is doing this from minute 4 to minute 6, but with a sprite instead of a game object.

Anyone knows how it should be written? Is it even possible?

答:
You would probably mean

```<code>public class GroundItem : MonoBehaviour, ISerializationCallbackReceiver
{
    public ItemObject item;

    public void OnBeforeSerialize()
    {
        if(!item) return;
        if(!item.gameObj) return;

        // make according object a child of this object
        item.gameObj.transform.parent = transform;

        // make it the firs child
        item.gameObj.transform.SetSiblingIndex(0);
    }
}
</code>```

However, in general ScriptableObjects are assets and GameObjects are instances in the scene hierarchy -> you can't simply reference scene objects in assets, doing so anyway might lead to unexpected behavior.

Is there a good reason why this has to be done in ISerializationCallbackReceiver?

I think what you actually rather want to achieve would be e.g.

```<code>public class GroundItem : MonoBehaviour
{
    public ItemObject item;

#if UNITY_EDITOR
    [HideInInspector]
    [SerializeField]
    private ItemObject _lastItem;

    // This is called whenever something is changed in this objects Inspector
    // like e.g. item ;)
    private void OnValidate()
    {
        // Delay the call in order to not get warnings for SendMessage
        UnityEditor.EditorApplication.delayCall += DelayedOnValidate;
    }

    private void DelayedOnValidate()
    {
        // remove the callback since we want to be sure it is always added only once
        UnityEditor.EditorApplication.delayCall -= DelayedOnValidate;

        // if item hasn't changed nothing to do
        if (item == _lastItem) return;

        // otherwise first destroy current child if any
        if (_lastItem && transform.childCount > 0)
        {
            if (Application.isPlaying) Destroy(transform.GetChild(0).gameObject);
            else DestroyImmediate(transform.GetChild(0).gameObject);
        }

        // is an item referenced and does it even have a gameObject ?
        if (item && item.gameObj)
        {
            // instantiate the new one as child of this object
            var obj = Instantiate(item.gameObj, transform);

            // set as first child (if needed)
            obj.transform.SetSiblingIndex(0);

            if (!Application.isPlaying)
            {
                // if in edit mode mark this object as dirty so it needs to be saved
                UnityEditor.EditorUtility.SetDirty(gameObject);
                UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene());
            }
        }

        _lastItem = item;
    }
#endif
}
</code>```

Which would now look like

Body:
I want to assign each item I create with a GameObject of some sort and then when I create a new object (called Item) it will have the assigned GameObject as a child.

For that I have a class of a scriptable object which holds a public GameObject called "gameObj" within it:

public abstract class ItemObject : ScriptableObject
{
    public int id;
    public GameObject gameObj;
}

Then, in another class I want to have something of this sort:

public class GroundItem : MonoBehaviour, ISerializationCallbackReceiver
{
    public ItemObject item;

    public void OnBeforeSerialize()
    {
        this.gameObject.transform.GetChild(0) = item.gameObj; //WRONG CODE, NEED HELP HERE
    }
}

The purpose is to set the gameObj from the given ItemObject.item as the GameObject for the GroundItem.

The purpose is in the end to have lots of scriptable items of all sorts (like bread, sword, stone etc) and each one will have a GameObject assigned to it, and once I create a new GroundItem game object I will simply assign the scriptable object item and its child will have the game object itself (which includes all the visuals, special scripts etc).

For reference, in the following link the person is doing this from minute 4 to minute 6, but with a sprite instead of a game object.

Anyone knows how it should be written? Is it even possible?

Body:
You would probably mean

public class GroundItem : MonoBehaviour, ISerializationCallbackReceiver
{
    public ItemObject item;

    public void OnBeforeSerialize()
    {
        if(!item) return;
        if(!item.gameObj) return;

        // make according object a child of this object
        item.gameObj.transform.parent = transform;

        // make it the firs child
        item.gameObj.transform.SetSiblingIndex(0);
    }
}

However, in general ScriptableObjects are assets and GameObjects are instances in the scene hierarchy -> you can't simply reference scene objects in assets, doing so anyway might lead to unexpected behavior.

Is there a good reason why this has to be done in ISerializationCallbackReceiver?

I think what you actually rather want to achieve would be e.g.

public class GroundItem : MonoBehaviour
{
    public ItemObject item;

#if UNITY_EDITOR
    [HideInInspector]
    [SerializeField]
    private ItemObject _lastItem;

    // This is called whenever something is changed in this objects Inspector
    // like e.g. item ;)
    private void OnValidate()
    {
        // Delay the call in order to not get warnings for SendMessage
        UnityEditor.EditorApplication.delayCall += DelayedOnValidate;
    }

    private void DelayedOnValidate()
    {
        // remove the callback since we want to be sure it is always added only once
        UnityEditor.EditorApplication.delayCall -= DelayedOnValidate;

        // if item hasn't changed nothing to do
        if (item == _lastItem) return;

        // otherwise first destroy current child if any
        if (_lastItem && transform.childCount > 0)
        {
            if (Application.isPlaying) Destroy(transform.GetChild(0).gameObject);
            else DestroyImmediate(transform.GetChild(0).gameObject);
        }

        // is an item referenced and does it even have a gameObject ?
        if (item && item.gameObj)
        {
            // instantiate the new one as child of this object
            var obj = Instantiate(item.gameObj, transform);

            // set as first child (if needed)
            obj.transform.SetSiblingIndex(0);

            if (!Application.isPlaying)
            {
                // if in edit mode mark this object as dirty so it needs to be saved
                UnityEditor.EditorUtility.SetDirty(gameObject);
                UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene());
            }
        }

        _lastItem = item;
    }
#endif
}

Which would now look like


问:
jQuery disable a link
Anyone know how to disable a link in jquery WITHOUT using return false;?

Specifically, what I'm trying to do is disable the link of an item, performing a click on it using jquery which triggers some stuff, then re-enabling that link so that if it's clicked again it works as default.

Thanks.
Dave

UPDATE
Here's the code. What it needs to do after the .expanded class has been applied is to re-enable the disabled link.

```<code>$('ul li').click(function(e) {
    e.preventDefault();
    $('ul').addClass('expanded');
    $('ul.expanded').fadeIn(300);
    //return false;
});
</code>```

答:
As a back-end engineer, it took me a while to wrap my head around how to do this but here is how i solved the exact same problem.

```<code>const resendCodeTimeOutPeriodInMs = 30000; // 30seconds.

function resend2faCodeOnLogin(sendByEmail) {

const resendCodeLinkElement = $('#resendCodeLink');

const disabledState = resendCodeLinkElement.attr('disabled');
if (disabledState === 'disabled') {
    resendCodeLinkElement.preventDefault();
} else {
    resendCodeLinkElement.attr("disabled", true);
    resendCodeLinkElement.addClass('disabled');

    submitForm('#twoFactorResendCodeForm', (response) => {
        setTimeout(function () {
            $('#resendCodeLink').removeClass('disabled');
            resendCodeLinkElement.attr("disabled", false);
        }, resendCodeTimeOutPeriodInMs);

    }, (response) => {
        console.error(response);
    });
}
}
</code>```

Standard CSS taken from well known examples off the web:

```<code>a.disabled {
opacity: 0.5;
pointer-events: none;
cursor: default;
</code>```

My Approach was to ensure a given button is disabled for 30s before the UX can click it again.

ContentLicense: CC BY-SA 2.5

Title: jQuery disable a link

Body:
Anyone know how to disable a link in jquery WITHOUT using return false;?

Specifically, what I'm trying to do is disable the link of an item, performing a click on it using jquery which triggers some stuff, then re-enabling that link so that if it's clicked again it works as default.

Thanks.
Dave

UPDATE
Here's the code. What it needs to do after the .expanded class has been applied is to re-enable the disabled link.

$('ul li').click(function(e) {
    e.preventDefault();
    $('ul').addClass('expanded');
    $('ul.expanded').fadeIn(300);
    //return false;
});

Body:
As a back-end engineer, it took me a while to wrap my head around how to do this but here is how i solved the exact same problem.

const resendCodeTimeOutPeriodInMs = 30000; // 30seconds.

function resend2faCodeOnLogin(sendByEmail) {

const resendCodeLinkElement = $('#resendCodeLink');

const disabledState = resendCodeLinkElement.attr('disabled');
if (disabledState === 'disabled') {
    resendCodeLinkElement.preventDefault();
} else {
    resendCodeLinkElement.attr("disabled", true);
    resendCodeLinkElement.addClass('disabled');

    submitForm('#twoFactorResendCodeForm', (response) => {
        setTimeout(function () {
            $('#resendCodeLink').removeClass('disabled');
            resendCodeLinkElement.attr("disabled", false);
        }, resendCodeTimeOutPeriodInMs);

    }, (response) => {
        console.error(response);
    });
}
}

Standard CSS taken from well known examples off the web:

a.disabled {
opacity: 0.5;
pointer-events: none;
cursor: default;

My Approach was to ensure a given button is disabled for 30s before the UX can click it again.


问:
Kotlin - MutableList that does not allow duplicate Object
Is there idiomatic expression or extension sample for a MutableList and List that does not allow duplicate object or if possible, update the existing object in list if duplicate? Just like how HashMap works? I am not sure if using .map {} is the most efficient way of doing it.

Note: Still need having a correct index.

答:
The Set interface allows only one of each unique item, where "unique" is in terms of the class's equals function.

The Set interface does not guarantee fixed order of elements as part of its contract, but all the Kotlin standard library functions that create Sets create Sets that do maintain order of elements (the order they were added to the set).

You can iterate a Set with index using forEachIndexed or for((index, item) in set.withIndex()).

There's no indexed access operator for sets, but you could create an extension that enables it. Note that since Sets with order are backed by linked wrappers instead of an array, it is inefficient to access elements by index, because it has to iterate up to that index to retrieve the value.

```<code>operator fun <T> Set<T>.get(index: Int) = asSequence().drop(index).first()
</code>```

If you have a MutableSet, you cannot insert elements at a specific index. You would have to clear it and reinsert everything in the order you want.

Body:
The Set interface allows only one of each unique item, where "unique" is in terms of the class's equals function.

The Set interface does not guarantee fixed order of elements as part of its contract, but all the Kotlin standard library functions that create Sets create Sets that do maintain order of elements (the order they were added to the set).

You can iterate a Set with index using forEachIndexed or for((index, item) in set.withIndex()).

There's no indexed access operator for sets, but you could create an extension that enables it. Note that since Sets with order are backed by linked wrappers instead of an array, it is inefficient to access elements by index, because it has to iterate up to that index to retrieve the value.

operator fun <T> Set<T>.get(index: Int) = asSequence().drop(index).first()

If you have a MutableSet, you cannot insert elements at a specific index. You would have to clear it and reinsert everything in the order you want.


问:
Jetpack Compose text is not getting updated
I am trying a Tic tac toe sample project. Once user performs click I am receiving callbacks but when trying to update text it's not basically updating text. Below is my code, please help. So far I have tried Need to put below text to shut-up SO error bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla:</p>
```<code>enum class Player {
    Human, Computer
}

var board = arrayListOf("", "", "", "", "", "", "", "", "")
private var currentPlayer = Player.Computer

fun updatePosition(position: Int) {
    if (board[position].isEmpty())
        if (currentPlayer == Player.Human) {
            board[position] = "X"
            currentPlayer = Player.Computer
        } else {
            board[position] = "O"
            currentPlayer = Player.Human
        }
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
        ComposeTicTacToeTheme {
            Surface(
                modifier = Modifier.fillMaxWidth(),
                color = MaterialTheme.colors.background
            ) {
                Greeting(board, this::updatePosition)
            }
        }
    }
}
</code>```
```<code>@Composable
fun Greeting(board: ArrayList<String>, onclick: (Int) -> Unit) {
    Column{
        Row {
            Cell(board[0]) { onclick(0) }
            Cell(board[1]) { onclick(1) }
            Cell(board[2]) { onclick(2) }
        }
        Row {
            Cell(board[3]) { onclick(3) }
            Cell(board[4]) { onclick(4) }
            Cell(board[5]) { onclick(5) }
        }
        Row {
            Cell(board[6]) { onclick(6) }
            Cell(board[7]) { onclick(7) }
            Cell(board[8]) { onclick(8) }
        }
    }
}

@Composable
fun Cell(
    name: String,
    onClick: () -> Unit
) {
    Card(
        modifier = Modifier
            .width(130.dp)
            .height(130.dp)
            .padding(12.dp),
        elevation = 8.dp,
        contentColor = Color.Black,
        shape = RoundedCornerShape(80.dp),
        onClick = onClick
    ) {
        Text(
            name, fontSize = 80.sp,
            textAlign = TextAlign.Center,
            modifier = Modifier
                .background(color = Color.Yellow)
        )
    }
}

</code>```

答:
In order to let Compose know that recomposition is needed, you have to use a special State wrapper for your values. In case of array, you can use mutableStateListOf instead of arrayListOf:

```<code>val board = mutableStateListOf("", "", "", "", "", "", "", "", "")
</code>```

For more details I suggest you start with state in Compose documentation, including this youtube video which explains the basic principles.

Body:
I am trying a Tic tac toe sample project. Once user performs click I am receiving callbacks but when trying to update text it's not basically updating text. Below is my code, please help. So far I have tried Need to put below text to shut-up SO error bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla:

enum class Player {
    Human, Computer
}

var board = arrayListOf("", "", "", "", "", "", "", "", "")
private var currentPlayer = Player.Computer

fun updatePosition(position: Int) {
    if (board[position].isEmpty())
        if (currentPlayer == Player.Human) {
            board[position] = "X"
            currentPlayer = Player.Computer
        } else {
            board[position] = "O"
            currentPlayer = Player.Human
        }
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
        ComposeTicTacToeTheme {
            Surface(
                modifier = Modifier.fillMaxWidth(),
                color = MaterialTheme.colors.background
            ) {
                Greeting(board, this::updatePosition)
            }
        }
    }
}

@Composable
fun Greeting(board: ArrayList<String>, onclick: (Int) -> Unit) {
    Column{
        Row {
            Cell(board[0]) { onclick(0) }
            Cell(board[1]) { onclick(1) }
            Cell(board[2]) { onclick(2) }
        }
        Row {
            Cell(board[3]) { onclick(3) }
            Cell(board[4]) { onclick(4) }
            Cell(board[5]) { onclick(5) }
        }
        Row {
            Cell(board[6]) { onclick(6) }
            Cell(board[7]) { onclick(7) }
            Cell(board[8]) { onclick(8) }
        }
    }
}

@Composable
fun Cell(
    name: String,
    onClick: () -> Unit
) {
    Card(
        modifier = Modifier
            .width(130.dp)
            .height(130.dp)
            .padding(12.dp),
        elevation = 8.dp,
        contentColor = Color.Black,
        shape = RoundedCornerShape(80.dp),
        onClick = onClick
    ) {
        Text(
            name, fontSize = 80.sp,
            textAlign = TextAlign.Center,
            modifier = Modifier
                .background(color = Color.Yellow)
        )
    }
}

Body:
In order to let Compose know that recomposition is needed, you have to use a special State wrapper for your values. In case of array, you can use mutableStateListOf instead of arrayListOf:

val board = mutableStateListOf("", "", "", "", "", "", "", "", "")

For more details I suggest you start with state in Compose documentation, including this youtube video which explains the basic principles.


问:
XML String in ImageView
I have a String with xml's drawable code. I need to use this String inside ImageView like image. And I need to create many such images in activity using kotlin/java code.

I tried to write data to xml file and then convert file to Drawable

```<code>     /**
     * Write text to file
     */
    fun stringToDom(xmlSource : String, filePath: String) {
        val fw = FileWriter(filePath)
        fw.write(xmlSource)
        fw.close()
    }

    //...
    val uri : Uri = Uri.parse("android.resource://com.example.package/" + R.drawable.temp)
    stringToDom(i, uri.toString())
    val d : Drawable = Drawable.createFromXml(context.resources, context.resources.getXml(R.drawable.temp))
    //...
</code>```

And parse xml string with XmlPullParser

```<code>     val parser : XmlPullParser = Xml.newPullParser();
     parser.setInput(StringReader(myXmlString));
     val d : Drawable = Drawable.createFromXml(resources, parser)
</code>```

But all of this doesn't work.

答:
The Android framework works with binary (compiled) XML files for drawables. If you are trying to work with with drawable XML source directly, you have some work to do. First you will have to compile the source XML into the binary format. This answer from Nicolas explains how to do that. It doesn't appear to be a complete answer, though, since it looks like it just compiles "Path" statements, but it's a start. This type of compilation is what the AAPT tool does for you through the regular tool chain. Other than AAPT, I don't know of another library that will do the compilation, but one may exist. I haven't tried Nicolas's code, but it looks right.

Once you have the compilation done, this answer, also from Nicolas, explains how to get the binary XML you create into a format that Android can use.

If your source refers to just Android resources (resource id = 0x01xxxxxx) then you will be able to match them within your app since Android resource ids are stable across releases. If your source refers to application resources (resource id = 0x7fxxxxxx), you will have trouble if the resource id doesn't exist in your app or is otherwise different.

(If this sounds like a little too much, you should consider an SVG converting library as CommonsWare suggests.)

If you can influence what comes over the network, you can precompile the drawables in the binary format within an app, extract the compiled XML and send that over the network. This will save you the first step since AAPT will do the compilation for you and leave you with just the second step. You will still need to ensure that there is no resource mismatch.

Title: XML String in ImageView

Body:
I have a String with xml's drawable code. I need to use this String inside ImageView like image. And I need to create many such images in activity using kotlin/java code.

I tried to write data to xml file and then convert file to Drawable

     /**
     * Write text to file
     */
    fun stringToDom(xmlSource : String, filePath: String) {
        val fw = FileWriter(filePath)
        fw.write(xmlSource)
        fw.close()
    }

    //...
    val uri : Uri = Uri.parse("android.resource://com.example.package/" + R.drawable.temp)
    stringToDom(i, uri.toString())
    val d : Drawable = Drawable.createFromXml(context.resources, context.resources.getXml(R.drawable.temp))
    //...

And parse xml string with XmlPullParser

     val parser : XmlPullParser = Xml.newPullParser();
     parser.setInput(StringReader(myXmlString));
     val d : Drawable = Drawable.createFromXml(resources, parser)

But all of this doesn't work.


问:
Setting up a WindowsHook in Python (ctypes, Windows API)
I am trying to globally track the mouse with a Python (3.4.3) background app (in Windows 7/8). This involves setting up a WindowsHook which should return me a valid handle to that specific hook - but my handle is always 0.

Tracking only the mouse position is very easy with GetCursorPos (as an alternative GetCursorInfo works as well):

from ctypes.wintypes import *
ppoint = ctypes.pointer(POINT())
ctypes.windll.user32.GetCursorPos(ppoint)
print('({}, {})'.format(ppoint[0].x, ppoint[0].y))
```

<p>Also convenient to track only the position is <code>GetMouseMovePointsEx</code>, which tracks the last 64 mouse positions:</p>

<pre class="lang-py prettyprint-override"><code>from ctypes.wintypes import *

# some additional types and structs
ULONG_PTR = ctypes.c_ulong
class MOUSEMOVEPOINT(ctypes.Structure):
    _fields_ = [
        ("x", ctypes.c_int),
        ("y", ctypes.c_int),
        ("time", DWORD),
        ("dwExtraInfo", ULONG_PTR)
    ]
GMMP_USE_DISPLAY_POINTS = 1

# get initial tracking point
ppoint = ctypes.pointer(POINT())
ctypes.windll.user32.GetCursorPos(ppoint)
point = MOUSEMOVEPOINT(ppoint[0].x,ppoint[0].y)

# track last X points
number_mouse_points = 64
points = (MOUSEMOVEPOINT * number_mouse_points)()
ctypes.windll.user32.GetMouseMovePointsEx(ctypes.sizeof(MOUSEMOVEPOINT),
    ctypes.pointer(point), ctypes.pointer(points), number_mouse_points,
    GMMP_USE_DISPLAY_POINTS)

# print results
for point in points:
    print('({}, {})'.format(point.x, point.y))
</code>```

However I want to be able to also track clicks, drags, etc.
A good solution seems to be the LowLevelMouseProc. (There might be another way yet to be explored: Raw Input)

To be able to use the LowLevelMouseProc the documentation tells us to use SetWindowsHookEx(W/A), which is also covered in various (C++) tutorials (C#), as well as some interesting projects (also C#).

The documentation defines it in C++ as follows:

HHOOK WINAPI SetWindowsHookEx(
  _In_ int       idHook,
  _In_ HOOKPROC  lpfn,
  _In_ HINSTANCE hMod,
  _In_ DWORD     dwThreadId
);
```

<p>Where the following should be the correct values for me in python:</p>

<ul>
<li><code>idHook</code>: <code>WH_MOUSE_LL = 14</code></li>
<li><code>hMod</code>: <code>HINSTANCE(0)</code> (basically a null pointer)</li>
<li><code>dwThreadId</code>: <code>ctypes.windll.kernel32.GetCurrentThreadId()</code></li>
</ul>

<p>And for the <code>lpfn</code> I need some callback implementing the <code>LowLevelMouseProc</code>, here <code>LLMouseProc</code>: </p>

<pre class="lang-py prettyprint-override"><code>def _LLMouseProc (nCode, wParam, lParam):
    return ctypes.windll.user32.CallNextHookEx(None, nCode, wParam, lParam)
LLMouseProcCB = ctypes.CFUNCTYPE(LRESULT, ctypes.c_int, WPARAM, LPARAM)
LLMouseProc = LLMouseProcCB(_LLMouseProc)
</code>```

Putting it all together I expected this to work:

from ctypes.wintypes import *

LONG_PTR = ctypes.c_long
LRESULT = LONG_PTR
WH_MOUSE_LL = 14

def _LLMouseProc(nCode, wParam, lParam):
    print("_LLMouseProc({!s}, {!s}, {!s})".format(nCode, wParam, lParam))
    return ctypes.windll.user32.CallNextHookEx(None, nCode, wParam, lParam)
LLMouseProcCB = ctypes.CFUNCTYPE(LRESULT, ctypes.c_int, WPARAM, LPARAM)
LLMouseProc = LLMouseProcCB(_LLMouseProc)

threadId = ctypes.windll.kernel32.GetCurrentThreadId()

# register callback as hook
print('hook = SetWindowsHookExW({!s}, {!s}, {!s}, {!s})'.format(WH_MOUSE_LL, LLMouseProc,
    HINSTANCE(0), threadId))
hook = ctypes.windll.user32.SetWindowsHookExW(WH_MOUSE_LL, LLMouseProc,
    HINSTANCE(0), threadId)
print('Hook: {}'.format(hook))

import time
try:
    while True:
        time.sleep(0.2)
except KeyboardInterrupt:
    pass
```

<p>But the output reveals that <code>hook == 0</code>:</p>

<pre class="lang-none prettyprint-override"><code>hook = SetWindowsHookExW(14, <CFunctionType object at 0x026183F0>, c_void_p(None), 5700)
Hook: 0
</code>```

I think that maybe the last parameter of the callback function, name lParam is not really correct as LPARAM (which is ctypes.c_long), since what I assume is really expected is a pointer to this struct:

class MSLLHOOKSTRUCT(ctypes.Structure):
    _fields_ = [
        ("pt", POINT),
        ("mouseData", DWORD),
        ("flags", DWORD),
        ("time", DWORD),
        ("dwExtraInfo", ULONG_PTR)
    ]
```

But changing the signature to LLMouseProcCB = ctypes.CFUNCTYPE(LRESULT, ctypes.c_int, WPARAM, ctypes.POINTER(MSLLHOOKSTRUCT)) does not solve the problem, I still have a hook of 0.

Is this the right approach of tracking the mouse? What do I need to change to be able to correctly register hooks with Windows?

答:
A simplified version of the accepted answer

Note: pip install pywin32 first.

# Created by BaiJiFeiLong@gmail.com at 2022/2/10 22:27

from ctypes import WINFUNCTYPE, c_int, Structure, cast, POINTER, windll
from ctypes.wintypes import LPARAM, WPARAM, DWORD, PULONG, LONG

import win32con
import win32gui

def genStruct(name="Structure", **kwargs):
    return type(name, (Structure,), dict(
        _fields_=list(kwargs.items()),
        __str__=lambda self: "%s(%s)" % (name, ",".join("%s=%s" % (k, getattr(self, k)) for k in kwargs))
    ))

@WINFUNCTYPE(LPARAM, c_int, WPARAM, LPARAM)
def hookProc(nCode, wParam, lParam):
    msg = cast(lParam, POINTER(HookStruct))[0]
    print(msgDict[wParam], msg)
    return windll.user32.CallNextHookEx(None, nCode, WPARAM(wParam), LPARAM(lParam))

HookStruct = genStruct(
    "Hook", pt=genStruct("Point", x=LONG, y=LONG), mouseData=DWORD, flags=DWORD, time=DWORD, dwExtraInfo=PULONG)
msgDict = {v: k for k, v in win32con.__dict__.items() if k.startswith("WM_")}
windll.user32.SetWindowsHookExW(win32con.WH_MOUSE_LL, hookProc, None, 0)
win32gui.PumpMessages()
```
<h2>Sample Output</h2>
```WM_MOUSEMOVE Hook(pt=Point(x=50,y=702),mouseData=0,flags=0,time=343134468,dwExtraInfo=<ctypes.wintypes.LP_c_ulong object at 0x000001A466CDF8C8>)
WM_MOUSEMOVE Hook(pt=Point(x=49,y=704),mouseData=0,flags=0,time=343134484,dwExtraInfo=<ctypes.wintypes.LP_c_ulong object at 0x000001A466CDF8C8>)
WM_MOUSEMOVE Hook(pt=Point(x=49,y=705),mouseData=0,flags=0,time=343134484,dwExtraInfo=<ctypes.wintypes.LP_c_ulong object at 0x000001A466CDF8C8>)
WM_MOUSEMOVE Hook(pt=Point(x=49,y=705),mouseData=0,flags=0,time=343134500,dwExtraInfo=<ctypes.wintypes.LP_c_ulong object at 0x000001A466CDF8C8>)
WM_MOUSEMOVE Hook(pt=Point(x=49,y=706),mouseData=0,flags=0,time=343134500,dwExtraInfo=<ctypes.wintypes.LP_c_ulong object at 0x000001A466CDF8C8>)
WM_MOUSEMOVE Hook(pt=Point(x=48,y=707),mouseData=0,flags=0,time=343134515,dwExtraInfo=<ctypes.wintypes.LP_c_ulong object at 0x000001A466CDF8C8>)
WM_LBUTTONDOWN Hook(pt=Point(x=48,y=707),mouseData=0,flags=0,time=343134593,dwExtraInfo=<ctypes.wintypes.LP_c_ulong object at 0x000001A466CDF8C8>)
WM_LBUTTONUP Hook(pt=Point(x=48,y=707),mouseData=0,flags=0,time=343134671,dwExtraInfo=<ctypes.wintypes.LP_c_ulong object at 0x000001A466CDF8C8>)
```

Body:
I am trying to globally track the mouse with a Python (3.4.3) background app (in Windows 7/8). This involves setting up a WindowsHook which should return me a valid handle to that specific hook - but my handle is always 0.

Tracking only the mouse position is very easy with GetCursorPos (as an alternative GetCursorInfo works as well):

from ctypes.wintypes import *
ppoint = ctypes.pointer(POINT())
ctypes.windll.user32.GetCursorPos(ppoint)
print('({}, {})'.format(ppoint[0].x, ppoint[0].y))

Also convenient to track only the position is GetMouseMovePointsEx, which tracks the last 64 mouse positions:

from ctypes.wintypes import *

# some additional types and structs
ULONG_PTR = ctypes.c_ulong
class MOUSEMOVEPOINT(ctypes.Structure):
    _fields_ = [
        ("x", ctypes.c_int),
        ("y", ctypes.c_int),
        ("time", DWORD),
        ("dwExtraInfo", ULONG_PTR)
    ]
GMMP_USE_DISPLAY_POINTS = 1

# get initial tracking point
ppoint = ctypes.pointer(POINT())
ctypes.windll.user32.GetCursorPos(ppoint)
point = MOUSEMOVEPOINT(ppoint[0].x,ppoint[0].y)

# track last X points
number_mouse_points = 64
points = (MOUSEMOVEPOINT * number_mouse_points)()
ctypes.windll.user32.GetMouseMovePointsEx(ctypes.sizeof(MOUSEMOVEPOINT),
    ctypes.pointer(point), ctypes.pointer(points), number_mouse_points,
    GMMP_USE_DISPLAY_POINTS)

# print results
for point in points:
    print('({}, {})'.format(point.x, point.y))

However I want to be able to also track clicks, drags, etc.
A good solution seems to be the LowLevelMouseProc. (There might be another way yet to be explored: Raw Input)

To be able to use the LowLevelMouseProc the documentation tells us to use SetWindowsHookEx(W/A), which is also covered in various (C++) tutorials (C#), as well as some interesting projects (also C#).

The documentation defines it in C++ as follows:

HHOOK WINAPI SetWindowsHookEx(
  _In_ int       idHook,
  _In_ HOOKPROC  lpfn,
  _In_ HINSTANCE hMod,
  _In_ DWORD     dwThreadId
);

Where the following should be the correct values for me in python:

idHook: WH_MOUSE_LL = 14

hMod: HINSTANCE(0) (basically a null pointer)

dwThreadId: ctypes.windll.kernel32.GetCurrentThreadId()

And for the lpfn I need some callback implementing the LowLevelMouseProc, here LLMouseProc:

def _LLMouseProc (nCode, wParam, lParam):
    return ctypes.windll.user32.CallNextHookEx(None, nCode, wParam, lParam)
LLMouseProcCB = ctypes.CFUNCTYPE(LRESULT, ctypes.c_int, WPARAM, LPARAM)
LLMouseProc = LLMouseProcCB(_LLMouseProc)

Putting it all together I expected this to work:

from ctypes.wintypes import *

LONG_PTR = ctypes.c_long
LRESULT = LONG_PTR
WH_MOUSE_LL = 14

def _LLMouseProc(nCode, wParam, lParam):
    print("_LLMouseProc({!s}, {!s}, {!s})".format(nCode, wParam, lParam))
    return ctypes.windll.user32.CallNextHookEx(None, nCode, wParam, lParam)
LLMouseProcCB = ctypes.CFUNCTYPE(LRESULT, ctypes.c_int, WPARAM, LPARAM)
LLMouseProc = LLMouseProcCB(_LLMouseProc)

threadId = ctypes.windll.kernel32.GetCurrentThreadId()

# register callback as hook
print('hook = SetWindowsHookExW({!s}, {!s}, {!s}, {!s})'.format(WH_MOUSE_LL, LLMouseProc,
    HINSTANCE(0), threadId))
hook = ctypes.windll.user32.SetWindowsHookExW(WH_MOUSE_LL, LLMouseProc,
    HINSTANCE(0), threadId)
print('Hook: {}'.format(hook))

import time
try:
    while True:
        time.sleep(0.2)
except KeyboardInterrupt:
    pass

But the output reveals that hook == 0:

hook = SetWindowsHookExW(14, <CFunctionType object at 0x026183F0>, c_void_p(None), 5700)
Hook: 0

I think that maybe the last parameter of the callback function, name lParam is not really correct as LPARAM (which is ctypes.c_long), since what I assume is really expected is a pointer to this struct:

class MSLLHOOKSTRUCT(ctypes.Structure):
    _fields_ = [
        ("pt", POINT),
        ("mouseData", DWORD),
        ("flags", DWORD),
        ("time", DWORD),
        ("dwExtraInfo", ULONG_PTR)
    ]

But changing the signature to LLMouseProcCB = ctypes.CFUNCTYPE(LRESULT, ctypes.c_int, WPARAM, ctypes.POINTER(MSLLHOOKSTRUCT)) does not solve the problem, I still have a hook of 0.

Is this the right approach of tracking the mouse? What do I need to change to be able to correctly register hooks with Windows?

Body:
A simplified version of the accepted answer

Note: pip install pywin32 first.

# Created by BaiJiFeiLong@gmail.com at 2022/2/10 22:27

from ctypes import WINFUNCTYPE, c_int, Structure, cast, POINTER, windll
from ctypes.wintypes import LPARAM, WPARAM, DWORD, PULONG, LONG

import win32con
import win32gui

def genStruct(name="Structure", **kwargs):
    return type(name, (Structure,), dict(
        _fields_=list(kwargs.items()),
        __str__=lambda self: "%s(%s)" % (name, ",".join("%s=%s" % (k, getattr(self, k)) for k in kwargs))
    ))

@WINFUNCTYPE(LPARAM, c_int, WPARAM, LPARAM)
def hookProc(nCode, wParam, lParam):
    msg = cast(lParam, POINTER(HookStruct))[0]
    print(msgDict[wParam], msg)
    return windll.user32.CallNextHookEx(None, nCode, WPARAM(wParam), LPARAM(lParam))

HookStruct = genStruct(
    "Hook", pt=genStruct("Point", x=LONG, y=LONG), mouseData=DWORD, flags=DWORD, time=DWORD, dwExtraInfo=PULONG)
msgDict = {v: k for k, v in win32con.__dict__.items() if k.startswith("WM_")}
windll.user32.SetWindowsHookExW(win32con.WH_MOUSE_LL, hookProc, None, 0)
win32gui.PumpMessages()

Sample Output

WM_MOUSEMOVE Hook(pt=Point(x=50,y=702),mouseData=0,flags=0,time=343134468,dwExtraInfo=<ctypes.wintypes.LP_c_ulong object at 0x000001A466CDF8C8>)
WM_MOUSEMOVE Hook(pt=Point(x=49,y=704),mouseData=0,flags=0,time=343134484,dwExtraInfo=<ctypes.wintypes.LP_c_ulong object at 0x000001A466CDF8C8>)
WM_MOUSEMOVE Hook(pt=Point(x=49,y=705),mouseData=0,flags=0,time=343134484,dwExtraInfo=<ctypes.wintypes.LP_c_ulong object at 0x000001A466CDF8C8>)
WM_MOUSEMOVE Hook(pt=Point(x=49,y=705),mouseData=0,flags=0,time=343134500,dwExtraInfo=<ctypes.wintypes.LP_c_ulong object at 0x000001A466CDF8C8>)
WM_MOUSEMOVE Hook(pt=Point(x=49,y=706),mouseData=0,flags=0,time=343134500,dwExtraInfo=<ctypes.wintypes.LP_c_ulong object at 0x000001A466CDF8C8>)
WM_MOUSEMOVE Hook(pt=Point(x=48,y=707),mouseData=0,flags=0,time=343134515,dwExtraInfo=<ctypes.wintypes.LP_c_ulong object at 0x000001A466CDF8C8>)
WM_LBUTTONDOWN Hook(pt=Point(x=48,y=707),mouseData=0,flags=0,time=343134593,dwExtraInfo=<ctypes.wintypes.LP_c_ulong object at 0x000001A466CDF8C8>)
WM_LBUTTONUP Hook(pt=Point(x=48,y=707),mouseData=0,flags=0,time=343134671,dwExtraInfo=<ctypes.wintypes.LP_c_ulong object at 0x000001A466CDF8C8>)


问:
Youtube - ListChannels with Username(forUsername) is not working
I'm trying to get channels info with ChannelsList. This endpoint has a parameter the name is: forUsername but it does not work for this page: https://www.youtube.com/c/FolkartTr

This is my query and it returns empty data:

Somehow, I got this channelID in the page source and its: "channelId":"[UCnS--2e1yzQCm5r4ClrMJBg]".
When I try to query with this ID it's okay and returns with correct data.

and this is its payload: http://jsonblob.com/941253671862419456

How will I be able to reach this channel info using a username? I got a few links with usernames and I want to get their info with their username. I don't have any chance to get their channelID's for all.

Thanks for your help.

答: If I understood correctly, your problem is that you can't do anything from such a c/ channel id with the Channels: list of the YouTube Data API v3. If you're just looking for the channel id linked to this id then because as YouTube Data API v3 doesn't work for this, I would recommend you to use my open-source YouTube operational API, indeed by requesting https://yt.lemnoslife.com/channels?cId=FolkartTr you'll receive a JSON with id equals to the channel id linked to the provided cId value.


问:
Chi -Square test in R using dplyr
I would like to perform a chi-square test in R using dpylr. Specifically, I would like to investigate whether there is a difference in customer churn between male and female customers. Here a short example of my data.

```<code>  sex   churn
  <fct> <lgl>
 1 W     FALSE
 2 W     FALSE
 3 W     FALSE
 4 W     FALSE
 5 W     FALSE
 6 W     FALSE
 7 W     FALSE
 8 W     FALSE
 9 W     FALSE
10 W     FALSE
11 W     FALSE
12 W     FALSE
13 M     FALSE
14 W     FALSE
15 W     FALSE
16 W     FALSE
17 W     FALSE
18 M     FALSE
19 W     FALSE
20 W     TRUE
21 W     TRUE
22 M     FALSE
23 M     FALSE
24 W     TRUE
25 W     FALSE
</code>```

With the summarise and spread function I already get a nice summary table.

```<code>churn_latest %>%
group_by(sex, churn) %>%
summarise(n = n()) %>%
spread(key = sex, value =  n)
</code>```

Now I would like to apply a chi-square test to it, but I always get the following error: 'x' and 'y' must have at least 2 levels. This is of course the case for me, so I must have an error in the syntax.

```<code>churn_latest %>%
group_by(sex, churn) %>%
summarise(chi = chisq.test(sex, churn))
</code>```

I would be very happy if someone had a solution to my problem. Many thanks in advance!

答:
You’ll first need to produce a contingency table from your data, which you can then pass to chisq.test. To produce the contingency table using ‘dplyr’ & ‘tidyr’ you can use

```<code>churn_latest %>%
    count(sex, churn) %>%
    pivot_wider(names_from = sex, values_from = n, values_fill = 0L)
</code>```

```<code># A tibble: 2 × 3
  churn     M     W
  <lgl> <int> <int>
1 FALSE     4    18
2 TRUE      0     3
</code>```

Next, you need to convert this into a matrix (dropping the key column):

```<code>… %>%
    select(-churn) %>%
    as.matrix()
</code>```

```<code>     M  W
[1,] 4 18
[2,] 0  3
</code>```

And that, finally, can be passed to chisq.test. Putting it all together:

```<code>churn_latest %>%
    count(sex, churn) %>%
    pivot_wider(names_from = sex, values_from = n, values_fill = 0L) %>%
    select(-churn) %>%
    as.matrix() %>%
    chisq.test()
</code>```

… to be fair, using ‘dpyr’ and ‘tidyr’ here is a bit overkill. Base R table does the same much more concisely:

```<code>churn_latest %>%
    table() %>%
    chisq.test()
</code>```

Title: Chi -Square test in R using dplyr

Body:
I would like to perform a chi-square test in R using dpylr. Specifically, I would like to investigate whether there is a difference in customer churn between male and female customers. Here a short example of my data.

  sex   churn
  <fct> <lgl>
 1 W     FALSE
 2 W     FALSE
 3 W     FALSE
 4 W     FALSE
 5 W     FALSE
 6 W     FALSE
 7 W     FALSE
 8 W     FALSE
 9 W     FALSE
10 W     FALSE
11 W     FALSE
12 W     FALSE
13 M     FALSE
14 W     FALSE
15 W     FALSE
16 W     FALSE
17 W     FALSE
18 M     FALSE
19 W     FALSE
20 W     TRUE
21 W     TRUE
22 M     FALSE
23 M     FALSE
24 W     TRUE
25 W     FALSE

With the summarise and spread function I already get a nice summary table.

churn_latest %>%
group_by(sex, churn) %>%
summarise(n = n()) %>%
spread(key = sex, value =  n)

Now I would like to apply a chi-square test to it, but I always get the following error: 'x' and 'y' must have at least 2 levels. This is of course the case for me, so I must have an error in the syntax.

churn_latest %>%
group_by(sex, churn) %>%
summarise(chi = chisq.test(sex, churn))

I would be very happy if someone had a solution to my problem. Many thanks in advance!

Body:
You’ll first need to produce a contingency table from your data, which you can then pass to chisq.test. To produce the contingency table using ‘dplyr’ & ‘tidyr’ you can use

churn_latest %>%
    count(sex, churn) %>%
    pivot_wider(names_from = sex, values_from = n, values_fill = 0L)

# A tibble: 2 × 3
  churn     M     W
  <lgl> <int> <int>
1 FALSE     4    18
2 TRUE      0     3

Next, you need to convert this into a matrix (dropping the key column):

… %>%
    select(-churn) %>%
    as.matrix()

     M  W
[1,] 4 18
[2,] 0  3

And that, finally, can be passed to chisq.test. Putting it all together:

churn_latest %>%
    count(sex, churn) %>%
    pivot_wider(names_from = sex, values_from = n, values_fill = 0L) %>%
    select(-churn) %>%
    as.matrix() %>%
    chisq.test()

… to be fair, using ‘dpyr’ and ‘tidyr’ here is a bit overkill. Base R table does the same much more concisely:

churn_latest %>%
    table() %>%
    chisq.test()


问:
Weird result of using recursion to concat array in javascript
I want to use recursion to build list to array function but the expected result is reversed to real solution. How could I improve the function of listToArray(list)

function arrayToList(arr){
    if(arr.length==1){
        return {value:arr.pop(), rest:null};
    }else{
        return {value:arr.pop(), rest: arrayToList(arr)};
    }
}

//weired result can't find answer
function listToArray(list){
    if(list.rest == null){
        return [list.value];
    }else{
        return [list.value].concat(listToArray(list.rest));
    }
}

console.log(arrayToList([10, 20]));
// → {value: 10, rest: {value: 20, rest: null}}
console.log(listToArray(arrayToList([10, 20, 30])));
// → [10, 20, 30]```

答:
pop() removes the last item so you are reading from the end to the start. So read from the start to the end using shift()

function arrayToList(arr){
    if(arr.length==1){
        return {value:arr.shift(), rest:null};
    }else{
        return {value:arr.shift(), rest: arrayToList(arr)};
    }
}

//weired result can't find answer
function listToArray(list){
    if(list.rest == null){
        return [list.value];
    }else{
        return [list.value].concat(listToArray(list.rest));
    }
}

console.log(arrayToList([10, 20]));
// → {value: 10, rest: {value: 20, rest: null}}
console.log(listToArray(arrayToList([10, 20, 30])));
// → [10, 20, 30]```


问:
The Strange behavior of CompletableFuture
Why the below code does not print I just woke up

```<code>    import java.util.concurrent.CompletableFuture;
    public class CompletableFutureTest {
        public static void main(String[] args) {
            CompletableFuture completableFuture = CompletableFuture.runAsync(()->{
                try {
                    Thread.sleep(4000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("I just woke up.");
            });
            System.out.println("I am main");
        }
    }
</code>```

And the code given below prints I just woke up

```<code>import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CompletableFutureTest {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        CompletableFuture completableFuture = CompletableFuture.runAsync(()->{
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("I just woke up.");
        }, executorService);
        executorService.shutdown();
        System.out.println("I am main");
    }
}
</code>```

The possible noticeable difference between both the codes is that the second sample of code takes Single Thread pool into runAsync method, while the first one does not take any argument that is It uses ForkJoin pool.
Please help me get the reason why is I just woke up not printed in first program

答:
From ForkJoinPool

...All worker threads are initialized with Thread.isDaemon() set true.

From Executors.defaultThreadFactory

...Each new thread is created as a non-daemon thread.

From Thread.setDaemon

...The Java Virtual Machine exits when the only threads running are all daemon threads.

In the first case, the thread is coming from ForkJoinPool.commonPool and hence it is daemon.

And in the second case, the thread is created using Executors.defaultThreadFactory, so is non-daemon.

This explain the different behaviour.

Body:
Why the below code does not print I just woke up

    import java.util.concurrent.CompletableFuture;
    public class CompletableFutureTest {
        public static void main(String[] args) {
            CompletableFuture completableFuture = CompletableFuture.runAsync(()->{
                try {
                    Thread.sleep(4000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("I just woke up.");
            });
            System.out.println("I am main");
        }
    }

And the code given below prints I just woke up

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CompletableFutureTest {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        CompletableFuture completableFuture = CompletableFuture.runAsync(()->{
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("I just woke up.");
        }, executorService);
        executorService.shutdown();
        System.out.println("I am main");
    }
}

The possible noticeable difference between both the codes is that the second sample of code takes Single Thread pool into runAsync method, while the first one does not take any argument that is It uses ForkJoin pool.
Please help me get the reason why is I just woke up not printed in first program


问:
SQL - Update multiple records in one query
I have table - config.
Schema:
config_name | config_value

And I would like to update multiple records in one query. I try like that:

```<code>UPDATE config
SET t1.config_value = 'value'
  , t2.config_value = 'value2'
WHERE t1.config_name = 'name1'
  AND t2.config_name = 'name2';
</code>```

but that query is wrong :(

Can you help me?

答:
just make a transaction statement, with multiple update statement and commit. In error case, you can just rollback modification handle by starting transaction.

```<code>START TRANSACTION;
/*Multiple update statement*/
COMMIT;
</code>```

(This syntax is for MySQL, for PostgreSQL, replace 'START TRANSACTION' by 'BEGIN')

Body:
I have table - config.
Schema:
config_name | config_value

And I would like to update multiple records in one query. I try like that:

UPDATE config
SET t1.config_value = 'value'
  , t2.config_value = 'value2'
WHERE t1.config_name = 'name1'
  AND t2.config_name = 'name2';

but that query is wrong :(

Can you help me?

Body:
just make a transaction statement, with multiple update statement and commit. In error case, you can just rollback modification handle by starting transaction.

START TRANSACTION;
/*Multiple update statement*/
COMMIT;

(This syntax is for MySQL, for PostgreSQL, replace 'START TRANSACTION' by 'BEGIN')


问:
'train' and 'class' have different lengths error in R
I just wanted to conduct a kNN classification with the situation when k is 3. I would like to predict the dependent variable “diabetes” in valid set using train set and calculate the accuracy.

But I faced to the error message with

Error in knn(train = TrainXNormDF, test = ValidXNormDF, cl = MLdata2[,  :  'train' and 'class' have different lengths

I can't solve this problem with get approach with

```<code>for(i in ((length(MLValidY) + 1):length(TrainXNormDF)))+(MLValidY = c(MLValidY, 0))
</code>```

What can I do for it? Please help.

My code is as like below

```<code>install.packages("mlbench")
install.packages("gbm")

library(mlbench)
library(gbm)

data("PimaIndiansDiabetes2")
head(PimaIndiansDiabetes2)

MLdata <- as.data.frame(PimaIndiansDiabetes2)
head(MLdata)
str(MLdata)
View(MLdata)

any(is.na(MLdata))
sum(is.na(MLdata))

MLdata2 <- na.omit(MLdata)
any(is.na(MLdata2))
sum(is.na(MLdata2))
View(MLdata2)

MLIdx <- sample(1:3, size = nrow(MLdata2), prob = c(0.6, 0.2, 0.2), replace = TRUE)

MLTrain <- MLdata2[MLIdx == 1,]
MLValid <- MLdata2[MLIdx == 2,]
MLTest <- MLdata2[MLIdx == 3,]

head(MLTrain)
head(MLValid)
head(MLTest)

str(MLTrain)
str(MLValid)
str(MLTest)

View(MLTestY)

MLTrainX <- MLTrain[ , -9]
MLValidX <- MLValid[ , -9]
MLTestX <- MLTest[ , -9]

MLTrainY <- as.data.frame(MLTrain[ , 9])
MLValidY <- as.data.frame(MLValid[ , 9])
MLTestY <- as.data.frame(MLTest[ , 9])

View(MLTrainX)
View(MLTrainY)

library(caret)

NormValues <- preProcess(MLTrainX, method = c("center", "scale"))

TrainXNormDF <- predict(NormValues, MLTrainX)
ValidXNormDF <- predict(NormValues, MLValidX)
TestXNormDF <- predict(NormValues, MLTestX)

head(TrainXNormDF)
head(ValidXNormDF)
head(TestXNormDF)

install.packages('FNN')
library(FNN)
library(class)

NN <- knn(train = TrainXNormDF,
      test = ValidXNormDF,
      cl = MLValidY,
      k = 3)
</code>```

Thank you

答:
Your cl variable is not the same length as your train variable. MLValidY only has 74 observations, while TrainXNormDF has 224.

cl should provide the true classification for every row in your training set.

Furthermore, cl is a data.frame instead of a vector.

Try the following:

```<code>NN <- knn(train = TrainXNormDF,
      test = ValidXNormDF,
      cl = MLTrainY$`MLTrain[, 9]`,
      k = 3)
</code>```

Body:
I just wanted to conduct a kNN classification with the situation when k is 3. I would like to predict the dependent variable “diabetes” in valid set using train set and calculate the accuracy.

But I faced to the error message with

Error in knn(train = TrainXNormDF, test = ValidXNormDF, cl = MLdata2[,  :  'train' and 'class' have different lengths

I can't solve this problem with get approach with

for(i in ((length(MLValidY) + 1):length(TrainXNormDF)))+(MLValidY = c(MLValidY, 0))

What can I do for it? Please help.

My code is as like below

install.packages("mlbench")
install.packages("gbm")

library(mlbench)
library(gbm)

data("PimaIndiansDiabetes2")
head(PimaIndiansDiabetes2)

MLdata <- as.data.frame(PimaIndiansDiabetes2)
head(MLdata)
str(MLdata)
View(MLdata)

any(is.na(MLdata))
sum(is.na(MLdata))

MLdata2 <- na.omit(MLdata)
any(is.na(MLdata2))
sum(is.na(MLdata2))
View(MLdata2)

MLIdx <- sample(1:3, size = nrow(MLdata2), prob = c(0.6, 0.2, 0.2), replace = TRUE)

MLTrain <- MLdata2[MLIdx == 1,]
MLValid <- MLdata2[MLIdx == 2,]
MLTest <- MLdata2[MLIdx == 3,]

head(MLTrain)
head(MLValid)
head(MLTest)

str(MLTrain)
str(MLValid)
str(MLTest)

View(MLTestY)

MLTrainX <- MLTrain[ , -9]
MLValidX <- MLValid[ , -9]
MLTestX <- MLTest[ , -9]

MLTrainY <- as.data.frame(MLTrain[ , 9])
MLValidY <- as.data.frame(MLValid[ , 9])
MLTestY <- as.data.frame(MLTest[ , 9])

View(MLTrainX)
View(MLTrainY)

library(caret)

NormValues <- preProcess(MLTrainX, method = c("center", "scale"))

TrainXNormDF <- predict(NormValues, MLTrainX)
ValidXNormDF <- predict(NormValues, MLValidX)
TestXNormDF <- predict(NormValues, MLTestX)

head(TrainXNormDF)
head(ValidXNormDF)
head(TestXNormDF)

install.packages('FNN')
library(FNN)
library(class)

NN <- knn(train = TrainXNormDF,
      test = ValidXNormDF,
      cl = MLValidY,
      k = 3)

Thank you

Body:
Your cl variable is not the same length as your train variable. MLValidY only has 74 observations, while TrainXNormDF has 224.

cl should provide the true classification for every row in your training set.

Furthermore, cl is a data.frame instead of a vector.

Try the following:

NN <- knn(train = TrainXNormDF,
      test = ValidXNormDF,
      cl = MLTrainY$`MLTrain[, 9]`,
      k = 3)


问:
Java MS Graph SDK get GraphClient Using an Existing AccessToken (5.13.0 version)
Our Front End using PKCE flow and fetches a access Token. As per the old implementation (microsoft-graph@2.8.1 version) this below snippet gets a Graph Client using an existing access token. Now I cannot get the same working in the newer MS Graph Java SDK.

```<code>IGraphServiceClient client = GraphServiceClient.builder()
                        .authenticationProvider( request -> request.addHeader("Authorization", "Bearer " + tokenAuthentication.getToken().getTokenValue()) )
                        .buildClient();
</code>```

Dependencies I have added to my project

```<code><dependency>
            <!-- Include the sdk as a dependency -->
            <groupId>com.microsoft.graph</groupId>
            <artifactId>microsoft-graph</artifactId>
            <version>5.13.0</version>
        </dependency>
        <dependency>
            <!-- This dependency is only needed if you are using the TokenCrendentialAuthProvider -->
            <groupId>com.azure</groupId>
            <artifactId>azure-identity</artifactId>
            <version>1.2.5</version>
        </dependency>
</code>```

答:
finally got it working.. see below snippet..</p>
```<code>IAuthenticationProvider authProvider = new IAuthenticationProvider() {

            @Override
            public CompletableFuture<String> getAuthorizationTokenAsync(URL requestUrl) {
                CompletableFuture<String> future = new CompletableFuture<>();
                future.complete(yourToken);
                return future;
            }
        };

        GraphServiceClient<Request> graphClient = GraphServiceClient
                .builder()
                .authenticationProvider(authProvider)
                .buildClient();

         return graphClient.me().buildRequest().get();
</code>```

Body:
Our Front End using PKCE flow and fetches a access Token. As per the old implementation (microsoft-graph@2.8.1 version) this below snippet gets a Graph Client using an existing access token. Now I cannot get the same working in the newer MS Graph Java SDK.

IGraphServiceClient client = GraphServiceClient.builder()
                        .authenticationProvider( request -> request.addHeader("Authorization", "Bearer " + tokenAuthentication.getToken().getTokenValue()) )
                        .buildClient();

Dependencies I have added to my project

<dependency>

            <groupId>com.microsoft.graph</groupId>
            <artifactId>microsoft-graph</artifactId>
            <version>5.13.0</version>
        </dependency>
        <dependency>

            <groupId>com.azure</groupId>
            <artifactId>azure-identity</artifactId>
            <version>1.2.5</version>
        </dependency>

Body:
finally got it working.. see below snippet..

IAuthenticationProvider authProvider = new IAuthenticationProvider() {

            @Override
            public CompletableFuture<String> getAuthorizationTokenAsync(URL requestUrl) {
                CompletableFuture<String> future = new CompletableFuture<>();
                future.complete(yourToken);
                return future;
            }
        };

        GraphServiceClient<Request> graphClient = GraphServiceClient
                .builder()
                .authenticationProvider(authProvider)
                .buildClient();

         return graphClient.me().buildRequest().get();


问:
Trying to import SQL File with command
I want to import a sql file to a database. I work on Windows 10 and I want to use the commands lines.

I tried this :

```<code>C:\Program Files\MySQL\MySQL Server 8.0\bin\mysql -u {username} -p{password} db_test < F:\BDD\_databasetest\test.sql
</code>```

But I have an error : "C:\Program not recognized"

So I tried to go by step :

```<code>cd C:\Program Files\MySQL\MySQL Server 8.0\bin
mysql -u {username} -p{password}
mysql db_test < F:\BDD\_databasetest\test.sql
</code>```

But at the third command, I have this error :

ERROR:
Unknown command '\B'.
ERROR:
Unknown command '_'.
Outfile disabled.

For the command "mysql db_test < F:\BDD_databasetest\test.sql" I'm not sure about the "mysql" part so I tried both, with the same error. I tried to double the \ in the path, and I tried to used '' and "" for the path, without succes.

PS : english is not my native language. I clarifications are needed, don't hesitate.

答:
So as the OP confirmed, double-quoting the Windows path helped:
"C:\Program Files\MySQL\MySQL Server 8.0\bin\mysql" -u {username} -p{password} db_test < F:\BDD\_databasetest\test.sql

The error message 'error : "C:\Program not recognized"' suggest that it is not a  mysql-related issue.

Title: Trying to import SQL File with command

Body:
I want to import a sql file to a database. I work on Windows 10 and I want to use the commands lines.

I tried this :

C:\Program Files\MySQL\MySQL Server 8.0\bin\mysql -u {username} -p{password} db_test < F:\BDD\_databasetest\test.sql

But I have an error : "C:\Program not recognized"

So I tried to go by step :

cd C:\Program Files\MySQL\MySQL Server 8.0\bin
mysql -u {username} -p{password}
mysql db_test < F:\BDD\_databasetest\test.sql

But at the third command, I have this error :

ERROR:
Unknown command '\B'.
ERROR:
Unknown command '_'.
Outfile disabled.

For the command "mysql db_test < F:\BDD_databasetest\test.sql" I'm not sure about the "mysql" part so I tried both, with the same error. I tried to double the \ in the path, and I tried to used '' and "" for the path, without succes.

PS : english is not my native language. I clarifications are needed, don't hesitate.


问:
What is good strategy to make a flexible layout for Landscape and Portrait orientation and should also work well in Desktop?
Currently I use fixed width:960px because I want to keep the layout centered in desktop. but doing this it makes problem in iPad portrait mode. I need to re-define widht to 768px and also do adjustments for according to that.

is there a way to make a flexible layout for **Desktop + iPad ( Portrait + Landscape mode) with minimal code and minimal efforts.

答: This might help.. http://matthewjamestaylor.com/blog/ipad-layout-with-landscape-portrait-modes</p>