问:
Does forkjoin return results in a particular order?
My app will make multiple parallel http call. Its based on a switch-fall though logic, so the number of query will vary (1, 2, or 3 calls). Is there a way for me to know which call gets returned first? I.e either assign a key or does it return in an ordered way based on the http request on the list?

Either way works for me. I just need to find a way to match the right result with the right call.

答:
Yes it returns the results in the same order that you make requests in an array

example,

```<code>const bothrequests= Observable.combineLatest(
  this.http.get('https://testdb1.com/.json').map((res: Response) => res.json()),
  this.http.get('https://testdb2.com/.json').map((res: Response) => res.json())
)
bothrequests.subscribe(latestValues => {

});
</code>```

Body:
Yes it returns the results in the same order that you make requests in an array

example,

const bothrequests= Observable.combineLatest(
  this.http.get('https://testdb1.com/.json').map((res: Response) => res.json()),
  this.http.get('https://testdb2.com/.json').map((res: Response) => res.json())
)
bothrequests.subscribe(latestValues => {

});


来源: stackexchange

问:
USQL msbuild - composite build output
I'm following the instructions on this link https://blogs.msdn.microsoft.com/azuredatalake/2017/10/24/continuous-integration-made-easy-with-msbuild-support-for-u-sql-preview/

It states that

After running MSBuild from command line or as a VSTS task, all scripts in the U-SQL project are built and output to a single file at "Build output path/script name/script name.usql". You can copy this composite U-SQL script to the release folder for further deployment.

Within my Visual Studio project (.usqlproj) I have multiple .usql scripts

CreateDatabase.usql

CreateTable.usql

CreateTvf.usql

when I do clean and msbuild and then check bin\debug folder, all I get is just CreateDatabase.usql and within that there is only CREATE DATBASE statement. As per the blog I would have thought all the 3 usql scripts would have merged into 1 composite usql script. The msbuild command I executed from command prompt on my machine

```<code>msbuild TheProject\TheProject.usqlproj /t:Clean /t:Rebuild /property:USQLSDKPath=C:\TheProject\src\packages\Microsoft.Azure.DataLake.USQL.SDK.1.3.1019-preview\build\runtime,USQLTargetType=Merge
</code>```

I'm using Visual Studio 2017 15.4.3 and Azure Data Lake tools 2.3.0000.1

What am I doing wrong?

答:
The command msbuild TheProject\TheProject.usqlproj /t:Clean /t:Rebuild /property:USQLSDKPath=C:\TheProject\src\packages\Microsoft.Azure.DataLake.USQL.SDK.1.3.1019-preview\build\runtime,USQLTargetType=Merge actually build the script you selected.

If you are selecting CreateDatabase.usql in VS, it will build the script CreateDatabase.usql in command line.

As below example, since it's selecting test.usql, when execute msbuild command, it will only build test.usql. As the way clicking Build button for the USQL project.

If you want to build all the scripts under the USQL project, you should select Build All Scripts button in VS.

ContentLicense: CC BY-SA 3.0

Title: USQL msbuild - composite build output

Body:
I'm following the instructions on this link https://blogs.msdn.microsoft.com/azuredatalake/2017/10/24/continuous-integration-made-easy-with-msbuild-support-for-u-sql-preview/

It states that

After running MSBuild from command line or as a VSTS task, all scripts in the U-SQL project are built and output to a single file at "Build output path/script name/script name.usql". You can copy this composite U-SQL script to the release folder for further deployment.

Within my Visual Studio project (.usqlproj) I have multiple .usql scripts

CreateDatabase.usql

CreateTable.usql

CreateTvf.usql

when I do clean and msbuild and then check bin\debug folder, all I get is just CreateDatabase.usql and within that there is only CREATE DATBASE statement. As per the blog I would have thought all the 3 usql scripts would have merged into 1 composite usql script. The msbuild command I executed from command prompt on my machine

msbuild TheProject\TheProject.usqlproj /t:Clean /t:Rebuild /property:USQLSDKPath=C:\TheProject\src\packages\Microsoft.Azure.DataLake.USQL.SDK.1.3.1019-preview\build\runtime,USQLTargetType=Merge

I'm using Visual Studio 2017 15.4.3 and Azure Data Lake tools 2.3.0000.1

What am I doing wrong?


问:
ASP.net MVC Controller Architecture
This might seem a slightly subjective question however I am looking for what is deemed best practice in the MVC World.  I am fine with the idea of separate controllers for separate logical areas and in the whole this makes sense however how should standard pages be handled?  For example, I have an about us page, a careers page, etc.  Some of these pages will have their own functionality and where that is the case they will have their own controller and views.  The rest of these pages will just be text - do these then warrant their own controller?  Or should they be routed to a SimplePageController which returns a view based on the URL?</p>

答: I think you can have a controller for static pages. The Controller will manage the shares, which in the case of these pages would only GET actions. If you see, when you create an MVC application in Visual 2010, that's created with a HomeController, which has the action for static pages such as home and about.</p>

ContentLicense: CC BY-SA 2.5

Title: ASP.net MVC Controller Architecture


答:
I think you need change columns=['index'] to columns='datetime_start' first and then use ffill (fillna with method='ffill'):

```<code>table = (pd.pivot_table(df,
                        values='value',
                        index='id',
                        columns='datetime_start',
                        aggfunc=np.sum)
           .ffill(axis=1, limit=1))
</code>```

EDIT with less data:

```<code>data = [
{ 'datetime_start' : "2017-03-15 14:31:20.507", "id" : "usr_21",  "value": "-1.286452"},
{ 'datetime_start' : "2017-03-16 15:17:45.550", "id" : "usr_15",  "value": "-2.349203"},
{ 'datetime_start' : "2017-03-17 14:20:47.437", "id" : "usr_13",  "value": "-2.397038"},
{ 'datetime_start' : "2017-03-19 09:43:47.262", "id" : "usr_12",  "value": "-1.250512"},
]

df = pd.DataFrame(data)
df['datetime_start'] = pd.to_datetime(df['datetime_start'])

table = (pd.pivot_table(df,
                        values='value',
                        index='id',
                        columns='datetime_start',
                        aggfunc=np.sum)
         )

print (table)
datetime_start 2017-03-15 14:31:20.507 2017-03-16 15:17:45.550  \
id
usr_12                            None                    None
usr_13                            None                    None
usr_15                            None               -2.349203
usr_21                       -1.286452                    None

datetime_start 2017-03-17 14:20:47.437 2017-03-19 09:43:47.262
id
usr_12                            None               -1.250512
usr_13                       -2.397038                    None
usr_15                            None                    None
usr_21                            None                    None
</code>```

Replace only one value None if previous value is not None - then add parameter limit:

```<code>table1 = (pd.pivot_table(df,
                        values='value',
                        index='id',
                        columns='datetime_start',
                        aggfunc=np.sum)
           .ffill(axis=1, limit=1)
           )

print (table1)
datetime_start 2017-03-15 14:31:20.507 2017-03-16 15:17:45.550  \
id
usr_12                            None                    None
usr_13                            None                    None
usr_15                            None               -2.349203
usr_21                       -1.286452               -1.286452

datetime_start 2017-03-17 14:20:47.437 2017-03-19 09:43:47.262
id
usr_12                            None               -1.250512
usr_13                       -2.397038               -2.397038
usr_15                       -2.349203                    None
usr_21                            None                    None
</code>```

Replace all NaNs by previous non NaNs, last replace all NaNs by 0, remove limit and add fillna(0):

```<code>table2 = (pd.pivot_table(df,
                        values='value',
                        index='id',
                        columns='datetime_start',
                        aggfunc=np.sum)
            .ffill(axis=1)
            .fillna(0)
           )

print (table2)
datetime_start 2017-03-15 14:31:20.507 2017-03-16 15:17:45.550  \
id
usr_12                               0                       0
usr_13                               0                       0
usr_15                               0               -2.349203
usr_21                       -1.286452               -1.286452

datetime_start 2017-03-17 14:20:47.437 2017-03-19 09:43:47.262
id
usr_12                               0               -1.250512
usr_13                       -2.397038               -2.397038
usr_15                       -2.349203               -2.349203
usr_21                       -1.286452               -1.286452
</code>```

Title: Pandas pivot manipulation replace None with last row value

Body:
I have a dataframe with idex as datetime, different ids and different values
I have a df as :

data = [
{ 'datetime_start' : "2017-03-15 14:31:20.507", "id" : "usr_21",  "value": "-1.286452"},
{ 'datetime_start' : "2017-03-16 15:17:45.550", "id" : "usr_15",  "value": "-2.349203"},
{ 'datetime_start' : "2017-03-17 14:20:47.437", "id" : "usr_13",  "value": "-2.397038"},
{ 'datetime_start' : "2017-03-19 09:43:47.262", "id" : "usr_12",  "value": "-1.250512"},
{ 'datetime_start' : "2017-03-19 15:18:47.941", "id" : "usr_21",  "value": "-0.681998"},
{ 'datetime_start' : "2017-03-19 20:03:52.905", "id" : "usr_15",   "value": "-1.018452"},
{ 'datetime_start' : "2017-03-22 13:40:48.178", "id" : "usr_21",  "value": "-1.531373"},
{ 'datetime_start' : "2017-03-22 19:54:48.320", "id" : "usr_18",  "value": "-3.789466"},
{ 'datetime_start' : "2017-03-23 13:53:48.789", "id" : "usr_21",  "value": "-1.288360"},
{ 'datetime_start' : "2017-03-24 15:54:48.649", "id" : "usr_21",  "value": "0.213171"},
{ 'datetime_start' : "2017-03-25 17:53:48.422", "id" : "usr_13",  "value": "-2.020710"},
{ 'datetime_start' : "2017-03-26 06:10:48.197", "id" : "usr_12",  "value": "-1.484709"},
{ 'datetime_start' : "2017-03-15 14:31:20.507", "id" : "usr_21",  "value": "-1.286452"},
{ 'datetime_start' : "2017-03-16 15:18:45.550", "id" : "usr_18",  "value": "-2.349203"},
{ 'datetime_start' : "2017-03-17 14:18:47.437", "id" : "usr_11",  "value": "-2.397038"},
{ 'datetime_start' : "2017-03-19 09:48:47.262", "id" : "usr_15",  "value": "-1.250512"},
{ 'datetime_start' : "2017-03-19 15:18:47.941", "id" : "usr_21",  "value": "-0.681998"},
{ 'datetime_start' : "2017-03-19 20:03:52.905", "id" : "usr_13",  "value": "-1.018452"},
{ 'datetime_start' : "2017-03-22 13:53:48.178", "id" : "usr_21",  "value": "-1.531373"},
{ 'datetime_start' : "2017-03-22 19:53:48.320", "id" : "usr_18",  "value": "-3.789466"},
{ 'datetime_start' : "2017-03-23 13:53:48.789", "id" : "usr_21",  "value": "-1.288360"},
{ 'datetime_start' : "2017-03-24 15:53:48.649", "id" : "usr_11",  "value": "0.213171"},
{ 'datetime_start' : "2017-03-25 16:53:48.422", "id" : "usr_13",  "value": "-2.020710"},
{ 'datetime_start' : "2017-03-26 06:08:48.197", "id" : "usr_15",  "value": "-1.484709"}
]

df = pd.DataFrame(data)
df['datetime_start'] = pd.to_datetime(df['datetime_start'])

I want a representation of this data as a pivot

table = pd.pivot_table(df, values='value', index='id'],
                     columns=['index'], aggfunc=np.sum)

so for each (id, datetime) we have a value
if there is no value it's a None

Is there an elegant way to replace the None value with this rules:

if value(id_i, datetime_i) == None :
    if value(id_i, datetime_i-1)  != 0 :
        value(id_i, datetime_i) = value(id_i, datetime_i-1)
    else:
        value(id_i, datetime_i) = 0

as this kind of propagation :

