问:
Export actual functions for different routes in different files
Currently my routes file is setup like this:

```<code>    const logoutHelper = function (request, response) {
        if (request.session) {
            console.log("User '" + request.session.username + "' logged out.");
            request.session.destroy(function (err) {
                if (err) {
                    return next(err);
                } else {
                    return response.redirect('/');
                }
            });
        }
    }

    // Logout user and delete the session object
    app.get('/logout', logoutHelper);
</code>```

How can I move the logoutHelper functions to another file in the same directory? I want to split the post and get routes into different files because my original routes.js grew too big.

答:
In your new file:

```<code>const logoutHelper = function (request, response) {
    if (request.session) {
        console.log("User '" + request.session.username + "' logged out.");
        request.session.destroy(function (err) {
            if (err) {
                return next(err);
            } else {
                return response.redirect('/');
            }
        });
    }
}

module.exports = {
    logoutHelper: logoutHelper
};
</code>```

In your route file:

```<code>const Helpers = require('<helper file>');

// Logout user and delete the session object
app.get('/logout', Helpers.logoutHelper);
</code>```

Something else to note, you are using next but don't have it defined in your callback function. You probably need to add it as the third parameter of the logoutHelper function.

Also I'm assuming you're not using es6-you can probably clean up that export object if you are.

Body:
Currently my routes file is setup like this:

    const logoutHelper = function (request, response) {
        if (request.session) {
            console.log("User '" + request.session.username + "' logged out.");
            request.session.destroy(function (err) {
                if (err) {
                    return next(err);
                } else {
                    return response.redirect('/');
                }
            });
        }
    }

    // Logout user and delete the session object
    app.get('/logout', logoutHelper);

How can I move the logoutHelper functions to another file in the same directory? I want to split the post and get routes into different files because my original routes.js grew too big.

Body:
In your new file:

const logoutHelper = function (request, response) {
    if (request.session) {
        console.log("User '" + request.session.username + "' logged out.");
        request.session.destroy(function (err) {
            if (err) {
                return next(err);
            } else {
                return response.redirect('/');
            }
        });
    }
}

module.exports = {
    logoutHelper: logoutHelper
};

In your route file:

const Helpers = require('<helper file>');

// Logout user and delete the session object
app.get('/logout', Helpers.logoutHelper);

Something else to note, you are using next but don't have it defined in your callback function. You probably need to add it as the third parameter of the logoutHelper function.

Also I'm assuming you're not using es6-you can probably clean up that export object if you are.


来源: stackexchange

答:
You want to combine the values for a given key by taking the sum. This is precisely what reduceByKey does. You just need to define an associative and commutative reduce function to combine the values as desired.

def myReducer(a, b):
    a, b = map(int, a.split(";")), map(int, b.split(";"))
    maxLength = max(len(a), len(b))
    if len(a) < len(b):
        a = a + [0]*(len(b)-len(a))
    elif len(b) < len(a):
        b = b + [0]*(len(a)-len(b))
    return ";".join([str(a[i] + b[i]) for i in range(maxLength)])
```

<p>The only real tricky part here is that your sample input lists are not all the same size. In this case, I defined the function to zero pad the shorter list.</p>

<p>Now call <code>reduceByKey</code>:</p>

<pre class="lang-python prettyprint-override"><code>countryCountsRdd.reduceByKey(myReducer).collect()
#[('CANADA', '183;258;150;263;71'),
# ('CHINA', '218;239;234;209;75'),
# ('INDIA', '246;153;148;100;90'),
# ('ENGLAND', '178;114;175;173;153'),
# ('GERMANY', '153;172;156;171;51')]
</code>```

ContentLicense: CC BY-SA 4.0

Title: Addition of elements in multiple list corresponding to a key column of RDD

Body:
I have PythonRDDs. I have to perform addition of elements for multiple lists. Add element 1 of list 1 to element 1 of list 2 then add to element 1 of list 3.
For Canada, add 47,59,77 as element 1, 97,98,63 as second element and so on.

I tried to flatten the list to add them and tried to convert to dataframe but I failed to do so. And I want to do it through all 3 ways

countryCounts = [
('CANADA','47;97;33;94;6'),
('CANADA','59;98;24;83;3'),
('CANADA','77;63;93;86;62'),
('CHINA','86;71;72;23;27'),
('CHINA','74;69;72;93;7'),
('CHINA','58;99;90;93;41'),
('ENGLAND','40;13;85;75;90'),
('ENGLAND','39;13;33;29;14'),
('ENGLAND','99;88;57;69;49'),
('GERMANY','67;93;90;57;3'),
('GERMANY','9;15;20;19'),
('GERMANY','77;64;46;95;48'),
('INDIA','90;49;91;14;70'),
('INDIA','70;83;38;27;16'),
('INDIA','86;21;19;59;4')
]
countryCountsRdd = sc.parallelize(countryCounts)
countryCountsSplit.collect()
countryCountsGroup=countryCountsSplit.groupByKey().mapValues(list)
countryCountsGroup.collect()
CountsSplit=countryCountsRdd.map(lambda x : (x[0], ",".join(x[1].split(';'))))
countryCountsSplit.collect()

Inputs :
Way 1
[('CANADA', [47, 97, 33, 94, 6]), ('CANADA', [59, 98, 24, 83, 3]), ('CANADA', [77, 63, 93, 86, 62]), ('CHINA', [86, 71, 72, 23, 27]), ('CHINA', [74, 69, 72, 93, 7]), ('CHINA', [58, 99, 90, 93, 41]), ('ENGLAND', [40, 13, 85, 75, 90]), ('ENGLAND', [39, 13, 33, 29, 14]), ('ENGLAND', [99, 88, 57, 69, 49]), ('GERMANY', [67, 93, 90, 57, 3]), ('GERMANY', [9, 15, 20, 19]), ('GERMANY', [77, 64, 46, 95, 48]), ('INDIA', [90, 49, 91, 14, 70]), ('INDIA', [70, 83, 38, 27, 16]), ('INDIA', [86, 21, 19, 59, 4])]
Way 2:
[('CANADA', [[47, 97, 33, 94, 6], [59, 98, 24, 83, 3], [77, 63, 93, 86, 62]]), ('CHINA', [[86, 71, 72, 23, 27], [74, 69, 72, 93, 7], [58, 99, 90, 93, 41]]), ('INDIA', [[90, 49, 91, 14, 70], [70, 83, 38, 27, 16], [86, 21, 19, 59, 4]]), ('ENGLAND', [[40, 13, 85, 75, 90], [39, 13, 33, 29, 14], [99, 88, 57, 69, 49]]), ('GERMANY', [[67, 93, 90, 57, 3], [9, 15, 20, 19], [77, 64, 46, 95, 48]])]
Way 3:
[('CANADA', '47 ,97 ,33 ,94 ,6'), ('CANADA', '59 ,98 ,24 ,83 ,3'), ('CANADA', '77 ,63 ,93 ,86 ,62'), ('CHINA', '86 ,71 ,72 ,23 ,27'), ('CHINA', '74 ,69 ,72 ,93 ,7'), ('CHINA', '58 ,99 ,90 ,93 ,41'), ('ENGLAND', '40 ,13 ,85 ,75 ,90'), ('ENGLAND', '39 ,13 ,33 ,29 ,14'), ('ENGLAND', '99 ,88 ,57 ,69 ,49'), ('GERMANY', '67 ,93 ,90 ,57 ,3'), ('GERMANY', '9 ,15 ,20 ,19'), ('GERMANY', '77 ,64 ,46 ,95 ,48'), ('INDIA', '90 ,49 ,91 ,14 ,70'), ('INDIA', '70 ,83 ,38 ,27 ,16'), ('INDIA', '86 ,21 ,19 ,59 ,4')]

