问:
combine 2 observables
I am using firestore as database and use angularfire2 to retrieve data from it.
I have a collection of comments, in which each comment stores a user id. I want to get the user info such as user displayName and photoURL, and then combine it with the original comments stream to result in a stream consists of both comment info and user info. My attempt to combine the comments and users stream as follows:

```<code>const comments$ = this.afs.collection(`comments`).valueChanges();
const users$ = this.afs.collection(`comments`).valueChanges().pipe(
  switchMap((comments) => {
    return comments.map(comment => this.afs.doc(`users/${comment.uid}`).valueChanges());
  })
);
const combine = zip(comments$, users$, (comments, users) => {
  return {...comments, ...users };
});
</code>```

The above code failed to achieve what I want. Essentially it reads the user id from each of the comment, and then use this user id to find the related user info, and combines them together as a resulting stream. The comments$ observable works properly. The users$ observable didn't work. Also, I am not sure if zip is a proper use in this case.

答:
Seems you have missed the collection name for users. Second line.

```<code>const comments$ = this.afs.collection(`comments`).valueChanges();
const users$ = this.afs.collection(/** HERE?? **/).valueChanges().pipe(
  switchMap((comments) => {
    return comments.map(comment => this.afs.doc(`users/${comment.uid}`).valueChanges());
  })
);
const combine = zip(comments$, users$, (comments, users) => {
  return {...comments, ...users };
});
</code>```

Also it doesn't seem to work, because in must return an observable inside of switchMap.

Title: combine 2 observables

Body:
I am using firestore as database and use angularfire2 to retrieve data from it.
I have a collection of comments, in which each comment stores a user id. I want to get the user info such as user displayName and photoURL, and then combine it with the original comments stream to result in a stream consists of both comment info and user info. My attempt to combine the comments and users stream as follows:

const comments$ = this.afs.collection(`comments`).valueChanges();
const users$ = this.afs.collection(`comments`).valueChanges().pipe(
  switchMap((comments) => {
    return comments.map(comment => this.afs.doc(`users/${comment.uid}`).valueChanges());
  })
);
const combine = zip(comments$, users$, (comments, users) => {
  return {...comments, ...users };
});

The above code failed to achieve what I want. Essentially it reads the user id from each of the comment, and then use this user id to find the related user info, and combines them together as a resulting stream. The comments$ observable works properly. The users$ observable didn't work. Also, I am not sure if zip is a proper use in this case.

Body:
Seems you have missed the collection name for users. Second line.

const comments$ = this.afs.collection(`comments`).valueChanges();
const users$ = this.afs.collection(/** HERE?? **/).valueChanges().pipe(
  switchMap((comments) => {
    return comments.map(comment => this.afs.doc(`users/${comment.uid}`).valueChanges());
  })
);
const combine = zip(comments$, users$, (comments, users) => {
  return {...comments, ...users };
});

Also it doesn't seem to work, because in must return an observable inside of switchMap.


来源: stackexchange

问:
How to change the number of replicas of a Kafka topic?
After a Kafka topic has been created by a producer or an administrator, how would you change the number of replicas of this topic?</p>

答:
Łukasz Dumiszewski's answer is correct but manually generating that file is a bit hard.
Luckily there are some easy ways to achieve what @Łukasz Dumiszewski said.

If you are using kafka-manager tool, from version 2.0.0.2 you can change the replication factor in Generate Partition Assignment section in a topic view. Then you should click on Reassign Partitions to apply the generated partition assignment (if you select a different replication factor, you will get a warning but you can click on Force Reassign afterward).

If you have ruby installed you can use this helper script

If you prefer nodejs you can generate the file with this gist too.

ContentLicense: CC BY-SA 4.0


问:
I want to learn how to make customize xpath for selenium java
I want to learn how to make customize xpath
I tried this

```<code>//*[@class='btn btn-primary goliveBtn btn-lg float-right']//*[@text()="Go Live"]
</code>```

but its not working

答:
you are using multiple attributes,if u want to use multiple attributes you can go for above one but you didn't mention tag for both elements, use tag *(any tag)

//[@class='btn btn-primary goliveBtn btn-lg float-right']//[@text()="Go Live"]

if it is single element to inpect thenuse below

//*[@class='btn btn-primary goliveBtn btn-lg float-right' and  @text()="Go Live"]

Body:
I want to learn how to make customize xpath
I tried this

//*[@class='btn btn-primary goliveBtn btn-lg float-right']//*[@text()="Go Live"]

but its not working


问:
error from service not being caught in component.ts
Once a user logs in, I retrieve their userAccount. In the case that it is not returned, I throw an error in the service. I then proceed to catch the error in a component.ts controller.

For some reason the component.ts does not catch the error being thrown. In console, I can see the errors, but for some reason my component.ts does not catch it in the try/catch block.

I've tested it multiple times to see where it failed and it seems that the error message doesn't reach the catch statement.

This is in my service:

```<code>/* On error: */
error => {

    if (error.status === 401) {

        Helpers.logGroupedErrorObjectsToDevConsole(
            'Login Service: getCustomerAccount()',
            [
                {
                    title: 'Session Timed Out:',
                    info:  true
                }
            ]
        );
    } else {
        Helpers.logGroupedErrorObjectsToDevConsole(
            'Login Service: getCustomerAccount()',
            [
                {
                    title: 'Cannot get customer account:',
                    info: true
                }
            ]
        );
    }

    throw new Error(error);
}
</code>```

this is in my component.ts

```<code>try {
        setTimeout(() => {
           this._service.customer(this.url, this.route)
        }, 1000);
     } catch (e) {
         this.showUnknownLoginFailureMessage  = true;
     }
</code>```

What I expect is for the error to be handled in component.ts

Is it possible?
Am I doing the error handling properly or am I missing something?

I need some guidance.

Thanks in advance!

答:
A try/catch won't catch anything in a callback passed to subscribe (or
  then, or setTimeout or anything smiilar) which runs on a different
  "tick" or "microtask". You have to catch errors in the task where they
  occurred.

There is a solution in this answer https://stackoverflow.com/a/50494803/7179294

Body:
Once a user logs in, I retrieve their userAccount. In the case that it is not returned, I throw an error in the service. I then proceed to catch the error in a component.ts controller.

For some reason the component.ts does not catch the error being thrown. In console, I can see the errors, but for some reason my component.ts does not catch it in the try/catch block.

I've tested it multiple times to see where it failed and it seems that the error message doesn't reach the catch statement.

This is in my service:

/* On error: */
error => {

    if (error.status === 401) {

        Helpers.logGroupedErrorObjectsToDevConsole(
            'Login Service: getCustomerAccount()',
            [
                {
                    title: 'Session Timed Out:',
                    info:  true
                }
            ]
        );
    } else {
        Helpers.logGroupedErrorObjectsToDevConsole(
            'Login Service: getCustomerAccount()',
            [
                {
                    title: 'Cannot get customer account:',
                    info: true
                }
            ]
        );
    }

    throw new Error(error);
}

this is in my component.ts

try {
        setTimeout(() => {
           this._service.customer(this.url, this.route)
        }, 1000);
     } catch (e) {
         this.showUnknownLoginFailureMessage  = true;
     }

What I expect is for the error to be handled in component.ts

Is it possible?
Am I doing the error handling properly or am I missing something?

I need some guidance.

Thanks in advance!


问:
Python - Screen-scraping and controlling mouse in OS X
I'm looking into screen-scraping and controlling the mouse in OS X for a hobby project.

I'm not looking for the most elegant way, but I need to be able to capture the screen every half a second or so.

I've found that I could use the screencapture command-line tool (screencapture -w -W -i ~/Desktop/capture.jpg), but I'm worried that it might not be fast enough.

I'm also looking for a way to send clicks, set the cursor position and obtain the cursor position. Sort of like what win32api provides: mouse_event, SetCursorPos and GetCursorPos.

I've found this sample code that uses the PyObjC library to set the cursor position, but it's always moving my mouse to (0,0) instead of the coordinates I pass it.

```<code>import objc

class ETMouse():
    def setMousePosition(self, x, y):
        bndl = objc.loadBundle('CoreGraphics', globals(),
                '/System/Library/Frameworks/ApplicationServices.framework')
        objc.loadBundleFunctions(bndl, globals(),
                [('CGWarpMouseCursorPosition', 'v{CGPoint=ff}')])
        CGWarpMouseCursorPosition((x, y))

if __name__ == "__main__":
    et = ETMouse()
    et.setMousePosition(500, 500)
</code>```

Edit: I'm running Snow Leopard (10.6) if it matters.

Thanks!

答: Take a look at autopy. Works in OSX, Linux and Windows.</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm looking into screen-scraping and controlling the mouse in OS X for a hobby project.

I'm not looking for the most elegant way, but I need to be able to capture the screen every half a second or so.

I've found that I could use the screencapture command-line tool (screencapture -w -W -i ~/Desktop/capture.jpg), but I'm worried that it might not be fast enough.

I'm also looking for a way to send clicks, set the cursor position and obtain the cursor position. Sort of like what win32api provides: mouse_event, SetCursorPos and GetCursorPos.

I've found this sample code that uses the PyObjC library to set the cursor position, but it's always moving my mouse to (0,0) instead of the coordinates I pass it.

import objc

class ETMouse():
    def setMousePosition(self, x, y):
        bndl = objc.loadBundle('CoreGraphics', globals(),
                '/System/Library/Frameworks/ApplicationServices.framework')
        objc.loadBundleFunctions(bndl, globals(),
                [('CGWarpMouseCursorPosition', 'v{CGPoint=ff}')])
        CGWarpMouseCursorPosition((x, y))

if __name__ == "__main__":
    et = ETMouse()
    et.setMousePosition(500, 500)

Edit: I'm running Snow Leopard (10.6) if it matters.

Thanks!

ContentLicense: CC BY-SA 3.0


问:
Graphite Returns All values, rather than function
Suppose I have the following query:

```<code>http:/graphite.server:####/render?&target=highestCurrent(metric.path.value,3)
</code>```

I am running into the issue that graphite is returning all values in the metric, rather than the last three "highest current".

I am having trouble finding an example that is end to end.  Typically, they consist of only: &target=..., and so I assume that this is just "supposed to work."

What could be a possible source of the issue?

答:
It is supposed to draw all values of the 3 highest metrics/series. Not 3 metrics from of one series.

highestCurrent(seriesList, n)

```<code>Takes one metric or a wildcard seriesList followed by an integer N. Out of all metrics passed, draws only the N metrics with the highest value at the end of the time period specified.

Example:

&target=highestCurrent(server*.instance*.threads.busy,5)

Draws the 5 servers with the highest busy threads.
</code>```

Body:
Suppose I have the following query:

http:/graphite.server:####/render?&target=highestCurrent(metric.path.value,3)

I am running into the issue that graphite is returning all values in the metric, rather than the last three "highest current".