Body:
I think you need change columns=['index'] to columns='datetime_start' first and then use ffill (fillna with method='ffill'):

table = (pd.pivot_table(df,
                        values='value',
                        index='id',
                        columns='datetime_start',
                        aggfunc=np.sum)
           .ffill(axis=1, limit=1))

EDIT with less data:

data = [
{ 'datetime_start' : "2017-03-15 14:31:20.507", "id" : "usr_21",  "value": "-1.286452"},
{ 'datetime_start' : "2017-03-16 15:17:45.550", "id" : "usr_15",  "value": "-2.349203"},
{ 'datetime_start' : "2017-03-17 14:20:47.437", "id" : "usr_13",  "value": "-2.397038"},
{ 'datetime_start' : "2017-03-19 09:43:47.262", "id" : "usr_12",  "value": "-1.250512"},
]

df = pd.DataFrame(data)
df['datetime_start'] = pd.to_datetime(df['datetime_start'])

table = (pd.pivot_table(df,
                        values='value',
                        index='id',
                        columns='datetime_start',
                        aggfunc=np.sum)
         )

print (table)
datetime_start 2017-03-15 14:31:20.507 2017-03-16 15:17:45.550  \
id
usr_12                            None                    None
usr_13                            None                    None
usr_15                            None               -2.349203
usr_21                       -1.286452                    None

datetime_start 2017-03-17 14:20:47.437 2017-03-19 09:43:47.262
id
usr_12                            None               -1.250512
usr_13                       -2.397038                    None
usr_15                            None                    None
usr_21                            None                    None

Replace only one value None if previous value is not None - then add parameter limit:

table1 = (pd.pivot_table(df,
                        values='value',
                        index='id',
                        columns='datetime_start',
                        aggfunc=np.sum)
           .ffill(axis=1, limit=1)
           )

print (table1)
datetime_start 2017-03-15 14:31:20.507 2017-03-16 15:17:45.550  \
id
usr_12                            None                    None
usr_13                            None                    None
usr_15                            None               -2.349203
usr_21                       -1.286452               -1.286452

datetime_start 2017-03-17 14:20:47.437 2017-03-19 09:43:47.262
id
usr_12                            None               -1.250512
usr_13                       -2.397038               -2.397038
usr_15                       -2.349203                    None
usr_21                            None                    None

Replace all NaNs by previous non NaNs, last replace all NaNs by 0, remove limit and add fillna(0):

table2 = (pd.pivot_table(df,
                        values='value',
                        index='id',
                        columns='datetime_start',
                        aggfunc=np.sum)
            .ffill(axis=1)
            .fillna(0)
           )

print (table2)
datetime_start 2017-03-15 14:31:20.507 2017-03-16 15:17:45.550  \
id
usr_12                               0                       0
usr_13                               0                       0
usr_15                               0               -2.349203
usr_21                       -1.286452               -1.286452

datetime_start 2017-03-17 14:20:47.437 2017-03-19 09:43:47.262
id
usr_12                               0               -1.250512
usr_13                       -2.397038               -2.397038
usr_15                       -2.349203               -2.349203
usr_21                       -1.286452               -1.286452


问:
reference error: grecaptcha is undefined in chrome
I have two captcha on same form. One on submit and other on a modal which will open after form submit. So I render it after reading many answer from here. Now it is working fine with mozilla but giving reference error in chrome.

My google api is:

```<code><script src='https://www.google.com/recaptcha/api.js'></script>
</code>```

Then my code renders this in java script:

```<code>$('.g-recaptcha').each(function(index, el) {
        widgetId = grecaptcha.render(el, {'sitekey' : 'My-SITE-KEY'});
});
</code>```

My html read like this

```<code><div id="user_recaptcha" class="reCaptcha">
    <div id="e_Captcha" class="g-recaptcha" data-sitekey="<?php echo SITE_KEY; ?>" data-callback="recaptchaCallbackEvent"></div>
</div>
</code>```

I declare widgetId at the top of my js.

答:
Recaptcha has a onload callback that will run once recaptcha is loaded. Place your code inside that callback function.

https://developers.google.com/recaptcha/docs/display

```<code>//call this function in your js
function onloadCallback() {
    $('.g-recaptcha').each(function(index, el) {
        widgetId = grecaptcha.render(el, {'sitekey' : 'My-SITE-KEY'});
    });
}

//load this script before your js is loading
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"></script>
//your html is absolutely fine.
</code>```

Body:
I have two captcha on same form. One on submit and other on a modal which will open after form submit. So I render it after reading many answer from here. Now it is working fine with mozilla but giving reference error in chrome.

My google api is:

Then my code renders this in java script:

$('.g-recaptcha').each(function(index, el) {
        widgetId = grecaptcha.render(el, {'sitekey' : 'My-SITE-KEY'});
});

My html read like this

    <div id="e_Captcha" class="g-recaptcha" data-sitekey="<?php echo SITE_KEY; ?>" data-callback="recaptchaCallbackEvent">

I declare widgetId at the top of my js.

Body:
Recaptcha has a onload callback that will run once recaptcha is loaded. Place your code inside that callback function.

https://developers.google.com/recaptcha/docs/display

//call this function in your js
function onloadCallback() {
    $('.g-recaptcha').each(function(index, el) {
        widgetId = grecaptcha.render(el, {'sitekey' : 'My-SITE-KEY'});
    });
}

//load this script before your js is loading
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"></script>
//your html is absolutely fine.


问:
3rd party jar which can not be put in any repository works with maven project
There is a 3rd party jar which is dependent by many programs on the target machine. That jar file is named as abc.jar.

I can add the jar file to the local repository as abc-1.0.jar and package my project. But that means I must manually replace abc-1.0.jar when abc.jar updates. Here are my questions:

1.Is it possible to just use abc.jar when development with Intellij IDEA? I tried add the abc.jar to the External Libraries with dependency adding. But the editor can not recognize classes within abc.jar

2.If the answer is yes, What should I do to let the war file use the system level's abc.jar not the bundled within the ear?

Many thanks

答:
You can add the abc.jar file to the particular module's dependency manually as described in mentioned SO answer and you also will have to manually add it to the artifact which is automatically generated by IDE based on Maven configuration.

Note that the artifact configuration will be overridden on the next re-import from Maven unless you create a copy of this artifact configuration and give it another name.

Generally such approach is not recommended for Maven project. Instead you should relay on Maven configuration.


问:
Enable the Ctrl + Scroll to Zoom google maps

How to enable message ctrl + Scroll  zoom message in google map?
Map option define below.

```<code> var mapOptions = {
    mapTypeId: 'roadmap', center: new google.maps.LatLng(countryLat, countryLon), zoom: countryZoom, gestureHandling: 'cooperative'
};
</code>```

I need output like this when mouse scroll :

答:
This function seems to only work in the experimental version of the API. So just change the version in the URL to 3.exp or to 3.30 (which is the current experminatal version) so your URL in the script would look something like this:

"https://maps.googleapis.com/maps/api/js?v=3.30&sensor=false&key=" + your_api_key

You can also remove the version tag so it will always use the latest version of the API.

Hope this fix your issue.

Body:
How to enable message ctrl + Scroll  zoom message in google map?
Map option define below.

 var mapOptions = {
    mapTypeId: 'roadmap', center: new google.maps.LatLng(countryLat, countryLon), zoom: countryZoom, gestureHandling: 'cooperative'
};

I need output like this when mouse scroll :


问:
Install BigDL in Data Science Experience on Cloud
I would like to use Intel BigDL in notebooks on Data Science Experience on Cloud.

How can I install it?

答:
If your notebooks are backed by an Apache Spark as a Service instance in DSX, installing BigDL is simple. But you have to collect some version information first.

Which Spark version? Currently, 2.1 is the latest supported by DSX.

With Python, you can only install BigDL for one Spark version per service.

Which BigDL version? Currently, 0.3.0 is the latest, and it supports Spark 2.1.

If in doubt, check the download page. The Spark fixlevel does not matter.

With this information, you can determine the URL of the required BigDL JAR file in the Maven repository.
For the example versions, BigDL 0.3.0 with Spark 2.1, the download URL is

https://repo1.maven.org/maven2/com/intel/analytics/bigdl/bigdl-SPARK_2.1/0.3.0/bigdl-SPARK_2.1-0.3.0-jar-with-dependencies.jar

For other versions, replace 0.3.0 and 2.1 in that URL as required. Note that both versions appear twice, once in the path and once in the filename.

Installing for Python

You need the JAR, and the matching Python package. The Python package depends only on the version of BigDL, not on the Spark version.
The installation steps can be executed from a Python notebook:

Install the JAR.

```<code>!(export sv=2.1 bv=0.3.0 ; cd ~/data/libs/ && wget  https://repo1.maven.org/maven2/com/intel/analytics/bigdl/bigdl-SPARK_${sv}/${bv}/bigdl-SPARK_${sv}-${bv}-jar-with-dependencies.jar)
</code>```

Here, the versions of Spark (sv) and BigDL (bv) are defined as environment variables, so you can easily adjust them without having to change the URL.

Install the Python module.

```<code>!pip install bigdl==0.3.0 --no-deps | cat
</code>```

If you want to switch your notebooks between Python versions, execute this step once with each Python version.
(Without --no-deps, a conflicting version of pyspark would be installed.)

After restarting the notebook kernel, BigDL is ready for use.

(Not) Installing for Scala

If you install the JAR as described above for Python, it is also available in Scala kernels.

If you want to use BigDL exclusively with Scala, better not install the JAR at all. Instead, use the %AddJar magic at the beginning of the notebook. It's best to do this in the very first code cell, to avoid class loading issues.

```<code>%AddJar https://repo1.maven.org/maven2/com/intel/analytics/bigdl/bigdl-SPARK_2.1/0.3.0/bigdl-SPARK_2.1-0.3.0-jar-with-dependencies.jar
</code>```

By not installing the JAR, you gain the flexibility of using different versions of Spark and BigDL in different Scala notebooks sharing the same service. As soon as you install a JAR, you're likely to run into conflicts between that one and the one you pull in with %AddJar.

Cleanup

If you want to install a different version of BigDL, you'll have to clean up first. Here are commands to check what is installed, and to get rid of it. Execute these commands from a Python notebook.

Check what JAR is installed. If the output is empty, none is installed.

```<code>!find ~/data/libs -name bigdl-\*
</code>```

Check what Python module is installed. If the output is empty, BigDL is not installed.

```<code>!pip freeze | grep -i BigDL
</code>```

Remove installed BigDL JARs.

```<code>!find ~/data/libs -name bigdl-\* -exec rm -vf {} +
</code>```

Remove the installed BigDL Python module for the current Python version.

```<code>!rm -rf ~/.local/lib/python${_py_version_}/site-packages/{bigdl,BigDL}*
</code>```

If re-installation fails with a "multiple dist-info directories" message, also execute:

```<code>!rm -rf $PIP_BUILD
</code>```

Body:
If your notebooks are backed by an Apache Spark as a Service instance in DSX, installing BigDL is simple. But you have to collect some version information first.

Which Spark version? Currently, 2.1 is the latest supported by DSX.

With Python, you can only install BigDL for one Spark version per service.

Which BigDL version? Currently, 0.3.0 is the latest, and it supports Spark 2.1.

If in doubt, check the download page. The Spark fixlevel does not matter.

With this information, you can determine the URL of the required BigDL JAR file in the Maven repository.
For the example versions, BigDL 0.3.0 with Spark 2.1, the download URL is

https://repo1.maven.org/maven2/com/intel/analytics/bigdl/bigdl-SPARK_2.1/0.3.0/bigdl-SPARK_2.1-0.3.0-jar-with-dependencies.jar

For other versions, replace 0.3.0 and 2.1 in that URL as required. Note that both versions appear twice, once in the path and once in the filename.

Installing for Python

You need the JAR, and the matching Python package. The Python package depends only on the version of BigDL, not on the Spark version.
The installation steps can be executed from a Python notebook:

Install the JAR.

!(export sv=2.1 bv=0.3.0 ; cd ~/data/libs/ && wget  https://repo1.maven.org/maven2/com/intel/analytics/bigdl/bigdl-SPARK_${sv}/${bv}/bigdl-SPARK_${sv}-${bv}-jar-with-dependencies.jar)

Here, the versions of Spark (sv) and BigDL (bv) are defined as environment variables, so you can easily adjust them without having to change the URL.

Install the Python module.

!pip install bigdl==0.3.0 --no-deps | cat

If you want to switch your notebooks between Python versions, execute this step once with each Python version.
(Without --no-deps, a conflicting version of pyspark would be installed.)

After restarting the notebook kernel, BigDL is ready for use.

(Not) Installing for Scala

If you install the JAR as described above for Python, it is also available in Scala kernels.

If you want to use BigDL exclusively with Scala, better not install the JAR at all. Instead, use the %AddJar magic at the beginning of the notebook. It's best to do this in the very first code cell, to avoid class loading issues.

%AddJar https://repo1.maven.org/maven2/com/intel/analytics/bigdl/bigdl-SPARK_2.1/0.3.0/bigdl-SPARK_2.1-0.3.0-jar-with-dependencies.jar

By not installing the JAR, you gain the flexibility of using different versions of Spark and BigDL in different Scala notebooks sharing the same service. As soon as you install a JAR, you're likely to run into conflicts between that one and the one you pull in with %AddJar.

Cleanup

If you want to install a different version of BigDL, you'll have to clean up first. Here are commands to check what is installed, and to get rid of it. Execute these commands from a Python notebook.

Check what JAR is installed. If the output is empty, none is installed.

!find ~/data/libs -name bigdl-\*

Check what Python module is installed. If the output is empty, BigDL is not installed.

!pip freeze | grep -i BigDL

Remove installed BigDL JARs.

!find ~/data/libs -name bigdl-\* -exec rm -vf {} +

Remove the installed BigDL Python module for the current Python version.

!rm -rf ~/.local/lib/python${_py_version_}/site-packages/{bigdl,BigDL}*

If re-installation fails with a "multiple dist-info directories" message, also execute:

!rm -rf $PIP_BUILD


问:
Wrap text in a table reportlab?
I use a table but, I draw in in a canvas to control the position of the flowables, this because I have a template in a pdf, an I merge with pyPDF.

The wrap is done in a table but the text go up, not down that's what I hope.

c is the canvas

Code

```<code>from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import Paragraph, Table
from reportlab.lib.units cm

width, height = A4
styles = getSampleStyleSheet()

def coord(x, y, unit=1):
    x, y = x * unit, height -  y * unit
    return x, y

descrpcion = Paragraph('long paragraph', styles["Normal"])
partida = Paragraph('1', styles["Center"])
candidad = Paragraph('120', styles["Center"])
precio_unitario = Paragraph('$52.00', styles["right"])
precio_total = Paragraph('$6240.00', styles["right"])

data= [[partida, candidad, descrpcion, precio_unitario, precio_total]]
table = Table(data, colWidths=[2.05 * cm, 2.7 * cm, 9.6 * cm,
                               2.65 * cm, 2.7 * cm])

c = canvas.Canvas(PDF, pagesize=A4)
table.wrapOn(c, width, height)
table.drawOn(c, *coord(1.8, 9.6, cm))
c.save()
</code>```

答: I know that Postscript's reference is the lower, left corner.  I'm guessing that PDF is the same, so you subtract from the y value to go down.  Print the beginning and ending "y" values in the function to see how they are changing and adjust the "y" value depending on the length of the sentence. And how does the function know what "height" is?  I use ReportLab but could probably help with a specific example if you care to post one.</p>

ContentLicense: CC BY-SA 4.0

Title: Wrap text in a table reportlab?

Body:
I use a table but, I draw in in a canvas to control the position of the flowables, this because I have a template in a pdf, an I merge with pyPDF.

The wrap is done in a table but the text go up, not down that's what I hope.

c is the canvas

Code

from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import Paragraph, Table
from reportlab.lib.units cm

width, height = A4
styles = getSampleStyleSheet()

def coord(x, y, unit=1):
    x, y = x * unit, height -  y * unit
    return x, y

descrpcion = Paragraph('long paragraph', styles["Normal"])
partida = Paragraph('1', styles["Center"])
candidad = Paragraph('120', styles["Center"])
precio_unitario = Paragraph('$52.00', styles["right"])
precio_total = Paragraph('$6240.00', styles["right"])

data= [[partida, candidad, descrpcion, precio_unitario, precio_total]]
table = Table(data, colWidths=[2.05 * cm, 2.7 * cm, 9.6 * cm,
                               2.65 * cm, 2.7 * cm])

c = canvas.Canvas(PDF, pagesize=A4)
table.wrapOn(c, width, height)
table.drawOn(c, *coord(1.8, 9.6, cm))
c.save()


问:
Undefined: App with mux
So I just started learning Go yesterday and I have been following a fairly simple tutorial on creating a restful api. I can run the tests and everything but when I try to run the app and have it listen on a part it gives me undefined: App.

I cannot seem to find the error in this as Initialize and run should be sufficient enough to start the server. The tutorial also has it exactly like this and I followed it carefully.

UPDATE:

As clarification I attempt to run the program with go run main.go and that's what prompts the error.

I also attempted to follow the advice of an answer and ran go run main.go app.go and I get undefined: getUsers and it points to the line where it says users, err := getUsers(a.DB, start, count). I have added them to my app.go code below.

main.go

```<code>package main

func main() {
    a := App{}

    a.Initialize("root", "password", "user")

    a.Run(":8080")
}
</code>```

app.go

```<code>package main

import (
    "fmt"
    "log"
    "strconv"
    "encoding/json"
    "net/http"
    "github.com/gorilla/mux"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)

type App struct {
    Router *mux.Router
    DB     *sql.DB
}

func (a *App) Initialize(user, password, dbname string) {
    connectionString := fmt.Sprintf("%s:%s@/%s", user, password, dbname)

    var err error

    a.DB, err = sql.Open("mysql", connectionString)

    if err != nil {
        log.Fatal(err)
    }

    a.Router = mux.NewRouter()
    a.initializeRoutes()
}

func (a *App) initializeRoutes() {
    a.Router.HandleFunc("/users", a.getUsers).Methods("GET")
}

func (a *App) Run(addr string) {
    log.Fatal(http.ListenAndServe(addr, a.Router))
}

func (a *App) getUsers(w http.ResponseWriter, r *http.Request) {
    count, _ := strconv.Atoi(r.FormValue("count"))
    start, _ := strconv.Atoi(r.FormValue("start"))

    if count > 10 || count < 1 {
        count = 10
    }

    if start < 0 {
        start = 0
    }

    users, err := getUsers(a.DB, start, count)

    if err != nil {
        respondWithError(w, http.StatusInternalServerError, err.Error())

        return
    }

    respondWithJSON(w, http.StatusOK, users);
}
</code>```

答:
Just to add to @Eugene Lisitsky's answer.

If *.go doesn't work for you for some reason you'll have to manually list all files on which your program depends.

That means that besides main.go and app.go you also need to list files that define the getUsers, respondWithError and respondWithJSON functions, and if the files in which you define these functions reference some other identifiers that are defined in yet other files you'll also need to include those and so on.

And as you can see this can get pretty annoying pretty quickly so it might be a good idea to put all of your app code, and all other code that's outside of the main.go file into separate packages, then have main.go import those packages, and with that you should be able to run your app with go run main.go.

Title: Undefined: App with mux

Body:
So I just started learning Go yesterday and I have been following a fairly simple tutorial on creating a restful api. I can run the tests and everything but when I try to run the app and have it listen on a part it gives me undefined: App.

I cannot seem to find the error in this as Initialize and run should be sufficient enough to start the server. The tutorial also has it exactly like this and I followed it carefully.

UPDATE:

As clarification I attempt to run the program with go run main.go and that's what prompts the error.

I also attempted to follow the advice of an answer and ran go run main.go app.go and I get undefined: getUsers and it points to the line where it says users, err := getUsers(a.DB, start, count). I have added them to my app.go code below.

main.go

package main

func main() {
    a := App{}

    a.Initialize("root", "password", "user")

    a.Run(":8080")
}

app.go

package main

import (
    "fmt"
    "log"
    "strconv"
    "encoding/json"
    "net/http"
    "github.com/gorilla/mux"
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)

type App struct {
    Router *mux.Router
    DB     *sql.DB
}

func (a *App) Initialize(user, password, dbname string) {
    connectionString := fmt.Sprintf("%s:%s@/%s", user, password, dbname)

    var err error

    a.DB, err = sql.Open("mysql", connectionString)

    if err != nil {
        log.Fatal(err)
    }

    a.Router = mux.NewRouter()
    a.initializeRoutes()
}

func (a *App) initializeRoutes() {
    a.Router.HandleFunc("/users", a.getUsers).Methods("GET")
}

func (a *App) Run(addr string) {
    log.Fatal(http.ListenAndServe(addr, a.Router))
}

func (a *App) getUsers(w http.ResponseWriter, r *http.Request) {
    count, _ := strconv.Atoi(r.FormValue("count"))
    start, _ := strconv.Atoi(r.FormValue("start"))

    if count > 10 || count < 1 {
        count = 10
    }

    if start < 0 {
        start = 0
    }

    users, err := getUsers(a.DB, start, count)

    if err != nil {
        respondWithError(w, http.StatusInternalServerError, err.Error())

        return
    }

    respondWithJSON(w, http.StatusOK, users);
}


问:
How do I select a node within a template string in html?
Create an element and pass it an innerHTML string.

let mydiv = document.createElement('div');
mydiv.innerHTML = "

Intro

Hello Example

";
console.log(mydiv.getElementByID("greet"))```
</div>
</div>
</p>

<p>.. How do I get the element with id='greet'?</p>

```mydiv.getElementbyID('greet')   //doesn't work.
```

答:
getElementById is on document and not on a node.
So you can always use queryselector like this.</p>

```<code>let mydiv = document.createElement('div');
mydiv.innerHTML = "<div> <p>Intro</p> </div> <div id='greet'> <p>Hello Example</p> </div>";
console.log(mydiv.querySelector("#greet"));
</code>```

Body:
Create an element and pass it an innerHTML string.

let mydiv = document.createElement('div');
mydiv.innerHTML = "

Intro

Hello Example

";
console.log(mydiv.getElementByID("greet"))

.. How do I get the element with id='greet'?

mydiv.getElementbyID('greet')   //doesn't work.

Body:
getElementById is on document and not on a node.
So you can always use queryselector like this.

let mydiv = document.createElement('div');
mydiv.innerHTML = "<div> <p>Intro</p> </div> <div id='greet'> <p>Hello Example</p> </div>";
console.log(mydiv.querySelector("#greet"));


问:
Same workbook in two windows; Sub changes which tab is viewed
I have a workbook that uses a macro to add extra lines, as the workbook has to be heavily locked down to protect it from users. I'm using Excel 2010.

However, if I have two windows open looking at different sheets of the workbook, running the macro makes both windows shift to the sheet in which I added the lines(s), which is disruptive to workflow.

My guess is that this is down to using .PasteSpecial but I am unsure of how else to do it, as the lines to be added include formatting and formulae so .value = .value won't work.

The sub is called from one of four other subs; one to add a single row, one to add multiple rows,  one to add a special header row, and one that adds costs rows (done by sending a negative number of rows). The code is:

```<code>Sub InsertAnyRows(NumRows As Integer)

    Dim thisWS As Worksheet
    Set thisWS = ActiveSheet
    If Not (InRange(ActiveCell, thisWS.Range("QuoteLines")) Or InRange(ActiveCell, thisWS.Range("LabourLines")) Or InRange(ActiveCell, thisWS.Range("OptionsLines"))) Then Exit Sub

    Application.ScreenUpdating = False
    Application.CutCopyMode = False

    Dim RowLoc As Range
    Set RowLoc = thisWS.Cells(Selection.Rows(1).Row, 1)

    Select Case NumRows

        Case Is < 0 ' must be inserting costs rows
            NumRows = NumRows * -1
            RowLoc.Resize(NumRows).Offset(1, 0).EntireRow.Insert
            thisWS.Range("CostsBlankRow").Copy
            RowLoc.Resize(NumRows).Offset(1, 0).PasteSpecial Paste:=xlPasteAll

        Case 0 ' must be inserting a header row
            RowLoc.Offset(1, 0).EntireRow.Insert
            thisWS.Range("TabHeaderRow").Copy
            RowLoc.Offset(1, 0).PasteSpecial Paste:=xlPasteAll

        Case Else ' must be inserting normal rows
            RowLoc.Resize(NumRows).Offset(1, 0).EntireRow.Insert
            thisWS.Range("TabBlankRow").Copy
            RowLoc.Resize(NumRows).Offset(1, 0).PasteSpecial Paste:=xlPasteAll

    End Select

    Application.CutCopyMode = False
    Application.ScreenUpdating = True

End Sub
</code>```

答:
This is rather messy and I'm sure there is a more elegant solution, but in a quick test adding these lines after End Select seemed to preserve the windows.

```<code>Windows(1).Activate
thisWS.Activate
Windows(2).Activate
Sheets(2).Activate 'adjust sheet name/index to suit
</code>```

Body:
I have a workbook that uses a macro to add extra lines, as the workbook has to be heavily locked down to protect it from users. I'm using Excel 2010.

However, if I have two windows open looking at different sheets of the workbook, running the macro makes both windows shift to the sheet in which I added the lines(s), which is disruptive to workflow.

My guess is that this is down to using .PasteSpecial but I am unsure of how else to do it, as the lines to be added include formatting and formulae so .value = .value won't work.

The sub is called from one of four other subs; one to add a single row, one to add multiple rows,  one to add a special header row, and one that adds costs rows (done by sending a negative number of rows). The code is:

Sub InsertAnyRows(NumRows As Integer)

    Dim thisWS As Worksheet
    Set thisWS = ActiveSheet
    If Not (InRange(ActiveCell, thisWS.Range("QuoteLines")) Or InRange(ActiveCell, thisWS.Range("LabourLines")) Or InRange(ActiveCell, thisWS.Range("OptionsLines"))) Then Exit Sub

    Application.ScreenUpdating = False
    Application.CutCopyMode = False

    Dim RowLoc As Range
    Set RowLoc = thisWS.Cells(Selection.Rows(1).Row, 1)

    Select Case NumRows

        Case Is < 0 ' must be inserting costs rows
            NumRows = NumRows * -1
            RowLoc.Resize(NumRows).Offset(1, 0).EntireRow.Insert
            thisWS.Range("CostsBlankRow").Copy
            RowLoc.Resize(NumRows).Offset(1, 0).PasteSpecial Paste:=xlPasteAll

        Case 0 ' must be inserting a header row
            RowLoc.Offset(1, 0).EntireRow.Insert
            thisWS.Range("TabHeaderRow").Copy
            RowLoc.Offset(1, 0).PasteSpecial Paste:=xlPasteAll

        Case Else ' must be inserting normal rows
            RowLoc.Resize(NumRows).Offset(1, 0).EntireRow.Insert
            thisWS.Range("TabBlankRow").Copy
            RowLoc.Resize(NumRows).Offset(1, 0).PasteSpecial Paste:=xlPasteAll

    End Select

    Application.CutCopyMode = False
    Application.ScreenUpdating = True

End Sub

Body:
This is rather messy and I'm sure there is a more elegant solution, but in a quick test adding these lines after End Select seemed to preserve the windows.

Windows(1).Activate
thisWS.Activate
Windows(2).Activate
Sheets(2).Activate 'adjust sheet name/index to suit


问:
Upload an image on Facebook via FBConnect
I know many question has been post and answer for this question. I still stuck by a little thing.
I did success upload an UIImage on Facebook via my iPhone app but I realize that photos goes to a pending album. And user had to accept it to get it post on their wall.

Here is my code

```<code>- (void)start
{
    NSArray *permissions = [NSArray arrayWithObjects:
                            @"read_stream", @"offline_access", nil];
    [_fbEngine authorize:kFbAppId
             permissions:permissions
                delegate:self];
}

#pragma mark -
#pragma mark FBSession delegate

- (void)fbDidLogin
{

    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   self.image, @"picture",
                                   nil];
    [_fbEngine requestWithMethodName:@"photos.upload"
                           andParams:params
                       andHttpMethod:@"POST"
                         andDelegate:self];
}
</code>```

Is there a way to post a photo directly on the wall without passing by the pending album.

Regards,

KL94

答:
Add @"publish_stream" to your list of requested permissions.

That'll let you push straight to their wall without an intermediate step. @"offline_access" would allow you to do that via the graph api instead of with a FBDialog, too, so you could make the post happen entirely in the background.

Body:
I know many question has been post and answer for this question. I still stuck by a little thing.
I did success upload an UIImage on Facebook via my iPhone app but I realize that photos goes to a pending album. And user had to accept it to get it post on their wall.

Here is my code

- (void)start
{
    NSArray *permissions = [NSArray arrayWithObjects:
                            @"read_stream", @"offline_access", nil];
    [_fbEngine authorize:kFbAppId
             permissions:permissions
                delegate:self];
}

#pragma mark -
#pragma mark FBSession delegate

- (void)fbDidLogin
{

    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   self.image, @"picture",
                                   nil];
    [_fbEngine requestWithMethodName:@"photos.upload"
                           andParams:params
                       andHttpMethod:@"POST"
                         andDelegate:self];
}

Is there a way to post a photo directly on the wall without passing by the pending album.

Regards,

KL94


问:
Php send to mail
I've been code my own web and currently stuck on making forms. I can't receive any email that I have input on my own website eventhought my php code is already Success.
Here's my form code in HTML

```<code><form action="booking-process.php" method="post">
        <div class="container fluid">
           <h2 class="midtext">Booking Service</h2>
           <h5 class="ff2 note">* Harap Melakukan Booking 1 hari sebelumnya.</h5>
            <div class="col-md-4 col-xs-12 col-sm-6">
                <label for="nama">Nama</label>
                <input type="text" name="nama" class="form-control">

                <label for="telp">Telepon/HP</label>
                <input type="text" name="telp" class="form-control">
            </div>
            <div class="col-md-4 col-xs-12 col-sm-6">
                <label for="plat">Nomor Polisi/Plat</label>
                <input type="text" name="plat" class="form-control">

                <label for="jam">Jam</label>
                <input type="text" name="jam" class="form-control" placeholder="HH:MM">
            </div>
            <div class="col-md-4 col-xs-12 col-sm-6">
                <label for="tanggal">Tanggal</label>
                <input type="text" name="tanggal" class="form-control" placeholder="DD/MM/YYYY">

                <label for="jenis" class="bookingdate">Jenis</label> <br>
                <select name="jenis" id="jenis" class="form-control">
                    <option value="BookingShowroom">Booking Showroom</option>
                    <option value="ToyotaHomeService">Toyota Home Service</option>
                </select>
            </div>
        </div>
        <div class="col-md-12">
            <button type="submit" class="mybtn ff2">BOOK</button>
        </div>
    </form>