Require same output for all 3 :
[('CANADA','183;258;150;263;71)]
[('CHINA','218,239,234,209,75')]
[('ENGLAND','178,114,175,173,153')]
[('GERMANY','144,166,151,172,70')]
[('INDIA','246,153,148,100,90')]

Body:
You want to combine the values for a given key by taking the sum. This is precisely what reduceByKey does. You just need to define an associative and commutative reduce function to combine the values as desired.

def myReducer(a, b):
    a, b = map(int, a.split(";")), map(int, b.split(";"))
    maxLength = max(len(a), len(b))
    if len(a) < len(b):
        a = a + [0]*(len(b)-len(a))
    elif len(b) < len(a):
        b = b + [0]*(len(a)-len(b))
    return ";".join([str(a[i] + b[i]) for i in range(maxLength)])

The only real tricky part here is that your sample input lists are not all the same size. In this case, I defined the function to zero pad the shorter list.

Now call reduceByKey:

countryCountsRdd.reduceByKey(myReducer).collect()
#[('CANADA', '183;258;150;263;71'),
# ('CHINA', '218;239;234;209;75'),
# ('INDIA', '246;153;148;100;90'),
# ('ENGLAND', '178;114;175;173;153'),
# ('GERMANY', '153;172;156;171;51')]


问:
How to do a string replacement on a variable at the windows command prompt?
Is there was a way to do string replacement, at the command prompt, as opposed to inside a batch file?

A little background: A while ago I needed to register a custom URI protocol that would forward the invoked url to Chrome via a registry hack which resulted in:

```Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CNX]
@="Chrome HTML Document"
"URL Protocol"=""

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CNX\DefaultIcon]
@="C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe,0"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CNX\shell]

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CNX\shell\open]

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CNX\shell\open\command]
<b>@="cmd /c cd \"C:\\Program Files (x86)\\Google\\Chrome\\Application\\\" & FOR /f \"tokens=1-3delims=?#\" %%a IN (\"%1\") DO (if \"%%a#%%b%%c\"==\"%1\" (chrome.exe %1) else (chrome.exe %%a#%%c%%b) )"</b>

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\ProtocolExecute\CNX]
"WarnOnOpen"=dword:00000000```

The problem that I've noticed now is that via some new windows update, what used to be invoked as

```<code>cnx:// www.someurl.com
</code>```

in IE now gets turned into

```cnx://<b>%20</b>www.someurl.com```

when the command executes.

Therefore, I'm wondering if there's a way to do a string replace somewhere, and completely strip out cnx://%20 from my %%a variable or something?

But all my attempts at using https://ss64.com/nt/syntax-replace.html haven't worked. It would be great to hear or read that it's not possible at all, so I can stop spinning my wheels.

答:
The solution is using in Window registry file:

```<code>@="cmd.exe /V:ON /C cd /D \"C:\\Program Files (x86)\\Google\\Chrome\\Application\\\" & set \"url=%1\" & set \"url=!url:cnx://%%20=!\" & set \"url=!url:cnx://=!\" & for /F \"tokens=1-3 delims=?#\" %%a in (\"!url!\") do if \"%%a#%%b%%c\"==\"!url!\" (chrome.exe \"!url!\") else (chrome.exe \"%%a#%%c%%b\")"
</code>```

This results in following command line in Windows registry:

```<code>cmd.exe /V:ON /C cd /D "C:\Program Files (x86)\Google\Chrome\Application\" & set "url=%1" & set "url=!url:cnx://%%20=!" & set "url=!url:cnx://=!" & for /F "tokens=1-3 delims=?#" %%a in ("!url!") do if "%%a#%%b%%c"=="!url!" (chrome.exe "!url!") else (chrome.exe "%%a#%%c%%b")
</code>```

Important is Windows command processor option /V:ON which enables delayed expansion for environment variables as explained by help output on running in a command prompt window cmd /?. Option /V:ON must be specified left to option /C (close after execution of command line) respectively /K (keep command process running after execution of command line) because everything after /C or /K is interpreted as part of the command line to execute.

The usage of /K instead of /C makes it possible to see what happens on execution of this command line and set url can be executed by the user after the command line execution finished to see what is the final value of environment variable url.

The help output on running in a cmd window set /? explains when and how to use delayed environment variable expansion. It must be used if an environment variable is defined or modified on a command line and referenced on same command line as it is here the case with single line with multiple commands. It is also necessary if an environment variable is defined or modified within a command block starting with ( and ending with matching ) because of cmd.exe parses the entire command block and replaces all %variable% references by current value of reference environment variable before executing any command of this command block or left to begin of command block on same command line.

See also How does the Windows Command Interpreter (CMD.EXE) parse scripts?

It is necessary to reference environment variables with !variable! to expand this reference delayed after having enabled delayed expansion.

Note: Every exclamation mark in command line is interpreted as begin/end of delayed expanded environment variable reference once being enabled even inside a double quoted argument string.

A commented batch file with (nearly) same code would be:

```<code>@echo off
rem Explicitly enable command extensions although enabled by default
rem and delayed environment variable expansion disabled by default.
setlocal EnableExtensions EnableDelayedExpansion

rem Change current directory to directory containing Google Chrome browser.
cd /D "%ProgramFiles(x86)%\Google\Chrome\Application\"

rem Define environment variable url with value of first
rem argument with surrounding double quotes removed.
set "url=%~1"

rem Exit batch file if called without any argument or with just "".
if not defined url goto EndBatch

rem Remove case-insensitive all occurrences of string "cnx://"
rem with an additional percent encoded space from the url argument.
set "url=!url:cnx://%%20=!"

rem Remove case-insensitive all occurrences of string "cnx://".
set "url=!url:cnx://=!"

rem Split up the url strings on question mark and hash and assign just
rem first three ?# delimited substrings to loop variables a, b and c.
rem FOR would not run any command in command block on url starting with
rem a semicolon. Run Google Chrome with the url if first substring with #
rem and the two other substrings appended is case-sensitive equal the url.
rem Otherwise run Google Chrome with redefined url with second and third
rem substring exchanged after first substring and hash character.
for /F "tokens=1-3 delims=?#" %%a in ("!url!") do (
    if "%%a#%%b%%c" == "!url!" (
        start "" chrome.exe "!url!"
    ) else (
        start "" chrome.exe "%%a#%%c%%b"
    )
)

rem Restore initial environment on calling the batch file which means
rem discarding all environment variables defined or modified in block
rem above like environment variable url, restore initial current directory
rem as it was before using command CD and restore also initial states of
rem command extensions (most likely enabled) and delayed expansion (most
rem likely disabled).
:EndBatch
endlocal
</code>```

Body:
Is there was a way to do string replacement, at the command prompt, as opposed to inside a batch file?

A little background: A while ago I needed to register a custom URI protocol that would forward the invoked url to Chrome via a registry hack which resulted in:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CNX]
@="Chrome HTML Document"
"URL Protocol"=""

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CNX\DefaultIcon]
@="C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe,0"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CNX\shell]

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CNX\shell\open]

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CNX\shell\open\command]
@="cmd /c cd \"C:\\Program Files (x86)\\Google\\Chrome\\Application\\\" & FOR /f \"tokens=1-3delims=?#\" %%a IN (\"%1\") DO (if \"%%a#%%b%%c\"==\"%1\" (chrome.exe %1) else (chrome.exe %%a#%%c%%b) )"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\ProtocolExecute\CNX]
"WarnOnOpen"=dword:00000000

The problem that I've noticed now is that via some new windows update, what used to be invoked as

cnx:// www.someurl.com

in IE now gets turned into

cnx://%20www.someurl.com

when the command executes.

Therefore, I'm wondering if there's a way to do a string replace somewhere, and completely strip out cnx://%20 from my %%a variable or something?

But all my attempts at using https://ss64.com/nt/syntax-replace.html haven't worked. It would be great to hear or read that it's not possible at all, so I can stop spinning my wheels.

Body:
The solution is using in Window registry file:

@="cmd.exe /V:ON /C cd /D \"C:\\Program Files (x86)\\Google\\Chrome\\Application\\\" & set \"url=%1\" & set \"url=!url:cnx://%%20=!\" & set \"url=!url:cnx://=!\" & for /F \"tokens=1-3 delims=?#\" %%a in (\"!url!\") do if \"%%a#%%b%%c\"==\"!url!\" (chrome.exe \"!url!\") else (chrome.exe \"%%a#%%c%%b\")"

This results in following command line in Windows registry:

cmd.exe /V:ON /C cd /D "C:\Program Files (x86)\Google\Chrome\Application\" & set "url=%1" & set "url=!url:cnx://%%20=!" & set "url=!url:cnx://=!" & for /F "tokens=1-3 delims=?#" %%a in ("!url!") do if "%%a#%%b%%c"=="!url!" (chrome.exe "!url!") else (chrome.exe "%%a#%%c%%b")

Important is Windows command processor option /V:ON which enables delayed expansion for environment variables as explained by help output on running in a command prompt window cmd /?. Option /V:ON must be specified left to option /C (close after execution of command line) respectively /K (keep command process running after execution of command line) because everything after /C or /K is interpreted as part of the command line to execute.

The usage of /K instead of /C makes it possible to see what happens on execution of this command line and set url can be executed by the user after the command line execution finished to see what is the final value of environment variable url.

The help output on running in a cmd window set /? explains when and how to use delayed environment variable expansion. It must be used if an environment variable is defined or modified on a command line and referenced on same command line as it is here the case with single line with multiple commands. It is also necessary if an environment variable is defined or modified within a command block starting with ( and ending with matching ) because of cmd.exe parses the entire command block and replaces all %variable% references by current value of reference environment variable before executing any command of this command block or left to begin of command block on same command line.

See also How does the Windows Command Interpreter (CMD.EXE) parse scripts?

It is necessary to reference environment variables with !variable! to expand this reference delayed after having enabled delayed expansion.

Note: Every exclamation mark in command line is interpreted as begin/end of delayed expanded environment variable reference once being enabled even inside a double quoted argument string.

A commented batch file with (nearly) same code would be:

@echo off
rem Explicitly enable command extensions although enabled by default
rem and delayed environment variable expansion disabled by default.
setlocal EnableExtensions EnableDelayedExpansion

rem Change current directory to directory containing Google Chrome browser.
cd /D "%ProgramFiles(x86)%\Google\Chrome\Application\"

rem Define environment variable url with value of first
rem argument with surrounding double quotes removed.
set "url=%~1"

rem Exit batch file if called without any argument or with just "".
if not defined url goto EndBatch

rem Remove case-insensitive all occurrences of string "cnx://"
rem with an additional percent encoded space from the url argument.
set "url=!url:cnx://%%20=!"

rem Remove case-insensitive all occurrences of string "cnx://".
set "url=!url:cnx://=!"

rem Split up the url strings on question mark and hash and assign just
rem first three ?# delimited substrings to loop variables a, b and c.
rem FOR would not run any command in command block on url starting with
rem a semicolon. Run Google Chrome with the url if first substring with #
rem and the two other substrings appended is case-sensitive equal the url.
rem Otherwise run Google Chrome with redefined url with second and third
rem substring exchanged after first substring and hash character.
for /F "tokens=1-3 delims=?#" %%a in ("!url!") do (
    if "%%a#%%b%%c" == "!url!" (
        start "" chrome.exe "!url!"
    ) else (
        start "" chrome.exe "%%a#%%c%%b"
    )
)

rem Restore initial environment on calling the batch file which means
rem discarding all environment variables defined or modified in block
rem above like environment variable url, restore initial current directory
rem as it was before using command CD and restore also initial states of
rem command extensions (most likely enabled) and delayed expansion (most
rem likely disabled).
:EndBatch
endlocal


问:
Presto Singleton Class in qds-sdq-py needs to interact with different API Tokens at runtime
Our application (python 3.6) is a query generator, allowing its users to query several tables from different DataBases.
We are trying to add Qubole support. Currently trying to assimilate a Presto engined clusters.
We have several API tokens and need to be able to query different presto DB’s simultaneously.
We started implementing this using qds_sdk, however, it seems that the class Qubole is a Singlton and the Class PrestoCommand interact with it directly.

Please consider qds-sdk-py/example/qubole_presto_api_example.py
https://github.com/qubole/qds-sdk-py/blob/master/example/qubole_presto_api_example.py

lines 67-68

```<code>  Qubole.configure(api_token=‘YOUR-QUBOLE-API-TOKEN’)
  get_results(execute_query(“select * from  default.cities limit 100;“))
</code>```

Our service require the ability to have several Qubole.configure objects and to query them according to user interactions.
I.E:

```<code>    q1 =  Qubole.configure(api_token=‘Token1’)
    q2 =  Qubole.configure(api_token=‘Token2’)
    *user triggeres an event*
    q1.get_results(execute_query(“query”))
</code>```

How would you proceed? Should I implement some lock before trying to access the table?

答:
If your question is how to use different API Tokens to send queries to different Qubole accounts (and therefore Presto clusters), I believe you have that sorted with instantiating different Qubole clients.

If you need to wait for each query to complete before moving on, then you could also use a loop with polling. Here's a quick example of how you might approach it for one query:

```<code>presto_command=PrestoCommand.create(query=my_query, label='presto_cluster_label')
while True:
    sts = PrestoCommand.find(presto_command.id).status
    if sts == u'error' or sts == u'done' or sts == u'cancelled':
        break
    time.sleep(10)

if sts != u'done':
    error_str = presto_command.get_log()
    sys.stderr.write(error_str)
    raise QuboleError(error_str)

presto_command.get_results()
</code>```

Body:
Our application (python 3.6) is a query generator, allowing its users to query several tables from different DataBases.
We are trying to add Qubole support. Currently trying to assimilate a Presto engined clusters.
We have several API tokens and need to be able to query different presto DB’s simultaneously.
We started implementing this using qds_sdk, however, it seems that the class Qubole is a Singlton and the Class PrestoCommand interact with it directly.

Please consider qds-sdk-py/example/qubole_presto_api_example.py
https://github.com/qubole/qds-sdk-py/blob/master/example/qubole_presto_api_example.py

lines 67-68

  Qubole.configure(api_token=‘YOUR-QUBOLE-API-TOKEN’)
  get_results(execute_query(“select * from  default.cities limit 100;“))

Our service require the ability to have several Qubole.configure objects and to query them according to user interactions.
I.E:

    q1 =  Qubole.configure(api_token=‘Token1’)
    q2 =  Qubole.configure(api_token=‘Token2’)
    *user triggeres an event*
    q1.get_results(execute_query(“query”))

How would you proceed? Should I implement some lock before trying to access the table?

Body:
If your question is how to use different API Tokens to send queries to different Qubole accounts (and therefore Presto clusters), I believe you have that sorted with instantiating different Qubole clients.

If you need to wait for each query to complete before moving on, then you could also use a loop with polling. Here's a quick example of how you might approach it for one query:

presto_command=PrestoCommand.create(query=my_query, label='presto_cluster_label')
while True:
    sts = PrestoCommand.find(presto_command.id).status
    if sts == u'error' or sts == u'done' or sts == u'cancelled':
        break
    time.sleep(10)

if sts != u'done':
    error_str = presto_command.get_log()
    sys.stderr.write(error_str)
    raise QuboleError(error_str)

presto_command.get_results()


问:
How to send multiple commands to xbee router in one data packet transmission using arduino uno
I was wondering if I could control multiple IO pins on the xbee remotely with one command from a coordinator.

I can easily send one IO pin high or low as below

```<code>xB.write((byte)0x7E);
xB.write((byte)0x0);
xB.write((byte)0x10);
xB.write((byte)0x17);
xB.write((byte)0x0);  // Frame ID
xB.write((byte)0x00); // first byte
xB.write((byte)0x13); // 2
xB.write((byte)0xA2); // 3
xB.write((byte)0x00); // 4
xB.write(addy5); // 5
xB.write(addy6); // 6
xB.write(addy7); // 7
xB.write(addy8);// 8
xB.write((byte)0xFF);
xB.write((byte)0xFE);
xB.write((byte)0x02);
xB.write('D');
xB.write('0');
xB.write(val);
long sum = 0x17 + 0x13 + 0xA2 + addy5 + addy6 + addy7 + addy8 + 0xFF + 0xFE + 0x02 + 'D' + '0' + val;
xB.write((byte)0xFF - (sum & 0xFF));
</code>```

But I can't seem to send more than one digital pin change at once like this.

```<code>xB.write((byte)0x7E);
xB.write((byte)0x0);
xB.write((byte)0x1F);
xB.write((byte)0x17);
xB.write((byte)0x0);  // Frame ID
xB.write((byte)0x00); // first byte
xB.write((byte)0x13); // 2
xB.write((byte)0xA2); // 3
xB.write((byte)0x00); // 4
xB.write(addy5); // 5
xB.write(addy6); // 6
xB.write(addy7); // 7
xB.write(addy8);// 8
xB.write((byte)0xFF); // "10"67
xB.write((byte)0xFE);// 10"66"
xB.write((byte)0x02);

xB.write('D');
xB.write('1');
xB.write(bin[0]);

xB.write('D');
xB.write('0');
xB.write(bin[1]);

xB.write('D');
xB.write('2');
xB.write(bin[2]);

xB.write('D');
xB.write('3');
xB.write(bin[3]);

xB.write('D');
xB.write('5');
xB.write(bin[4]);

xB.write('D');
xB.write('4');
xB.write(bin[5]);

long sum = 0x17 + 0x13 + 0xA2 + addy5 + addy6 + addy7 + addy8 + 0xFF + 0xFE + 0x02 + 'D' + '1' + bin[0] + 'D' + '0' + bin[1] + 'D' + '2' + bin[2] + 'D' + '3' + bin[3] + 'D' + '5' + bin[4] + 'D' + '4' + bin[5];
xB.write((byte)0xFF - (sum & 0xFF));
</code>```

What might I be doing wrong? Thanks!

答:
As you can see from the API reference for the Remote AT Command Frame, the bytes after the command (D0) are the value for that command.  The XBee module doesn't have a frame type for multiple AT commands, but you can send a series of queued commands, and have them all apply at once when you set the "Apply Changes" bit of the options field.

So, where you're sending 0x02 right before the AT command, you would send 0x00 for the commands you want to queue up, and only send the 0x02 on the last command to have it apply all changes at once.

Also, consider writing some routines to simplify your frame sending.  For example, a single function that takes a pointer to a buffer with a length could automatically send the start of frame (0x7E 0x00 <length>) and a calculated checksum byte at the end of the frame.

Body:
I was wondering if I could control multiple IO pins on the xbee remotely with one command from a coordinator.

I can easily send one IO pin high or low as below

xB.write((byte)0x7E);
xB.write((byte)0x0);
xB.write((byte)0x10);
xB.write((byte)0x17);
xB.write((byte)0x0);  // Frame ID
xB.write((byte)0x00); // first byte
xB.write((byte)0x13); // 2
xB.write((byte)0xA2); // 3
xB.write((byte)0x00); // 4
xB.write(addy5); // 5
xB.write(addy6); // 6
xB.write(addy7); // 7
xB.write(addy8);// 8
xB.write((byte)0xFF);
xB.write((byte)0xFE);
xB.write((byte)0x02);
xB.write('D');
xB.write('0');
xB.write(val);
long sum = 0x17 + 0x13 + 0xA2 + addy5 + addy6 + addy7 + addy8 + 0xFF + 0xFE + 0x02 + 'D' + '0' + val;
xB.write((byte)0xFF - (sum & 0xFF));

But I can't seem to send more than one digital pin change at once like this.

xB.write((byte)0x7E);
xB.write((byte)0x0);
xB.write((byte)0x1F);
xB.write((byte)0x17);
xB.write((byte)0x0);  // Frame ID
xB.write((byte)0x00); // first byte
xB.write((byte)0x13); // 2
xB.write((byte)0xA2); // 3
xB.write((byte)0x00); // 4
xB.write(addy5); // 5
xB.write(addy6); // 6
xB.write(addy7); // 7
xB.write(addy8);// 8
xB.write((byte)0xFF); // "10"67
xB.write((byte)0xFE);// 10"66"
xB.write((byte)0x02);

xB.write('D');
xB.write('1');
xB.write(bin[0]);

xB.write('D');
xB.write('0');
xB.write(bin[1]);

xB.write('D');
xB.write('2');
xB.write(bin[2]);

xB.write('D');
xB.write('3');
xB.write(bin[3]);

xB.write('D');
xB.write('5');
xB.write(bin[4]);

xB.write('D');
xB.write('4');
xB.write(bin[5]);

long sum = 0x17 + 0x13 + 0xA2 + addy5 + addy6 + addy7 + addy8 + 0xFF + 0xFE + 0x02 + 'D' + '1' + bin[0] + 'D' + '0' + bin[1] + 'D' + '2' + bin[2] + 'D' + '3' + bin[3] + 'D' + '5' + bin[4] + 'D' + '4' + bin[5];
xB.write((byte)0xFF - (sum & 0xFF));

What might I be doing wrong? Thanks!


问:
WKWebView JavaScript communication on page load
EDIT

The below examples DO work. I was making a silly mistake and not calling the correct page in my web app. I'll leave this here for anybody else looking for how to do what I am doing.

I have Native -> WKWebView JavaScript communication working for my project with the exception of one thing: I am unable to have a postMessage() call be recognized when my web page loads.

I have added a message handler named "contentLoaded" that I'm trying to trigger like this from my webview:

```<code>window.addEventListener('load', (event) => {
    window.webkit.messageHandlers.contentLoaded.postMessage("content has loaded");
});
</code>```

and I has also tried:

```<code>window.addEventListener('DOMContentLoaded', (event) => {
    window.webkit.messageHandlers.contentLoaded.postMessage("content has loaded");
});
</code>```

Additionally, I'm actually using Vue.js so I've also tried to hook into Vue's created() and mounted() hooks like this:

```<code>mounted() {
    window.webkit.messageHandlers.contentLoaded.postMessage("content has loaded");
}
</code>```

or this:

```<code>mounted() {
    window.webkit.messageHandlers.contentLoaded.postMessage("content has loaded");
}
</code>```

None of these actually trigger the "contentLoaded" message handler.

However, I can trigger the message handler if I make some interaction with the web page, for example:

```<code>// This works!
button.addEventListener('click', () => {
   window.webkit.messageHandlers.contentLoaded.postMessage("content has loaded");
})
</code>```

The Swift side of my code is below. Any advice here?

import UIKit
import WebKit

class MainViewController: UIViewController, WKUIDelegate {
    var webView: WKWebView!