I am having trouble finding an example that is end to end.  Typically, they consist of only: &target=..., and so I assume that this is just "supposed to work."

What could be a possible source of the issue?

Body:
It is supposed to draw all values of the 3 highest metrics/series. Not 3 metrics from of one series.

highestCurrent(seriesList, n)

Takes one metric or a wildcard seriesList followed by an integer N. Out of all metrics passed, draws only the N metrics with the highest value at the end of the time period specified.

Example:

&target=highestCurrent(server*.instance*.threads.busy,5)

Draws the 5 servers with the highest busy threads.


问:
I need to split a value in the variable
I need to split the path defined in below code in following a manner that </p>

```<code>k[0] = /dev/mapper/centos-root
k[1] = 52403200
k[2] = 14460252 an so on.
</code>```

<p>What have I tried?
I tried using the split function but it currently takes k[0] = /
also, I tried passing it into a list where the whole context comes as one value </p>

```<code>command = ("df -P | egrep '([20][0-9]|100)%' |  awk '{print}'|sed -e 's/ / : /g'")
command_execute = (stdin, stdout, stderr) = ssh.exec_command(command)
read_contents = stdout.read().decode("utf-8")
read_contents
'/dev/mapper/centos-root :  :  :  : 52403200 : 14460252 :  : 37942948 :  :  :  :  :  : 28% : /\n'
k=read_contents[0]
k
'/'
k=read_contents[1]
k
'd'
k.split(" ")
['d']
m =k.split(":")
m
['d']
s = [read_contents]
s
['/dev/mapper/centos-root :  :  :  : 52403200 : 14460252 :  : 37942948 :  :  :  :  :  : 28% : /\n']
s[0]
'/dev/mapper/centos-root :  :  :  : 52403200 : 14460252 :  : 37942948 :  :  :  :  :  : 28% : /\n'
s[1]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
IndexError: list index out of range
s[0]
'/dev/mapper/centos-root :  :  :  : 52403200 : 14460252 :  : 37942948 :  :  :  :  :  : 28% : /\n'

k[0] = /dev/mapper/centos-root
k[1] = 52403200
k[2] = 14460252 an so on.
</code>```

Title: I need to split a value in the variable

Body:
I need to split the path defined in below code in following a manner that

k[0] = /dev/mapper/centos-root
k[1] = 52403200
k[2] = 14460252 an so on.

What have I tried?
I tried using the split function but it currently takes k[0] = /
also, I tried passing it into a list where the whole context comes as one value

command = ("df -P | egrep '([20][0-9]|100)%' |  awk '{print}'|sed -e 's/ / : /g'")
command_execute = (stdin, stdout, stderr) = ssh.exec_command(command)
read_contents = stdout.read().decode("utf-8")
read_contents
'/dev/mapper/centos-root :  :  :  : 52403200 : 14460252 :  : 37942948 :  :  :  :  :  : 28% : /\n'
k=read_contents[0]
k
'/'
k=read_contents[1]
k
'd'
k.split(" ")
['d']
m =k.split(":")
m
['d']
s = [read_contents]
s
['/dev/mapper/centos-root :  :  :  : 52403200 : 14460252 :  : 37942948 :  :  :  :  :  : 28% : /\n']
s[0]
'/dev/mapper/centos-root :  :  :  : 52403200 : 14460252 :  : 37942948 :  :  :  :  :  : 28% : /\n'
s[1]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
IndexError: list index out of range
s[0]
'/dev/mapper/centos-root :  :  :  : 52403200 : 14460252 :  : 37942948 :  :  :  :  :  : 28% : /\n'

k[0] = /dev/mapper/centos-root
k[1] = 52403200
k[2] = 14460252 an so on.

Body:
import re
a='/dev/mapper/centos-root :52403200 : 14460252 :  : 37942948 :  :  :  :  :  : 28% : /\n'
print(re.split(r'(?:\s+:)+',a))


问:
Laravel RAW query is orders of magnitude slower than the same query outside of Laravel
I'm using Laravel 5.2 and PHP 7.0.6 on Debian. MySQL is 5.5.30 on a remote server.

When I run the query through HeidiSQL or from the command line client it executes in about 0.2 seconds. Executing the exact same SQL in Laravel (debug mode on or off) takes nearly 500 seconds. I tried pulling the Laravel query out of the MySQL query log and running it, and it ran fast. It's only when executing the statement through Laravel that it's slow. The laravel code is below. My timer code is before and after this line, so the slowdown is definitely here. The query only returns one row.

```<code>$results = \DB::select($sql);
</code>```

An anonymized version of the query is below (business-specific data would otherwise be visible). Hopefully I haven't mangled anything in the process.

```<code>SELECT  ll.id,
    ll.other_id,
    ll.third_id,
    ll.created_at,
    ll.h_id,
    ll.sub,
    ll.sub2,
    ll.status,
    px.created_at,
    b.abbr,
    ldl.transaction_id,
    ldl.purchase_price,
    CONCAT(ld.first_name, ' ', ld.last_name) as fullname,
    lcase(ll.email_address) as email_address,
    ll.total_revenue

FROM    table1 ll
INNER JOIN table2 ld on ll.id = ld.fid
INNER JOIN table3 ldl on ll.id = ldl.fid
LEFT OUTER JOIN table4 px on ll.id = px.fid
INNER JOIN table5 b on ldl.bid = b.id

WHERE ll.created_at > '2016-05-04 00:00:00'
AND ll.created_at < '2016-05-04 23:59:59'
AND v_id IN (41,42,43,45,46)
AND ldl.b_id IN (131)
AND lcase(ll.email_address) in ('example@email.com')
AND ll.status = 'ACCEPTED'
</code>```

答:
I experienced this issue and finally found a solution. I had a query that when I ran on the command line it executed in about 40ms. When I put the same exact query into Laravel using:

```<code>DB::select( $myQuery ); // Where $myQuery is the exact string I ran on the command line
</code>```

...the query took about 1 minute. Something was clearly wrong.

In the end, it had everything to do with parameter binding. By simply changing this:

```<code>DB::select("SELECT * FROM users WHERE username='Andrew'");
</code>```

...to this:

```<code>DB::select("SELECT * FROM users WHERE username = :name",['name' => 'Andrew']);
</code>```

My problem was solved.

Body:
I'm using Laravel 5.2 and PHP 7.0.6 on Debian. MySQL is 5.5.30 on a remote server.

When I run the query through HeidiSQL or from the command line client it executes in about 0.2 seconds. Executing the exact same SQL in Laravel (debug mode on or off) takes nearly 500 seconds. I tried pulling the Laravel query out of the MySQL query log and running it, and it ran fast. It's only when executing the statement through Laravel that it's slow. The laravel code is below. My timer code is before and after this line, so the slowdown is definitely here. The query only returns one row.

$results = \DB::select($sql);

An anonymized version of the query is below (business-specific data would otherwise be visible). Hopefully I haven't mangled anything in the process.

SELECT  ll.id,
    ll.other_id,
    ll.third_id,
    ll.created_at,
    ll.h_id,
    ll.sub,
    ll.sub2,
    ll.status,
    px.created_at,
    b.abbr,
    ldl.transaction_id,
    ldl.purchase_price,
    CONCAT(ld.first_name, ' ', ld.last_name) as fullname,
    lcase(ll.email_address) as email_address,
    ll.total_revenue

FROM    table1 ll
INNER JOIN table2 ld on ll.id = ld.fid
INNER JOIN table3 ldl on ll.id = ldl.fid
LEFT OUTER JOIN table4 px on ll.id = px.fid
INNER JOIN table5 b on ldl.bid = b.id

WHERE ll.created_at > '2016-05-04 00:00:00'
AND ll.created_at < '2016-05-04 23:59:59'
AND v_id IN (41,42,43,45,46)
AND ldl.b_id IN (131)
AND lcase(ll.email_address) in ('example@email.com')
AND ll.status = 'ACCEPTED'

Body:
I experienced this issue and finally found a solution. I had a query that when I ran on the command line it executed in about 40ms. When I put the same exact query into Laravel using:

DB::select( $myQuery ); // Where $myQuery is the exact string I ran on the command line

...the query took about 1 minute. Something was clearly wrong.

In the end, it had everything to do with parameter binding. By simply changing this:

DB::select("SELECT * FROM users WHERE username='Andrew'");

...to this:

DB::select("SELECT * FROM users WHERE username = :name",['name' => 'Andrew']);

My problem was solved.


问:
Database Design For Historical Table
I have a table of employers(Table A). I want to create a similar table with an extra date column(Table B), showing the date the rows were inserted. I want to insert the rows from Table A to the new table at the end of every month. Is there a way to automate this in SQL?

I have heard that you can do this through stored procedures, but I don't have any experience using them and any guidance would be greatly appreciated.

Here is what the table may look like:

```<code>MemberID First Last   Department Salary Daily_Hours Active_Flag
100      Evan  Turner Sales      75000  8           1
200      Ron   Gold   Marketing  80000  9           1
300      Bob   Gun    HR         50000  8           1
</code>```

Desired output:

```<code>ID MemberID First Last   Department Salary Daily_Hours Active_Flag Date
1  100      Evan  Turner Sales      75000  8           1           3/31/19
2  200      Ron   Gold   Marketing  80000  9           1           3/31/19
3  300      Bob   Gun    HR         50000  8           1           3/31/19
4  100      Evan  Turner Sales      75000  8           1           4/30/19
5  200      Ron   Gold   Marketing  80000  9           1           4/30/19
6  300      Bob   Gun    HR         50000  8           1           4/30/19
7  100      Evan  Turner Finance    95000  8           1           5/31/19
8  200      Ron   Gold   Marketing  80000  9           1           5/31/19
9  300      Bob   Gun    HR         60000  8           1           5/31/19
</code>```

Note how Evan Turner has changed department and received a salary bump on the month of May. Bob got a salary increase in the same month as well

The idea is that table A gets updated once every month and I want to record that change into the new table.

答:
You can create a procedure like below and schedule it every month end.</p>

```<code>CREATE PROCEDURE usp_InsertHistory
AS
BEGIN

IF CAST(GETDATE() AS DATE) = CAST(EOMONTH(GETDATE()) AS DATE)

BEGIN

INSERT INTO HistoryTable
(
  Id
  ,MemberId
  ,First
  ,Last
  ,Department
  ,Salary
  ,Daily_Hours
  ,Active_Flag
  ,Date
)
SELECT   Id
  ,MemberId
  ,First
  ,Last
  ,Department
  ,Salary
  ,Daily_Hours
  ,Active_Flag
  ,GETDATE()
FROM Table

END

END
</code>```

Title: Database Design For Historical Table

Body:
I have a table of employers(Table A). I want to create a similar table with an extra date column(Table B), showing the date the rows were inserted. I want to insert the rows from Table A to the new table at the end of every month. Is there a way to automate this in SQL?