</code>```

and here's my php code

```<code><?php

$to = "elmokun17@gmail.com";
$nama = $_REQUEST['nama'];
$telp = $_REQUEST['telp'];
$plat = $_REQUEST['plat'];
$jam = $_REQUEST['jam'];
$tanggal = $_REQUEST['tanggal'];
$jenis = $_REQUEST['jenis'];
$headers = "From: $from";

$fields = array();
$fields{"nama"} = $nama;
$fields{"telp"} = $telp;
$fields{"plat"} = $plat;
$fields{"jam"} = $jam;
$fields{"tanggal"} = $tanggal;
$fields{"jenis"} = $jenis;

$body = "FORM BOOKING\n\n"; foreach($fields as $a => $b){   $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); }

$send = mail($to, $subject, $body, $headers);
echo 'SUCCESS'
?>
</code>```

答:
Just echo Success at the end of the file, does not mean it is working fine. You need to check whether is it working or not, use if else to verify this -

```<code>if ($send) {
echo "mail send ... OK";
} else {
echo "mail send ... ERROR!";
</code>```

}

Also you need to send more hearders to get it proper work like Content-Type, MIME-Version, Reply-To etc.

Refer this Link it has details.

Title: Php send to mail

Body:
I've been code my own web and currently stuck on making forms. I can't receive any email that I have input on my own website eventhought my php code is already Success.
Here's my form code in HTML

<form action="booking-process.php" method="post">

Booking Service

* Harap Melakukan Booking 1 hari sebelumnya.

                Nama
                <input type="text" name="nama" class="form-control">

                Telepon/HP
                <input type="text" name="telp" class="form-control">

                Nomor Polisi/Plat
                <input type="text" name="plat" class="form-control">

                Jam
                <input type="text" name="jam" class="form-control" placeholder="HH:MM">

                Tanggal
                <input type="text" name="tanggal" class="form-control" placeholder="DD/MM/YYYY">

                Jenis

                <select name="jenis" id="jenis" class="form-control">
                    <option value="BookingShowroom">Booking Showroom</option>
                    <option value="ToyotaHomeService">Toyota Home Service</option>
                </select>

            <button type="submit" class="mybtn ff2">BOOK</button>

    </form>

and here's my php code

<?php

$to = "elmokun17@gmail.com";
$nama = $_REQUEST['nama'];
$telp = $_REQUEST['telp'];
$plat = $_REQUEST['plat'];
$jam = $_REQUEST['jam'];
$tanggal = $_REQUEST['tanggal'];
$jenis = $_REQUEST['jenis'];
$headers = "From: $from";

$fields = array();
$fields{"nama"} = $nama;
$fields{"telp"} = $telp;
$fields{"plat"} = $plat;
$fields{"jam"} = $jam;
$fields{"tanggal"} = $tanggal;
$fields{"jenis"} = $jenis;

$body = "FORM BOOKING\n\n"; foreach($fields as $a => $b){   $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); }

$send = mail($to, $subject, $body, $headers);
echo 'SUCCESS'
?>

Body:
Just echo Success at the end of the file, does not mean it is working fine. You need to check whether is it working or not, use if else to verify this -

if ($send) {
echo "mail send ... OK";
} else {
echo "mail send ... ERROR!";

}

Also you need to send more hearders to get it proper work like Content-Type, MIME-Version, Reply-To etc.

Refer this Link it has details.


问:
formatting currency number depending on language
We have web Application and user can be in different locations in europe.

Few Write number like this 5,5 and few Write like 5.5 in a textbox

We try to use that number like below

```<code>double priceOfITem = 0;
double.TryParse(((TextBox)tabTest.Rows[0].Cells[3].Controls[0]).Text.Replace(".", ","), out priceOfITem )
</code>```

But this gives output as 55 which is totally wrong.

I tried like priceOfITem= Convert.ToDouble(string.Format(Thread.CurrentThread.CurrentCulture, "{0:#.##}",(((TextBox)tabTest.Rows[0].Cells[0].Controls[0]).Text)));

This Works if i type 5.5 and if i type 5,5 then it converts to 55.

Some users can type 5,5 and some can type 5.5 depending on coutry there are in. How to solve this in best manner?

答:
I would recommend you to parse the number with the CultureInfo-class. You need submit the user's culture e. g. from the browser-settings (visit Get CultureInfo from current visitor and setting resources based on that?).

In the C#-part, try the following snippet:

```<code>string deNumber = "5,5";
string usNumber = "6.8";
Console.WriteLine(double.Parse(deNumber, new CultureInfo("de-DE")));
Console.WriteLine(double.Parse(usNumber, new CultureInfo("en-US")));
</code>```

Console output:

```<code>5.5
6.8
</code>```

Body:
We have web Application and user can be in different locations in europe.

Few Write number like this 5,5 and few Write like 5.5 in a textbox

We try to use that number like below

double priceOfITem = 0;
double.TryParse(((TextBox)tabTest.Rows[0].Cells[3].Controls[0]).Text.Replace(".", ","), out priceOfITem )

But this gives output as 55 which is totally wrong.

I tried like priceOfITem= Convert.ToDouble(string.Format(Thread.CurrentThread.CurrentCulture, "{0:#.##}",(((TextBox)tabTest.Rows[0].Cells[0].Controls[0]).Text)));

This Works if i type 5.5 and if i type 5,5 then it converts to 55.

Some users can type 5,5 and some can type 5.5 depending on coutry there are in. How to solve this in best manner?

Body:
I would recommend you to parse the number with the CultureInfo-class. You need submit the user's culture e. g. from the browser-settings (visit Get CultureInfo from current visitor and setting resources based on that?).

In the C#-part, try the following snippet:

string deNumber = "5,5";
string usNumber = "6.8";
Console.WriteLine(double.Parse(deNumber, new CultureInfo("de-DE")));
Console.WriteLine(double.Parse(usNumber, new CultureInfo("en-US")));

Console output:

5.5
6.8


问:
Merge two arrays into one associative array
I have two arrays that I want to merge into one associative array.
My first array looks like this:

```<code>$names_array = ["John", "Paul", "George"];
</code>```

The second one looks like this:

```<code>$ages_array = [26, 29, 22];
</code>```

I would like to merge these two arrays and obtain this structure:

```<code>$members_infos = [{"name": "John", "age": 26}, {"name": "Paul", "age":
29}, {"name": "George", "age": 22}];
</code>```

Do I have to use a for loop in order to achieve what I want or can use a php function ?

Thank you

答:
It's a work for array_map function </p>

```<code>$res = array_map(function ($name, $age) { return ['name'=> $name, 'age'=>$age]; },
          $names_array, $ages_array);
</code>```

Body:
I have two arrays that I want to merge into one associative array.
My first array looks like this:

$names_array = ["John", "Paul", "George"];

The second one looks like this:

$ages_array = [26, 29, 22];

I would like to merge these two arrays and obtain this structure:

$members_infos = [{"name": "John", "age": 26}, {"name": "Paul", "age":
29}, {"name": "George", "age": 22}];

Do I have to use a for loop in order to achieve what I want or can use a php function ?

Thank you

Body:
It's a work for array_map function

$res = array_map(function ($name, $age) { return ['name'=> $name, 'age'=>$age]; },
          $names_array, $ages_array);


问:
How do I hide the header in a WPF Expander?
I have a business requirement that when the user clicks a series of checkboxes in a WPF application that it will show panels depending upon what checkboxes they select.  I would like to use the expander panel but I am not sure how to hide the header.  The user should not be allowed to see it unless they check the checkbox.  Does anyone know?</p>

答:
You can do this via making a custom Style for your Expander.

However, it might be easier to just place the controls in a different panel, and set it's visibility to Collapsed in response to the check box state.  The main reason to use Expander is specifically to have the header and controls.


问:
TypeError: $ is not a function WordPress
I might have an error in a .js document in a theme I have purchase:

```<code>$('.tagcloud a').wrap('<span class="st_tag" />');
</code>```

I am trying to solve it but I am not a programmer so I don't know how.
The site is this: http://www.framerental.com .

答:
Other than noConflict, this is helpful too:</p>

```<code>(function( $ ) {
    // Variables and DOM Caching using $.
    var body = $('body');
    console.log(body);
})( jQuery );
</code>```

Body:
I might have an error in a .js document in a theme I have purchase:

$('.tagcloud a').wrap('');

I am trying to solve it but I am not a programmer so I don't know how.
The site is this: http://www.framerental.com .

Body:
Other than noConflict, this is helpful too:

(function( $ ) {
    // Variables and DOM Caching using $.
    var body = $('body');
    console.log(body);
})( jQuery );


问:
Call the dialog from Intent
Is it possible to call a dialog from Intent. I have two Activity RegisterActivity and AuthenticActivity and I implemented custom dialog on RegisterActivity but I also need same dialog on AuthenticActivity. So how can we get that dialog on AuthenticActivity. Can we get that from Intent, Please suggest me? I don't want to write code on both Activity.</p>

答:
Have a BaseActivity in which you can common code, in your case have a
public method. Both your RegisterActivity and AuthenticActivity should extend BaseActivity.

public class BaseActivity extends AppCompatActivity{

```<code>public void displayCommonDialog() {

   View v = getLayoutInflater().inflate(R.layout.fragment_manage_account_dialog, null);
</code>```

........
........

```<code>}
</code>```

}

public class RegisterActivity extends BaseActivity{

........
.........
........

//To call the dialog
   displayCommonDialog();

}

You can use interface or EventBus library to trigger event/ have callback listeners to capture the click events in the dialog.

Title: Call the dialog from Intent

Body:
Have a BaseActivity in which you can common code, in your case have a
public method. Both your RegisterActivity and AuthenticActivity should extend BaseActivity.

public class BaseActivity extends AppCompatActivity{

public void displayCommonDialog() {

   View v = getLayoutInflater().inflate(R.layout.fragment_manage_account_dialog, null);

........
........

}

}

public class RegisterActivity extends BaseActivity{

........
.........
........

//To call the dialog
   displayCommonDialog();

}

You can use interface or EventBus library to trigger event/ have callback listeners to capture the click events in the dialog.


问:
Storing sex (gender) in database
I want to store a user's gender in a database with as little (size/performance) cost as possible.

So far, 3 scenarios come to mind

Int - aligned with Enum in code (1 = Male, 2 = Female, 3 = ...)

char(1) - Store m, f or another single character identifier

Bit (boolean) - is there an appropriate field name for this option?

The reason I ask is because of this answer which mentions that chars are smaller than booleans.

I should clarify that I'm using MS SQL 2008, which DOES in fact have the bit datatype.

答:
```<code>CREATE TABLE Admission (
    Rno INT PRIMARY KEY AUTO_INCREMENT,
    Name VARCHAR(25) NOT NULL,
    Gender ENUM('M','F'),
    Boolean_Valu boolean,
    Dob Date,
    Fees numeric(7,2) NOT NULL
);

insert into Admission (Name,Gender,Boolean_Valu,Dob,Fees)values('Raj','M',true,'1990-07-12',50000);
insert into Admission (Name,Gender,Boolean_Valu,Dob,Fees)values('Rani','F',false,'1994-05-10',15000);
select * from admission;
</code>```

enter link description here

Title: Storing sex (gender) in database

Body:
CREATE TABLE Admission (
    Rno INT PRIMARY KEY AUTO_INCREMENT,
    Name VARCHAR(25) NOT NULL,
    Gender ENUM('M','F'),
    Boolean_Valu boolean,
    Dob Date,
    Fees numeric(7,2) NOT NULL
);

insert into Admission (Name,Gender,Boolean_Valu,Dob,Fees)values('Raj','M',true,'1990-07-12',50000);
insert into Admission (Name,Gender,Boolean_Valu,Dob,Fees)values('Rani','F',false,'1994-05-10',15000);
select * from admission;

enter link description here


问:
Upload file to google drive using REST API in Node.js
I am trying to upload a file to google drive using rest API(insert) in node.js, I have access_token and refresh_token. how can I upload without any sdk.</p>

答:
I was successful in testing this NodeJS upload by modifying the NodeJS basic upload sample a bit and mixing it with the already available NodeJS Quickstart

Here's the upload function:

```<code>function uploadFile(auth){
  var drive = google.drive('v3');
  var fileMetadata = {
         'name': 'uploadImageTest.jpeg'
      };
  var media = {
          mimeType: 'image/jpeg',
          //PATH OF THE FILE FROM YOUR COMPUTER
          body: fs.createReadStream('/usr/local/google/home/rrenacia/Downloads/noogui.jpeg')
      };

      drive.files.create({
          auth: auth,
          resource: fileMetadata,
          media: media,
          fields: 'id'
      }, function (err, file) {
      if (err) {
          // Handle error
          console.error(err);
      } else {
          console.log('File Id: ', file.id);
      }
   });
}
</code>```

You can use the NodeJS Quickstart as reference for authorization. Change listFiles function name:

```<code>authorize(JSON.parse(content), listFiles);
</code>```

to the name of your upload function, in this case:

```<code>authorize(JSON.parse(content), uploadFile);
</code>```

A sucessful upload on my Google drive:

Body:
I was successful in testing this NodeJS upload by modifying the NodeJS basic upload sample a bit and mixing it with the already available NodeJS Quickstart

Here's the upload function:

function uploadFile(auth){
  var drive = google.drive('v3');
  var fileMetadata = {
         'name': 'uploadImageTest.jpeg'
      };
  var media = {
          mimeType: 'image/jpeg',
          //PATH OF THE FILE FROM YOUR COMPUTER
          body: fs.createReadStream('/usr/local/google/home/rrenacia/Downloads/noogui.jpeg')
      };

      drive.files.create({
          auth: auth,
          resource: fileMetadata,
          media: media,
          fields: 'id'
      }, function (err, file) {
      if (err) {
          // Handle error
          console.error(err);
      } else {
          console.log('File Id: ', file.id);
      }
   });
}

You can use the NodeJS Quickstart as reference for authorization. Change listFiles function name:

authorize(JSON.parse(content), listFiles);

to the name of your upload function, in this case:

authorize(JSON.parse(content), uploadFile);

A sucessful upload on my Google drive:


问:
How can one make two instances of this Singleton Class?
This code should be enough for restricting only one instance of singleton class. How can we make two instances of this object?</p>

```<code>class Singleton
{
private:
    Singleton()
    {}
    ~Singleton()
    {}
    static Singleton * ptr;
public:
    static Singleton * CreateObject()
    {
        if (!ptr)
            ptr = new Singleton;
        return ptr;
    }
    static void freeObject()
    {
        if (ptr)
        {
            delete ptr;
            ptr = 0;
        }
    }
};
Singleton * Singleton::ptr = 0;
</code>```

答:
Well, another possibility not yet exposed is the cuncurrency.
That singleton pattern is not secure enough.
If you have two (or more) different threads calling simultaneously the CreateObject() method they could easily get different instances of the object.

You should add a mutex to secure that pattern.
Or move to another pattern like this one:

```<code> static Singleton& instance()
 {
   static Singleton INSTANCE;
   return INSTANCE;
 }
</code>```

Body:
This code should be enough for restricting only one instance of singleton class. How can we make two instances of this object?

class Singleton
{
private:
    Singleton()
    {}
    ~Singleton()
    {}
    static Singleton * ptr;
public:
    static Singleton * CreateObject()
    {
        if (!ptr)
            ptr = new Singleton;
        return ptr;
    }
    static void freeObject()
    {
        if (ptr)
        {
            delete ptr;
            ptr = 0;
        }
    }
};
Singleton * Singleton::ptr = 0;

Body:
Well, another possibility not yet exposed is the cuncurrency.
That singleton pattern is not secure enough.
If you have two (or more) different threads calling simultaneously the CreateObject() method they could easily get different instances of the object.

You should add a mutex to secure that pattern.
Or move to another pattern like this one:

 static Singleton& instance()
 {
   static Singleton INSTANCE;
   return INSTANCE;
 }


问:
Is there a way to cap the max size on a STL::map container?
My application can only process up to a certain number of entry in the map structure, how do I specify that limit in my code so that my code does not get overwhelmed (for lack of better term).  Is there a way to specify the max limit when defining the variable of type map?

Thanks

答:
The stl containers also take an 'allocator' as a (defaulted) parameter.  This allocator is the container's means to allocate new space for it's data.

If you define a 'capped' allocator (sounds simple, hey?), you're there.

EDIT - In some fora, I found that the allocators, though initially intended stateless, can be statefull on most (modern) compilers.  That's why I carry on on this.  It's quite cumbersome, though, to do it this way, and probably way more easy and comprenensible to aggregate your map type in a cappedmap adapter.

It took me a lot of moments here and there, but here I got a compiling, capped, example:

```<code>// an allocator with maximally MAX elements.
template< typename T, size_t MAX = 5 >
struct AllocateCapped {

    // reuses an existing allocator
    typedef std::allocator<T> tallocator;

    typedef typename tallocator::value_type value_type;
    typedef typename tallocator::pointer pointer;
    typedef typename tallocator::reference reference;
    typedef typename tallocator::const_pointer const_pointer;
    typedef typename tallocator::const_reference const_reference;
    typedef typename tallocator::size_type size_type;
    typedef typename tallocator::difference_type difference_type;
</code>```

The actual code of the capped allocator delegates to the allocator member:

```<code>    size_t free;
    tallocator allocator;

    AllocateCapped():free(MAX){
        printf("capped");
    }

template<typename T2>
    AllocateCapped( const AllocateCapped<T2>& other ){}

    pointer allocate( size_type n, const_pointer hint = 0) {
        if( !free ) throw std::bad_alloc();
        free-=n;
        return allocator.allocate( n, hint );
    }

    void deallocate( pointer p, size_type n ) {
        free+=n;
        allocator.deallocate(p,n);
    }

    size_type max_size() const { return free; }
    void construct( pointer p, const_reference val ) {
        return allocator.construct(p,val);
    }
    void destroy( pointer p ) { allocator.destroy(p); }

    template<class _Other>
    struct rebind
    {   // convert this type to _ALLOCATOR<_Other>
        typedef typename AllocateCapped<_Other> other;
    };

};
</code>```

This allocator can be used like this:

```<code>// example structure
struct s {
    int i;
    s():i(){}
    s(int i):i(i){}
};

int main(int argc, char* argv[]) {
typedef AllocateCapped< std::pair<const int, s> > talloc;
talloc a;
talloc::pointer p = reinterpret_cast<talloc::pointer>( a.allocate(1,0) );
a.construct(p, talloc::value_type() );
a.destroy(p);
a.deallocate(p, 1 );

std::map<int , s, std::less<int>, talloc > m;
std::vector<int, AllocateCapped<int> > v;
for( int i = 0; i != 4; ++i ) {
    m[i]=s(i);
    v.push_back(i);
}
m[5]=s(5); // throws
v.push_back(5); // throws
return 0;
}
</code>```

Note: not thoroughly tested.  It's just an idea.

Body:
The stl containers also take an 'allocator' as a (defaulted) parameter.  This allocator is the container's means to allocate new space for it's data.

If you define a 'capped' allocator (sounds simple, hey?), you're there.

EDIT - In some fora, I found that the allocators, though initially intended stateless, can be statefull on most (modern) compilers.  That's why I carry on on this.  It's quite cumbersome, though, to do it this way, and probably way more easy and comprenensible to aggregate your map type in a cappedmap adapter.

It took me a lot of moments here and there, but here I got a compiling, capped, example:

// an allocator with maximally MAX elements.
template< typename T, size_t MAX = 5 >
struct AllocateCapped {

    // reuses an existing allocator
    typedef std::allocator<T> tallocator;

    typedef typename tallocator::value_type value_type;
    typedef typename tallocator::pointer pointer;
    typedef typename tallocator::reference reference;
    typedef typename tallocator::const_pointer const_pointer;
    typedef typename tallocator::const_reference const_reference;
    typedef typename tallocator::size_type size_type;
    typedef typename tallocator::difference_type difference_type;

The actual code of the capped allocator delegates to the allocator member:

    size_t free;
    tallocator allocator;

    AllocateCapped():free(MAX){
        printf("capped");
    }

template<typename T2>
    AllocateCapped( const AllocateCapped<T2>& other ){}

    pointer allocate( size_type n, const_pointer hint = 0) {
        if( !free ) throw std::bad_alloc();
        free-=n;
        return allocator.allocate( n, hint );
    }

    void deallocate( pointer p, size_type n ) {
        free+=n;
        allocator.deallocate(p,n);
    }

    size_type max_size() const { return free; }
    void construct( pointer p, const_reference val ) {
        return allocator.construct(p,val);
    }
    void destroy( pointer p ) { allocator.destroy(p); }

    template<class _Other>
    struct rebind
    {   // convert this type to _ALLOCATOR<_Other>
        typedef typename AllocateCapped<_Other> other;
    };

};

This allocator can be used like this:

// example structure
struct s {
    int i;
    s():i(){}
    s(int i):i(i){}
};

int main(int argc, char* argv[]) {
typedef AllocateCapped< std::pair<const int, s> > talloc;
talloc a;
talloc::pointer p = reinterpret_cast<talloc::pointer>( a.allocate(1,0) );
a.construct(p, talloc::value_type() );
a.destroy(p);
a.deallocate(p, 1 );

std::map<int , s, std::less<int>, talloc > m;
std::vector<int, AllocateCapped<int> > v;
for( int i = 0; i != 4; ++i ) {
    m[i]=s(i);
    v.push_back(i);
}
m[5]=s(5); // throws
v.push_back(5); // throws
return 0;
}

Note: not thoroughly tested.  It's just an idea.


问:
HTML5 Touch event: Getting word touched
I'm building a dicionary function for my website for mobile users.
I would like this function:
The user touches on a word, a popup window shows its definition.

I've found out the touch API of HTML5.
But couldn't figure out how to get the word touched.
Any hint?

答:
this will be a little bit tricky. if you want to know the specific word touched inside a sentence, you should save a word in a separate span, register a touch event on all spans and get the text content on touch.
Please see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener for event listeners and

https://developer.mozilla.org/en-US/docs/Web/API/Touch_events/Using_Touch_Events for capturing touch events.

Title: HTML5 Touch event: Getting word touched


问:
How to add stuff into existing base class in C#?
Say I have a Father class to be inherited by Children classes, later I want to add more stuff into the Father class without modifying the original Father class, please teach me how could I do it.

Let me clarify my question. Any valuables and methods in Father will automatically accessible to all the Children classes, right? For example:

```<code>public class Father
{
    public int a;
    public int b;
    public int c()
    {
        return a+b;
    }
}

public class Child : Father
{
    private int d=a*b+c();
}
</code>```

Now I want to add a boolean e and a method f() to Father so my Child could access it directly, without adding those lines directly in Father or make a new class in between Father and Child. Is that possible? How could I do it?

答:
If you want to add more fields to your father model then maybe your inheritance structure should be changed.

For example you had model A and model B. Model B inherited fields from model A

```<code>public class A
{
    public string FieldA { get; set; }
}

public class B : A
{
    public string FieldB { get; set; }
}
</code>```

This way the class B has fields FieldA and FieldB.

Now if you want your class B to inherit from a class that has the fields of A but more you could add another layer to your inheritance tree like this.

```<code>public class A
{
    public string FieldA { get; set; }
}

public class C : A
{
    public string FieldC { get; set; }
}

public class B : C
{
    public string FieldB { get; set; }
}
</code>```

Now your class B has fields FieldA and FieldB and FieldC and you don't have to alter your original father class A.

Now if you want to extend methods for a class you could also go with static extensions like this:

```<code>Public static void DoSomething(this A a)
{
    ...
}
</code>```

and then call A.DoSomething();

Body:
Say I have a Father class to be inherited by Children classes, later I want to add more stuff into the Father class without modifying the original Father class, please teach me how could I do it.

Let me clarify my question. Any valuables and methods in Father will automatically accessible to all the Children classes, right? For example:

public class Father
{
    public int a;
    public int b;
    public int c()
    {
        return a+b;
    }
}

public class Child : Father
{
    private int d=a*b+c();
}

Now I want to add a boolean e and a method f() to Father so my Child could access it directly, without adding those lines directly in Father or make a new class in between Father and Child. Is that possible? How could I do it?

Body:
If you want to add more fields to your father model then maybe your inheritance structure should be changed.

For example you had model A and model B. Model B inherited fields from model A

public class A
{
    public string FieldA { get; set; }
}

public class B : A
{
    public string FieldB { get; set; }
}

This way the class B has fields FieldA and FieldB.

Now if you want your class B to inherit from a class that has the fields of A but more you could add another layer to your inheritance tree like this.

public class A
{
    public string FieldA { get; set; }
}

public class C : A
{
    public string FieldC { get; set; }
}

public class B : C
{
    public string FieldB { get; set; }
}

Now your class B has fields FieldA and FieldB and FieldC and you don't have to alter your original father class A.

Now if you want to extend methods for a class you could also go with static extensions like this:

Public static void DoSomething(this A a)
{
    ...
}

and then call A.DoSomething();


问:
Debugger popup message "Getting DataTip text"
This Debugger message pops up randomly while i am attempting to examine a variable while a breakpoint has hit in Visual Studio 2017.

Shortly thereafter, a larger message box appears that shows the following: "Evaluating the function 'System.Reflection.Assembly.LoadForm' timed out."

After enabling option Tools / Options / Debugging / General / Only managed code, the second message box have disappeared. But first message is still showing.

The problem is that first popup window appears for a relatively long time, that makes debugging process very noncomfortable. What else Visual Studio debugger options could I set to disable this popup?

答:
This solution works fine for me:

Uncheck the new langage JavasScript Language Service in Options -> Editor -> JavaScript -> Language Service.

Option capture


问:
How to find value between commas
i need to find regex which selects data look like
987 0000 ASDS CT 2017-11-14,11.34.24 ASD SADASD
and 87 0001 ASDA CT 2017-11-14 11.35.24 ASD DASDAS

at two strings

987   ,0000,ASDS,CT,2017-11-14,11.34.24,ASD  ,SADASD

987   ,0001,ASDA,CT,2017-11-14,11.35.24,ASD  ,DASDAS

How do I select data without commas? Thank you.

答:
Try this, this will also provide the result what you want</p>

```<code>$string1= '987 ,0000,ASDS,CT,2017-11-14,11.34.24,ASD ,SADASD';
$expl = explode(',',$string1);
$new_val_string1 = '';

foreach($expl as $val){
   $new_val_string1 .= trim($val).' ';
}
echo  $new_val_string1;
</code>```

Title: How to find value between commas

Body:
Try this, this will also provide the result what you want

$string1= '987 ,0000,ASDS,CT,2017-11-14,11.34.24,ASD ,SADASD';
$expl = explode(',',$string1);
$new_val_string1 = '';

foreach($expl as $val){
   $new_val_string1 .= trim($val).' ';
}
echo  $new_val_string1;


问:
React Native GeoLocation is not working on Android
Can anyone confirm if React Native Geolocation is actually working on Android?
I am stuck with location request timed out while using getCurrentPosition() method and no error message while using watchPosition() method.

I have added the required permission (FINE LOCATION) on AndroidManifest.xml and location permission is allowed for the app.

Here is my implementation:

```<code>componentWillMount() {
 navigator.geolocation.getCurrentPosition((position) => {
        console.log('+++++++');
        console.log(position.coords.longitude);
        this.setState({
          longitude: position.coords.longitude,
          error: null,
        });
      },
      (error) => {
        console.log(error);

      },

    );
}
</code>```

React Native Version : 0.42

答:
Better if you try this code, I have tested in Android OS 8, RN 0.49.5
React Native current location
the trick is to set

{ enableHighAccuracy: true, timeout: 25000, maximumAge: 3600000 }

Body:
Can anyone confirm if React Native Geolocation is actually working on Android?
I am stuck with location request timed out while using getCurrentPosition() method and no error message while using watchPosition() method.

I have added the required permission (FINE LOCATION) on AndroidManifest.xml and location permission is allowed for the app.

Here is my implementation:

componentWillMount() {
 navigator.geolocation.getCurrentPosition((position) => {
        console.log('+++++++');
        console.log(position.coords.longitude);
        this.setState({
          longitude: position.coords.longitude,
          error: null,
        });
      },
      (error) => {
        console.log(error);

      },

    );
}

React Native Version : 0.42


问:
How can I update jquery to version 3.* in yii2 project using composer
I have a project which is working off of yii2's advanced template. When I checked the version of jquery in vendor/bower/jquery/dist/jquery.js the current version is 2.2.4. I want to update this version to version 3.2.1 but doing a composer update doesn't seem to update my bower assets. I tried setting composer global require "fxp/composer-asset-plugin:>=1.3.1"  and then ran composer update again but no luck. The jquery version is still 2.2.4.

Is there something I'm missing?

答:
You don't actually need to use composer for switching to newer jQuery version. By configuring yii\web\JqueryAsset you can override loaded jQuery library at your wish, e.g.

in /config/main.php:

```<code>...
'components' => [
    'assetManager' => [
        'bundles' => [
            'yii\web\JqueryAsset' => [
                'js' => [YII_DEBUG ? 'https://code.jquery.com/jquery-3.2.1.js' : 'https://code.jquery.com/jquery-3.2.1.min.js'],
                'jsOptions' => ['type' => 'text/javascript'],
            ],
        ],
    ],
],
</code>```

Body:
You don't actually need to use composer for switching to newer jQuery version. By configuring yii\web\JqueryAsset you can override loaded jQuery library at your wish, e.g.

in /config/main.php:

...
'components' => [
    'assetManager' => [
        'bundles' => [
            'yii\web\JqueryAsset' => [
                'js' => [YII_DEBUG ? 'https://code.jquery.com/jquery-3.2.1.js' : 'https://code.jquery.com/jquery-3.2.1.min.js'],
                'jsOptions' => ['type' => 'text/javascript'],
            ],
        ],
    ],
],


问:
MongoDB: How to search array consist nothing outside of specific values?
Let's say that I have a set of data below:

```<code>{_id: "something", array: ["a", "b", "c", "d"]},  // 1
{_id: "something", array: ["a", "b", "d"]},  // 2
{_id: "something", array: ["b", "c", "d"]},  // 3
{_id: "something", array: ["a", "d"]},  // 4
{_id: "something", array: ["a", "b"]},  // 5
{_id: "something", array: ["d"]},  // 6
{_id: "something", array: ["c"]},  // 7
{_id: "something", array: []},  // 8
{_id: "something"},  // 9
{_id: "something", array: ["a", "b", "c", "d", "e", "f", etc...]},  // 10
</code>```

I want to find the documents that have the array consist nothing outside of "a" and "d" in the array. So the wanted output should be 4th, 6th, 8th and 9th from the data. How should I write the query?

Both $in and $nin could not get what I want (as using $nin will require me to input too much possibilities in the query).

Another note, I am using MongoDB v3.2 with Mongoose.

Addon note after receiving answers:

- P.S. In this example, "a" and "d" is just example of 2 exclusion. However in actual implementation, it is a value inserted choosed by user. So it does not limit to 2 exclusion, which could later be "b", "c" and "d", or even more values base on user input.

答:
A quick and dirty solution would be:

```<code>use stackoverflow-example

db.examples.insertMany([{text: "something", array: ["a", "b", "c", "d"]},  // 1)
  {text: "something", array: ["a", "b", "d"]},  // 2
  {text: "something", array: ["b", "c", "d"]},  // 3
  {text: "something", array: ["a", "d"]},  // 4
  {text: "something", array: ["a", "b"]},  // 5
  {text: "something", array: ["d"]},  // 6
  {text: "something", array: ["c"]},  // 7
  {text: "something", array: []},  // 8
  {text: "something"},  // 9
  {text: "something", array: ["a", "b", "c", "d", "e", "f"]}]
)

db.examples.find({
  $or: [{
    $and: [{ array: 'a' }, { array: 'd' }, {array: { $size: 2 }}]
  }, {
    $and: [{ array: 'a' }, {array: { $size: 1 }}]
  }, {
    $and: [{ array: 'd' }, {array: { $size: 1 }}]
  }, {
    array: { $size: 0 }
  }, {
    array: { $exists: false }
  }]
})
</code>```

this returns the required objects. I'm sure a nicer solution can be found

Body:
Let's say that I have a set of data below:

{_id: "something", array: ["a", "b", "c", "d"]},  // 1
{_id: "something", array: ["a", "b", "d"]},  // 2
{_id: "something", array: ["b", "c", "d"]},  // 3
{_id: "something", array: ["a", "d"]},  // 4
{_id: "something", array: ["a", "b"]},  // 5
{_id: "something", array: ["d"]},  // 6
{_id: "something", array: ["c"]},  // 7
{_id: "something", array: []},  // 8
{_id: "something"},  // 9
{_id: "something", array: ["a", "b", "c", "d", "e", "f", etc...]},  // 10

I want to find the documents that have the array consist nothing outside of "a" and "d" in the array. So the wanted output should be 4th, 6th, 8th and 9th from the data. How should I write the query?

Both $in and $nin could not get what I want (as using $nin will require me to input too much possibilities in the query).

Another note, I am using MongoDB v3.2 with Mongoose.

Addon note after receiving answers:

- P.S. In this example, "a" and "d" is just example of 2 exclusion. However in actual implementation, it is a value inserted choosed by user. So it does not limit to 2 exclusion, which could later be "b", "c" and "d", or even more values base on user input.

Body:
A quick and dirty solution would be:

use stackoverflow-example

db.examples.insertMany([{text: "something", array: ["a", "b", "c", "d"]},  // 1)
  {text: "something", array: ["a", "b", "d"]},  // 2
  {text: "something", array: ["b", "c", "d"]},  // 3
  {text: "something", array: ["a", "d"]},  // 4
  {text: "something", array: ["a", "b"]},  // 5
  {text: "something", array: ["d"]},  // 6
  {text: "something", array: ["c"]},  // 7
  {text: "something", array: []},  // 8
  {text: "something"},  // 9
  {text: "something", array: ["a", "b", "c", "d", "e", "f"]}]
)

db.examples.find({
  $or: [{
    $and: [{ array: 'a' }, { array: 'd' }, {array: { $size: 2 }}]
  }, {
    $and: [{ array: 'a' }, {array: { $size: 1 }}]
  }, {
    $and: [{ array: 'd' }, {array: { $size: 1 }}]
  }, {
    array: { $size: 0 }
  }, {
    array: { $exists: false }
  }]
})

this returns the required objects. I'm sure a nicer solution can be found


问:
okio.Base64.encode ArrayIndexOutOfBoundsException why is that even happening?
I noticed such exception in fabric, which is occurring rarely but with every build, 3-5 crashes every week on 2-3 users (from ~500 DAU)
I didn't found any information about such crashes, does anyone knows what causes them?

I've found only one question about such issue but it was deleted as "duplicate" https://stackoverflow.com/questions/45868217/arrayindexoutofboundsexception-trying-to-cache-certificate-list-in-okhttp3

```<code>Fatal Exception: java.lang.ArrayIndexOutOfBoundsException
length=1305; index=1953974520

okio.Base64.encode (Base64.java:137)
okio.Base64.encode (Base64.java:125)
okio.ByteString.base64 (ByteString.java:105)
okhttp3.Cache$Entry.writeCertList (Cache.java:686)
okhttp3.Cache$Entry.writeTo (Cache.java:645)
okhttp3.Cache.put (Cache.java:249)
okhttp3.Cache.access$000 (Cache.java:136)
okhttp3.Cache$1.put (Cache.java:148)
okhttp3.internal.cache.CacheInterceptor.maybeCache (CacheInterceptor.java:173)
okhttp3.internal.cache.CacheInterceptor.intercept (CacheInterceptor.java:143)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:67)
okhttp3.internal.http.BridgeInterceptor.intercept (BridgeInterceptor.java:93)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92)
okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept (RetryAndFollowUpInterceptor.java:124)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:67)
</code>```

UPDATE:

https://github.com/square/okio/issues/325 Okio ticket for this issue
https://issuetracker.google.com/issues/69364976 Google ticket for this issue

UPDATE 2:
was fixed in Android Studio 3.1 Canary 6 Build

答:
It is probably bug in VM at particular devices starting from 8 of November only on Android 5.1.

We have found out that the problem is caused by using dex compiler D8. The solution is to disable it in gradle.properties by this line: android.enableD8=false

Ticket was already created here

Okio issue tracker

It is affecting almost all low cost phones excluding Samsung devices

Body:
I noticed such exception in fabric, which is occurring rarely but with every build, 3-5 crashes every week on 2-3 users (from ~500 DAU)
I didn't found any information about such crashes, does anyone knows what causes them?

I've found only one question about such issue but it was deleted as "duplicate" https://stackoverflow.com/questions/45868217/arrayindexoutofboundsexception-trying-to-cache-certificate-list-in-okhttp3

Fatal Exception: java.lang.ArrayIndexOutOfBoundsException
length=1305; index=1953974520

okio.Base64.encode (Base64.java:137)
okio.Base64.encode (Base64.java:125)
okio.ByteString.base64 (ByteString.java:105)
okhttp3.Cache$Entry.writeCertList (Cache.java:686)
okhttp3.Cache$Entry.writeTo (Cache.java:645)
okhttp3.Cache.put (Cache.java:249)
okhttp3.Cache.access$000 (Cache.java:136)
okhttp3.Cache$1.put (Cache.java:148)
okhttp3.internal.cache.CacheInterceptor.maybeCache (CacheInterceptor.java:173)
okhttp3.internal.cache.CacheInterceptor.intercept (CacheInterceptor.java:143)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:67)
okhttp3.internal.http.BridgeInterceptor.intercept (BridgeInterceptor.java:93)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92)
okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept (RetryAndFollowUpInterceptor.java:124)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:92)
okhttp3.internal.http.RealInterceptorChain.proceed (RealInterceptorChain.java:67)

UPDATE:

https://github.com/square/okio/issues/325 Okio ticket for this issue
https://issuetracker.google.com/issues/69364976 Google ticket for this issue

UPDATE 2:
was fixed in Android Studio 3.1 Canary 6 Build


问:
Wordpress responsive images not picking the right image or orientation
I have created custom image sizes in Wordpress to use with the responsive images plugin wordpress has installed by default. The images sizes i've added are:

```<code>add_image_size('portrait-case-study-xl', 1010, 1514, true);
add_image_size('portrait-case-study-lg', 505, 757, true);
add_image_size('portrait-case-study-md', 415, 622, true);
</code>```

I'm then building the images from PHP using the metabox.io plugin and setting the loaded to be displayed as portrait-case-study-lg. I then load the srcset using the function from metabox.io and i've created my custom sizes where i want the images to change.

```<code>$images = rwmb_meta('su_project-featured-portrait-left', array('limit' => 1,
 'size' => 'portrait-case-study-lg'), $post->ID);