    override func loadView() {
        super.loadView()

        let contentController = WKUserContentController()

        contentController.add(self, name: "contentLoaded")

        let webConfiguration = WKWebViewConfiguration()
        webConfiguration.userContentController = contentController
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        webView.navigationDelegate = self
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let myURL = URL(string:"https://example.com")
        var myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)
    }
}

extension MainViewController: WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        print("received")

        if message.name == "contentLoaded", let messageBody = message.body as? String {
            print(messageBody)
        }
    }
}

extension MainViewController: WKNavigationDelegate {
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("didFinish navigation")
    }

    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        print("didStartProvisionalNavigation")
    }
}
```

答:
Have you tried using the webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) method as your callback for when the window loads, in place of a javascript callback?

Swift usually isn't communicative with the window in WKWebView until it's fully loaded - at which point the didFinish method is the first thing called. Assuming you just need to know when the window/content is loaded, I would use that delegate method over JS.

Edit: If you need to retrieve some kind of data from the browser when the web page loads, you could call a Javascript method from the didFinish block that returns it, assuming you've written such a Javascript method to do so.

```<code>public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    webView.evaluateJavaScript("getData()", completionHandler: { (data, error) in
        if let data = data {
            print("Received: ", data)
        }
        if let error = error {
            print(error)
        }
    })
}
</code>```

Body:
EDIT

The below examples DO work. I was making a silly mistake and not calling the correct page in my web app. I'll leave this here for anybody else looking for how to do what I am doing.

I have Native -> WKWebView JavaScript communication working for my project with the exception of one thing: I am unable to have a postMessage() call be recognized when my web page loads.

I have added a message handler named "contentLoaded" that I'm trying to trigger like this from my webview:

window.addEventListener('load', (event) => {
    window.webkit.messageHandlers.contentLoaded.postMessage("content has loaded");
});

and I has also tried:

window.addEventListener('DOMContentLoaded', (event) => {
    window.webkit.messageHandlers.contentLoaded.postMessage("content has loaded");
});

Additionally, I'm actually using Vue.js so I've also tried to hook into Vue's created() and mounted() hooks like this:

mounted() {
    window.webkit.messageHandlers.contentLoaded.postMessage("content has loaded");
}

or this:

mounted() {
    window.webkit.messageHandlers.contentLoaded.postMessage("content has loaded");
}

None of these actually trigger the "contentLoaded" message handler.

However, I can trigger the message handler if I make some interaction with the web page, for example:

// This works!
button.addEventListener('click', () => {
   window.webkit.messageHandlers.contentLoaded.postMessage("content has loaded");
})

The Swift side of my code is below. Any advice here?

import UIKit
import WebKit

class MainViewController: UIViewController, WKUIDelegate {
    var webView: WKWebView!

    override func loadView() {
        super.loadView()

        let contentController = WKUserContentController()

        contentController.add(self, name: "contentLoaded")

        let webConfiguration = WKWebViewConfiguration()
        webConfiguration.userContentController = contentController
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        webView.navigationDelegate = self
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let myURL = URL(string:"https://example.com")
        var myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)
    }
}

extension MainViewController: WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        print("received")

        if message.name == "contentLoaded", let messageBody = message.body as? String {
            print(messageBody)
        }
    }
}

extension MainViewController: WKNavigationDelegate {
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("didFinish navigation")
    }

    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        print("didStartProvisionalNavigation")
    }
}

Body:
Have you tried using the webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) method as your callback for when the window loads, in place of a javascript callback?

Swift usually isn't communicative with the window in WKWebView until it's fully loaded - at which point the didFinish method is the first thing called. Assuming you just need to know when the window/content is loaded, I would use that delegate method over JS.

Edit: If you need to retrieve some kind of data from the browser when the web page loads, you could call a Javascript method from the didFinish block that returns it, assuming you've written such a Javascript method to do so.

public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    webView.evaluateJavaScript("getData()", completionHandler: { (data, error) in
        if let data = data {
            print("Received: ", data)
        }
        if let error = error {
            print(error)
        }
    })
}


问:
How to get function from function type?
Suppose I have hold of the concrete type of a normal, named Julia function, F = typeof(f).  Is it possible to get back f from F?  I assume this should work in principle, since F is a singleton type.

答: I would use F.instance, but maybe there is some better solution (as this one is using the internals).

Title: How to get function from function type?


问:
circle with dash lines uiview
I am trying to make a circle with dash lines. I am able to make lines in rectangle but I don't know how to make these in circle. Here is answer I got but it's in Objective-C: UIView Draw Circle with Dotted Line Border

Here is my code which makes a rectangle with dashed lines.

```<code>func addDashedBorder() {
    let color = UIColor.red.cgColor

    let shapeLayer:CAShapeLayer = CAShapeLayer()
    let frameSize = self.frame.size
    let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height)

    shapeLayer.bounds = shapeRect
    shapeLayer.position = CGPoint(x: frameSize.width/2, y: frameSize.height/2)
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.strokeColor = color
    shapeLayer.lineWidth = 2
    shapeLayer.lineJoin = CAShapeLayerLineJoin.round
    shapeLayer.lineDashPattern = [6,3]
    shapeLayer.path = UIBezierPath(roundedRect: shapeRect, cornerRadius: 5).cgPath

    self.layer.addSublayer(shapeLayer)
}
</code>```

答:
You can use UIBezierPath(ovalIn:) to create a circle path in a square view.

```<code>extension UIView {
    func addDashedCircle() {
        let circleLayer = CAShapeLayer()
        circleLayer.path = UIBezierPath(ovalIn: bounds).cgPath
        circleLayer.lineWidth = 2.0
        circleLayer.strokeColor =  UIColor.red.cgColor//border of circle
        circleLayer.fillColor = UIColor.white.cgColor//inside the circle
        circleLayer.lineJoin = .round
        circleLayer.lineDashPattern = [6,3]
        layer.addSublayer(circleLayer)
    }
}
</code>```

Set view background color .clear and fill color of the layer .white

```<code>class View1: UIViewController {
    @IBOutlet weak var circleView: UIView!
    override func viewDidLoad() {
        super.viewDidLoad()
        circleView.backgroundColor = .clear//outside the circle
        circleView.addDashedCircle()
    }
}
</code>```

Or using UIBezierPath(arcCenter:radius:startAngle:endAngle:clockwise:)

```<code>circleLayer.path = UIBezierPath(arcCenter: CGPoint(x: frame.size.width/2, y: frame.size.height/2),
                            radius: min(frame.size.height,frame.size.width)/2,
                            startAngle: 0,
                            endAngle: .pi * 2,
                            clockwise: true).cgPath
</code>```

Title: circle with dash lines uiview

Body:
I am trying to make a circle with dash lines. I am able to make lines in rectangle but I don't know how to make these in circle. Here is answer I got but it's in Objective-C: UIView Draw Circle with Dotted Line Border

Here is my code which makes a rectangle with dashed lines.

func addDashedBorder() {
    let color = UIColor.red.cgColor

    let shapeLayer:CAShapeLayer = CAShapeLayer()
    let frameSize = self.frame.size
    let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height)

    shapeLayer.bounds = shapeRect
    shapeLayer.position = CGPoint(x: frameSize.width/2, y: frameSize.height/2)
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.strokeColor = color
    shapeLayer.lineWidth = 2
    shapeLayer.lineJoin = CAShapeLayerLineJoin.round
    shapeLayer.lineDashPattern = [6,3]
    shapeLayer.path = UIBezierPath(roundedRect: shapeRect, cornerRadius: 5).cgPath

    self.layer.addSublayer(shapeLayer)
}

Body:
You can use UIBezierPath(ovalIn:) to create a circle path in a square view.

extension UIView {
    func addDashedCircle() {
        let circleLayer = CAShapeLayer()
        circleLayer.path = UIBezierPath(ovalIn: bounds).cgPath
        circleLayer.lineWidth = 2.0
        circleLayer.strokeColor =  UIColor.red.cgColor//border of circle
        circleLayer.fillColor = UIColor.white.cgColor//inside the circle
        circleLayer.lineJoin = .round
        circleLayer.lineDashPattern = [6,3]
        layer.addSublayer(circleLayer)
    }
}

Set view background color .clear and fill color of the layer .white

class View1: UIViewController {
    @IBOutlet weak var circleView: UIView!
    override func viewDidLoad() {
        super.viewDidLoad()
        circleView.backgroundColor = .clear//outside the circle
        circleView.addDashedCircle()
    }
}

Or using UIBezierPath(arcCenter:radius:startAngle:endAngle:clockwise:)

circleLayer.path = UIBezierPath(arcCenter: CGPoint(x: frame.size.width/2, y: frame.size.height/2),
                            radius: min(frame.size.height,frame.size.width)/2,
                            startAngle: 0,
                            endAngle: .pi * 2,
                            clockwise: true).cgPath


问:
Evaluate lazily with spring-data
I would like to have the roles set fetch lazily. Hibernate fetchType.Lazy doesn't work for this cases, where spring data is used. I 've been trying lots of possibilities like Entitygraph but none of them works on this, or I'm using them wrong.
I have the next classes:

A class User:

```<code>@Entity
@JsonRootName(value = "user")
@Table(name = "web_users", schema = "t_dw_comercial")
public class User {

   @Id
   private int userId;

   private String fullName;

    @OneToMany(fetch=FetchType.LAZY)
    @JoinTable(name="web_users_roles",
    joinColumns = {@JoinColumn(name="user_id")},
    inverseJoinColumns = {@JoinColumn(name="role_id")}
    )
    private List<Role> roles;

}
</code>```

A class Role:

```<code>    @Entity
    @JsonRootName(value = "roles")
    @Table(name = "web_roles", schema = "t_dw_comercial")
    public class Role {

       @Id
       private int roleId;

       private String roleName;

    }
</code>```

Service:

```<code> @Service
    public class UserService implements IUserService{

        @Autowired
        UserRepository repository;

        public User findUserByLdapId(String loginName) {

            return repository.findUserByLdapId(loginName);
        }
    }
</code>```

Repository:

```<code>@Repository
public interface UserRepository extends CrudRepository<User, Long>{