I have heard that you can do this through stored procedures, but I don't have any experience using them and any guidance would be greatly appreciated.

Here is what the table may look like:

MemberID First Last   Department Salary Daily_Hours Active_Flag
100      Evan  Turner Sales      75000  8           1
200      Ron   Gold   Marketing  80000  9           1
300      Bob   Gun    HR         50000  8           1

Desired output:

ID MemberID First Last   Department Salary Daily_Hours Active_Flag Date
1  100      Evan  Turner Sales      75000  8           1           3/31/19
2  200      Ron   Gold   Marketing  80000  9           1           3/31/19
3  300      Bob   Gun    HR         50000  8           1           3/31/19
4  100      Evan  Turner Sales      75000  8           1           4/30/19
5  200      Ron   Gold   Marketing  80000  9           1           4/30/19
6  300      Bob   Gun    HR         50000  8           1           4/30/19
7  100      Evan  Turner Finance    95000  8           1           5/31/19
8  200      Ron   Gold   Marketing  80000  9           1           5/31/19
9  300      Bob   Gun    HR         60000  8           1           5/31/19

Note how Evan Turner has changed department and received a salary bump on the month of May. Bob got a salary increase in the same month as well

The idea is that table A gets updated once every month and I want to record that change into the new table.

Body:
You can create a procedure like below and schedule it every month end.

CREATE PROCEDURE usp_InsertHistory
AS
BEGIN

IF CAST(GETDATE() AS DATE) = CAST(EOMONTH(GETDATE()) AS DATE)

BEGIN

INSERT INTO HistoryTable
(
  Id
  ,MemberId
  ,First
  ,Last
  ,Department
  ,Salary
  ,Daily_Hours
  ,Active_Flag
  ,Date
)
SELECT   Id
  ,MemberId
  ,First
  ,Last
  ,Department
  ,Salary
  ,Daily_Hours
  ,Active_Flag
  ,GETDATE()
FROM Table

END

END


问:
Can I change the Aspnet-version of my logic app?
I was recently handed over the support of an already built logic app that accepts some json and performs some validations and send it to some endpoint. There's nothing wrong with the Logic app functionality, it works completely fine.

The problem is, penetration testing was done on the app and it presented us with security concern of X-aspnet-Version:4.0.30319.

I found this post here and it says:

That is not the actual .NET framework version. It is the version of
  the CLR

My questions are, can the above quote be considered as the valid reference to address the issue? If not, can the logic app be somehow upgraded to use aspnet version 4.5 or higher?

And if I can change the version, can this have impacts on my current logic app's behavior?

Note: The app was made entirely through logic app designer and not a
 single chunk of coding was implemented

答:
No, the problem is with the test tool, not Logic Apps.

Just because it infers a problem doesn't mean there is a problem.

Explain to you 'security' testers that this is an Azure Logic App, not Windows/IIS.  If you tell us the exact 'security concern' we can explain why it's irrelevant.


问:
Upgrade from Ext JS 3.x to Ext JS 4 Beta?
What are the risks associated with updating from ExtJS 3.x to Ext JS 4 Beta?

Would you expect that user extensions which work with Ext JS 3.x will work with Ext JS 4 Beta?

Would it be as simple as replacing Ext Js 3.x with ExtJs 4?

Should I update or wait until there is an official stable release?

答:
I think this question isn't specific to ext js at all.  I think the answer to the same for the following question: "Upgrade from <some library i'm using> to <Beta version of next release for library I'm using>?"

And the answer is a recommended no.  Betas for 3rd party libs aren't like betas for websites.  They could have major changes by the time the final release comes out and any code you write on top of a beta could become useless.  To be honest, the most I would do with a beta release is just try and plug it in to my project to gauge how much work is going to be involved in upgrading once the final release comes out.


问:
Video won't play autoplay with sound HTML
I have a video for my website but it won't autoplay till I refresh the page

Tried changing the code but it only work when the audio is muted. when there is audio it doesn't autoplay and I have to refresh the page

```<code><div class="carousel-inner" role="listbox">
    <div class="carousel-item active">
        <video  autoplay loop muted width="1900">
            <source src="images/video/ad.mp4" type="video/mp4" />  <!-- Declaring it is a video and from where the file should be played from -->
        </video>
    </div>
</div>
</code>```

I would like it to autoplay when I open the page with audio instead of me refreshing the page for it to play with audio.

答:
This is coming from Googles Autoplay Policy Changes:

Chrome's autoplay policies are simple:

Muted autoplay is always allowed.

Autoplay with sound is allowed if:

User has interacted with the domain (click, tap, etc.).

On desktop, the user's Media Engagement Index threshold has been crossed, meaning the user has previously play video with sound.

On mobile, the user has [added the site to their home screen].

Top frames can delegate autoplay permission to their iframes to allow autoplay with sound.

https://developers.google.com/web/updates/2017/09/autoplay-policy-changes

I would think having the user click would be the best solution to unmute an ad. Below is an example using a stock video. Your code is the same just the video url changed and a basic button was added below the video.