<a href="<?php echo $image['full_url']; ?>" itemprop="contentUrl" data-size="<?php echo $image['width']; ?>x<?php echo $image['height'];?>">
                                    <img class="scene_element scene_element--fadeinup" src="<?php echo $image['url']; ?>" srcset="<?php echo esc_attr($image['srcset']); ?>"
                                    sizes="(max-width:40em) 767px, (min-width: 40.063em) and (max-width: 64em) 455px, (min-width: 64.063em) and (max-width: 90em) 455px, (min-width: 90.063em) 505px, 100vw" itemprop="thumbnail" alt="Image description" >
                                </a>
</code>```

The result looks like this:

```<code><img class="scene_element scene_element--fadeinup"
 src="http://localhost:8888/wp-content/uploads/2017/11/chelsea-sw3-apartment-bedroom-505x757.jpg" srcset="http://localhost:8888/wp-
content/uploads/2017/11/chelsea-sw3-apartment-bedroom-300x200.jpg 300w,
http://localhost:8888/wp-content/uploads/2017/11/chelsea-sw3-apartment-bedroom-768x512.jpg 768w, http://localhost:8888/wp-content/uploads/2017/11/chelsea-sw3-apartment-bedroom-1024x683.jpg 1024w,
http://localhost:8888/wp-content/uploads/2017/11/chelsea-sw3-apartment-bedroom-355x238.jpg 355w, http://localhost:8888/wp-content/uploads/2017/11/chelsea-sw3-apartment-bedroom-955x637.jpg 955w,
 http://localhost:8888/wp-content/uploads/2017/11/chelsea-sw3-apartment-bedroom-940x627.jpg 940w" sizes="(max-width:40em) 767px,