    @Query("SELECT u FROM User u where u.ldapId= ?1")
public User findUserByLdapId(String loginName);

}
</code>```

Controller:

```<code>@Controller
@RestController
public class UserController {

    @Autowired
    private IUserService userService;

    @CrossOrigin
    @RequestMapping(value = "/dashboard", params = {"user"}, method = RequestMethod.GET,  produces = "application/json")
    public ResponseEntity<User>  getUser(@RequestParam(value = "user") String ldapId) {

        User user =  userService.findUserByLdapId(ldapId);

        if(user == null)
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);

        return new ResponseEntity<>(user, HttpStatus.OK);

    };
}
</code>```

So a json would looks like:

```<code>{
    "user": {
        "userId": 1,
        "fullName": "Carolina Ponce",
        "roles":[]
    }
}
</code>```

Thanks in advance!

答:
First of all Hibernate and Spring Data are totally different tools designed for different purposes and they work with each other just fine. You can read more about the differences between both here: What Is the Difference Between Hibernate and Spring Data JPA?

Spring Data has nothing to do with how you fetch entity's related collections, Hibernate, as an implementation of JPA, does.

I assume you indeed fetch your collection lazily and that happens during serialization of your entity so the mechanism works as it should.

I suggest you to create some sort of DTO object that you could return from your controller rather than returning an entity. It seems like you don't want to expose user's roles so creating a DTO without roles may be a good idea. Other solution is to instruct Jackson to ommit roles property during serialization using @JsonIgnore annotation.

Title: Evaluate lazily with spring-data

Body:
I would like to have the roles set fetch lazily. Hibernate fetchType.Lazy doesn't work for this cases, where spring data is used. I 've been trying lots of possibilities like Entitygraph but none of them works on this, or I'm using them wrong.
I have the next classes:

A class User:

@Entity
@JsonRootName(value = "user")
@Table(name = "web_users", schema = "t_dw_comercial")
public class User {

   @Id
   private int userId;

   private String fullName;

    @OneToMany(fetch=FetchType.LAZY)
    @JoinTable(name="web_users_roles",
    joinColumns = {@JoinColumn(name="user_id")},
    inverseJoinColumns = {@JoinColumn(name="role_id")}
    )
    private List<Role> roles;

}

A class Role:

    @Entity
    @JsonRootName(value = "roles")
    @Table(name = "web_roles", schema = "t_dw_comercial")
    public class Role {

       @Id
       private int roleId;

       private String roleName;

    }

Service:

 @Service
    public class UserService implements IUserService{

        @Autowired
        UserRepository repository;

        public User findUserByLdapId(String loginName) {

            return repository.findUserByLdapId(loginName);
        }
    }

Repository:

@Repository
public interface UserRepository extends CrudRepository<User, Long>{

    @Query("SELECT u FROM User u where u.ldapId= ?1")
public User findUserByLdapId(String loginName);

}

Controller:

@Controller
@RestController
public class UserController {

    @Autowired
    private IUserService userService;

    @CrossOrigin
    @RequestMapping(value = "/dashboard", params = {"user"}, method = RequestMethod.GET,  produces = "application/json")
    public ResponseEntity<User>  getUser(@RequestParam(value = "user") String ldapId) {

        User user =  userService.findUserByLdapId(ldapId);

        if(user == null)
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);

        return new ResponseEntity<>(user, HttpStatus.OK);

    };
}

So a json would looks like:

{
    "user": {
        "userId": 1,
        "fullName": "Carolina Ponce",
        "roles":[]
    }
}

Thanks in advance!


问:
Slicing a string from end to begining
I am trying to perform palindromic slicing on a string and comparing the forward version of a string vs to the backward version of the string

```<code>string = "nitin"
i = 0
j = len(string)

while i<j:
    if string[i:j] == string[j-1:i-1:-1]:
        print("".join(string[i:j]))
    i +=1
    j-=1
</code>```

but I found the string[end:start-1:-1] method doesn't accept a parameter such as string[4:-1:-1]. I understand why (because index -1 is the same as the start of the string) but I don't know how to overcome this problem using list slicing in combination with my method.

(I mean I could shorten the string each time but I'd rather be able to solve my problem using list slicing if possible) as below:

```<code>string = "nitin"
i = 0
j = len(string)

while i+1<j:
    string=string[i:j]
    if string == string[::-1]:
        print(string)
    i +=1
    j-=1
</code>```

Any ideas?
Thanks

EDIT
I want every possible sub-palindromic sequence
(e.g: nitin would give nitin, iti)

答:
If you want to check is a string palindromic, you can simply use reversed function:

''.join(reversed(string)) == string

You can also use reversed in your loops because it returns an iterator:

Return a reverse iterator. seq must be an object which has a reversed() method or supports the sequence protocol (the len() method and the getitem() method with integer arguments starting at 0).

Title: Slicing a string from end to begining

Body:
I am trying to perform palindromic slicing on a string and comparing the forward version of a string vs to the backward version of the string

string = "nitin"
i = 0
j = len(string)

while i<j:
    if string[i:j] == string[j-1:i-1:-1]:
        print("".join(string[i:j]))
    i +=1
    j-=1

but I found the string[end:start-1:-1] method doesn't accept a parameter such as string[4:-1:-1]. I understand why (because index -1 is the same as the start of the string) but I don't know how to overcome this problem using list slicing in combination with my method.

(I mean I could shorten the string each time but I'd rather be able to solve my problem using list slicing if possible) as below:

string = "nitin"
i = 0
j = len(string)

while i+1<j:
    string=string[i:j]
    if string == string[::-1]:
        print(string)
    i +=1
    j-=1

Any ideas?
Thanks

EDIT
I want every possible sub-palindromic sequence
(e.g: nitin would give nitin, iti)


问:
Now that the Quests API is deprecated, is there still a reason to use the Events API?
I'm having trouble understanding what the point of the Events API is in a Google Play Game Service. I understand that it can be used to create quests, but the quests API is now deprecated. If the only point of events were to create quests, why isn't the events API deprecated now?

Is there a reason to use the Events API? From what I can tell, even if I create evens, users have no ideas what events there are. I would like users to be able to see how many entities they have killed. There are intents for achievements and leaderboards, but none for events. What can I use the events API for?

答: User can still use events to keep track of score or entities defeated. The action to trigger when the event passes a threshold must be handled in code and not in a quest as before.</p>


问:
% change of 2 time period calculations in SQL (GBQ)
Currently have multiple calculations similar to this:

SELECT SUM(A)/COUNT(B) AS CALCULATION
  FROM TABLE
  WHERE YEAR = 2019
```

But I want to find the percent change between Year 2019 and 2018,
like (Calculation1/Calculation2-1) where calc1 is 2019 and calc2 is 2018.

Is the best way a temp table or a subquery? What would be some base code to accomplish analysis?

答:
Below is for BigQuery Standard SQL    </p>

```<code>#standardSQL
SELECT
  (SUM(IF(year = 2019, A, 0)) / COUNT(IF(year = 2019, B, NULL))) /
  (SUM(IF(year = 2018, A, 0)) / COUNT(IF(year = 2018, B, NULL))) - 1 AS CALCULATION
FROM `project.dataset.table`
WHERE year IN (2018, 2019)
</code>```

Body:
Currently have multiple calculations similar to this:

SELECT SUM(A)/COUNT(B) AS CALCULATION
  FROM TABLE
  WHERE YEAR = 2019

But I want to find the percent change between Year 2019 and 2018,
like (Calculation1/Calculation2-1) where calc1 is 2019 and calc2 is 2018.

Is the best way a temp table or a subquery? What would be some base code to accomplish analysis?

Body:
Below is for BigQuery Standard SQL

#standardSQL
SELECT
  (SUM(IF(year = 2019, A, 0)) / COUNT(IF(year = 2019, B, NULL))) /
  (SUM(IF(year = 2018, A, 0)) / COUNT(IF(year = 2018, B, NULL))) - 1 AS CALCULATION
FROM `project.dataset.table`
WHERE year IN (2018, 2019)


问:
Git - head (lowercase) vs HEAD (uppercase)
Did I understand correct and the difference between Git head (lowercase) and Git HEAD (uppercase) is that the former is the end commit and the latter is just the current commit (whether an end-commit or a non-end commit chosen to be the HEAD commit)?

Edit: By "end-commit" I meant to "last commit of a given branch".

答:
It's worth mentioning that when you're on a case-insensitive file system—as is the default on Windows and MacOS, for instance—that trying to open the file abc will open instead the existing file ABC, if it indeed exists, and of course vice versa.