unmuteButton.addEventListener('click', function() {
  video.muted = false;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="carousel-inner" role="listbox">
  <div class="carousel-item active">
    <video muted autoplay loop width="1900" id="video">
        <source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" type="video/mp4" />  <!-- Declaring it is a video and from where the file should be played from -->
      </video>
    <button id="unmuteButton">Unmute</button>
  </div>
</div></code>```

Body:
I have a video for my website but it won't autoplay till I refresh the page

Tried changing the code but it only work when the audio is muted. when there is audio it doesn't autoplay and I have to refresh the page

        <video  autoplay loop muted width="1900">
            <source src="images/video/ad.mp4" type="video/mp4" />
        </video>

I would like it to autoplay when I open the page with audio instead of me refreshing the page for it to play with audio.

Body:
This is coming from Googles Autoplay Policy Changes:

Chrome's autoplay policies are simple:

Muted autoplay is always allowed.

Autoplay with sound is allowed if:

User has interacted with the domain (click, tap, etc.).

On desktop, the user's Media Engagement Index threshold has been crossed, meaning the user has previously play video with sound.

On mobile, the user has [added the site to their home screen].

Top frames can delegate autoplay permission to their iframes to allow autoplay with sound.

https://developers.google.com/web/updates/2017/09/autoplay-policy-changes

I would think having the user click would be the best solution to unmute an ad. Below is an example using a stock video. Your code is the same just the video url changed and a basic button was added below the video.

unmuteButton.addEventListener('click', function() {
  video.muted = false;
});

<div class="carousel-inner" role="listbox">
  <div class="carousel-item active">
    <video muted autoplay loop width="1900" id="video">
        <source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" type="video/mp4" />  <!-- Declaring it is a video and from where the file should be played from -->
      </video>
    <button id="unmuteButton">Unmute</button>
  </div>
</div>


问:
Basic movie database interacting with external API
In job offers I often see the word "REST-API". So, I'd like to learn what REST-API actually is. I have some experience in Django. Well, I'm a beginner actually.

I found on GitHub a simple task: https://github.com/netguru/python-recruitment-task The only thing I don't understand is how to do this:

```<code>POST /movies:
    Request body should contain only movie title, and its presence should be validated.
    Based on passed title, other movie details should be fetched from http://www.omdbapi.com/ (or other similar, public movie database) - and saved to application database.
    Request response should include full movie object, along with all data fetched from external API.
</code>```

How should it looks like?

How to validate the "presence"?

How to download data from public databases?

答:
your question is very big.
First of all i would recommend you to check some blog about API REST like this one

Then before coding, you can try some request directly with Postman, for understand how the post & request work.

And when this job is finish, take a look to django DRF (django rest framework), that do all the work for you :)

Body:
In job offers I often see the word "REST-API". So, I'd like to learn what REST-API actually is. I have some experience in Django. Well, I'm a beginner actually.

I found on GitHub a simple task: https://github.com/netguru/python-recruitment-task The only thing I don't understand is how to do this:

POST /movies:
    Request body should contain only movie title, and its presence should be validated.
    Based on passed title, other movie details should be fetched from http://www.omdbapi.com/ (or other similar, public movie database) - and saved to application database.
    Request response should include full movie object, along with all data fetched from external API.

How should it looks like?

How to validate the "presence"?

How to download data from public databases?


问:
VueJs2 Autocomplete imported but not working
I have a small web project in Laravel+VueJs and now I'm migrating it from VueJs 1.x to 2. Everything was good with the vue-migration-helper but my problem is with the vuejsautocomplete component. I googled that for VueJs2 there's a vuejs2autocomplete library based on vuejsautocomplete so I imported it, then used it but mi autocomplete inputs didn't work properly.

Here's my Vue object

        var cadApp = new Vue({
            el: '#cadContainer',
            data: {
                inputPrestadorEfector: '',
                frmAfiliado: {
                    inputNumeroAfiliado: '',
                    inputDocumentoAfiliado: '',
                    inputTipoDocumentoAfiliado: '',
                },
                dataAfiliado: {
                    msje:'',
                    contextualClass:'',
                    idUnico:'',
                },//resultado de la consulta
                //prestaciones
                frmPrestaciones : {
                    inputPrestacionCodigo :'',
                    inputPrestacionDescripcion :'',
                },
                dataPrestacion: {
                    msje:'',//no viene en la consulta
                },//resultado de la consulta
                dataPrestaciones: {!! json_encode(old('dataPrestaciones') ?: []) !!},//lista de prestaciones consultadas
                //solicitudes
                frmSolicitud:{

                },
                dataSolicitud: {!! json_encode(old('dataSolicitud') ?: ['idSolicitud'=>0, 'msje'=>'', 'contextualClass'=>'']) !!},
//                {
//                    idSolicitud:0,//0 indica que la solicitud no fue creada
//                    msje:'',
//                    contextualClass:'',
//                },//resultado de la consulta
                solicitudes: [],
                loading: false,
                error: false,
                query: ''
            },
            components: {
                autocomplete: Vue2Autocomplete
            },
            methods: {
......
......```
</div>
</div>
</p>

<p>And here's how i used the autocomplete component (at least with the first version it worked)</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="input-group-addon">Código:</div>
                        <autocomplete
                                class="form-control"
                                name="inputPrestacionCodigo"
                                placeholder="Código práctica"
                                url="prestacion/codigo"
                                param="CODIGO_PRESTACION"
                                min="2"
                                max="9"
                                limit="50"
                                anchor="CODIGO_PRESTACION"
                                model="frmPrestaciones.inputPrestacionCodigo">
                        </autocomplete></code>```

Vuedevtools recognizes both autocomplete components but in browser console i get:

[Vue warn]: Failed to mount component: template or render function not defined.

found in

---> <Autocomplete>
       <Root>```

答:
Finally after some research i've found the solution.
Adding default to the component registration fixed the problem:

```<code>components: {
            autocomplete: Vue2Autocomplete.default
        },
</code>```

Hope it can help others too.

Body:
I have a small web project in Laravel+VueJs and now I'm migrating it from VueJs 1.x to 2. Everything was good with the vue-migration-helper but my problem is with the vuejsautocomplete component. I googled that for VueJs2 there's a vuejs2autocomplete library based on vuejsautocomplete so I imported it, then used it but mi autocomplete inputs didn't work properly.

Here's my Vue object

        var cadApp = new Vue({
            el: '#cadContainer',
            data: {
                inputPrestadorEfector: '',
                frmAfiliado: {
                    inputNumeroAfiliado: '',
                    inputDocumentoAfiliado: '',
                    inputTipoDocumentoAfiliado: '',
                },
                dataAfiliado: {
                    msje:'',
                    contextualClass:'',
                    idUnico:'',
                },//resultado de la consulta
                //prestaciones
                frmPrestaciones : {
                    inputPrestacionCodigo :'',
                    inputPrestacionDescripcion :'',
                },
                dataPrestacion: {
                    msje:'',//no viene en la consulta
                },//resultado de la consulta
                dataPrestaciones: {!! json_encode(old('dataPrestaciones') ?: []) !!},//lista de prestaciones consultadas
                //solicitudes
                frmSolicitud:{

                },
                dataSolicitud: {!! json_encode(old('dataSolicitud') ?: ['idSolicitud'=>0, 'msje'=>'', 'contextualClass'=>'']) !!},
//                {
//                    idSolicitud:0,//0 indica que la solicitud no fue creada
//                    msje:'',
//                    contextualClass:'',
//                },//resultado de la consulta
                solicitudes: [],
                loading: false,
                error: false,
                query: ''
            },
            components: {
                autocomplete: Vue2Autocomplete
            },
            methods: {
......
......

And here's how i used the autocomplete component (at least with the first version it worked)

Código:

                        <autocomplete
                                class="form-control"
                                name="inputPrestacionCodigo"
                                placeholder="Código práctica"
                                url="prestacion/codigo"
                                param="CODIGO_PRESTACION"
                                min="2"
                                max="9"
                                limit="50"
                                anchor="CODIGO_PRESTACION"
                                model="frmPrestaciones.inputPrestacionCodigo">
                        </autocomplete>

Vuedevtools recognizes both autocomplete components but in browser console i get:

[Vue warn]: Failed to mount component: template or render function not defined.

found in

---> <Autocomplete>
       <Root>

Body:
Finally after some research i've found the solution.
Adding default to the component registration fixed the problem:

components: {
            autocomplete: Vue2Autocomplete.default
        },

Hope it can help others too.


问:
python .xml and .csv files manipulation
I made a conversion from an .xml file to .csv. In the .xml file there were some values from the txtDescricao column of this type: "Logistics, Search and Support." Because of this, when I read the file, pandas interprets that comma after Logisticsas a column separator, and throws the rest of the text forward. I am trying to work around this with the following code:

```<code>in_file = 'dados_limpos_2018.csv'
out_file = 'dados_2018.csv'
output = open(out_file, 'w')
with open(in_file, 'r') as source:
    for line in source:
    # split by semicolon
        data = line.strip().split(';')
    # remove all quotes found
        data = [t.replace('"','') for t in data]
        for item in data[:-1]:
            item.replace(',', '')
            output.write(''.join(['', item, '',',']))
            # write the last item separately, without the trailing ';'
        output.write(''.join(['"', item, '"']))
        output.write('\n')
output.close()
</code>```

however, in the line python already interprets the comma as separator and turns it into a semicolon. Here I would like to know: Is there any way I can handle this in the .csv file, or would I have to do this in .xml to .csv conversion?
Example of .cs file

```<code>name, number, sgUF, txtDescricao, year
Romario, 15, RJ, Consultoria, 2018
Ronaldo, 9, RJ, Logistics, Search and Support, 2018
</code>```

Example .xml file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xml>
    <dados>
          <despesa>
                  <name>Romario</name>
                  <number>15</number>
                  <sgUF>RJ</sgUF>
                  <txtDescricao>Consultoria</txtDescricao>
                  <year>2018</year>
           </despesa>

           <despesa>
                  <name>Ronaldo</name>
                  <number>9</number>
                  <sgUF>RJ</sgUF>
                  <txtDescricao>Logistics, Search and Support</txtDescricao>
                  <year>2018</year>
           </despesa>
     </dados>
</xml>
</code>```

Note: The original file is too large to open in spreadsheet editor.

答:
It would be nice if you share your xml file.

Based on supplied info,

If your xml file data has , as value, use different separator(semicolon,tab,space) to form your csv file.
Or
Just replace , with null when its in XML file, then convert.

In both situations, you should handle this while converting from xml to csv. With csv -> csv will be hard to implement and count of , will be unpredictable.

EDIT 1:

I suggest to use objectify from lxml.
Dont forget to delete <?xml version="1.0" encoding="UTF-8"?> from your xml.
Solution is below.

```<code>from lxml import objectify
import csv

file_xml = open('d:\\path\\to\\xml.xml','r')
converted_csv_file = open("converted.csv","w")
xml_string = file_xml.read()
xml_object = objectify.fromstring(xml_string)
csvwriter = csv.writer(converted_csv_file, delimiter=',',lineterminator = '\n')
count = 0
for row in xml_object.dados.despesa:
    if count == 0:
        csvwriter.writerow([row.name.tag,row.number.tag,row.sgUF.tag,row.txtDescricao.tag,row.year.tag])
    csvwriter.writerow([row.name.text,row.number.text,row.sgUF.text,row.txtDescricao.text.replace(',',''),row.year.text])
    count += 1
</code>```

You can install lxml by

```<code>pip install lxml
</code>```

Title: python .xml and .csv files manipulation

Body:
I made a conversion from an .xml file to .csv. In the .xml file there were some values from the txtDescricao column of this type: "Logistics, Search and Support." Because of this, when I read the file, pandas interprets that comma after Logisticsas a column separator, and throws the rest of the text forward. I am trying to work around this with the following code:

in_file = 'dados_limpos_2018.csv'
out_file = 'dados_2018.csv'
output = open(out_file, 'w')
with open(in_file, 'r') as source:
    for line in source:
    # split by semicolon
        data = line.strip().split(';')
    # remove all quotes found
        data = [t.replace('"','') for t in data]
        for item in data[:-1]:
            item.replace(',', '')
            output.write(''.join(['', item, '',',']))
            # write the last item separately, without the trailing ';'
        output.write(''.join(['"', item, '"']))
        output.write('\n')
output.close()

however, in the line python already interprets the comma as separator and turns it into a semicolon. Here I would like to know: Is there any way I can handle this in the .csv file, or would I have to do this in .xml to .csv conversion?
Example of .cs file

name, number, sgUF, txtDescricao, year
Romario, 15, RJ, Consultoria, 2018
Ronaldo, 9, RJ, Logistics, Search and Support, 2018

Example .xml file:

<?xml version="1.0" encoding="UTF-8"?>
<xml>
    <dados>
          <despesa>
                  <name>Romario</name>
                  <number>15</number>
                  <sgUF>RJ</sgUF>
                  <txtDescricao>Consultoria</txtDescricao>
                  <year>2018</year>
           </despesa>

           <despesa>
                  <name>Ronaldo</name>
                  <number>9</number>
                  <sgUF>RJ</sgUF>
                  <txtDescricao>Logistics, Search and Support</txtDescricao>
                  <year>2018</year>
           </despesa>
     </dados>
</xml>

Note: The original file is too large to open in spreadsheet editor.

Body:
It would be nice if you share your xml file.

Based on supplied info,

If your xml file data has , as value, use different separator(semicolon,tab,space) to form your csv file.
Or
Just replace , with null when its in XML file, then convert.

In both situations, you should handle this while converting from xml to csv. With csv -> csv will be hard to implement and count of , will be unpredictable.

EDIT 1:

I suggest to use objectify from lxml.
Dont forget to delete <?xml version="1.0" encoding="UTF-8"?> from your xml.
Solution is below.

from lxml import objectify
import csv

file_xml = open('d:\\path\\to\\xml.xml','r')
converted_csv_file = open("converted.csv","w")
xml_string = file_xml.read()
xml_object = objectify.fromstring(xml_string)
csvwriter = csv.writer(converted_csv_file, delimiter=',',lineterminator = '\n')
count = 0
for row in xml_object.dados.despesa:
    if count == 0:
        csvwriter.writerow([row.name.tag,row.number.tag,row.sgUF.tag,row.txtDescricao.tag,row.year.tag])
    csvwriter.writerow([row.name.text,row.number.text,row.sgUF.text,row.txtDescricao.text.replace(',',''),row.year.text])
    count += 1

You can install lxml by

pip install lxml


问:
Why does Thread.Sleep(0) fix my problems, and how to avoid it?
I'm working on a client server application.  At certain times, on certain machines, when there's more than 5 clients requesting data, it seems to reach a deadlock.  If I step in to debug the problem, then the program appears to be processing.  Simply setting a break point where I know the program is executing, and causing it to hit the breakpoint a few times causes it to finish. If I insert Thread.Sleep(0) at certain points in the code, mostly around some cpu intensive loops, it seems to pretty much totally resolve the problem.  The one problem that I have now is that if I call Thread.Sleep(0) too much, it can slow down the code.  If I don't call it enough, the code seems to be in deadlock.  Although I can verify that it isn't in deadlock because if I step into the code, it causes the problem to disappear, simply because I'm pausing a thread.

Is there a good way to track down exactly what is causing this.  It seems that it only happens on my laptop which is running Vista, but not on my desktop which is running Windows XP.  However, it's impossible to debug, because simply stepping into the code causes the problem to go away.  I've read comments that calling Thread.Sleep(0) is a bad practice, and shouldn't be necessary, and I don't like putting witchcraft type code into my applications that I don't understand why it has to be there.  Any pointers would be greatly appreciated.

[EDIT]
I can also verify that the code is still running when it is "deadlocked" because if I leave it long enough, it will finish, only the amount of time it takes is many orders of magnitude higher.  I mean like it's actually at least 100 times slower when it's in this "deadlocked" mode.  The CPU is pegged at 80-95%, so it is working, altough what it is doing is beyond me, because it's taking forever to complete the task.

[More Info]
Just because everybody here is insistent that it's a deadlock, I removed all the code that did any locking. There was only a couple lines of code that did any locking whatsoever. The threads work completely independantly for the most part, so it wasn't much work to remove the locking completely.  Still the problem persists.  There is no more synclocks in my code, no more mutex's no more stuff that I see see that would cause a deadlock, but the problem is still there.  And it's not deadlocked.  It runs, albeit very slowly, even though it's eating up all the processor resources.

答:
Thread.Sleep(0) is a yield. I am guessing this rearranges the way you call to avoid some issues. I think if you released code with the yield and ran it on 1000 machines, you would get a lot of bug reports. I am guessing you need some type of lock/critical section to avoid your dead lock because some where your code is not thread safe. That could be in a library you are calling.

Add in logging and see if the problems still happens. Hopefully you can figure out what functions are causing the dead lock

Add some critical sections. Uses a divide and conquer approach you should be able to narrow down where the problem is happening.

OwnerDisplayName: Kibbee

LastEditorDisplayName: Kibbee

OwnerDisplayName: hacken

LastEditorDisplayName: sixlettervariables


问:
How to save entire scrollable canvas as PNG?
I have a scrollable canvas who's content i want into a png image.

The problem is I only get a photo of the canvas, missing the non visible part of the canvas at that given time.

How do i get the whole scrollable canvas into a png image?

My current code is the following:

```<code>my $canvas_to_get_photo=$mw->Photo(-format=>'Window', -data=>oct($canvas_to_get->id));
$canvas_to_get_photo->write('somepath/image.png', -format=>'png');
</code>```

答:
There isn't a native way to do it; Tk only paints to windows, not to image-based surfaces. Your options are therefore to either:

scroll the canvas, taking snapshots, and then stitch them together

generate encapsulated postscript (which does support going over the whole canvas, provided you use the right options) and generate your image from that with a tool like ghostscript.

Body:
I have a scrollable canvas who's content i want into a png image.

The problem is I only get a photo of the canvas, missing the non visible part of the canvas at that given time.

How do i get the whole scrollable canvas into a png image?

My current code is the following:

my $canvas_to_get_photo=$mw->Photo(-format=>'Window', -data=>oct($canvas_to_get->id));
$canvas_to_get_photo->write('somepath/image.png', -format=>'png');


问:
Each VBA sub works perfectly separately, but calling subs from another function doesn't work
I wrote 2 subs to automate a daily task.

First sub MatriksFlowUpdate calls 2 other subs RightClick and SingleClick to simulate a right click and then a left click on a certain part of the screen.  This is done in order to prompt another program to create an Excel file and save it under C:.  This sub works correctly on its own (i.e. it simulates a right click and a left click at the desired locations on the screen, prompting another program to produce an Excel sheet)

Second sub CloseInstance finds the Excel sheet created above, and closes it.  This sub also works correctly on its own.

However, when I try to call these 2 subs one after the other in another sub MainSequence, I get an error saying the Excel that should be found and closed by the second sub can't be found. So I get an error on the CloseInstance sub at the location below

```<code>    Set xlApp =GetObject("C:\MATRIKS\USER\REPORTS\EXCEL\Temp.xls").Application
</code>```

I've tried many things to fix this, but I feel like I am going around in circles for the past few days.  Any help would be much much appreciated.

P.S. My first time posting a q on stackoverflow so please bear with me with the formatting.

```<code>    Public Declare PtrSafe Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long
    Public Declare PtrSafe Sub mouse_event Lib "user32" (ByVal dwFlags As Long, ByVal dx As Long, ByVal dy As Long, ByVal cButtons As Long, ByVal dwExtraInfo As Long)
    Public Const MOUSEEVENTF_LEFTDOWN = &H2
    Public Const MOUSEEVENTF_LEFTUP = &H4
    Public Const MOUSEEVENTF_RIGHTDOWN As Long = &H8
    Public Const MOUSEEVENTF_RIGHTUP As Long = &H10
    Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr)

    Sub MainSequence()
        'This sub pieces together MatriksFlowUpdate and CloseInstance
        Call MatriksFlowUpdate
        Sleep 2000
        Call CloseInstance
        End Sub

    Sub MatriksFlowUpdate()
        'Prompts 3rd party software (Matriks) to produce Excel with latest flow data
        Call RightClick
        Call SingleClick
        End Sub

    Private Sub RightClick()
    'Simulates a mouse right click at desired screen coordinates
    Sleep 1000
    SetCursorPos 1750, 750 'x and y position
    mouse_event MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0
    mouse_event MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0
    End Sub

    Private Sub SingleClick()
    'Simulates a mouse left click at desired screen coordinates
    Sleep 1000
    SetCursorPos 1750, 650 'x and y position
    mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
    mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
    End Sub

    Sub CloseInstance()
    'Finds the instance of Excel where Matriks exported its excel and closes that instance of Excel
    Dim xlApp As Excel.Application
    Dim WB As Workbook
    Set xlApp =GetObject("C:\MATRIKS\USER\REPORTS\EXCEL\Temp.xls").Application
    Set WB = xlApp.Workbooks("Temp.xls")
    WB.Close
    End Sub
</code>```

答:
should it be a timing issue you could keep on trying and getting the Excel application until it's found (not tested):</p>

```<code>Sub CloseInstance()
    'Finds the instance of Excel where Matriks exported its excel and closes that instance of Excel
    Dim xlApp As Excel.Application

    On Error Resume Next
    Do
        Set xlApp = GetObject("C:\MATRIKS\USER\REPORTS\EXCEL\Temp.xls").Application
        DoEvents
    Loop While xlApp Is Nothing
    xlApp.Workbooks("Temp.xls").Close
End Sub
</code>```

Body:
I wrote 2 subs to automate a daily task.

First sub MatriksFlowUpdate calls 2 other subs RightClick and SingleClick to simulate a right click and then a left click on a certain part of the screen.  This is done in order to prompt another program to create an Excel file and save it under C:.  This sub works correctly on its own (i.e. it simulates a right click and a left click at the desired locations on the screen, prompting another program to produce an Excel sheet)

Second sub CloseInstance finds the Excel sheet created above, and closes it.  This sub also works correctly on its own.

However, when I try to call these 2 subs one after the other in another sub MainSequence, I get an error saying the Excel that should be found and closed by the second sub can't be found. So I get an error on the CloseInstance sub at the location below

    Set xlApp =GetObject("C:\MATRIKS\USER\REPORTS\EXCEL\Temp.xls").Application

I've tried many things to fix this, but I feel like I am going around in circles for the past few days.  Any help would be much much appreciated.

P.S. My first time posting a q on stackoverflow so please bear with me with the formatting.

    Public Declare PtrSafe Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long
    Public Declare PtrSafe Sub mouse_event Lib "user32" (ByVal dwFlags As Long, ByVal dx As Long, ByVal dy As Long, ByVal cButtons As Long, ByVal dwExtraInfo As Long)
    Public Const MOUSEEVENTF_LEFTDOWN = &H2
    Public Const MOUSEEVENTF_LEFTUP = &H4
    Public Const MOUSEEVENTF_RIGHTDOWN As Long = &H8
    Public Const MOUSEEVENTF_RIGHTUP As Long = &H10
    Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr)

    Sub MainSequence()
        'This sub pieces together MatriksFlowUpdate and CloseInstance
        Call MatriksFlowUpdate
        Sleep 2000
        Call CloseInstance
        End Sub

    Sub MatriksFlowUpdate()
        'Prompts 3rd party software (Matriks) to produce Excel with latest flow data
        Call RightClick
        Call SingleClick
        End Sub

    Private Sub RightClick()
    'Simulates a mouse right click at desired screen coordinates
    Sleep 1000
    SetCursorPos 1750, 750 'x and y position
    mouse_event MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0
    mouse_event MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0
    End Sub

    Private Sub SingleClick()
    'Simulates a mouse left click at desired screen coordinates
    Sleep 1000
    SetCursorPos 1750, 650 'x and y position
    mouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0
    mouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0
    End Sub

    Sub CloseInstance()
    'Finds the instance of Excel where Matriks exported its excel and closes that instance of Excel
    Dim xlApp As Excel.Application
    Dim WB As Workbook
    Set xlApp =GetObject("C:\MATRIKS\USER\REPORTS\EXCEL\Temp.xls").Application
    Set WB = xlApp.Workbooks("Temp.xls")
    WB.Close
    End Sub

Body:
should it be a timing issue you could keep on trying and getting the Excel application until it's found (not tested):

Sub CloseInstance()
    'Finds the instance of Excel where Matriks exported its excel and closes that instance of Excel
    Dim xlApp As Excel.Application

    On Error Resume Next
    Do
        Set xlApp = GetObject("C:\MATRIKS\USER\REPORTS\EXCEL\Temp.xls").Application
        DoEvents
    Loop While xlApp Is Nothing
    xlApp.Workbooks("Temp.xls").Close
End Sub


问:
How can I run both nginx and Apache together on Ubuntu?
I want to configure both Apache and nginx to run together on Ubuntu because I want to develop on both nginx and Apache. I have read that I have to edit the configuration on Apache or nginx to make one of them run on another port rather than 80.

Which files should I edit in Nginx to make it run through another port?

答:
Here is the answer how to have both Apache and NGINX installed on the same 80 port (on localhost).

Assuming that you have both NGINX and Apache installed...

1. Select different IP addresses for each one.

Let's setup the hosts file for quick access to start pages.

```<code>sudo nano /etc/hosts
</code>```

append lines (use any local IP you like)

```<code>127.0.0.1   nginx
127.0.0.2   apache
</code>```

2. Setup listen IP and port for NGINX

NGINX must listen on one IP address only.

```<code>sudo nano /etc/nginx/sites-enabled/default
</code>```

And replace the lines

--- (remove lines)
+++ (add lines)

```<code>--- listen 80 default_server;
--- listen [::]:80 default_server;
+++ listen nginx:80;
</code>```

If you want to use SSL, make the same things for 443 port.

IMPORTANT!

Make sure all enabled NGINX websites listen on nginx:80

Restart NGINX

```<code>sudo service nginx restart
</code>```

Make a check using command sudo netstat -tulpn | grep :80

```<code>tcp        0      0 127.0.0.1:80            0.0.0.0:*               LISTEN      26540/nginx: master
</code>```

Done! Now you can access default NGINX host by url http://nginx

3. Setup listen IP and port for Apache

Apache must listen on one IP address only as well.

Ports:

```<code>sudo nano /etc/apache2/ports.conf
</code>```

And replace the lines

--- (remove lines)
+++ (add lines)

```<code>--- Listen 80
--- Listen 443
+++ Listen apache:80
+++ Listen apache:443
</code>```

Default virtual host:

```<code>sudo nano /etc/apache/sites-enabled/000-default
</code>```

And replace the lines

--- (remove lines)
+++ (add lines)

```<code>--- <VirtualHost *:80>
+++ <VirtualHost apache:80>
</code>```

If you want to use SSL, make the same things for 443 port.

IMPORTANT!

Make sure all enabled Apache websites listen on apache:80

Restart Apache

```<code>127.0.0.1   nginx
127.0.0.2   apache
</code>```0

Make a check using command sudo netstat -tulpn | grep :80

```<code>127.0.0.1   nginx
127.0.0.2   apache
</code>```1

Done! Now you can access default Apache host by url http://apache

Body:
Here is the answer how to have both Apache and NGINX installed on the same 80 port (on localhost).

Assuming that you have both NGINX and Apache installed...

1. Select different IP addresses for each one.

Let's setup the hosts file for quick access to start pages.

sudo nano /etc/hosts

append lines (use any local IP you like)

127.0.0.1   nginx
127.0.0.2   apache

2. Setup listen IP and port for NGINX

NGINX must listen on one IP address only.

sudo nano /etc/nginx/sites-enabled/default

And replace the lines

--- (remove lines)
+++ (add lines)

--- listen 80 default_server;
--- listen [::]:80 default_server;
+++ listen nginx:80;

If you want to use SSL, make the same things for 443 port.

IMPORTANT!

Make sure all enabled NGINX websites listen on nginx:80

Restart NGINX

sudo service nginx restart

Make a check using command sudo netstat -tulpn | grep :80

tcp        0      0 127.0.0.1:80            0.0.0.0:*               LISTEN      26540/nginx: master

Done! Now you can access default NGINX host by url http://nginx

3. Setup listen IP and port for Apache

Apache must listen on one IP address only as well.

Ports:

sudo nano /etc/apache2/ports.conf

And replace the lines

--- (remove lines)
+++ (add lines)

--- Listen 80
--- Listen 443
+++ Listen apache:80
+++ Listen apache:443

Default virtual host:

sudo nano /etc/apache/sites-enabled/000-default

And replace the lines

--- (remove lines)
+++ (add lines)

--- <VirtualHost *:80>
+++ <VirtualHost apache:80>

If you want to use SSL, make the same things for 443 port.

IMPORTANT!

Make sure all enabled Apache websites listen on apache:80

Restart Apache

sudo service apache2 restart

Make a check using command sudo netstat -tulpn | grep :80

tcp        0      0 127.0.0.2:80            0.0.0.0:*               LISTEN      26829/apache2

Done! Now you can access default Apache host by url http://apache


问:
How to handle null value in JSON in SWIFT
I have a problem with JSON decoding. I have UpdateNickname and UpdateNicknameMessage structs and variable Message inside UpdateNickname could be a null. I got an error whenever it is a null. I want to handle this problem. Here is my struct:

```<code>struct UpdateNicknameMessage: Codable {
 let id: Int
 let nickname: String
 let email: String
}

struct UpdateNickname: Codable {
 var Status: Int
 var Result: String
 var Message: UpdateNicknameMessage

enum CodingKeys: String, CodingKey {
    case Status = "Status"
    case Result = "Result"
    case Message = "Message"
}

init?(from jsonObject: AnyObject) {
    guard let Status1: Int = jsonObject.object(forKey: "Status") as? Int,
        let Result1: String = jsonObject.object(forKey: "Result") as? String,
        let Message1: UpdateNicknameMessage = jsonObject.object(forKey: "Message") as? UpdateNicknameMessage
        else { return nil }

    Status = Status1
    Result = Result1
    Message = Message1
  }
}
</code>```

and JSON looks like this:

```<code>{"Message": {
    email = "123@123.com";
    id = 56;
    nickname = testNickname;
},
 "Status": 200,
 "Result": success}
</code>```

And this is my code for decoding JSON in swift. I use try catch to handle my error.

```<code>            let decoder = JSONDecoder()
            do {
                let model = try decoder.decode(UpdateNickname.self, from: data)
                let serverStatus = model.Status

                if serverStatus == 200 {
                     //EVERYTHING IS FINE
                } else {
                     //server not working
                }
            } catch {
               //cant convert JSON into struct
               print(error.localizedDescription)
            }
</code>```

so my variable Message can return null if something goes wrong with the server.

```<code>{"Message": null,
 "Status": 400,
 "Result": problem}
</code>```

When i try to decode JSON when Message is null i get an error

The data couldn’t be read because it is missing.

How can i fix this problem and handle null value?

答:
Set all your variables in Structs as optionals.

EX:

```<code>var Status: Int?
 var Result: String?
 var Message: UpdateNicknameMessage? ```

```

Body:
I have a problem with JSON decoding. I have UpdateNickname and UpdateNicknameMessage structs and variable Message inside UpdateNickname could be a null. I got an error whenever it is a null. I want to handle this problem. Here is my struct:

struct UpdateNicknameMessage: Codable {
 let id: Int
 let nickname: String
 let email: String
}

struct UpdateNickname: Codable {
 var Status: Int
 var Result: String
 var Message: UpdateNicknameMessage

enum CodingKeys: String, CodingKey {
    case Status = "Status"
    case Result = "Result"
    case Message = "Message"
}

init?(from jsonObject: AnyObject) {
    guard let Status1: Int = jsonObject.object(forKey: "Status") as? Int,
        let Result1: String = jsonObject.object(forKey: "Result") as? String,
        let Message1: UpdateNicknameMessage = jsonObject.object(forKey: "Message") as? UpdateNicknameMessage
        else { return nil }

    Status = Status1
    Result = Result1
    Message = Message1
  }
}

and JSON looks like this:

{"Message": {
    email = "123@123.com";
    id = 56;
    nickname = testNickname;
},
 "Status": 200,
 "Result": success}

And this is my code for decoding JSON in swift. I use try catch to handle my error.

            let decoder = JSONDecoder()
            do {
                let model = try decoder.decode(UpdateNickname.self, from: data)
                let serverStatus = model.Status

                if serverStatus == 200 {
                     //EVERYTHING IS FINE
                } else {
                     //server not working
                }
            } catch {
               //cant convert JSON into struct
               print(error.localizedDescription)
            }

so my variable Message can return null if something goes wrong with the server.

{"Message": null,
 "Status": 400,
 "Result": problem}

When i try to decode JSON when Message is null i get an error

The data couldn’t be read because it is missing.

How can i fix this problem and handle null value?

Body:
Set all your variables in Structs as optionals.

EX:

var Status: Int?
 var Result: String?
 var Message: UpdateNicknameMessage? ```


问:
How to convert string numbers to list?
I have a string of numbers like this

```<code>i = '584,569.2,11515,632'
</code>```

want to convert it to list of number like this.

```<code>[584,569.2,11515,632]
</code>```

答:
You can do it like this:

```<code>i = '584,569.2,11515,632'
numbers = list(map(float, i.split(',')))
print(numbers)
</code>```

Output:

```<code>[584.0, 569.2, 11515.0, 632.0]
</code>```

Also, as Chris A pointed out, if the distinction between int and float is important, you can use is_integer():

```<code>numbers = [int(x) if x.is_integer() else x for x in map(float, i.split(','))]
</code>```

Output:

```<code>[584, 569.2, 11515, 632]
</code>```

Title: How to convert string numbers to list?

Body:
I have a string of numbers like this

i = '584,569.2,11515,632'

want to convert it to list of number like this.

[584,569.2,11515,632]

Body:
You can do it like this:

i = '584,569.2,11515,632'
numbers = list(map(float, i.split(',')))
print(numbers)

Output:

[584.0, 569.2, 11515.0, 632.0]

Also, as Chris A pointed out, if the distinction between int and float is important, you can use is_integer():

numbers = [int(x) if x.is_integer() else x for x in map(float, i.split(','))]

Output:

[584, 569.2, 11515, 632]


问:
Inserting rows in to a table using WHERE condition and JOIN from another table in SQLite
I have two tables (say table 1 and table 2) and I have 8 columns in each table(v_id, p_id, cat, s1, s2,s3,s4,s5,s6,u_name,P_date)

I want to insert values into table1 from table2 with following conditions:

if v_id already exists in table1, and p_id in table 2 matches with table 1, it should replace the v_id in table 1 with v_id in table 2

if v_id doesn't exist in table 1, it should just add those v_ids to table 1

if v_id exists, but p_id in table 2 doesn't match with table 1, it should add v_ids to table 1

so far, I tried:

I have initiated the tables like this:

```<code>CREATE TABLE IF NOT EXISTS table1(v_id, cat TEXT, s1 TEXT,s2 TEXT,s3 TEXT, s4 TEXT,s5 TEXT,s6 TEXT, u_name TEXT, p_date DATE, p_id TEXT)

CREATE TABLE IF NOT EXISTS table2(v_id, cat TEXT, s1 TEXT,s2 TEXT,s3 TEXT, s4 TEXT,s5 TEXT,s6 TEXT, u_name TEXT, p_date DATE, p_id TEXT)
</code>```

I have inserted some data in to table 1 and table 2 and tried the following code:

```<code>INSERT OR REPLACE INTO table1 SELECT * FROM table2
LEFT JOIN table1 ON table2.v_id=table1.v_id
WHERE table2.p_id=table1.p_id OR table1.v_id IS NULL
</code>```

But, it gives me the following error:

```<code>"table table1 has 11 columns but 22 values were supplied"
</code>```

what am I doing wrong??

答:
This SELECT * is returning 22 columns. Why? Because it is returning the columns from the JOIN, not only those from table2. From the sqlite SELECT doc:

If the join-operator is a "LEFT JOIN" or "LEFT OUTER JOIN", then after
  the ON or USING filtering clauses have been applied, an extra row is
  added to the output for each row in the original left-hand input
  dataset that corresponds to no rows at all in the composite dataset
  (if any). The added rows contain NULL values in the columns that would
  normally contain values copied from the right-hand input dataset.

SELECT table2.* from ..... would fix that problem.

Let's forget about the INSERT for a moment and evaluate what rows will be returned by

```<code>SELECT * FROM table2
LEFT JOIN table1 ON table2.v_id=table1.v_id
WHERE table2.p_id=table1.p_id OR table1.v_id IS NULL
</code>```

It will not select rows where table2.v_id = table1.v_id AND table2.p_id != table1.p_id so condition 3 will never be met.

Unless table1 has a UNIQUE or PRIMARY KEY constraint, there will never be a replace, so condition 1 will never be met (it will simply insert the rows from table2). From the sqlite ON CONFLICT doc:

REPLACE

When a UNIQUE or PRIMARY KEY constraint violation occurs, the REPLACE algorithm deletes pre-existing rows that are causing the
  constraint violation prior to inserting or updating the current row
  and the command continues executing normally. If a NOT NULL constraint
  violation occurs, the REPLACE conflict resolution replaces the NULL
  value with the default value for that column, or if the column has no
  default value, then the ABORT algorithm is used. If a CHECK constraint
  violation occurs, the REPLACE conflict resolution algorithm always
  works like ABORT.

You will need to create index(es) on table1 in order to use the REPLACE action. Perhaps a composite index on v_id, p_id would do the trick. Something like CREATE UNIQUE INDEX "vid_pid_idx" on table1 (v_id,p_id). Then simply INSERT OR REPLACE INTO table1 SELECT * FROM table2 to accomplish the objectives.

Rows where v_ids and p_ids are equal will "REPLACE" because the UNIQUE constraint will be "violated".

All other rows from table2 will be inserted.

Body:
I have two tables (say table 1 and table 2) and I have 8 columns in each table(v_id, p_id, cat, s1, s2,s3,s4,s5,s6,u_name,P_date)

I want to insert values into table1 from table2 with following conditions:

if v_id already exists in table1, and p_id in table 2 matches with table 1, it should replace the v_id in table 1 with v_id in table 2

if v_id doesn't exist in table 1, it should just add those v_ids to table 1

if v_id exists, but p_id in table 2 doesn't match with table 1, it should add v_ids to table 1

so far, I tried:

I have initiated the tables like this:

CREATE TABLE IF NOT EXISTS table1(v_id, cat TEXT, s1 TEXT,s2 TEXT,s3 TEXT, s4 TEXT,s5 TEXT,s6 TEXT, u_name TEXT, p_date DATE, p_id TEXT)

CREATE TABLE IF NOT EXISTS table2(v_id, cat TEXT, s1 TEXT,s2 TEXT,s3 TEXT, s4 TEXT,s5 TEXT,s6 TEXT, u_name TEXT, p_date DATE, p_id TEXT)

I have inserted some data in to table 1 and table 2 and tried the following code:

INSERT OR REPLACE INTO table1 SELECT * FROM table2
LEFT JOIN table1 ON table2.v_id=table1.v_id
WHERE table2.p_id=table1.p_id OR table1.v_id IS NULL

But, it gives me the following error:

"table table1 has 11 columns but 22 values were supplied"

what am I doing wrong??

Body:
This SELECT * is returning 22 columns. Why? Because it is returning the columns from the JOIN, not only those from table2. From the sqlite SELECT doc:

If the join-operator is a "LEFT JOIN" or "LEFT OUTER JOIN", then after
  the ON or USING filtering clauses have been applied, an extra row is
  added to the output for each row in the original left-hand input
  dataset that corresponds to no rows at all in the composite dataset
  (if any). The added rows contain NULL values in the columns that would
  normally contain values copied from the right-hand input dataset.

SELECT table2.* from ..... would fix that problem.

Let's forget about the INSERT for a moment and evaluate what rows will be returned by

SELECT * FROM table2
LEFT JOIN table1 ON table2.v_id=table1.v_id
WHERE table2.p_id=table1.p_id OR table1.v_id IS NULL

It will not select rows where table2.v_id = table1.v_id AND table2.p_id != table1.p_id so condition 3 will never be met.

Unless table1 has a UNIQUE or PRIMARY KEY constraint, there will never be a replace, so condition 1 will never be met (it will simply insert the rows from table2). From the sqlite ON CONFLICT doc:

REPLACE

When a UNIQUE or PRIMARY KEY constraint violation occurs, the REPLACE algorithm deletes pre-existing rows that are causing the
  constraint violation prior to inserting or updating the current row
  and the command continues executing normally. If a NOT NULL constraint
  violation occurs, the REPLACE conflict resolution replaces the NULL
  value with the default value for that column, or if the column has no
  default value, then the ABORT algorithm is used. If a CHECK constraint
  violation occurs, the REPLACE conflict resolution algorithm always
  works like ABORT.

You will need to create index(es) on table1 in order to use the REPLACE action. Perhaps a composite index on v_id, p_id would do the trick. Something like CREATE UNIQUE INDEX "vid_pid_idx" on table1 (v_id,p_id). Then simply INSERT OR REPLACE INTO table1 SELECT * FROM table2 to accomplish the objectives.

Rows where v_ids and p_ids are equal will "REPLACE" because the UNIQUE constraint will be "violated".

All other rows from table2 will be inserted.


问:
"Interruption" callback when another animation starts for the same object in DOTween
I have a method which is called on button tap which fades audio volume and mutes when completes:

```<code>MusicBox.musicAudioSource.DOFade(0.0f, 1.0f).OnComplete(() => { MusicBox.musicAudioSource.mute = true; });
</code>```

If I tap on button quicker than 1 second than OnComplete() doesn't call. What callback I should use for those cases?

答:
Since DOFade does something with the object in a period of time, the problem is you are setting the variable to do something again before it finishes the first time, and thus its setting the time to 0 again ( I dont know how it works interally but i had a problem like this with an animation before ).

What you should be doing, is waiting for completion before activating the button again, something like disabling the button and then reenabling it should do the trick.

Body:
I have a method which is called on button tap which fades audio volume and mutes when completes:

MusicBox.musicAudioSource.DOFade(0.0f, 1.0f).OnComplete(() => { MusicBox.musicAudioSource.mute = true; });

If I tap on button quicker than 1 second than OnComplete() doesn't call. What callback I should use for those cases?


问:
How to use a value i get from a form in another php
```<code><?php

 if(isset($_POST['edit_button'])){
    $ID=$_POST['edit_button'];
    $query = "SELECT  PNAME , GENDER, AGE, ADDRESS , PHONENUMBER
    FROM PATIENT LEFT OUTER JOIN PHONENUMBER
    ON PID=EPID AND '$ID'=PID";

    $stid = oci_parse($conn, $query);
    oci_execute($stid);
    $row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);

        $patient_name= $row['PNAME'];
        $patient_gender= $row['GENDER'];
        $patient_address= $row['ADDRESS'];
        $patient_age= $row['AGE'];
        $patient_phone= $row['PHONENUMBER'];
    }
?>

 <?php
if(isset($_POST['Edit_Patient'])){
    $new_pname=$_POST['pName'];
    $new_pGender=$_POST['pGender'];
    $new_pAge=$_POST['pAge'];
    $new_pAddress=$_POST['pAddress'];
    $new_phone=$_POST['phone'];
    $update_query=" UPDATE PATIENT
                   SET PNAME= '$new_pname', GENDER= '$new_pGender', AGE=$new_pAge, ADDRESS='$new_pAddress'
                   WHERE PID= '$ID'";
    $stid = oci_parse($conn, $update_query);
    $result=oci_execute($stid);
    if (!$result) {
        echo oci_error();
    }

}
</code>```

?>

THESE TWO PHPS ARE IN THE PHP FILE registration.php

So, my question is: i get the Id from the first php but i can't use in the second where both are in the same php file.Also, i tried putting the $ID=$_POST['edit_button']; above the if statement, but it gave me an error

答:
You need to assign $ID in one hidden field of Update Patient form. So when you submit that form you will get a value of $ID as follows:

Initialize $ID with blank value above the first if statement:

```<code>$ID = "";
</code>```

Update Patient Form

```<code><form>
...
<input type="hidden" name="patient_id" value="<?php echo $ID; ?>" />
...
</form>
</code>```

Second If statement

```<code>if(isset($_POST['Edit_Patient'])){
    ...
    $ID = $_POST['patient_id'];
    ...
}
</code>```

Hope this may helpful to anyone!

Body:
<?php

 if(isset($_POST['edit_button'])){
    $ID=$_POST['edit_button'];
    $query = "SELECT  PNAME , GENDER, AGE, ADDRESS , PHONENUMBER
    FROM PATIENT LEFT OUTER JOIN PHONENUMBER
    ON PID=EPID AND '$ID'=PID";

    $stid = oci_parse($conn, $query);
    oci_execute($stid);
    $row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);

        $patient_name= $row['PNAME'];
        $patient_gender= $row['GENDER'];
        $patient_address= $row['ADDRESS'];
        $patient_age= $row['AGE'];
        $patient_phone= $row['PHONENUMBER'];
    }
?>

 <?php
if(isset($_POST['Edit_Patient'])){
    $new_pname=$_POST['pName'];
    $new_pGender=$_POST['pGender'];
    $new_pAge=$_POST['pAge'];
    $new_pAddress=$_POST['pAddress'];
    $new_phone=$_POST['phone'];
    $update_query=" UPDATE PATIENT
                   SET PNAME= '$new_pname', GENDER= '$new_pGender', AGE=$new_pAge, ADDRESS='$new_pAddress'
                   WHERE PID= '$ID'";
    $stid = oci_parse($conn, $update_query);
    $result=oci_execute($stid);
    if (!$result) {
        echo oci_error();
    }

}

?>

THESE TWO PHPS ARE IN THE PHP FILE registration.php

So, my question is: i get the Id from the first php but i can't use in the second where both are in the same php file.Also, i tried putting the $ID=$_POST['edit_button']; above the if statement, but it gave me an error

Body:
You need to assign $ID in one hidden field of Update Patient form. So when you submit that form you will get a value of $ID as follows:

Initialize $ID with blank value above the first if statement:

$ID = "";

Update Patient Form

<form>
...
<input type="hidden" name="patient_id" value="<?php echo $ID; ?>" />
...
</form>

Second If statement

if(isset($_POST['Edit_Patient'])){
    ...
    $ID = $_POST['patient_id'];
    ...
}

Hope this may helpful to anyone!


问:
DHT InfoHash Lookup sequence. PeerID vs InfoHash
I know there is a previous question about this somewhere on SO, but I cannot find it again. The relationship between NodeId and InfoHash.
Is the following diagram roughly correct?

Background (no need to read)

I'm trying to implement my own DHT/bittorrent application in Java.
I know that there are already some excellent implementations that I will never better. But this is purely a hedonistic pursuit.
What was it Kennedy said? "we choose to do this not because it is easy.."

I have conquered the easy part, which is to write the low level socket handling and Remote Procedure Call syntax etc.
Now I am on to the hard part, I must behave responsibly and service incoming requests on the DHT. (maintain KBuckets etc.)

答:
Yes that diagram is correct. Here some python code that implements FIND_VALUE algorithm you describe:

```<code>async def _get(self, key):
    """Fetch the value associated with KEY from the network"""
    uid = pack(key)
    queried = set()
    while True:
        # retrieve the k nearest peers and remove already queried peers
        peers = await self.peers((None, None), uid)
        peers = [address for address in peers if address not in queried]
        # no more peer to query, the key is not found in the dht
        if not peers:
            raise KeyError(unpack(uid))
        # query selected peers
        queries = dict()
        for address in peers:
            query = self._protocol.rpc(address, "value", uid)
            queries[address] = query
        responses = await gather(queries, return_exceptions=True)
        for (address, response) in responses.items():
            queried.add(address)
            if isinstance(response, Exception):
                continue
            elif response[0] == b"VALUE":
                value = response[1]
                if hash(value) == unpack(uid):
                    # store it
                    @h.transactional
                    def add(tr, key, value):
                        tr.add("QADOM:MAPPING", key, "value", value)

                    await self._run(add, self._hoply, key, value)
                    # at last!
                    return value
                else:
                    log.warning(
                        "[%r] bad value returned from %r", self._uid, address
                    )
                    await self.blacklist(address)
                    continue
            elif response[0] == b"PEERS":
                await self._welcome_peers(response[1])
            else:
                await self.blacklist(address)
                log.warning(
                    "[%r] unknown response %r from %r",
                    self._uid,
                    response[0],
                    address,
</code>```

This is extract from qadom project peer.py.

Body:
Yes that diagram is correct. Here some python code that implements FIND_VALUE algorithm you describe:

async def _get(self, key):
    """Fetch the value associated with KEY from the network"""
    uid = pack(key)
    queried = set()
    while True:
        # retrieve the k nearest peers and remove already queried peers
        peers = await self.peers((None, None), uid)
        peers = [address for address in peers if address not in queried]
        # no more peer to query, the key is not found in the dht
        if not peers:
            raise KeyError(unpack(uid))
        # query selected peers
        queries = dict()
        for address in peers:
            query = self._protocol.rpc(address, "value", uid)
            queries[address] = query
        responses = await gather(queries, return_exceptions=True)
        for (address, response) in responses.items():
            queried.add(address)
            if isinstance(response, Exception):
                continue
            elif response[0] == b"VALUE":
                value = response[1]
                if hash(value) == unpack(uid):
                    # store it
                    @h.transactional
                    def add(tr, key, value):
                        tr.add("QADOM:MAPPING", key, "value", value)

                    await self._run(add, self._hoply, key, value)
                    # at last!
                    return value
                else:
                    log.warning(
                        "[%r] bad value returned from %r", self._uid, address
                    )
                    await self.blacklist(address)
                    continue
            elif response[0] == b"PEERS":
                await self._welcome_peers(response[1])
            else:
                await self.blacklist(address)
                log.warning(
                    "[%r] unknown response %r from %r",
                    self._uid,
                    response[0],
                    address,

This is extract from qadom project peer.py.


问:
How to handle a large number of activities in android studio
Iam a student and Iam developing an app for my college for downloading previous year question papers,my college has 14 departments and for each department 8 semesters and in each semester minimum 10 subjects are there so 14*2*8= 1120 java files and XML files I have to create if I keep on intenting from one activity to another it will take a huge time.how handle this huge activities.my app structure would be
Select department(14) >> Select sem(8)>> select subject(10)
Is there any methods like nestedif or something else to reduce the activity files.if there are any methods please do help me to complete the project.thanks in advance</p>

答: No, you don't need that many activities.  You need to write abstract activities that take parameters and displays different data based on those.  At most I see 4 activities here-  department selector, semester selector, subject selector, and the actual subject activity.  And arguably some of those should be fragments instead, although that's more personal choice.</p>


问:
Check Status of replicas of StatefulState using io.fabric8.kubernetes
I am terminating pods in a stateful state using io.fabric8.kubernetes client as

```<code>client
        .inNamespace(namespace)
        .pods()
        .withLabel("xx", "xxx")
        .delete()
</code>```

How can check if the StatefulSet is recovered back ?

What I am trying :

```<code>StatefulSet statefulSet = client
            .pods()
            .inNamespace("namespace-xxx")
            .statefulSets()
            .inNamespace(namespace)
            .withName("statefulset-name")
            .get();

StatefulSetStatus status = statefulSet.getStatus();
StatefulSetSpec spec = statefulSet.getSpec();
</code>```

and then checking the condition

```<code>spec.getReplicas.intValue != status.getReadyReplicas.intValue
</code>```

However this condition seems to be meeting even when the pods are not Ready!

答: As someone said in the comments, the client API is asynchronous by nature. This means that you should think differently from the procedural way to check the status of an action. As you can see from the documentation https://github.com/fabric8io/kubernetes-client#following-events the client allows you to define a watcher, where you can specify in the anonymous class all the actions to be performed when the desired event/status happens.</p>

Body:
I am terminating pods in a stateful state using io.fabric8.kubernetes client as

client
        .inNamespace(namespace)
        .pods()
        .withLabel("xx", "xxx")
        .delete()

How can check if the StatefulSet is recovered back ?

What I am trying :

StatefulSet statefulSet = client
            .pods()
            .inNamespace("namespace-xxx")
            .statefulSets()
            .inNamespace(namespace)
            .withName("statefulset-name")
            .get();

StatefulSetStatus status = statefulSet.getStatus();
StatefulSetSpec spec = statefulSet.getSpec();

and then checking the condition

spec.getReplicas.intValue != status.getReadyReplicas.intValue

However this condition seems to be meeting even when the pods are not Ready!


问:
How can I use For, While, Repeat functions with changing rep times
How can i print following code with For, While and Repeat functions in R?

[1] 9 9 9 9 9

[1] 7 7 7

[1] 5

[1] 3 3 3

[1] 1 1 1 1 1

With 2 hours of trial, I've discovered following code works to print above result

x<-c(5,0,3,0,1,0,3,0,5,0)

for(i in 10:1) {   if(!i %%2) {    next   }

print(rep(i,x[i]))

}

while func

t<-c(5,0,3,0,1,0,3,0,5)

i<-9

while(i>=1)

{print(rep(i,t[i]))

i<-i-2}

repeat

i<-9

  repeat{if(i<1)

  break
   print(rep(i,t[i]))

  i<- i-2}

but it seems so unnatural for me.
Is there any more compact or easier way to solve the problem?

Body:
We can use rep directly using x as times argument

rep(9:0, x)
#[1] 9 9 9 9 9 7 7 7 5 3 3 3 1 1 1 1 1

If you want them as list you can do

mapply(rep, (9:0)[x > 0], x[x > 0])

#[[1]]
#[1] 9 9 9 9 9

#[[2]]
#[1] 7 7 7

#[[3]]
#[1] 5

#[[4]]
#[1] 3 3 3

#[[5]]
#[1] 1 1 1 1 1


问:
Reusing CSS in JS
I'm using Material UI for the first time and I'm starting to repeat a lot of CSS. I'm used to a global style sheet and reusing classes from that but I'm unsure how to do it with this framework.

I read through the docs and the only thing I can understand for my situation is to create a createMuiTheme and use it like this:

Index.js

```<code>const theme = createMuiTheme({
  fontFamily: {
    primary: "\"IM Fell DW Pica SC\", serif",
})

ReactDOM.render(
<MuiThemeProvider theme={theme}>
 <CssBaseline />
 <App />
</MuiThemeProvider>,
document.getElementById('app')
)
</code>```

app.js

```<code>const styles = theme => ({
  paragraph: {
   "fontFamily": theme.fontFamily.primary
  }
})

\\ DOM

<Typography variant="caption" gutterBottom className={paragraph}>
  Here is my paragraph text
</Typography>
</code>```

Am I even using this correctly? To me, this doesn't cut down on a lot of code because if I create another a component that wants to use the same font family, I have to create the paragraph class again.

I have multiple components in separate files and find myself reusing a lot of simple styles like textAlign: 'center' and fontWeight: 'bold'

I thought about creating a separate JS file for the CSS and pulling from that but I'm not sure that's what Material UI was designed for. I'm thinking that I'm not using createMuiTheme to its full potential. Can anybody give me a simple solution to reusing some of these CSS styles?

答:
You have to restyle the component, and then it will be applied to all components inside the Theme wrapper, I did it like this:

```<code>import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';

const THEME = createMuiTheme({
  typography: {
    "fontFamily": "\"IM Fell DW Pica SC\", serif",
    "fontSize": 20,
    "lineHeight": 1.5,
    "letterSpacing": 0.32,
    useNextVariants: true,
    suppressDeprecationWarnings: true,
  },
});

class App extends Component {
  render() {
    return (
      <MuiThemeProvider theme={THEME}>
        </YourComponentsThatHasThisFont>
      </MuiThemeProvider>
    );
  }
}

export default App;

</code>```

In this case I changed the typography component form material-ui, so all the text that is written using their tag will be in this new font style.

If you want to override what your theme is setting, here's an example of an HOC that you can do.

// imports

const styles = theme => ({
  text: {
    "&.override1": {
      fontSize: 15
    },
    "&.override2": {
      fontSize: 53,
      fontWeight: 700
    }
  }
});

const Text = ({ classes, children, override, ...rest }) => (
  <Typography
    classes={{ root: classes.text }}
    className={`${override}`}
    {...rest}
  >
    {children}
  </Typography>
);

export default withStyles(styles)(Text);```

And you would just use that component just like you would a regular Typography component except you could also pass in things like <Text variant="h2" override="override1">Hello World</Text>

Title: Reusing CSS in JS

Body:
I'm using Material UI for the first time and I'm starting to repeat a lot of CSS. I'm used to a global style sheet and reusing classes from that but I'm unsure how to do it with this framework.

I read through the docs and the only thing I can understand for my situation is to create a createMuiTheme and use it like this:

Index.js

const theme = createMuiTheme({
  fontFamily: {
    primary: "\"IM Fell DW Pica SC\", serif",
})

ReactDOM.render(
<MuiThemeProvider theme={theme}>
 <CssBaseline />
 <App />
</MuiThemeProvider>,
document.getElementById('app')
)

app.js

const styles = theme => ({
  paragraph: {
   "fontFamily": theme.fontFamily.primary
  }
})

\\ DOM

<Typography variant="caption" gutterBottom className={paragraph}>
  Here is my paragraph text
</Typography>

Am I even using this correctly? To me, this doesn't cut down on a lot of code because if I create another a component that wants to use the same font family, I have to create the paragraph class again.

I have multiple components in separate files and find myself reusing a lot of simple styles like textAlign: 'center' and fontWeight: 'bold'

I thought about creating a separate JS file for the CSS and pulling from that but I'm not sure that's what Material UI was designed for. I'm thinking that I'm not using createMuiTheme to its full potential. Can anybody give me a simple solution to reusing some of these CSS styles?

Body:
You have to restyle the component, and then it will be applied to all components inside the Theme wrapper, I did it like this:

import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';

const THEME = createMuiTheme({
  typography: {
    "fontFamily": "\"IM Fell DW Pica SC\", serif",
    "fontSize": 20,
    "lineHeight": 1.5,
    "letterSpacing": 0.32,
    useNextVariants: true,
    suppressDeprecationWarnings: true,
  },
});

class App extends Component {
  render() {
    return (
      <MuiThemeProvider theme={THEME}>
        </YourComponentsThatHasThisFont>
      </MuiThemeProvider>
    );
  }
}

export default App;

In this case I changed the typography component form material-ui, so all the text that is written using their tag will be in this new font style.

If you want to override what your theme is setting, here's an example of an HOC that you can do.

// imports

const styles = theme => ({
  text: {
    "&.override1": {
      fontSize: 15
    },
    "&.override2": {
      fontSize: 53,
      fontWeight: 700
    }
  }
});

const Text = ({ classes, children, override, ...rest }) => (
  <Typography
    classes={{ root: classes.text }}
    className={`${override}`}
    {...rest}
  >
    {children}
  </Typography>
);

export default withStyles(styles)(Text);

And you would just use that component just like you would a regular Typography component except you could also pass in things like <Text variant="h2" override="override1">Hello World</Text>