(min-width: 40.063em) and (max-width: 64em) 455px,
(min-width: 64.063em) and (max-width: 90em) 455px,
(min-width: 90.063em) 505px, 100vw" itemprop="thumbnail" alt="Image
description">
</code>```

The problem i have is it's now loading the landscape image with the width and height of 768x512 rather than loading the 505x757 image. Can anyone help me please? I'm very new to responsive images and when i thought i'd cracked it. It then starts to choose the wrong image :(

Thanks in advance.

答: I cracked it. I wasn't adding the custom image sizes into the Wordpress srcset :)</p>

Body:
I have created custom image sizes in Wordpress to use with the responsive images plugin wordpress has installed by default. The images sizes i've added are:

add_image_size('portrait-case-study-xl', 1010, 1514, true);
add_image_size('portrait-case-study-lg', 505, 757, true);
add_image_size('portrait-case-study-md', 415, 622, true);

I'm then building the images from PHP using the metabox.io plugin and setting the loaded to be displayed as portrait-case-study-lg. I then load the srcset using the function from metabox.io and i've created my custom sizes where i want the images to change.

$images = rwmb_meta('su_project-featured-portrait-left', array('limit' => 1,
 'size' => 'portrait-case-study-lg'), $post->ID);

<a href="<?php echo $image['full_url']; ?>" itemprop="contentUrl" data-size="<?php echo $image['width']; ?>x<?php echo $image['height'];?>">
                                    <img class="scene_element scene_element--fadeinup" src="<?php echo $image['url']; ?>" srcset="<?php echo esc_attr($image['srcset']); ?>"
                                    sizes="(max-width:40em) 767px, (min-width: 40.063em) and (max-width: 64em) 455px, (min-width: 64.063em) and (max-width: 90em) 455px, (min-width: 90.063em) 505px, 100vw" itemprop="thumbnail" alt="Image description" >

The result looks like this:

<img class="scene_element scene_element--fadeinup"
 src="http://localhost:8888/wp-content/uploads/2017/11/chelsea-sw3-apartment-bedroom-505x757.jpg" srcset="http://localhost:8888/wp-
content/uploads/2017/11/chelsea-sw3-apartment-bedroom-300x200.jpg 300w,
http://localhost:8888/wp-content/uploads/2017/11/chelsea-sw3-apartment-bedroom-768x512.jpg 768w, http://localhost:8888/wp-content/uploads/2017/11/chelsea-sw3-apartment-bedroom-1024x683.jpg 1024w,
http://localhost:8888/wp-content/uploads/2017/11/chelsea-sw3-apartment-bedroom-355x238.jpg 355w, http://localhost:8888/wp-content/uploads/2017/11/chelsea-sw3-apartment-bedroom-955x637.jpg 955w,
 http://localhost:8888/wp-content/uploads/2017/11/chelsea-sw3-apartment-bedroom-940x627.jpg 940w" sizes="(max-width:40em) 767px,
(min-width: 40.063em) and (max-width: 64em) 455px,
(min-width: 64.063em) and (max-width: 90em) 455px,
(min-width: 90.063em) 505px, 100vw" itemprop="thumbnail" alt="Image
description">

The problem i have is it's now loading the landscape image with the width and height of 768x512 rather than loading the 505x757 image. Can anyone help me please? I'm very new to responsive images and when i thought i'd cracked it. It then starts to choose the wrong image :(

Thanks in advance.


问:
static variables in c
Static variables when declared in a file cannot be accessed from outside the file.
But if we declare a static variable inside a file and a global pointer and then assign the address of the static variable to the pointer and then externing the pointer, it can be accessed.

So is it right saying that static variables can't be accessed directly but it can be accessed indirectly using global pointers and then externing?

答:
The variable cannot be accessed and there will be no name clashing with this variable name and no one will be able to find the symbol of this variable.

But of course you can always access it via a pointer. The whole memory (stack + heap) of the process can be accessed via pointers and there is no way to prevent that.

Using static variable is not a security to prevent access to it from outside a module.

OwnerDisplayName: maddy

Title: static variables in c


问:
Give unique group ID by condition in other columns
I would like to group the rows into groups giving them a unique group ID in a new column group. The rows should be given the same ID if RNAClass and V1 is simlar and diff is less than 10000. E.g. all rows with rRNA and chr1 and diff < 10000 is given ID1.

I though if using interaction

```<code>transform(input, group_ID = as.numeric(interaction(RNAClass, V1, drop=TRUE)))
</code>```

Input:

```<code>   RNAClass    V1       diff
21     rRNA  chr8        122
33     rRNA  chr1       1140
45     rRNA  chr1       1313
68     rRNA  chr8       2222
72     tRNA  chr9       9207
80     tRNA  chr9       5111
72     tRNA  chr9     492407
80     tRNA  chr9      54111
</code>```

Output:

```<code>   RNAClass    V1       diff    group
21     rRNA  chr8        122    ID1
33     rRNA  chr1       1140    ID2
45     rRNA  chr1       1313    ID2
68     rRNA  chr8       2222    ID1
72     tRNA  chr9       9207    ID3
80     tRNA  chr9       5111    ID3
72     tRNA  chr9     492407    ID4
80     tRNA  chr9       5111    ID3
</code>```

答:
A base R option would be to create a logical index 'i1' based on the 'diff' column, paste the 'RNAClass', and 'V1' ('str1'), change the elements in 'str1' based on 'i1' to make it a unique string.  Convert the 'str1' to factor with levels specified as unique values of 'str1', coerce to integer and paste with 'ID'

```<code>i1 <- input$diff >= 10000
str1 <- with(input, paste(RNAClass, V1))
str1[i1] <- paste0(str1[i1], seq_len(sum(i1)))
input$group <- paste0("ID", as.integer(factor(str1, levels = unique(str1))))
input$group
#[1] "ID1" "ID2" "ID2" "ID1" "ID3" "ID3" "ID4" "ID3"
</code>```

Or using dplyr

```<code>library(dplyr)
input %>%
  mutate(group = paste0(RNAClass, V1,  as.integer(diff> 10000)),
         group = paste0("ID", as.integer(factor(group, levels = unique(group)))))