Git stores information about the current commit in a file.  For most cases, that file is named .git/HEAD.  So when Git tries to access information about the current commit, it just opens .git/HEAD and reads it.  (The file usually contains the name of the current branch.  For instance, if you're on your master branch, your .git/HEAD file will read: ref: refs/heads/master.)

For instance, when you run git show with no addition arguments, Git reads .git/HEAD to find out that you're on master, then reads either .git/packed-refs or .git/refs/heads/master to find out which commit master means, and shows that commit.  All of these are implementation details that might change in the future, and some of these do change in modern Git under some circumstances, so it's not wise to depend on this.  But that's how it actually works today.

If you run git show xyz, Git tries to find .git/refs/heads/xyz and, if that doesn't work, tries to find .git/packed-refs to see if there's a line in it about branch xyz.  Git also tries to find .git/refs/tags/xyz, and .git/xyz.  The precise order in which Git tries each of these operations is another implementation detail, but is actually documented—after a fashion; the documentation describes the result rather than the method—in the gitrevisions manual.

If you run git show head, and you're on Windows or MacOS, Git eventually tries to open .git/head.  Since your operating system is willing to treat that as a request to open, instead, .git/HEAD, and since .git/HEAD does actually exist, your OS opens .git/HEAD.  Git reads ref: refs/heads/master (or whatever) out of that file, and shows you the same commit you would have seen if you had run git show HEAD or just plain git show.

Where this goes wrong, in modern Git, is when you're in an added work-tree, one constructed by running git worktree add ....  The HEAD of an added work-tree is not in .git/HEAD.  It's in another subdirectory of .git.  If you run git show HEAD in this added work-tree, Git itself sees the special name HEAD in all-capital-letters and knows to look up the right HEAD, the one for this work-tree.  But if you run git show head, Git doesn't see all-uppercase-HEAD, and goes on to try to open various files, starting with .git/head.  If this succeeds—if it opens .git/HEAD—Git reads the branch for the main work-tree, and not the branch for the work-tree you're actually on in the added work-tree.  So git show HEAD, in the added work-tree, shows the current commit there; but git show head, in this same added work-tree, shows the current commit of the main work-tree, rather than this one.

On Linux, using the usual file systems (which are case-sensitive), git show head just doesn't work at all.  Avoid this bad habit: if you don't like typing HEAD in all uppercase, use @.

ContentLicense: CC BY-SA 3.0


Title: Slicing a string from end to begining

Body:
Why not just combine [::-1] and regular array slicing?

In [2]: a = [1,2,3,4,5,6]
In [4]: a[::-1]
Out[4]: [6, 5, 4, 3, 2, 1]
In [13]: a[::-1][:5]
Out[13]: [6, 5, 4, 3, 2]

So I guess if you apply that to a variable length string it would be

In [14]: f = 'pallapi'

In [15]: f[::-1][1:]
Out[15]: 'pallap'

In [16]: f[::-1][1:] == f[:-1]
Out[16]: True


答:
you can do</p>

```<code>>>> foo = 'abcde'
>>> foo[::-1]
 'edcba'
>>> bar = 'nidin'
>>> bar == bar[::-1]
True
>>> foo == foo[::-1]
False
>>>
</code>```

Title: Slicing a string from end to begining

Body:
you can do

>>> foo = 'abcde'
>>> foo[::-1]
 'edcba'
>>> bar = 'nidin'
>>> bar == bar[::-1]
True
>>> foo == foo[::-1]
False
>>>


问:
How to detect phoenix application started from `mix phx.server`?
I have some workers (children) in Application.start. They shouldn't be started if phoenix app running from task other than mix phx.server (for example with mix ecto.reset).

So, how to know in Application.start that it is mix phx.server running the code?

答: You can use Phoenix.Endpoint.server?(otp_app, endpoint) to check if an endpoint is running its server under the given app. Here are the docs: https://hexdocs.pm/phoenix/Phoenix.Endpoint.html#server?/2


问:
Xamarin.iOS status bar becomes default when app on (Task Manager)/App Switcher
I have an issue on iOS when switching apps. The status bar color changes to default , does anyone knows how to fix this? Seems like it's a bug on iOS itself.

Note: I am not using a Navigation Bar in this case.

So far I only have this service in iOS whenever I want to change the status bar color.

```<code>public void ChangeStatusBarEffects(Color StatusBarColor, bool IsDarkTheme = false)
{
    if (IsDarkTheme)
    {
        Device.BeginInvokeOnMainThread(() =>
        {
            UIApplication.SharedApplication.SetStatusBarStyle(UIStatusBarStyle.LightContent, false);
            UIView statusBar = UIApplication.SharedApplication.ValueForKey(new NSString("statusBar")) as UIView;
            if (statusBar.RespondsToSelector(new ObjCRuntime.Selector("setBackgroundColor:")))
            {
               statusBar.BackgroundColor = StatusBarColor.ToUIColor();
            }
        });
    }
    else
    {
        Device.BeginInvokeOnMainThread(() =>
        {
            UIApplication.SharedApplication.SetStatusBarStyle(UIStatusBarStyle.BlackOpaque, false);
            UIView statusBar = UIApplication.SharedApplication.ValueForKey(new NSString("statusBar")) as UIView;
            if (statusBar.RespondsToSelector(new ObjCRuntime.Selector("setBackgroundColor:")))
            {
                statusBar.BackgroundColor = StatusBarColor.ToUIColor();
            }
        });
    }
}
</code>```

答:
I have found a way around this.

I have added a view with the colour that I want to appear when the app is the task manager view. This view is in between the main view and the safe area.

This view will be underneath the system bar, however when the app goes to the task manager (or app switch screen) then the view becomes visible.

Might have a better way around this but this is the only way I got this to work!

Body:
I have an issue on iOS when switching apps. The status bar color changes to default , does anyone knows how to fix this? Seems like it's a bug on iOS itself.

Note: I am not using a Navigation Bar in this case.

So far I only have this service in iOS whenever I want to change the status bar color.

public void ChangeStatusBarEffects(Color StatusBarColor, bool IsDarkTheme = false)
{
    if (IsDarkTheme)
    {
        Device.BeginInvokeOnMainThread(() =>
        {
            UIApplication.SharedApplication.SetStatusBarStyle(UIStatusBarStyle.LightContent, false);
            UIView statusBar = UIApplication.SharedApplication.ValueForKey(new NSString("statusBar")) as UIView;
            if (statusBar.RespondsToSelector(new ObjCRuntime.Selector("setBackgroundColor:")))
            {
               statusBar.BackgroundColor = StatusBarColor.ToUIColor();
            }
        });
    }
    else
    {
        Device.BeginInvokeOnMainThread(() =>
        {
            UIApplication.SharedApplication.SetStatusBarStyle(UIStatusBarStyle.BlackOpaque, false);
            UIView statusBar = UIApplication.SharedApplication.ValueForKey(new NSString("statusBar")) as UIView;
            if (statusBar.RespondsToSelector(new ObjCRuntime.Selector("setBackgroundColor:")))
            {
                statusBar.BackgroundColor = StatusBarColor.ToUIColor();
            }
        });
    }
}


问:
java.lang.Class java.lang.Object.getClass()' on a null object reference
I try to use viewPager with the tablayout but when i set adapter with the view pager i'm getting error "java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass() on a null object reference" i don't understand why this error is show.

view pager set Adapter:

```<code>viewPager= (ViewPager) findViewById(R.id.viewPager_id);
  viewPager.setAdapter(newViewPagerAdapterUseThisClass(getSupportFragmentManager(),14));
</code>```

Adapter clss:

```<code>class ViewPagerAdapterUseThisClass extends FragmentPagerAdapter {
    int countTabItem;
     ViewPagerAdapterUseThisClass(FragmentManager fm,int contTabItem) {
        super(fm);

        this.countTabItem=contTabItem;
    }

    @Override
    public Fragment getItem(int position) {

        if(position==0){
            EnthusamTab enthusamTab=new EnthusamTab();
            return enthusamTab;
        }

        return null;
    }

    @Override
    public int getCount() {
        return countTabItem;
    }
}
</code>```

view pager xml file:

```<code> <android.support.v4.view.ViewPager
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@id/tab_layout_id"
            android:id="@+id/viewPager_id"/>
</code>```

Error log:

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
                                                                                at android.support.v4.app.BackStackRecord.doAddOp(BackStackRecord.java:380)
                                                                                at android.support.v4.app.BackStackRecord.add(BackStackRecord.java:375)
                                                                                at android.support.v4.app.FragmentPagerAdapter.instantiateItem(FragmentPagerAdapter.java:103)
                                                                                at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:1034)
                                                                                at android.support.v4.view.ViewPager.populate(ViewPager.java:1248)
                                                                                at android.support.v4.view.ViewPager.populate(ViewPager.java:1116)
                                                                                at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1642)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
                                                                                at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:1081)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                                at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                                                at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
                                                                                at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
                                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                                                at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
                                                                                at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
                                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                                at com.android.internal.policy.DecorView.onMeasure(DecorView.java:689)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2275)
                                                                                at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1366)
                                                                                at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1619)
                                                                                at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254)
                                                                                at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6343)
                                                                                at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
                                                                                at android.view.Choreographer.doCallbacks(Choreographer.java:686)
                                                                                at android.view.Choreographer.doFrame(Choreographer.java:621)
                                                                                at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6126)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

答:
I got this error because I forget to set break command. Check your break operators at first.

Now I have this code:

```<code>@Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return new FollowersFragment();
            case 1:
                return new PostsFragment();
            case 2:
                return new ReactsFragment();
            case 3:
                return new StoriesFragment();
            case 4:
                return new FollowersFragment();
            case 5:
                return new FollowersFragment();
            case 6:
                return new FollowersFragment();
        }
        return null;
    }
</code>```

Body:
I try to use viewPager with the tablayout but when i set adapter with the view pager i'm getting error "java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass() on a null object reference" i don't understand why this error is show.

view pager set Adapter:

viewPager= (ViewPager) findViewById(R.id.viewPager_id);
  viewPager.setAdapter(newViewPagerAdapterUseThisClass(getSupportFragmentManager(),14));

Adapter clss:

class ViewPagerAdapterUseThisClass extends FragmentPagerAdapter {
    int countTabItem;
     ViewPagerAdapterUseThisClass(FragmentManager fm,int contTabItem) {
        super(fm);

        this.countTabItem=contTabItem;
    }

    @Override
    public Fragment getItem(int position) {

        if(position==0){
            EnthusamTab enthusamTab=new EnthusamTab();
            return enthusamTab;
        }

        return null;
    }

    @Override
    public int getCount() {
        return countTabItem;
    }
}

view pager xml file:

 <android.support.v4.view.ViewPager
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@id/tab_layout_id"
            android:id="@+id/viewPager_id"/>

Error log:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
                                                                                at android.support.v4.app.BackStackRecord.doAddOp(BackStackRecord.java:380)
                                                                                at android.support.v4.app.BackStackRecord.add(BackStackRecord.java:375)
                                                                                at android.support.v4.app.FragmentPagerAdapter.instantiateItem(FragmentPagerAdapter.java:103)
                                                                                at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:1034)
                                                                                at android.support.v4.view.ViewPager.populate(ViewPager.java:1248)
                                                                                at android.support.v4.view.ViewPager.populate(ViewPager.java:1116)
                                                                                at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1642)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
                                                                                at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:1081)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                                at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                                                at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
                                                                                at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
                                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                                                at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
                                                                                at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
                                                                                at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
                                                                                at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                                                                                at com.android.internal.policy.DecorView.onMeasure(DecorView.java:689)
                                                                                at android.view.View.measure(View.java:19861)
                                                                                at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2275)
                                                                                at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1366)
                                                                                at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1619)
                                                                                at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1254)
                                                                                at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6343)
                                                                                at android.view.Choreographer$CallbackRecord.run(Choreographer.java:874)
                                                                                at android.view.Choreographer.doCallbacks(Choreographer.java:686)
                                                                                at android.view.Choreographer.doFrame(Choreographer.java:621)
                                                                                at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:860)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6126)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Body:
I got this error because I forget to set break command. Check your break operators at first.

Now I have this code:

@Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return new FollowersFragment();
            case 1:
                return new PostsFragment();
            case 2:
                return new ReactsFragment();
            case 3:
                return new StoriesFragment();
            case 4:
                return new FollowersFragment();
            case 5:
                return new FollowersFragment();
            case 6:
                return new FollowersFragment();
        }
        return null;
    }


问:
PHP/MySQL - Multiple Selects For Query
I'm writing an simple Musicians database that has a search function that will e-mail details of musicians to people when they search for a specific instrument in that database. I have people who play more then one instrument therefore I have 5 tables, instrument, instrument2, instrument3, instrument4, instrument5.

I have a MYSQL query on my e-mail function but I cannot get it to search more then one table.

Here is the code:

```<code>$query = "SELECT * FROM instruments WHERE (instrument, instrument2, instrument3, instrument4, instrument5) = '$search'";
</code>```

Am I being stupid with my syntax or am I going about the wrong way with this.

Many thanks.

答:
http://dev.mysql.com/doc/refman/5.0/en/multiple-tables.html

You should just have one table with fields instrument and email. It seems that is all you want.

Title: PHP/MySQL - Multiple Selects For Query

Body:
I'm writing an simple Musicians database that has a search function that will e-mail details of musicians to people when they search for a specific instrument in that database. I have people who play more then one instrument therefore I have 5 tables, instrument, instrument2, instrument3, instrument4, instrument5.

I have a MYSQL query on my e-mail function but I cannot get it to search more then one table.

Here is the code:

$query = "SELECT * FROM instruments WHERE (instrument, instrument2, instrument3, instrument4, instrument5) = '$search'";

Am I being stupid with my syntax or am I going about the wrong way with this.

Many thanks.


问:
How to remove the spacing between rows in a GridLayout composite?
these are just sample codes. I created a GridLayout composite and removed the margins. But there are still spaces in between the rows.

```<code>Composite composite = new Composite(shell, SWT.NONE);
GridLayout gl_composite = new GridLayout(1, false);
gl_composite.marginWidth = 0;
gl_composite.marginHeight = 0;
composite.setLayout(gl_composite);

Composite composite_1 = new Composite(composite, SWT.BORDER);
GridData gd_composite_1 = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
gd_composite_1.heightHint = 52;
gd_composite_1.widthHint = 802;
composite_1.setLayoutData(gd_composite_1);
composite_1.setLayout(new GridLayout(1, false));

Composite composite_2 = new Composite(composite, SWT.BORDER);
GridData gd_composite_2 = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
gd_composite_2.widthHint = 803;
composite_2.setLayoutData(gd_composite_2);
</code>```

I need the rows to not have any spaces in between. The composites are bordered since I need to have a line below . I'm new to SWT so..

Thanks!!

答:
The verticalSpacing field of GridLayout sets the spacing between rows, so:

gl_composite.verticalSpacing = 0;
```

Use horizontalSpacing for spacing between columns.

The default for both values is 5

Body:
these are just sample codes. I created a GridLayout composite and removed the margins. But there are still spaces in between the rows.

Composite composite = new Composite(shell, SWT.NONE);
GridLayout gl_composite = new GridLayout(1, false);
gl_composite.marginWidth = 0;
gl_composite.marginHeight = 0;
composite.setLayout(gl_composite);

Composite composite_1 = new Composite(composite, SWT.BORDER);
GridData gd_composite_1 = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
gd_composite_1.heightHint = 52;
gd_composite_1.widthHint = 802;
composite_1.setLayoutData(gd_composite_1);
composite_1.setLayout(new GridLayout(1, false));

Composite composite_2 = new Composite(composite, SWT.BORDER);
GridData gd_composite_2 = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
gd_composite_2.widthHint = 803;
composite_2.setLayoutData(gd_composite_2);

I need the rows to not have any spaces in between. The composites are bordered since I need to have a line below . I'm new to SWT so..

Thanks!!

Body:
The verticalSpacing field of GridLayout sets the spacing between rows, so:

gl_composite.verticalSpacing = 0;

Use horizontalSpacing for spacing between columns.

The default for both values is 5


问:
std::find_if map to object
Should I use example 1 or example 2 for map pointer from find_if to object
Which one is the best?</p>

```<code>struct test {
 INT id
}

std::vector<std::shared_ptr<test>> vec;

int ID = 75;

auto obj = std::find_if(vec.begin(), vec.end(), [&ID](std::shared_ptr<test>& r){
 return r->id == ID;
});