</code>```

NOTE: The last element showed in the 'diff' is taken as '5111' and not '54111'

Body:
I would like to group the rows into groups giving them a unique group ID in a new column group. The rows should be given the same ID if RNAClass and V1 is simlar and diff is less than 10000. E.g. all rows with rRNA and chr1 and diff < 10000 is given ID1.

I though if using interaction

transform(input, group_ID = as.numeric(interaction(RNAClass, V1, drop=TRUE)))

Input:

   RNAClass    V1       diff
21     rRNA  chr8        122
33     rRNA  chr1       1140
45     rRNA  chr1       1313
68     rRNA  chr8       2222
72     tRNA  chr9       9207
80     tRNA  chr9       5111
72     tRNA  chr9     492407
80     tRNA  chr9      54111

Output:

   RNAClass    V1       diff    group
21     rRNA  chr8        122    ID1
33     rRNA  chr1       1140    ID2
45     rRNA  chr1       1313    ID2
68     rRNA  chr8       2222    ID1
72     tRNA  chr9       9207    ID3
80     tRNA  chr9       5111    ID3
72     tRNA  chr9     492407    ID4
80     tRNA  chr9       5111    ID3

Body:
A base R option would be to create a logical index 'i1' based on the 'diff' column, paste the 'RNAClass', and 'V1' ('str1'), change the elements in 'str1' based on 'i1' to make it a unique string.  Convert the 'str1' to factor with levels specified as unique values of 'str1', coerce to integer and paste with 'ID'

i1 <- input$diff >= 10000
str1 <- with(input, paste(RNAClass, V1))
str1[i1] <- paste0(str1[i1], seq_len(sum(i1)))
input$group <- paste0("ID", as.integer(factor(str1, levels = unique(str1))))
input$group
#[1] "ID1" "ID2" "ID2" "ID1" "ID3" "ID3" "ID4" "ID3"

Or using dplyr

library(dplyr)
input %>%
  mutate(group = paste0(RNAClass, V1,  as.integer(diff> 10000)),
         group = paste0("ID", as.integer(factor(group, levels = unique(group)))))

NOTE: The last element showed in the 'diff' is taken as '5111' and not '54111'


问:
Add item into array without push
Trying to do immutable way of pushing an array into existing array but somehow my code is not working.

```<code>function insertItem(array, action) {
  return [
    ...array.slice(0, action.index),
    action.item,
    ...array.slice(action.index)
  ]
}