if ( obj != vec.end() ) {
 // example 1
 std::shared_ptr<test> example1 = (*obj);

 // example 2 by reference
 std::shared_ptr<test>& example2 = (*obj);
}
</code>```

答: If you will not modify vec between the call to find_if and the usage of the shared_ptr, then take a reference to the element as in example2 to avoid unnecessary adjustments to the reference count. If you cannot be sure that this is the case, then copy the shared_ptr by value, as in example.

Title: std::find_if map to object

Body:
Should I use example 1 or example 2 for map pointer from find_if to object
Which one is the best?

struct test {
 INT id
}

std::vector<std::shared_ptr<test>> vec;

int ID = 75;

auto obj = std::find_if(vec.begin(), vec.end(), [&ID](std::shared_ptr<test>& r){
 return r->id == ID;
});

if ( obj != vec.end() ) {
 // example 1
 std::shared_ptr<test> example1 = (*obj);

 // example 2 by reference
 std::shared_ptr<test>& example2 = (*obj);
}


问:
Is there a concise way to check if an int variable is equal to a series of ints? | C#
Rather than something like this:

```<code>switch (id) {
case 2:
case 5:
case 11:
case 15:
...
}
</code>```

Is there a concise way to check if an int variable is equal to any one of a series of integers? Maybe something like if (id == {2|5|11|15}) ...?

答:
```<code>if((new List<int> { 2, 5, 11, 15}).Contains(id))
</code>```

But you probably don't want to create a new List instance every time, so it would be better to create it in the constructor of your class.

Body:
Rather than something like this:

switch (id) {
case 2:
case 5:
case 11:
case 15:
...
}

Is there a concise way to check if an int variable is equal to any one of a series of integers? Maybe something like if (id == {2|5|11|15}) ...?

Body:
if((new List<int> { 2, 5, 11, 15}).Contains(id))

But you probably don't want to create a new List instance every time, so it would be better to create it in the constructor of your class.


问:
Code Execution Directly in a React Function Component, When Multiple States Causes Multiple Re-Renders
I have component that uses both useState() and other custom hooks multiple times.

I want to act based on these state values. I could do that directly in the function component's body:

```<code>const MyComponent = () => {
  const [someState, setSomeState] = useState(false);
  const [otherState, setOtherState] = useState(false);
  const customHookValue = useCustomHook();

  if (someState) foo();
  const foo = () => setOtherState(!otherState);

  if (customHookValue > 10) bar();
  const bar = () => setSomeState(somestate > customHookValue);
}
</code>```

However, every time someState changes (and a re-render happens) the second conditional also runs, causing bar() to run if the conditional passes. This feels unnatural. Logically, bar() should only run when customHookValue changes, as someState only changes if customHookValue has changed since last render.

In summary, a re-render caused by a change to someState should not cause a bunch of unrelated state setting functions to run again. Even though re-running them causes no change in the outcome of the program, it is not logically right. They only need to re-run when their corresponding conditional changes. It could effect performance.

This must be a common challenge in React. I am quite new to it, so I do not know what the approach to solve this would be.

Questions

How would I solve the above in the recommended manner?

Would I have to wrap every conditional in a useEffect or a useMemo?

EDIT:

Updated the second conditional, to make my question clearer (it should depend on customHook).

CLARIFICATION:

As it might not have been clear, my issue is as follows. When state changes, a re-render occurs. This causes all functions in the component's body to re-run. Now, if we have many useState in a component, and only one changes, a bunch of potentially unrelated state-changing and potentially expensive functions I have defined in the components body will run. These state-changing functions would only have to run if the state values they are trying to set has changed. If the values they are setting has not changed, it is unnecessary for them to run again. But, the re-render reruns all functions in the component's body regardless.

答:
It looks like (as others have suggested) you want useEffect:

```<code>useEffect(() => {
  if (someState) {
    setOtherState(!otherState)
  }
}, [someState, otherState])
useEffect(() => {
  if (customHookValue > 10) {
    setSomeState(someState > customHookValue)
  }
}, [customHookValue])
</code>```

Since you only want the setSomeState to run if customHookValue changes, make it the only item in the dependencies array passed to useEffect.

The exhaustive-deps eslint-plugin-react-hooks will complain about the second useEffect, since the function depends on the value of someState, even though someState will only potentially change if customHookValue changes. I also wouldn't worry about things potentially affecting performance until they do. I don't know a ton about the internals of React, but it does some things under the hood to avoid re-renders it doesn't need to do, and can do multiple renders before an actual update is painted.

Body:
I have component that uses both useState() and other custom hooks multiple times.

I want to act based on these state values. I could do that directly in the function component's body:

const MyComponent = () => {
  const [someState, setSomeState] = useState(false);
  const [otherState, setOtherState] = useState(false);
  const customHookValue = useCustomHook();

  if (someState) foo();
  const foo = () => setOtherState(!otherState);

  if (customHookValue > 10) bar();
  const bar = () => setSomeState(somestate > customHookValue);
}

However, every time someState changes (and a re-render happens) the second conditional also runs, causing bar() to run if the conditional passes. This feels unnatural. Logically, bar() should only run when customHookValue changes, as someState only changes if customHookValue has changed since last render.

In summary, a re-render caused by a change to someState should not cause a bunch of unrelated state setting functions to run again. Even though re-running them causes no change in the outcome of the program, it is not logically right. They only need to re-run when their corresponding conditional changes. It could effect performance.

This must be a common challenge in React. I am quite new to it, so I do not know what the approach to solve this would be.

Questions

How would I solve the above in the recommended manner?

Would I have to wrap every conditional in a useEffect or a useMemo?

EDIT:

Updated the second conditional, to make my question clearer (it should depend on customHook).

CLARIFICATION:

As it might not have been clear, my issue is as follows. When state changes, a re-render occurs. This causes all functions in the component's body to re-run. Now, if we have many useState in a component, and only one changes, a bunch of potentially unrelated state-changing and potentially expensive functions I have defined in the components body will run. These state-changing functions would only have to run if the state values they are trying to set has changed. If the values they are setting has not changed, it is unnecessary for them to run again. But, the re-render reruns all functions in the component's body regardless.

Body:
It looks like (as others have suggested) you want useEffect:

useEffect(() => {
  if (someState) {
    setOtherState(!otherState)
  }
}, [someState, otherState])
useEffect(() => {
  if (customHookValue > 10) {
    setSomeState(someState > customHookValue)
  }
}, [customHookValue])

Since you only want the setSomeState to run if customHookValue changes, make it the only item in the dependencies array passed to useEffect.

The exhaustive-deps eslint-plugin-react-hooks will complain about the second useEffect, since the function depends on the value of someState, even though someState will only potentially change if customHookValue changes. I also wouldn't worry about things potentially affecting performance until they do. I don't know a ton about the internals of React, but it does some things under the hood to avoid re-renders it doesn't need to do, and can do multiple renders before an actual update is painted.


问:
IotEdge - Error calling Create module image-classifier-service
I'm very new to Azure IoT Edge and I'm trying to deploy to my Raspberry PI : Image Recognition with Azure IoT Edge and Cognitive Services
but after Build & Push IoT Edge Solution and Deploy it to Single Device ID I see none of those 2 modules listed in Docker PS -a & Iotedge list
And when try to check it on EdgeAgent Logs there's error message and it seems EdgeAgent get error while creating those Modules (camera-capture and image-classifier-service)

I've tried :
1. Re-build it from fresh folder package
2. Pull the image manually from Azure Portal and run the image manually by script

I'm stuck on this for days.

in deployment.arm32v7.json for those modules I define the Image with registered registry url :

```<code>"modules": {
          "camera-capture": {
            "version": "1.0",
            "type": "docker",
            "status": "running",
            "restartPolicy": "always",
            "settings": {
              "image": "zzzz.azurecr.io/camera-capture-opencv:1.1.12-arm32v7",
              "createOptions": "{\"Env\":[\"Video=0\",\"azureSpeechServicesKey=2f57f2d9f1074faaa0e9484e1f1c08c1\",\"AiEndpoint=http://image-classifier-service:80/image\"],\"HostConfig\":{\"PortBindings\":{\"5678/tcp\":[{\"HostPort\":\"5678\"}]},\"Devices\":[{\"PathOnHost\":\"/dev/video0\",\"PathInContainer\":\"/dev/video0\",\"CgroupPermissions\":\"mrw\"},{\"PathOnHost\":\"/dev/snd\",\"PathInContainer\":\"/dev/snd\",\"CgroupPermissions\":\"mrw\"}]}}"
            }
          },
          "image-classifier-service": {
            "version": "1.0",
            "type": "docker",
            "status": "running",
            "restartPolicy": "always",
            "settings": {
              "image": "zzzz.azurecr.io/image-classifier-service:1.1.5-arm32v7",
              "createOptions": "{\"HostConfig\":{\"Binds\":[\"/home/pi/images:/images\"],\"PortBindings\":{\"8000/tcp\":[{\"HostPort\":\"80\"}],\"5679/tcp\":[{\"HostPort\":\"5679\"}]}}}"
            }
</code>```

Error message from EdgeAgent Logs :

```<code>(Inner Exception #0) Microsoft.Azure.Devices.Edge.Agent.Edgelet.EdgeletCommunicationException- Message:Error calling Create module
image-classifier-service: Could not create module image-classifier-service
        caused by: Could not pull image zzzzz.azurecr.io/image-classifier-service:1.1.5-arm32v7
        caused by: Get https://zzzzz.azurecr.io/v2/image-classifier-service/manifests/1.1.5-arm32v7: unauthorized: authentication required
</code>```

When trying to run the pulled image by script :

```<code>sudo docker run --rm --name testName -it zzzz.azurecr.io/camera-capture-opencv:1.1.12-arm32v7
</code>```

None

I get this error :

```<code>Camera Capture Azure IoT Edge Module. Press Ctrl-C to exit.
Error: Time:Fri May 24 10:01:09 2019 File:/usr/sdk/src/c/iothub_client/src/iothub_client_core_ll.c Func:retrieve_edge_environment_variabes Line:191 Environment IOTEDGE_AUTHSCHEME not set
Error: Time:Fri May 24 10:01:09 2019 File:/usr/sdk/src/c/iothub_client/src/iothub_client_core_ll.c Func:IoTHubClientCore_LL_CreateFromEnvironment Line:1572 retrieve_edge_environment_variabes failed
Error: Time:Fri May 24 10:01:09 2019 File:/usr/sdk/src/c/iothub_client/src/iothub_client_core.c Func:create_iothub_instance Line:941 Failure creating iothub handle
Unexpected error IoTHubClient.create_from_environment, IoTHubClientResult.ERROR from IoTHub
</code>```

答:
When you pulled the image directly with docker run, it pulled but then failed to run outside of the edge runtime, which is expected. But when the edge agent tried to pull it, it failed because it was not authorized. No credentials were supplied to the runtime, so it attempted to access the registry anonymously.

Make sure that you add your container registry credentials to the deployment so that edge runtime can pull images. The deployment should contain something like the following in the runtime settings:

```<code>"MyRegistry" :{
  "username": "<username>",
  "password": "<password>",
  "address": "<registry-name>.azurecr.io"
}
</code>```

As @silent pointed out in the comments, the documentation is here, including an example deployment that includes container registry credentials.

Body:
I'm very new to Azure IoT Edge and I'm trying to deploy to my Raspberry PI : Image Recognition with Azure IoT Edge and Cognitive Services
but after Build & Push IoT Edge Solution and Deploy it to Single Device ID I see none of those 2 modules listed in Docker PS -a & Iotedge list
And when try to check it on EdgeAgent Logs there's error message and it seems EdgeAgent get error while creating those Modules (camera-capture and image-classifier-service)

I've tried :
1. Re-build it from fresh folder package
2. Pull the image manually from Azure Portal and run the image manually by script

I'm stuck on this for days.

in deployment.arm32v7.json for those modules I define the Image with registered registry url :

"modules": {
          "camera-capture": {
            "version": "1.0",
            "type": "docker",
            "status": "running",
            "restartPolicy": "always",
            "settings": {
              "image": "zzzz.azurecr.io/camera-capture-opencv:1.1.12-arm32v7",
              "createOptions": "{\"Env\":[\"Video=0\",\"azureSpeechServicesKey=2f57f2d9f1074faaa0e9484e1f1c08c1\",\"AiEndpoint=http://image-classifier-service:80/image\"],\"HostConfig\":{\"PortBindings\":{\"5678/tcp\":[{\"HostPort\":\"5678\"}]},\"Devices\":[{\"PathOnHost\":\"/dev/video0\",\"PathInContainer\":\"/dev/video0\",\"CgroupPermissions\":\"mrw\"},{\"PathOnHost\":\"/dev/snd\",\"PathInContainer\":\"/dev/snd\",\"CgroupPermissions\":\"mrw\"}]}}"
            }
          },
          "image-classifier-service": {
            "version": "1.0",
            "type": "docker",
            "status": "running",
            "restartPolicy": "always",
            "settings": {
              "image": "zzzz.azurecr.io/image-classifier-service:1.1.5-arm32v7",
              "createOptions": "{\"HostConfig\":{\"Binds\":[\"/home/pi/images:/images\"],\"PortBindings\":{\"8000/tcp\":[{\"HostPort\":\"80\"}],\"5679/tcp\":[{\"HostPort\":\"5679\"}]}}}"
            }

Error message from EdgeAgent Logs :

(Inner Exception #0) Microsoft.Azure.Devices.Edge.Agent.Edgelet.EdgeletCommunicationException- Message:Error calling Create module
image-classifier-service: Could not create module image-classifier-service
        caused by: Could not pull image zzzzz.azurecr.io/image-classifier-service:1.1.5-arm32v7
        caused by: Get https://zzzzz.azurecr.io/v2/image-classifier-service/manifests/1.1.5-arm32v7: unauthorized: authentication required

When trying to run the pulled image by script :

sudo docker run --rm --name testName -it zzzz.azurecr.io/camera-capture-opencv:1.1.12-arm32v7

None

I get this error :

Camera Capture Azure IoT Edge Module. Press Ctrl-C to exit.
Error: Time:Fri May 24 10:01:09 2019 File:/usr/sdk/src/c/iothub_client/src/iothub_client_core_ll.c Func:retrieve_edge_environment_variabes Line:191 Environment IOTEDGE_AUTHSCHEME not set
Error: Time:Fri May 24 10:01:09 2019 File:/usr/sdk/src/c/iothub_client/src/iothub_client_core_ll.c Func:IoTHubClientCore_LL_CreateFromEnvironment Line:1572 retrieve_edge_environment_variabes failed
Error: Time:Fri May 24 10:01:09 2019 File:/usr/sdk/src/c/iothub_client/src/iothub_client_core.c Func:create_iothub_instance Line:941 Failure creating iothub handle
Unexpected error IoTHubClient.create_from_environment, IoTHubClientResult.ERROR from IoTHub

Body:
When you pulled the image directly with docker run, it pulled but then failed to run outside of the edge runtime, which is expected. But when the edge agent tried to pull it, it failed because it was not authorized. No credentials were supplied to the runtime, so it attempted to access the registry anonymously.

Make sure that you add your container registry credentials to the deployment so that edge runtime can pull images. The deployment should contain something like the following in the runtime settings:

"MyRegistry" :{
  "username": "<username>",
  "password": "<password>",
  "address": "<registry-name>.azurecr.io"
}

As @silent pointed out in the comments, the documentation is here, including an example deployment that includes container registry credentials.