const ori_arr = [{
  id: 1,
  name: 'james',
  age: 10
}, {
  id: 2,
  name: 'terrance',
  age: 20
}]

console.log(insertItem(ori_arr, {
  action: {
    index: 1,
    item: {
       id: 3,
       name: 'she',
       age: 44
    }
  }
}))
</code>```

possibly wrong at the index part.

答:
Since the object you want to add has a nested property action, you might want to use destructuring to get just the action key as your inserItem function's argument.

const insertItem = (array, { action }) => [
   ...array.slice(0, action.index),
   action.item,
   ...array.slice(action.index),
];

const ori_arr = [{
  id: 1,
  name: 'james',
  age: 10
}, {
  id: 2,
  name: 'terrance',
  age: 20
}]

console.log(insertItem(ori_arr, {
  action: {
    index: 1,
    item: {
       id: 3,
       name: 'she',
       age: 44
    }
  }
}))```
</div>
</div>
</p>

<p><strong>Hovever</strong>, if you'd prefer to avoid <code>destructuring</code>, just change the name of your second argument in the <code>insertItem</code> function for e.g. <code>obj</code> and then just add <code>obj</code> before every <code>action.index</code> in your function:</p>

```const insertItem = (array, obj) => [
   ...array.slice(0, obj.action.index),
   obj.action.item,
   ...array.slice(obj.action.index),
];
```

Title: Add item into array without push

Body:
Trying to do immutable way of pushing an array into existing array but somehow my code is not working.

function insertItem(array, action) {
  return [
    ...array.slice(0, action.index),
    action.item,
    ...array.slice(action.index)
  ]
}

const ori_arr = [{
  id: 1,
  name: 'james',
  age: 10
}, {
  id: 2,
  name: 'terrance',
  age: 20
}]

console.log(insertItem(ori_arr, {
  action: {
    index: 1,
    item: {
       id: 3,
       name: 'she',
       age: 44
    }
  }
}))

possibly wrong at the index part.

Body:
Since the object you want to add has a nested property action, you might want to use destructuring to get just the action key as your inserItem function's argument.

const insertItem = (array, { action }) => [
   ...array.slice(0, action.index),
   action.item,
   ...array.slice(action.index),
];

const ori_arr = [{
  id: 1,
  name: 'james',
  age: 10
}, {
  id: 2,
  name: 'terrance',
  age: 20
}]

console.log(insertItem(ori_arr, {
  action: {
    index: 1,
    item: {
       id: 3,
       name: 'she',
       age: 44
    }
  }
}))

Hovever, if you'd prefer to avoid destructuring, just change the name of your second argument in the insertItem function for e.g. obj and then just add obj before every action.index in your function:

const insertItem = (array, obj) => [
   ...array.slice(0, obj.action.index),
   obj.action.item,
   ...array.slice(obj.action.index),
];