问:
Why do my tensorflow graph weights and biases not change?
the following code runs, but when I print each weight and bias tensors, the fields in it are all zero. I know, I initialized them with zeros, but why doesn't the optimizer work as I expected? Therefore the cost function doesn't change, too. What's the missunderstanding?

Here The Code:

```<code>x = tf.placeholder(tf.float32, [None, 5], name='input')

W = tf.Variable(tf.zeros([5,1]))
b = tf.Variable(tf.zeros([1]))

y = tf.nn.softmax(tf.matmul(x, W) + b)

y_tensor = tf.placeholder(tf.float32, [None, 1],     name='output')
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_tensor
* tf.log(y), reduction_indices=[1]))

optimizer =
 tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

session = tf.Session()
init = tf.global_variables_initializer()
session.run(init)

for i in range(10):
  batch_xs = [dataA[i], dataB[i], dataC[i], dataD[i],
          dataE[i]]]
  batch_ys = [[dataG[i]]]
  session.run(optimizer ,feed_dict={x: batch_xs, y_tensor: batch_ys})
</code>```

答:
I think I found the mistake. The batches are initialized again in every iteraion in the for loop. This causes an array wich does not contain my complete dataset. It contains only 1 field with the given data. So the optimizer can not optize, because the loss funktion consits of only one data field, equivalent to a one dimensional funktion with only on pair of x and y. This funktion has no gradient, because it is a single point! The problem should be solved, when I cut this peace of code

```<code> batch_xs = [dataA[i], dataB[i], dataC[i], dataD[i],
          dataE[i]]]
 batch_ys = [[dataG[i]]]
</code>```

and put it the right way outside the for loop to initialize the batches correctly.

Body:
the following code runs, but when I print each weight and bias tensors, the fields in it are all zero. I know, I initialized them with zeros, but why doesn't the optimizer work as I expected? Therefore the cost function doesn't change, too. What's the missunderstanding?

Here The Code:

x = tf.placeholder(tf.float32, [None, 5], name='input')

W = tf.Variable(tf.zeros([5,1]))
b = tf.Variable(tf.zeros([1]))

y = tf.nn.softmax(tf.matmul(x, W) + b)

y_tensor = tf.placeholder(tf.float32, [None, 1],     name='output')
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_tensor
* tf.log(y), reduction_indices=[1]))

optimizer =
 tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

session = tf.Session()
init = tf.global_variables_initializer()
session.run(init)

for i in range(10):
  batch_xs = [dataA[i], dataB[i], dataC[i], dataD[i],
          dataE[i]]]
  batch_ys = [[dataG[i]]]
  session.run(optimizer ,feed_dict={x: batch_xs, y_tensor: batch_ys})

Body:
I think I found the mistake. The batches are initialized again in every iteraion in the for loop. This causes an array wich does not contain my complete dataset. It contains only 1 field with the given data. So the optimizer can not optize, because the loss funktion consits of only one data field, equivalent to a one dimensional funktion with only on pair of x and y. This funktion has no gradient, because it is a single point! The problem should be solved, when I cut this peace of code

 batch_xs = [dataA[i], dataB[i], dataC[i], dataD[i],
          dataE[i]]]
 batch_ys = [[dataG[i]]]

and put it the right way outside the for loop to initialize the batches correctly.


来源: stackexchange

问:
Selenium implicit and explicit wait, timeout exception element not found
I am new to selenium (but experienced java developer).

I am using something like below:

```<code>WebElement searchBasket = pDriver.findElement(By.xpath("//a[contains(.,'Search&Baskets')]"));
WebElement searchproduct = pDriver.findElement(By.xpath("//a[contains(.,'Search a product')]"));

//if search an agreement is not show up, then click on other menu, then click it back
pWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(.,'Search&Baskets')]")));
pDriver.findElement(By.xpath("//a[contains(.,'Search&Baskets')]")).click();

// click on search an agreement
try {
    pWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(.,'Search&Baskets')]")));
    action = new Actions(pDriver);
    action.moveToElement(searchBasket).build().perform();

    pWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(.,'Search a product')]")));
    searchproduct.click();
} catch (TimeoutException e) {
}
</code>```

where pWait is:

```<code>WebDriverWait wait = new WebDriverWait(driver, 15);
</code>```

however when I run the test case I get below error:

```<code>Unable to locate element: {"method":"xpath","selector":"//a[contains(.,'Search&Baskets')]"}
Command duration or timeout: 4 milliseconds
</code>```

I thought it should have wait atleast 15 seconds before throwing this exception. From the log above it looks like it threw exception only in 4ms.
and i could see on console that as soon as it hit that line, it threw exception.

I have implicit waiting set as 0 and using explicit wait.

Am i missing anything here.

Also, in explicit and implicit wait, is it upto that much time OR exact that much time,
example if I set implicit wait as 10 sec, then does it mean wait for exact 10 sec OR wait upto 10 sec (if element found then proceed, even if element founf on 6th second)

is above same for explicit wait as well?

Please help

答:
ExpectedConditions.elementToBeClickable invokes isDisplayed() and isEnabled() methods on EXISTING WebElement.

You are providing By as a parameter which means, the driver has to find your element first. It failed to do this.

Make sure your element is present by using wait until presenceOfElementLocatedBy(By by).

Example:

```<code>WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.presenceOfElementLocatedBy(By.xpath("//a[contains(.,'Search&Baskets')]")));
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(.,'Search&Baskets')]")));
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am new to selenium (but experienced java developer).

I am using something like below:

WebElement searchBasket = pDriver.findElement(By.xpath("//a[contains(.,'Search&Baskets')]"));
WebElement searchproduct = pDriver.findElement(By.xpath("//a[contains(.,'Search a product')]"));

//if search an agreement is not show up, then click on other menu, then click it back
pWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(.,'Search&Baskets')]")));
pDriver.findElement(By.xpath("//a[contains(.,'Search&Baskets')]")).click();

// click on search an agreement
try {
    pWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(.,'Search&Baskets')]")));
    action = new Actions(pDriver);
    action.moveToElement(searchBasket).build().perform();

    pWait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(.,'Search a product')]")));
    searchproduct.click();
} catch (TimeoutException e) {
}

where pWait is:

WebDriverWait wait = new WebDriverWait(driver, 15);

however when I run the test case I get below error:

Unable to locate element: {"method":"xpath","selector":"//a[contains(.,'Search&Baskets')]"}
Command duration or timeout: 4 milliseconds

I thought it should have wait atleast 15 seconds before throwing this exception. From the log above it looks like it threw exception only in 4ms.
and i could see on console that as soon as it hit that line, it threw exception.

I have implicit waiting set as 0 and using explicit wait.

Am i missing anything here.

Also, in explicit and implicit wait, is it upto that much time OR exact that much time,
example if I set implicit wait as 10 sec, then does it mean wait for exact 10 sec OR wait upto 10 sec (if element found then proceed, even if element founf on 6th second)

is above same for explicit wait as well?

Please help

Body:
ExpectedConditions.elementToBeClickable invokes isDisplayed() and isEnabled() methods on EXISTING WebElement.

You are providing By as a parameter which means, the driver has to find your element first. It failed to do this.

Make sure your element is present by using wait until presenceOfElementLocatedBy(By by).

Example:

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.presenceOfElementLocatedBy(By.xpath("//a[contains(.,'Search&Baskets')]")));
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(.,'Search&Baskets')]")));

ContentLicense: CC BY-SA 3.0


问:
How to debug RED code?
What is the preferred way to debug the RED prog lang code? Is there a RED debugger?</p>

答:
There's no debugger AFAIK, but there are functions that can help you with debugging. Take a look at these two articles, they should help you:

https://github.com/red/red/wiki/Debugging

https://github.com/red/red/wiki/How-to-Debug:-A-use-case-by-@DocKimbel

Basically you should use inbuilt functions like probe, ??, dump4, stack/dump or print-symbol.

You can also turn various debugging info with system/preprocessor/debug?: on, system/view/debug?: on and system/reactivity/debug?: on.

Title: How to debug RED code?


问:
JavaScript not decoding parameter
So from the textarea I take the shortcode %91samurai id="19"%93 it should be [samurai id="19"]:

```<code>var not_decoded_content = jQuery('[data-module_type="et_pb_text_forms_00132547"]')
.find('#et_pb_et_pb_text_form_content').html();
</code>```

But when I try to decode the %91 and %93

```<code>self.content = decodeURI(not_decoded_content);
</code>```

I get the error:

Uncaught URIError: URI malformed

How can i solve this problem?

答:
The string you're trying to decode is not a URI. Use decodeURIComponent() instead.

UPDATE

Hmm, that's not actually the issue, the issues are the %91 and %93.

```<code>encodeURI('[]')
</code>```

gives %5b%5d, it looks like whatever has encoded this string has used the decimal rather than hexadecimal value.

```<code>Decimal 91 = hex 5b
Decimal 93 = hex 5d
</code>```

Trying again with the hex values

```<code>decodeURI('%5bsamurai id="19"%5d') == '[samurai id="19"]'
</code>```

Title: JavaScript not decoding parameter

Body:
So from the textarea I take the shortcode %91samurai id="19"%93 it should be [samurai id="19"]:

var not_decoded_content = jQuery('[data-module_type="et_pb_text_forms_00132547"]')
.find('#et_pb_et_pb_text_form_content').html();

But when I try to decode the %91 and %93

self.content = decodeURI(not_decoded_content);

I get the error:

Uncaught URIError: URI malformed

How can i solve this problem?

Body:
The string you're trying to decode is not a URI. Use decodeURIComponent() instead.

UPDATE

Hmm, that's not actually the issue, the issues are the %91 and %93.

encodeURI('[]')

gives %5b%5d, it looks like whatever has encoded this string has used the decimal rather than hexadecimal value.

Decimal 91 = hex 5b
Decimal 93 = hex 5d

Trying again with the hex values

decodeURI('%5bsamurai id="19"%5d') == '[samurai id="19"]'


问:
AWS Lambda Java return string with slashes
I have problem with returning string from Lambda after

```<code>JSONObject.toString
</code>```

in return i have

```<code>"{\"Key2\":\"Value2\",\"Key1\":\"Value1\"}"
</code>```

instead of

```<code>"{"Key2":"Value2","Key1":"Value1"}"
</code>```

Can somebody explain how to exclude these slashes?

答:
If you really need to remove them ...

```<code>yourstring.replace("\\", "");
</code>```

However, those "stupid slashes" are necessary if you are treating your response as a string, as they escape your " character. Specifically, without those, your compiler would behave as such:

```<code>"{"     // is a string
Key2    // Not known by Java
":"     // is a string
Value2  // Not known by Java
","     // is a string
Key1    // Not known by Java
":"     // is a string
Value1  // Not known by Java
"}"     // is a string
</code>```

By escaping your " character with a backslash, you are mentionning to your compiler that it should not be taken as an end of string nor a begin. Thus, asking it to only take in account the first and last ".

Body:
I have problem with returning string from Lambda after

JSONObject.toString

in return i have

"{\"Key2\":\"Value2\",\"Key1\":\"Value1\"}"

instead of

"{"Key2":"Value2","Key1":"Value1"}"

Can somebody explain how to exclude these slashes?

Body:
If you really need to remove them ...

yourstring.replace("\\", "");

However, those "stupid slashes" are necessary if you are treating your response as a string, as they escape your " character. Specifically, without those, your compiler would behave as such:

"{"     // is a string
Key2    // Not known by Java
":"     // is a string
Value2  // Not known by Java
","     // is a string
Key1    // Not known by Java
":"     // is a string
Value1  // Not known by Java
"}"     // is a string

By escaping your " character with a backslash, you are mentionning to your compiler that it should not be taken as an end of string nor a begin. Thus, asking it to only take in account the first and last ".


问:
Windows reports error when trying to install package using pipenv
I installed pipenv by following the instructions here.  From the Windows command prompt I ran

```<code>pip install --user pipenv
</code>```

which returned the message

```<code>Successfully installed pipenv-5.3.3
</code>```

Now I want to install the requests package using pipenv, so I ran

```<code>pipenv install requests
</code>```

but this returned

```<code>'pipenv' is not recognized as an internal or external command,
operable program or batch file.
</code>```

I have added the path

```<code>C:\Users\Robert\AppData\Roaming\Python\Python35\site-packages
</code>```

to my Windows path environment variable, but I still receive the same error.
How can I install the requests package using pipenv?

EDIT:  As I have remnants of Python 3.5 and Python 3.6 on my system, I'm going to uninstall everything and start anew.  (I've just started learning Python and I want to keep this as simple as possible.)

答:
I have a similar setup and faced a similar problem, but the solution I found was fairly simple. All of my PATH variables were already correct (from Python 3 the Windows Installer automatically does all of this).

The problem

The problem actually arises because of conflicting installations of virtualenv.

Fix

To address this problem you need to simply run the following commands:

First, remove your current version of virtualenv: pip uninstall virtualenv

Then, remove your current version of pipenv: pip uninstall pipenv

When you are asked Proceed (y/n)? just enter y. This will give you a clean slate.

Finally, you can once again install pipenv and its dependencies: pip install pipenv

This will also install the latest version of virtualenv.

Testing if it worked

Just enter pipenv --version in the command prompt and you should see the desired output.

Notes

I know this sounds the mundane, but it is actually the solution for Windows systems. You do not need to modify any of your system environment variables (please do not add site-packages to your environment variables).

Body:
I installed pipenv by following the instructions here.  From the Windows command prompt I ran

pip install --user pipenv

which returned the message

Successfully installed pipenv-5.3.3

Now I want to install the requests package using pipenv, so I ran

pipenv install requests

but this returned

'pipenv' is not recognized as an internal or external command,
operable program or batch file.

I have added the path

C:\Users\Robert\AppData\Roaming\Python\Python35\site-packages

to my Windows path environment variable, but I still receive the same error.
How can I install the requests package using pipenv?

EDIT:  As I have remnants of Python 3.5 and Python 3.6 on my system, I'm going to uninstall everything and start anew.  (I've just started learning Python and I want to keep this as simple as possible.)


问:
Centimeter to pixel
How do I convert centimeter to pixel in c# ?</p>

答:
Length in CM = LenghtPixels * 2.54 / DPI

I think you can get the DPI of every display using WMI, the value you're searching for is in the class Win32_DisplayConfiguration, under the field LogPixe.

Check this link about using WMI to retrieve data: LINK

Title: Centimeter to pixel

ContentLicense: CC BY-SA 2.5


问:
How to do geofencing when app is unresponsive
The new Geofencing API from Google is not triggering any of the events when the app is dead. I tried using PendingIntent.getBroadcast() and PendingIntent.getService() but only being able to get the transition events when the app is opened.

I followed this tutorial from code labs but adapted the code to use the new GeofencingClient

UPDATE

This is how I create the pending intent:

```<code>private PendingIntent getGeofencePendingIntent() {
    if (mGeofencePendingIntent != null) {
        Log.d(TAG, "Pending intent is already there");
        return mGeofencePendingIntent;
    }
    Log.d(TAG, "Creating a new pending intent");

    // In case I'm using Service, the second parameter will be GeoIntentService.class
    Intent mIntent = new Intent(mContext, GeoReceiver.class);

    // In case I'm using Service, the method will be getService(...)
    mGeofencePendingIntent = PendingIntent.getBroadcast(mContext, 0, mIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        return mGeofencePendingIntent;
 }
</code>```

The code inside my GeoReceiver's onReceive method. Somehow the code is similar when using Services inside onHandleIntent method

```<code>@Override
public void onReceive(Context context, Intent intent) {
    Log.d(TAG, "onReceive");
    if (intent == null) {
        Log.e(TAG, "Intent is null");
        return;
    }
    final String action = intent.getAction();
    if (ACTION_ADD_GEOFENCE.equals(action)) {
        GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
        if (geofencingEvent.hasError()) {
            String errMsg = GeofenceExceptionMessages.getErrorString(context, geofencingEvent.getErrorCode());
            Log.e(TAG, "onReceive Error: " + errMsg);
            return;
        }
        int geofenceTransition = geofencingEvent.getGeofenceTransition();
        if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
                    geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {

            List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();

            NotificationHelper helper = new NotificationHelper();

            String geofenceTransitionDetails = helper.getGeofenceTransitionDetails(
                    context,
                    geofenceTransition,
                    triggeringGeofences
            );

            helper.sendNotificaiton(context, geofenceTransitionDetails);
            Log.i(TAG, "onReceive: " + geofenceTransitionDetails);
        }
    } else {
        Log.d(TAG, "Different Action: " + action);
    }
}
</code>```

答:
Geofencing is not working because some devices only allow background services for some whitelist app by default. If your app also has to work like that means you have to enable AutoStart from settings, below code will help you to make user to enable autostart for your app.If AutoStart is enabled, your service will work well in background.

For the better performance of the Phone, some companies will stop all the background services of the app("Some whitelisted App's will only have the permission to do services in background, eg: WhatsApp,Google Apps and well recognized apps.").So If our app also has to work like that means,we have to enable Autostart Services.

AutoStart:

When an Android system boots, it sends out a boot complete event. Android applications can listen and capture this event to take specific actions, such as automatically starting an activity or service.

As of now,there is no way to determine whether AutoStart is enabled or not.
So you can redirect them to settings and tell user to enable it.I'am providing codes for redirecting for most common phone's companies which will kill background service.(Show it to user only for once, manage it using SharedPreference, as i told earlier there is no way to determine whether it is enabled or disabled.)

To Achieve this,

Declare the permission in AndroidManifest.xml. Add the android.permission.RECEIVE_BOOT_COMPLETED permission to your application's manifest file just before the application declaration node:

This is the function code which has to be called.

```<code>private void enableAutoStart() {
    if (Build.BRAND.equalsIgnoreCase("xiaomi")) {
      new MaterialDialog.Builder(MainActivity.this).title("Enable AutoStart")
        .content(
          "Please allow AppName to always run in the background,else our services can't be accessed.")
        .theme(Theme.LIGHT)
        .positiveText("ALLOW")
        .onPositive(new MaterialDialog.SingleButtonCallback() {
          @Override
          public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

            Intent intent = new Intent();
            intent.setComponent(new ComponentName("com.miui.securitycenter",
              "com.miui.permcenter.autostart.AutoStartManagementActivity"));
            startActivity(intent);
          }
        })
        .show();
    } else if (Build.BRAND.equalsIgnoreCase("Letv")) {
      new MaterialDialog.Builder(MainActivity.this).title("Enable AutoStart")
        .content(
          "Please allow AppName to always run in the background,else our services can't be accessed.")
        .theme(Theme.LIGHT)
        .positiveText("ALLOW")
        .onPositive(new MaterialDialog.SingleButtonCallback() {
          @Override
          public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

            Intent intent = new Intent();
            intent.setComponent(new ComponentName("com.letv.android.letvsafe",
              "com.letv.android.letvsafe.AutobootManageActivity"));
            startActivity(intent);
          }
        })
        .show();
    } else if (Build.BRAND.equalsIgnoreCase("Honor")) {
      new MaterialDialog.Builder(MainActivity.this).title("Enable AutoStart")
        .content(
          "Please allow AppName to always run in the background,else our services can't be accessed.")
        .theme(Theme.LIGHT)
        .positiveText("ALLOW")
        .onPositive(new MaterialDialog.SingleButtonCallback() {
          @Override
          public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName("com.huawei.systemmanager",
              "com.huawei.systemmanager.optimize.process.ProtectActivity"));
            startActivity(intent);
          }
        })
        .show();
    } else if (Build.MANUFACTURER.equalsIgnoreCase("oppo")) {
      new MaterialDialog.Builder(MainActivity.this).title("Enable AutoStart")
        .content(
          "Please allow AppName to always run in the background,else our services can't be accessed.")
        .theme(Theme.LIGHT)
        .positiveText("ALLOW")
        .onPositive(new MaterialDialog.SingleButtonCallback() {
          @Override
          public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
            try {
              Intent intent = new Intent();
              intent.setClassName("com.coloros.safecenter",
                "com.coloros.safecenter.permission.startup.StartupAppListActivity");
              startActivity(intent);
            } catch (Exception e) {
              try {
                Intent intent = new Intent();
                intent.setClassName("com.oppo.safe",
                  "com.oppo.safe.permission.startup.StartupAppListActivity");
                startActivity(intent);
              } catch (Exception ex) {
                try {
                  Intent intent = new Intent();
                  intent.setClassName("com.coloros.safecenter",
                    "com.coloros.safecenter.startupapp.StartupAppListActivity");
                  startActivity(intent);
                } catch (Exception exx) {

                }
              }
            }
          }
        })
        .show();
    } else if (Build.MANUFACTURER.contains("vivo")) {
      new MaterialDialog.Builder(MainActivity.this).title("Enable AutoStart")
        .content(
          "Please allow AppName to always run in the background.Our app runs in background else our services can't be accesed.")
        .theme(Theme.LIGHT)
        .positiveText("ALLOW")
        .onPositive(new MaterialDialog.SingleButtonCallback() {
          @Override
          public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
            try {
              Intent intent = new Intent();
              intent.setComponent(new ComponentName("com.iqoo.secure",
                "com.iqoo.secure.ui.phoneoptimize.AddWhiteListActivity"));
              startActivity(intent);
            } catch (Exception e) {
              try {
                Intent intent = new Intent();
                intent.setComponent(new ComponentName("com.vivo.permissionmanager",
                  "com.vivo.permissionmanager.activity.BgStartUpManagerActivity"));
                startActivity(intent);
              } catch (Exception ex) {
                try {
                  Intent intent = new Intent();
                  intent.setClassName("com.iqoo.secure",
                    "com.iqoo.secure.ui.phoneoptimize.BgStartUpManager");
                  startActivity(intent);
                } catch (Exception exx) {
                  ex.printStackTrace();
                }
              }
            }
          }
        })
        .show();
    }
  }
</code>```

Body:
The new Geofencing API from Google is not triggering any of the events when the app is dead. I tried using PendingIntent.getBroadcast() and PendingIntent.getService() but only being able to get the transition events when the app is opened.

I followed this tutorial from code labs but adapted the code to use the new GeofencingClient

UPDATE

This is how I create the pending intent:

private PendingIntent getGeofencePendingIntent() {
    if (mGeofencePendingIntent != null) {
        Log.d(TAG, "Pending intent is already there");
        return mGeofencePendingIntent;
    }
    Log.d(TAG, "Creating a new pending intent");

    // In case I'm using Service, the second parameter will be GeoIntentService.class
    Intent mIntent = new Intent(mContext, GeoReceiver.class);

    // In case I'm using Service, the method will be getService(...)
    mGeofencePendingIntent = PendingIntent.getBroadcast(mContext, 0, mIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        return mGeofencePendingIntent;
 }

The code inside my GeoReceiver's onReceive method. Somehow the code is similar when using Services inside onHandleIntent method

@Override
public void onReceive(Context context, Intent intent) {
    Log.d(TAG, "onReceive");
    if (intent == null) {
        Log.e(TAG, "Intent is null");
        return;
    }
    final String action = intent.getAction();
    if (ACTION_ADD_GEOFENCE.equals(action)) {
        GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
        if (geofencingEvent.hasError()) {
            String errMsg = GeofenceExceptionMessages.getErrorString(context, geofencingEvent.getErrorCode());
            Log.e(TAG, "onReceive Error: " + errMsg);
            return;
        }
        int geofenceTransition = geofencingEvent.getGeofenceTransition();
        if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
                    geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {

            List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();

            NotificationHelper helper = new NotificationHelper();

            String geofenceTransitionDetails = helper.getGeofenceTransitionDetails(
                    context,
                    geofenceTransition,
                    triggeringGeofences
            );

            helper.sendNotificaiton(context, geofenceTransitionDetails);
            Log.i(TAG, "onReceive: " + geofenceTransitionDetails);
        }
    } else {
        Log.d(TAG, "Different Action: " + action);
    }
}

Body:
Geofencing is not working because some devices only allow background services for some whitelist app by default. If your app also has to work like that means you have to enable AutoStart from settings, below code will help you to make user to enable autostart for your app.If AutoStart is enabled, your service will work well in background.

For the better performance of the Phone, some companies will stop all the background services of the app("Some whitelisted App's will only have the permission to do services in background, eg: WhatsApp,Google Apps and well recognized apps.").So If our app also has to work like that means,we have to enable Autostart Services.

AutoStart:

When an Android system boots, it sends out a boot complete event. Android applications can listen and capture this event to take specific actions, such as automatically starting an activity or service.

As of now,there is no way to determine whether AutoStart is enabled or not.
So you can redirect them to settings and tell user to enable it.I'am providing codes for redirecting for most common phone's companies which will kill background service.(Show it to user only for once, manage it using SharedPreference, as i told earlier there is no way to determine whether it is enabled or disabled.)

To Achieve this,

Declare the permission in AndroidManifest.xml. Add the android.permission.RECEIVE_BOOT_COMPLETED permission to your application's manifest file just before the application declaration node:

This is the function code which has to be called.

private void enableAutoStart() {
    if (Build.BRAND.equalsIgnoreCase("xiaomi")) {
      new MaterialDialog.Builder(MainActivity.this).title("Enable AutoStart")
        .content(
          "Please allow AppName to always run in the background,else our services can't be accessed.")
        .theme(Theme.LIGHT)
        .positiveText("ALLOW")
        .onPositive(new MaterialDialog.SingleButtonCallback() {
          @Override
          public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

            Intent intent = new Intent();
            intent.setComponent(new ComponentName("com.miui.securitycenter",
              "com.miui.permcenter.autostart.AutoStartManagementActivity"));
            startActivity(intent);
          }
        })
        .show();
    } else if (Build.BRAND.equalsIgnoreCase("Letv")) {
      new MaterialDialog.Builder(MainActivity.this).title("Enable AutoStart")
        .content(
          "Please allow AppName to always run in the background,else our services can't be accessed.")
        .theme(Theme.LIGHT)
        .positiveText("ALLOW")
        .onPositive(new MaterialDialog.SingleButtonCallback() {
          @Override
          public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {

            Intent intent = new Intent();
            intent.setComponent(new ComponentName("com.letv.android.letvsafe",
              "com.letv.android.letvsafe.AutobootManageActivity"));
            startActivity(intent);
          }
        })
        .show();
    } else if (Build.BRAND.equalsIgnoreCase("Honor")) {
      new MaterialDialog.Builder(MainActivity.this).title("Enable AutoStart")
        .content(
          "Please allow AppName to always run in the background,else our services can't be accessed.")
        .theme(Theme.LIGHT)
        .positiveText("ALLOW")
        .onPositive(new MaterialDialog.SingleButtonCallback() {
          @Override
          public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName("com.huawei.systemmanager",
              "com.huawei.systemmanager.optimize.process.ProtectActivity"));
            startActivity(intent);
          }
        })
        .show();
    } else if (Build.MANUFACTURER.equalsIgnoreCase("oppo")) {
      new MaterialDialog.Builder(MainActivity.this).title("Enable AutoStart")
        .content(
          "Please allow AppName to always run in the background,else our services can't be accessed.")
        .theme(Theme.LIGHT)
        .positiveText("ALLOW")
        .onPositive(new MaterialDialog.SingleButtonCallback() {
          @Override
          public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
            try {
              Intent intent = new Intent();
              intent.setClassName("com.coloros.safecenter",
                "com.coloros.safecenter.permission.startup.StartupAppListActivity");
              startActivity(intent);
            } catch (Exception e) {
              try {
                Intent intent = new Intent();
                intent.setClassName("com.oppo.safe",
                  "com.oppo.safe.permission.startup.StartupAppListActivity");
                startActivity(intent);
              } catch (Exception ex) {
                try {
                  Intent intent = new Intent();
                  intent.setClassName("com.coloros.safecenter",
                    "com.coloros.safecenter.startupapp.StartupAppListActivity");
                  startActivity(intent);
                } catch (Exception exx) {

                }
              }
            }
          }
        })
        .show();
    } else if (Build.MANUFACTURER.contains("vivo")) {
      new MaterialDialog.Builder(MainActivity.this).title("Enable AutoStart")
        .content(
          "Please allow AppName to always run in the background.Our app runs in background else our services can't be accesed.")
        .theme(Theme.LIGHT)
        .positiveText("ALLOW")
        .onPositive(new MaterialDialog.SingleButtonCallback() {
          @Override
          public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
            try {
              Intent intent = new Intent();
              intent.setComponent(new ComponentName("com.iqoo.secure",
                "com.iqoo.secure.ui.phoneoptimize.AddWhiteListActivity"));
              startActivity(intent);
            } catch (Exception e) {
              try {
                Intent intent = new Intent();
                intent.setComponent(new ComponentName("com.vivo.permissionmanager",
                  "com.vivo.permissionmanager.activity.BgStartUpManagerActivity"));
                startActivity(intent);
              } catch (Exception ex) {
                try {
                  Intent intent = new Intent();
                  intent.setClassName("com.iqoo.secure",
                    "com.iqoo.secure.ui.phoneoptimize.BgStartUpManager");
                  startActivity(intent);
                } catch (Exception exx) {
                  ex.printStackTrace();
                }
              }
            }
          }
        })
        .show();
    }
  }


问:
How import a function from another view with Django?
I have this folder hierarchy:

```<code>|---- saga
    |---- core
         |---- views.py
    |---- study_time
         |---- views.py
</code>```

On my study_time/views.py, I have this functions:

```<code>def study_time(request):
    def tasks_subjects(week_day, key):
        #Code here
        return __tasks

    def day_studies(week_day):
        __tasks_subjects = tasks_subjects(week_day, 0)
        #Code here
        return __studies

    return render(request, 'study_time.html', context)
</code>```

On my core/views.py, I need the day_studies() function, so I'm importing like this:

```<code>from saga.study_time.views import day_studies
    def home(request):
        day_progress = day_studies(datetime.date.today().isoweekday())
</code>```

But I'm getting the error:

ImportError: cannot import name 'day_studies'

How can I make this importation? I don't want to reply all code.

答:
You've defined a nested function. That simply isn't visible outside the containing function; in fact, making it invisible from outside is pretty much the only good reason for defining nested functions in Python. Don't do that; move it outside the study_time function.

(Also, don't use double-underscore prefixes like that. They don't make any sense outside a class; and even there you should rarely if ever use them.)

Body:
I have this folder hierarchy:

|---- saga
    |---- core
         |---- views.py
    |---- study_time
         |---- views.py

On my study_time/views.py, I have this functions:

def study_time(request):
    def tasks_subjects(week_day, key):
        #Code here
        return __tasks

    def day_studies(week_day):
        __tasks_subjects = tasks_subjects(week_day, 0)
        #Code here
        return __studies

    return render(request, 'study_time.html', context)

On my core/views.py, I need the day_studies() function, so I'm importing like this:

from saga.study_time.views import day_studies
    def home(request):
        day_progress = day_studies(datetime.date.today().isoweekday())

But I'm getting the error:

ImportError: cannot import name 'day_studies'

How can I make this importation? I don't want to reply all code.


问:
The default XML namespace of the project must be the MSBuild XML namespace
I cloned the ASP.NET Core SignalR Repo locally, and try opening the solution from within the following environment.

IDE

```<code>Microsoft Visual Studio Enterprise 2015
Version 14.0.25431.01 Update 3
Microsoft .NET Framework
Version 4.6.01055
</code>```

DOT NET CLI

```<code>λ dotnet --info
.NET Command Line Tools (1.0.0-preview2-1-003177)

Product Information:
 Version:            1.0.0-preview2-1-003177
 Commit SHA-1 hash:  a2df9c2576

Runtime Environment:
 OS Name:     Windows
 OS Version:  6.1.7601
 OS Platform: Windows
 RID:         win7-x64
</code>```

I end up seeing a lot of these kinds of error messages:

..\Repos\SignalR\src\Microsoft.AspNetCore.SignalR\Microsoft.AspNetCore.SignalR.csproj
  : error  : The default XML namespace of the project must be the
  MSBuild XML namespace. If the project is authored in the MSBuild 2003
  format, please add
  xmlns="http://schemas.microsoft.com/developer/msbuild/2003" to the
   element. If the project has been authored in the old 1.0 or
  1.2 format, please convert it to MSBuild 2003 format.  ..\Repos\SignalR\src\Microsoft.AspNetCore.SignalR\Microsoft.AspNetCore.SignalR.csproj

I want to know how to fix this the correct way.

答: If getting this error trying to build .Net Core 2.0 app on VSTS then ensure your build definition is using the Hosted VS2017 Agent queue.

Body:
I cloned the ASP.NET Core SignalR Repo locally, and try opening the solution from within the following environment.

IDE

Microsoft Visual Studio Enterprise 2015
Version 14.0.25431.01 Update 3
Microsoft .NET Framework
Version 4.6.01055

DOT NET CLI

λ dotnet --info
.NET Command Line Tools (1.0.0-preview2-1-003177)

Product Information:
 Version:            1.0.0-preview2-1-003177
 Commit SHA-1 hash:  a2df9c2576

Runtime Environment:
 OS Name:     Windows
 OS Version:  6.1.7601
 OS Platform: Windows
 RID:         win7-x64

I end up seeing a lot of these kinds of error messages:

..\Repos\SignalR\src\Microsoft.AspNetCore.SignalR\Microsoft.AspNetCore.SignalR.csproj
  : error  : The default XML namespace of the project must be the
  MSBuild XML namespace. If the project is authored in the MSBuild 2003
  format, please add
  xmlns="http://schemas.microsoft.com/developer/msbuild/2003" to the
   element. If the project has been authored in the old 1.0 or
  1.2 format, please convert it to MSBuild 2003 format.  ..\Repos\SignalR\src\Microsoft.AspNetCore.SignalR\Microsoft.AspNetCore.SignalR.csproj

I want to know how to fix this the correct way.


问:
Electron White Flash on every Rendering process
I'm new to Electron JS Framework. Was reading plenty of that, want to know how to solve that one. It's obvious that on loading new html/page or something that redirects to new html file it calls rendering process on each html call. And that's causing that "White Flash" before the new page loads.

Just to be clear, would like to know how to load html files wihout that flash or maybe it's possible to wait on press till rendering process of that page is complete?

Would like to get some help here. Thanks!

Electron version : "electron": "^1.7.9"

答:
Use the ready-to-show event description from from the docs

While loading the page, the ready-to-show event will be emitted when the renderer process has rendered the page for the first time if the window has not been shown yet. Showing the window after this event will have no visual flash

Simple example

```<code>const {BrowserWindow} = require('electron')
let win = new BrowserWindow({show: false})
win.once('ready-to-show', () => {
  win.show()
})
</code>```

Body:
Use the ready-to-show event description from from the docs

While loading the page, the ready-to-show event will be emitted when the renderer process has rendered the page for the first time if the window has not been shown yet. Showing the window after this event will have no visual flash

Simple example

const {BrowserWindow} = require('electron')
let win = new BrowserWindow({show: false})
win.once('ready-to-show', () => {
  win.show()
})


问:
Python 3.6 converting 8 bit binary to decimal
I am making a Python code in Python 3,6 that will prompt the user to input either 2 decimals up to 255 or an 8 bit binary number with the conversion to decimal, getting the user to input the 2 standard decimal numbers is no problem, also the same with getting them to input a binary number, however the once I print the binary conversion, it displays every binary number up to the corresponding number in decimal, lets say I type 11111111, it'd display, 1, 3, 7, 15, 31, etc up to 255

```<code>def add2():

    binary = input('enter a number in binary: ')
    decimal = 0
    for digit in binary:
        decimal= decimal*2 + int(digit)

        print ("This is the decimal equivalent" , decimal,)
</code>```

This is the print result:

That is what my code is and I will attach a picture of what the printed calculation looks like. In the image you can see that it prints 8 times, each bit up to 255, realistically I just want the code to print the corresponding decimal integer, to what bits the user has put in, like for example if they put in 11111111, just print 255.

答: Just take your print() instruction out of your for loop, otherwise it will print every step to your answer.

Body:
I am making a Python code in Python 3,6 that will prompt the user to input either 2 decimals up to 255 or an 8 bit binary number with the conversion to decimal, getting the user to input the 2 standard decimal numbers is no problem, also the same with getting them to input a binary number, however the once I print the binary conversion, it displays every binary number up to the corresponding number in decimal, lets say I type 11111111, it'd display, 1, 3, 7, 15, 31, etc up to 255

def add2():

    binary = input('enter a number in binary: ')
    decimal = 0
    for digit in binary:
        decimal= decimal*2 + int(digit)

        print ("This is the decimal equivalent" , decimal,)

This is the print result:

That is what my code is and I will attach a picture of what the printed calculation looks like. In the image you can see that it prints 8 times, each bit up to 255, realistically I just want the code to print the corresponding decimal integer, to what bits the user has put in, like for example if they put in 11111111, just print 255.


问:
Call childs of parent object siblings

Hi, I'm trying to make my own Pokédex site, but sinds I'm not very good at databases, SQL, PHP and such, I'm doing it in JavaScript, JSON style. While doing this I bumped into a problem: I wanted to refer gen1.gps.Route_1.Exits.South to gen1.gps.Pallet_Town.Title but I didn't know how. Of course I searched the internet for a while first, to find a solution, but I didn't understand it in the context.

```<code>var gen1 = {
  'gps': {
    'Route_1': {
      'Title': 'Route 1',
      'Exits': {
        'North': 0,
        'South': // pallet town link here
      },
    },
    'Pallet_Town': {
      'Title': 'Pallet Town',
      'Exits': {
        'North': /* route 1 here */,
        'South': 0
      }
    }
  }
}
</code>```

I expect to be able to call the gen1.gps.Route_1.Exits.South object to get the Title object of gen1.gps.Pallet_Town.

I haven't debugged anything yet so I have no idea what my errors are or will be.

I hope somebody can help me by posting a useful answer.

答:
You can save a lot of work if you create your object dynamically, like this:

var gen1 = {
  gps: {}
};

function checkPlace(a) {
  if (!gen1.gps[a]) gen1.gps[a] = {};
  if (!gen1.gps[a].Title) gen1.gps[a].Title = a.split("_").join(" ");
  if (!gen1.gps[a].Exits) gen1.gps[a].Exits = {};
}

function connect(a, b, dir) {
  checkPlace(a);
  checkPlace(b);
  if (dir == "ns") {
    gen1.gps[a].Exits.South = gen1.gps[b];
    gen1.gps[b].Exits.North = gen1.gps[a];
  }
  if (dir == "we") {
    gen1.gps[a].Exits.East = gen1.gps[b];
    gen1.gps[b].Exits.West = gen1.gps[a];
  }
}

connect("Route_1", "Pallet_Town", "ns");

console.log(gen1.gps.Route_1.Exits.South.Title);
console.log(gen1.gps);```

Title: Call childs of parent object siblings

Body:
Hi, I'm trying to make my own Pokédex site, but sinds I'm not very good at databases, SQL, PHP and such, I'm doing it in JavaScript, JSON style. While doing this I bumped into a problem: I wanted to refer gen1.gps.Route_1.Exits.South to gen1.gps.Pallet_Town.Title but I didn't know how. Of course I searched the internet for a while first, to find a solution, but I didn't understand it in the context.

var gen1 = {
  'gps': {
    'Route_1': {
      'Title': 'Route 1',
      'Exits': {
        'North': 0,
        'South': // pallet town link here
      },
    },
    'Pallet_Town': {
      'Title': 'Pallet Town',
      'Exits': {
        'North': /* route 1 here */,
        'South': 0
      }
    }
  }
}

I expect to be able to call the gen1.gps.Route_1.Exits.South object to get the Title object of gen1.gps.Pallet_Town.

I haven't debugged anything yet so I have no idea what my errors are or will be.

I hope somebody can help me by posting a useful answer.


问:
Move constructor seemingly not executed
This is my first experiment with C++0x rvalue references and something strange seems to be going on.

In the code sample below the factory function MakeWindow returns a Window object by value. The caller uses it to initialize a Window object. If I understood correctly, this should invoke the move constructor. In order to detect this I throw an exception there. On top of that I disabled the copy constructor:

```<code>#include <iostream>

// Fake WinAPI
typedef void* HWND;
HWND CreateWindow() { return (void*)1; }
void DestroyWindow(HWND) { }
// End WinAPI

// C++ WinAPI Wrapper Library
class Window
{
public:
    Window(HWND inHandle) :
        mHandle(inHandle)
    {
        std::cout << "Window constructor. Handle: " << inHandle << std::endl;
    }

    Window(Window && rhs) :
        mHandle(rhs.mHandle)
    {
        std::cout << "Window move constructor. Handle: " << mHandle << std::endl;
        rhs.mHandle = 0;
        throw 1; // this is my "breakpoint"
    }

    ~Window()
    {
        std::cout << "Window destructor. Handle: " << mHandle << std::endl;
        if (mHandle)
        {
            DestroyWindow(mHandle);
        }
    }

private:
    Window(const Window&);
    Window& operator=(const Window&);

    HWND mHandle;
};

// Factory function
Window MakeWindow()
{
    return Window(CreateWindow());
}

int main()
{

    {
        Window window(MakeWindow());
    }
    std::cout << "Everything is OK." << std::endl;
    return 0;
}
</code>```

However the code runs fine without this exception being thrown. This is the console output:

```<code>Window constructor. Handle: 0x1
Window destructor. Handle: 0x1
Everything is OK.
</code>```

If I comment out the move constructor then compilation fails with the following errors:

```<code>MysteryMove.cpp: In function 'Window MakeWindow()':
MysteryMove.cpp:39:5: error: 'Window::Window(const Window&)' is private
MysteryMove.cpp:49:33: error: within this context
MysteryMove.cpp: In function 'int main()':
MysteryMove.cpp:39:5: error: 'Window::Window(const Window&)' is private
MysteryMove.cpp:57:35: error: within this context
make: *** [all] Error 1
</code>```

It doesn't seem to make sense. Can anyone explain what is going on?

Update

Thanks to @Philipp I learned that move constructors can also be omitted. This is described in §12.8/34 and footnote 124 of the N3126 draft standard.

It is there also mentioned that RVO is only allowed for non-volatile objects. This means I can get around it writing the factory function like this:

```<code>// Factory function
Window MakeWindow()
{
    volatile Window window(CreateWindow());
    return const_cast<Window&&>(window);
}
</code>```

And indeed it works:

```<code>Window constructor. Handle: 0x1
Window move constructor. Handle: 0x1
terminate called after throwing an instance of 'int'
Abort trap
</code>```

答:
Isn’t it obvious? Your code returns a copy of the local temporary Window:

```<code>Window MakeWindow()
{
    return Window(CreateWindow());
}
</code>```

The compiler will in fact optimize this copy away (via return value optimization) – this is why your move constructor is never actually called – but for correctness a copy constructor must still be present.

Title: Move constructor seemingly not executed

Body:
This is my first experiment with C++0x rvalue references and something strange seems to be going on.

In the code sample below the factory function MakeWindow returns a Window object by value. The caller uses it to initialize a Window object. If I understood correctly, this should invoke the move constructor. In order to detect this I throw an exception there. On top of that I disabled the copy constructor:

#include <iostream>

// Fake WinAPI
typedef void* HWND;
HWND CreateWindow() { return (void*)1; }
void DestroyWindow(HWND) { }
// End WinAPI

// C++ WinAPI Wrapper Library
class Window
{
public:
    Window(HWND inHandle) :
        mHandle(inHandle)
    {
        std::cout << "Window constructor. Handle: " << inHandle << std::endl;
    }

    Window(Window && rhs) :
        mHandle(rhs.mHandle)
    {
        std::cout << "Window move constructor. Handle: " << mHandle << std::endl;
        rhs.mHandle = 0;
        throw 1; // this is my "breakpoint"
    }

    ~Window()
    {
        std::cout << "Window destructor. Handle: " << mHandle << std::endl;
        if (mHandle)
        {
            DestroyWindow(mHandle);
        }
    }

private:
    Window(const Window&);
    Window& operator=(const Window&);

    HWND mHandle;
};

// Factory function
Window MakeWindow()
{
    return Window(CreateWindow());
}

int main()
{

    {
        Window window(MakeWindow());
    }
    std::cout << "Everything is OK." << std::endl;
    return 0;
}

However the code runs fine without this exception being thrown. This is the console output:

Window constructor. Handle: 0x1
Window destructor. Handle: 0x1
Everything is OK.

If I comment out the move constructor then compilation fails with the following errors:

MysteryMove.cpp: In function 'Window MakeWindow()':
MysteryMove.cpp:39:5: error: 'Window::Window(const Window&)' is private
MysteryMove.cpp:49:33: error: within this context
MysteryMove.cpp: In function 'int main()':
MysteryMove.cpp:39:5: error: 'Window::Window(const Window&)' is private
MysteryMove.cpp:57:35: error: within this context
make: *** [all] Error 1

It doesn't seem to make sense. Can anyone explain what is going on?

Update

Thanks to @Philipp I learned that move constructors can also be omitted. This is described in §12.8/34 and footnote 124 of the N3126 draft standard.

It is there also mentioned that RVO is only allowed for non-volatile objects. This means I can get around it writing the factory function like this:

// Factory function
Window MakeWindow()
{
    volatile Window window(CreateWindow());
    return const_cast<Window&&>(window);
}

And indeed it works:

Window constructor. Handle: 0x1
Window move constructor. Handle: 0x1
terminate called after throwing an instance of 'int'
Abort trap

Body:
Isn’t it obvious? Your code returns a copy of the local temporary Window:

Window MakeWindow()
{
    return Window(CreateWindow());
}

The compiler will in fact optimize this copy away (via return value optimization) – this is why your move constructor is never actually called – but for correctness a copy constructor must still be present.


问:
How to distinguish negative number from subtraction?
I want to create a very simple math calculator which could give me results of simple equations, like 5*(5-9).

In the first step I split the equation into meaningful tokens, eg.:

```<code>5
*
(
5
-
9
)
</code>```

Now how can I (algorithmically) tell the difference between a negative number (eg. -5) and subtraction (x - 5)?

Edit: I won't have variables (like x) in my equations but I can have functions (like sin, abs).

答: At a high level, if the previous token is something that can be subtracted from then it will be subtraction, otherwise it is negation.</p>

Body:
I want to create a very simple math calculator which could give me results of simple equations, like 5*(5-9).

In the first step I split the equation into meaningful tokens, eg.:

5
*
(
5
-
9
)

Now how can I (algorithmically) tell the difference between a negative number (eg. -5) and subtraction (x - 5)?

Edit: I won't have variables (like x) in my equations but I can have functions (like sin, abs).


问:
Unable to execute githooks on some windows machines
I had compiled a golang code and got a binary out of it. This binary was the pre-commit git hook.
However this git hook does work on some windows machines and it does not work on some windows machines. I use GitBash for running git commands.

I don't know what the issue might be. I did run it on Windows 10 and it worked on one of the machines and didn't work on another one.

答:
Please make sure your script is executable. To check whether the file is executable, run this in your terminal

```<code>ls -l /path/of/file
</code>```

If you find it as non executable, Use this command for making it as an executable.

```<code>chmod +x /path/of/file
</code>```

If you don't know what is ls -l. Please go through here. https://askubuntu.com/a/528433

Body:
Please make sure your script is executable. To check whether the file is executable, run this in your terminal

ls -l /path/of/file

If you find it as non executable, Use this command for making it as an executable.

chmod +x /path/of/file

If you don't know what is ls -l. Please go through here. https://askubuntu.com/a/528433


问:
How to access UI from thread in C++ UWP App?
I have a native C++ multi-threaded console application.
I ported this application into UWP app with minimal change/
now I want to print out text into textbox in UI as there is no console app available in UWP app.

For this, I required access to a text box from a thread.

答:
Call Dispatcher->RunAsync on your TextBox (or your page, or any control on the UI thread you want to access, in order to execute your code on the respective UI thread:</p>

```<code>myTextBox->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal,
    ref new Windows::UI::Core::DispatchedHandler ([this]
{
    myTextBox->Text = "Test";
}));
</code>```

Body:
Call Dispatcher->RunAsync on your TextBox (or your page, or any control on the UI thread you want to access, in order to execute your code on the respective UI thread:

myTextBox->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal,
    ref new Windows::UI::Core::DispatchedHandler ([this]
{
    myTextBox->Text = "Test";
}));


问:
Loop through an array and then move some elements
So, im trying to write a code that will loop through an array and find if that element is in another array, then I'm trying to play with them, as I'm newbie to VBA, some of the code I wrote myself, and some of it I borrow from here (like this fuction below)

To be more clear (as you can see below - link to a screenshot), im looping through column data and looking if each element (in each cell) is on my list to the left. If yes it should extract it next to the data column. But what I wrote so far it is extracting only one of element. I'm not sure where I should add some condition which would work like on the screen below.

https://ibb.co/kn70jb

```<code>Sub Find_other()

Dim i, j, As Integer
Dim splitArray() As String

Set dataSheet = Worksheets("Data")
maxRow = dataSheet.UsedRange.Rows(dataSheet.UsedRange.Rows.Count).Row

Range("A2").Select
List_Array = Range(Selection, Selection.End(xlDown)).Value

For i = 2 To maxRow
    fullVal = dataSheet.Cells(i, 3).Value
    splitArray() = Split(fullVal, "|")
    For j = 0 To UBound(splitArray)
        partVal = splitArray(j)
        If isInArray(partVal, List_Array) = False Then
        Cells(i, 4) = partVal
        End If

    Next j
Next i

End Sub

Function isInArray(ByVal stringToBeFound As String, ByVal arr As Variant) As Boolean
For Each element In arr
    If element = stringToBeFound Then
        isInArray = True
        Exit Function
    End If
Next element
End Function
</code>```

Thanks for any suggestions.

答:
The problem you're having is with

```<code>Cells(i, 4) = partVal
</code>```

This will always put the item it finds into column D, overwriting the previous value each time it finds something new. You can solve this by making a counter variable.

```<code>Dim count As Integer

For i = 2 To maxRow
    fullVal = dataSheet.Cells(i, 3).Value
    splitArray() = Split(fullVal, "|")
    count = 4
    For j = 0 To UBound(splitArray)
        partVal = splitArray(j)
        If isInArray(partVal, List_Array) = False Then
            Cells(i, count) = partVal
            count = count + 1
        End If

    Next j
Next i
</code>```

This should increase the column number any time that it finds a match and reset it back to the start when you begin checking with a new word

Body:
So, im trying to write a code that will loop through an array and find if that element is in another array, then I'm trying to play with them, as I'm newbie to VBA, some of the code I wrote myself, and some of it I borrow from here (like this fuction below)

To be more clear (as you can see below - link to a screenshot), im looping through column data and looking if each element (in each cell) is on my list to the left. If yes it should extract it next to the data column. But what I wrote so far it is extracting only one of element. I'm not sure where I should add some condition which would work like on the screen below.

https://ibb.co/kn70jb

Sub Find_other()

Dim i, j, As Integer
Dim splitArray() As String

Set dataSheet = Worksheets("Data")
maxRow = dataSheet.UsedRange.Rows(dataSheet.UsedRange.Rows.Count).Row

Range("A2").Select
List_Array = Range(Selection, Selection.End(xlDown)).Value

For i = 2 To maxRow
    fullVal = dataSheet.Cells(i, 3).Value
    splitArray() = Split(fullVal, "|")
    For j = 0 To UBound(splitArray)
        partVal = splitArray(j)
        If isInArray(partVal, List_Array) = False Then
        Cells(i, 4) = partVal
        End If

    Next j
Next i

End Sub

Function isInArray(ByVal stringToBeFound As String, ByVal arr As Variant) As Boolean
For Each element In arr
    If element = stringToBeFound Then
        isInArray = True
        Exit Function
    End If
Next element
End Function

Thanks for any suggestions.

Body:
The problem you're having is with

Cells(i, 4) = partVal

This will always put the item it finds into column D, overwriting the previous value each time it finds something new. You can solve this by making a counter variable.

Dim count As Integer

For i = 2 To maxRow
    fullVal = dataSheet.Cells(i, 3).Value
    splitArray() = Split(fullVal, "|")
    count = 4
    For j = 0 To UBound(splitArray)
        partVal = splitArray(j)
        If isInArray(partVal, List_Array) = False Then
            Cells(i, count) = partVal
            count = count + 1
        End If

    Next j
Next i

This should increase the column number any time that it finds a match and reset it back to the start when you begin checking with a new word


问:
Access Class properties inside callback
I'm using this plugin: https://github.com/blinkmobile/cordova-plugin-sketch with Ionic 3.

My last important step is to get the result outside the callback functions to work further with it.

This is my Code:

```<code>anhangArray: Array<{ name: string, value: string }>=[];

  takePhoto() {
  const options: CameraOptions = {
  quality: 100,
  destinationType: this.camera.DestinationType.FILE_URI,
  encodingType: this.camera.EncodingType.JPEG,
  mediaType: this.camera.MediaType.PICTURE,
  correctOrientation: true,
  allowEdit: false,
}

this.camera.getPicture(options).then((imageData) => {

  // imageData is either a base64 encoded string or a file URI
  // If it's base64:
  //base64Image = 'data:image/jpeg;base64,' + imageData;
  //>>> FILE_URI
  this.getSketch(imageData);

}, (err) => {
  // Handle error
});
}

getSketch(src: string) {
window.navigator.sketch.getSketch(this.onSuccess, this.onFail, {
  destinationType: window.navigator.sketch.DestinationType.DATA_URL,
  encodingType: window.navigator.sketch.EncodingType.JPEG,
  inputType: window.navigator.sketch.InputType.FILE_URI,
  inputData: src
});
}

onSuccess(imageData) {
var _mythis = this;
if (imageData == null) { return; }

// do your thing here!
setTimeout(function () {
  if (imageData.indexOf("data:image") >= 0) {
  } else {
    imageData = "data:image/jpeg;base64," + imageData;
  }
  _mythis.anhangArray.push({ name: "anhang_" + parseInt(_mythis.user._kunnr), value: imageData });
  console.log(this.anhang);

}, 0);
}
</code>```

Error: Uncaught TypeError: Cannot read property 'anhangArray' of undefined

答:
Your problem is with window.navigator.sketch.getSketch(). While window.navigator.sketch.getSketch triggers your callback this.onSuccess, that changes scope of your the callback. To solve the issue, you can change the implementation like below.

```<code>getSketch(src: string) {
  window.navigator.sketch.getSketch(imageData => {
    this.onSuccess(imageData);
  }, error => {
    this.onFail(error);
  }, {
    destinationType: window.navigator.sketch.DestinationType.DATA_URL,
    encodingType: window.navigator.sketch.EncodingType.JPEG,
    inputType: window.navigator.sketch.InputType.FILE_URI,
    inputData: src
  });
}
</code>```

Title: Access Class properties inside callback

Body:
I'm using this plugin: https://github.com/blinkmobile/cordova-plugin-sketch with Ionic 3.

My last important step is to get the result outside the callback functions to work further with it.

This is my Code:

anhangArray: Array<{ name: string, value: string }>=[];

  takePhoto() {
  const options: CameraOptions = {
  quality: 100,
  destinationType: this.camera.DestinationType.FILE_URI,
  encodingType: this.camera.EncodingType.JPEG,
  mediaType: this.camera.MediaType.PICTURE,
  correctOrientation: true,
  allowEdit: false,
}

this.camera.getPicture(options).then((imageData) => {

  // imageData is either a base64 encoded string or a file URI
  // If it's base64:
  //base64Image = 'data:image/jpeg;base64,' + imageData;
  //>>> FILE_URI
  this.getSketch(imageData);

}, (err) => {
  // Handle error
});
}

getSketch(src: string) {
window.navigator.sketch.getSketch(this.onSuccess, this.onFail, {
  destinationType: window.navigator.sketch.DestinationType.DATA_URL,
  encodingType: window.navigator.sketch.EncodingType.JPEG,
  inputType: window.navigator.sketch.InputType.FILE_URI,
  inputData: src
});
}

onSuccess(imageData) {
var _mythis = this;
if (imageData == null) { return; }

// do your thing here!
setTimeout(function () {
  if (imageData.indexOf("data:image") >= 0) {
  } else {
    imageData = "data:image/jpeg;base64," + imageData;
  }
  _mythis.anhangArray.push({ name: "anhang_" + parseInt(_mythis.user._kunnr), value: imageData });
  console.log(this.anhang);

}, 0);
}

Error: Uncaught TypeError: Cannot read property 'anhangArray' of undefined

Body:
Your problem is with window.navigator.sketch.getSketch(). While window.navigator.sketch.getSketch triggers your callback this.onSuccess, that changes scope of your the callback. To solve the issue, you can change the implementation like below.

getSketch(src: string) {
  window.navigator.sketch.getSketch(imageData => {
    this.onSuccess(imageData);
  }, error => {
    this.onFail(error);
  }, {
    destinationType: window.navigator.sketch.DestinationType.DATA_URL,
    encodingType: window.navigator.sketch.EncodingType.JPEG,
    inputType: window.navigator.sketch.InputType.FILE_URI,
    inputData: src
  });
}


问:
What does "abstract over" mean?
Often in the Scala literature, I encounter the phrase "abstract over", but I don't understand the intent.  For example, Martin Odersky writes

You can pass methods (or "functions") as parameters, or you can abstract over them. You can specify types as parameters, or you can abstract over them.

As another example, in the "Deprecating the Observer Pattern" paper,

A consequence from our event streams being first-class values is that we can abstract over them.

I have read that first order generics "abstract over types", while monads "abstract over type constructors".  And we also see phrases like this in the Cake Pattern paper.  To quote one of many such examples:

Abstract type members provide flexible way to abstract over concrete types of components.

Even relevant stack overflow questions use this terminology.  "can't existentially abstract over parameterized type..."

So... what does "abstract over" actually mean?

答:
The other answers give already a good idea of what kinds of abstractions exist. Lets go over the quotes one by one, and provide an example:

You can pass methods (or "functions")
  as parameters, or you can abstract
  over them. You can specify types as
  parameters, or you can abstract over
  them.

Pass function as a parameter: List(1,-2,3).map(math.abs(x)) Clearly abs is passed as parameter here. map itself abstracts over a function that does a certain specialiced thing with each list element. val list = List[String]() specifies a type paramter (String). You could write a collection type which uses abstract type members instead: val buffer = Buffer{ type Elem=String }. One difference is that you have to write def f(lis:List[String])... but def f(buffer:Buffer)..., so the element type is kind of "hidden" in the second method.

A consequence from our event streams
  being first-class values is that we
  can abstract over them.

In Swing an event just "happens" out of the blue, and you have to deal with it here and now. Event streams allow you to do all the plumbing an wiring in a more declarative way. E.g. when you want to change the responsible listener in Swing, you have to unregister the old and to register the new one, and to know all the gory details (e.g. threading issues). With event streams, the source of the events becomes a thing you can simply pass around, making it not very different from a byte or char stream, hence a more "abstract" concept.

Abstract type members provide flexible
  way to abstract over concrete types of
  components.

The Buffer class above is already an example for this.

Title: What does "abstract over" mean?


问:
Centos: fn start : mounting none on /sys/kernel/security failed: Permission denied
After installing fn from https://github.com/fnproject/fn

I run "fn start" as root

I get the following error

```<code>[root@localhost my-docker-app]# fn start
sh: overlay: unknown operand
mount: mounting none on /sys/kernel/security failed: Permission denied
Could not mount /sys/kernel/security.
AppArmor detection and --privileged mode might break.
mount: permission denied (are you root?)
time="2017-10-07T09:42:36Z" level=error msg="couldn't ping db" error="unable to open database file" url=/app/data/fn.db
time="2017-10-07T09:42:36Z" level=fatal msg="Error initializing datastore." error="unable to open database file"
2017/10/07 11:42:37 error: proce

ssed finished with error exit status 1
</code>```

any help?

Centos version and fn version

```<code>[root@localhost my-docker-app]# cat /etc/os-release
NAME="CentOS Linux"
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
PRETTY_NAME="CentOS Linux 7 (Core)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:centos:centos:7"
HOME_URL="https://www.centos.org/"
BUG_REPORT_URL="https://bugs.centos.org/"

CENTOS_MANTISBT_PROJECT="CentOS-7"
CENTOS_MANTISBT_PROJECT_VERSION="7"
REDHAT_SUPPORT_PRODUCT="centos"
REDHAT_SUPPORT_PRODUCT_VERSION="7"

[root@localhost my-docker-app]# fn version
Client version: 0.4.7
ERROR: Get http://localhost:8080/version: dial tcp [::1]:8080: getsockopt: connection refused
[root@localhost my-docker-app]#
</code>```

答:
You need to Disable Security-Enhanced Linux (SELinux), Its caused due to this.

Issue the below command as root for temporaryly disable selinux

$ setenforce 0

OR

vi /etc/sysconfig/selinux

Change the value of SELINUX as below

SELINUX=disabled

reboot

Body:
After installing fn from https://github.com/fnproject/fn

I run "fn start" as root

I get the following error

[root@localhost my-docker-app]# fn start
sh: overlay: unknown operand
mount: mounting none on /sys/kernel/security failed: Permission denied
Could not mount /sys/kernel/security.
AppArmor detection and --privileged mode might break.
mount: permission denied (are you root?)
time="2017-10-07T09:42:36Z" level=error msg="couldn't ping db" error="unable to open database file" url=/app/data/fn.db
time="2017-10-07T09:42:36Z" level=fatal msg="Error initializing datastore." error="unable to open database file"
2017/10/07 11:42:37 error: proce

ssed finished with error exit status 1

any help?

Centos version and fn version

[root@localhost my-docker-app]# cat /etc/os-release
NAME="CentOS Linux"
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
PRETTY_NAME="CentOS Linux 7 (Core)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:centos:centos:7"
HOME_URL="https://www.centos.org/"
BUG_REPORT_URL="https://bugs.centos.org/"

CENTOS_MANTISBT_PROJECT="CentOS-7"
CENTOS_MANTISBT_PROJECT_VERSION="7"
REDHAT_SUPPORT_PRODUCT="centos"
REDHAT_SUPPORT_PRODUCT_VERSION="7"

[root@localhost my-docker-app]# fn version
Client version: 0.4.7
ERROR: Get http://localhost:8080/version: dial tcp [::1]:8080: getsockopt: connection refused
[root@localhost my-docker-app]#


问:
How do I see the commands issued by cmake with --build option
How could I see the commands issued when I run "cmake --build . --target INSTALL" command? There doesn't seem to be an option like --versbose or something. The cmake help says that "cmake --build" is an interface to the underlying build tool, but doesn't say anything about the dump of commands issued.

The reason I need this is because, when I try to run msbuild on commandline, it fails with an error saying the target INSTALL doesn't exist in the project. However, cmake succeeds. So, I guess, cmake also might be using msbuild itself, albeit with some specific options.

答:
you can found the solution at:

https://cmake.org/Wiki/CMake_FAQ

On Windows (nmake) you can override CMAKE_VERBOSE_MAKEFILE by using
nmake /S
If you actually want to see what the command looks like, set CMAKE_START_TEMP_FILE and CMAKE_END_TEMP_FILE to "" -- be warned, however, you cannot set these as variables on the CMake command line with -D. Instead, see the very bottom of the file "Modules/Platform/Windows.cmake" and uncomment the lines that set these variables to the empty string.


问:
DoCmd.PrintOut does only Print one copy
I saw that there is a similar question as mine but the workaround that is given there is not a possible way for me.
I have to print up to 1000 or more.

```<code> DoCmd.OpenReport Report, acViewReport 'Open report
 DoCmd.PrintOut , , , acHigh, copys' Print report
</code>```

(As copys I have specified the amount of copys.)

Did I do something wrong?

Is there an other way to print the Report out?

Thanks for any help.

complete Code:

```<code>Private Sub cmd_openreport_Click()

'Set Variables
Dim Report
Dim Etikette
Dim Copyes As String
Dim SQLString
Dim SQLString2

DoCmd.SetWarnings False 'Turns Off Warnings

Etikette = comb_etiketten_auswahl 'Etikette Equals the             comb_etiketten_auswahl value
Report = comb_etiketten_layout 'Report equals the value in the dropdown list
Copyes = Forms!frm_Hauptmenu!comb_etiketten_auswahl.Column(1)

'If The Etiketten Dropdown is empty message to client
If Etikette <> "" Then

'Do Nothing/Continue

Else
MsgBox "Bitte wählen Sie einen Datensatz aus"
Exit Sub

End If

'If The Report Dropdown is empty message to client
If Report <> "" Then

'Do Nothing (because dropdown is mot empty)

Else
MsgBox "Bitte wählen Sie ein Etikettenlayout aus"
Exit Sub

End If

MsgBox anzahl
'If Amount of copies is less than 1 message to client
If anzahl > 0 Then

On Error GoTo Error_MayCauseAnError
    DoCmd.OpenReport Report, acViewReport 'Open report
    DoCmd.PrintOut , , , , Copyes
    DoCmd.Close Report ' Close the Report
</code>```

EDIT :

This question is Irelevant and does not have a purpose anymore!
it was an internal script mistake!

答:
Did you declared copyes as Variant?

Reading PrintOut documentation, I found the following:

Name    Copies

Required/Optional   Optional

Data Type   Variant

Description  The number of copies to print. If you leave this argument blank, the default (1) is assumed.

https://msdn.microsoft.com/en-us/vba/access-vba/articles/docmd-printout-method-access

Also, try using a value instead of a variable just for testing.

When you use functions is really important to read the function documentation, to know what kind of variables this function (or procedure) expects.
In this case, this function uses a Variant variable (Don't know why), then you should provide a Variant object.
Let me give you an example.

You have a drink machine.
Let's think about money in terms of variants. paper and metal.
Your drink machine only accepts paper as money. If you try to insert metal (coins), your machine will give an error.
In this case you need to provide the specific kind of money that your drink machine accepts.

Hope this clarifications let you understand better the issue and help you to read the documentation of the functions or procedure you are using.

Title: DoCmd.PrintOut does only Print one copy

Body:
I saw that there is a similar question as mine but the workaround that is given there is not a possible way for me.
I have to print up to 1000 or more.

 DoCmd.OpenReport Report, acViewReport 'Open report
 DoCmd.PrintOut , , , acHigh, copys' Print report

(As copys I have specified the amount of copys.)

Did I do something wrong?

Is there an other way to print the Report out?

Thanks for any help.

complete Code:

Private Sub cmd_openreport_Click()

'Set Variables
Dim Report
Dim Etikette
Dim Copyes As String
Dim SQLString
Dim SQLString2

DoCmd.SetWarnings False 'Turns Off Warnings

Etikette = comb_etiketten_auswahl 'Etikette Equals the             comb_etiketten_auswahl value
Report = comb_etiketten_layout 'Report equals the value in the dropdown list
Copyes = Forms!frm_Hauptmenu!comb_etiketten_auswahl.Column(1)

'If The Etiketten Dropdown is empty message to client
If Etikette <> "" Then

'Do Nothing/Continue

Else
MsgBox "Bitte wählen Sie einen Datensatz aus"
Exit Sub

End If

'If The Report Dropdown is empty message to client
If Report <> "" Then

'Do Nothing (because dropdown is mot empty)

Else
MsgBox "Bitte wählen Sie ein Etikettenlayout aus"
Exit Sub

End If

MsgBox anzahl
'If Amount of copies is less than 1 message to client
If anzahl > 0 Then

On Error GoTo Error_MayCauseAnError
    DoCmd.OpenReport Report, acViewReport 'Open report
    DoCmd.PrintOut , , , , Copyes
    DoCmd.Close Report ' Close the Report

EDIT :

This question is Irelevant and does not have a purpose anymore!
it was an internal script mistake!


问:
ChartJS with AngularJS
How do I show canvas element inside custom angular directives?

I am very new to angularjs. Please get me any demo/idea about chartjs with angularjs.

Note: I want custom directive to show charts

This is what i tried in js->

```<code>var demo = angular.module('newchart');

demo.directive('chartdiv', function() {
    return {
        restrict: 'E',
        template: '<canvas id="chartNew" class="chart chart-line col-md-12 col-sm-12" chart-data="chartData" chart-labels="chartLbl" chart-series="chartseries" width="700" height="280" chart-colors="colr_nofill" chart-options="chartopt"></canvas>'
    };
});
</code>```

答:
In directive you can't access the scope variable of particular controllers.To know about scope access directive try this https://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-2-isolate-scope

You can also try the below code

```<code>demo.directive('chartdiv', function() {

return {
transclude: true,
restrict: 'E',
 scope: {
            chartLbl: "@",
            chartseries:"@",
            chartopt:"@",
            chartData:"@",
            colr_nofill:"@",

    },
template: '<canvas id="chartNew"
chart-data="chartData" chart-labels="chartLbl" chart-series="chartseries"
width="700" height="280" chart-colors="colr_nofill" chart-
options="chartopt">
</canvas>'

    link: function(scope){
    /*You can add css class here */
    chartNew.addClass("chart");
    }
};
});
</code>```

In HTML you can pass the angularjs scope data in a variable on custom directive tag and get it in directive and use it in the template.

```<code><chart chartData="{{chart_chartData}}"
chartLbl="{{chart_chartLbl}}" chartopt="{{chart_chartopt}}"
colr_nofill="{{chart_colr_nofill}}"
chartseries="{{chart_chartseries}}">
</chart>
</code>```

Title: ChartJS with AngularJS

Body:
How do I show canvas element inside custom angular directives?

I am very new to angularjs. Please get me any demo/idea about chartjs with angularjs.

Note: I want custom directive to show charts

This is what i tried in js->

var demo = angular.module('newchart');

demo.directive('chartdiv', function() {
    return {
        restrict: 'E',
        template: '<canvas id="chartNew" class="chart chart-line col-md-12 col-sm-12" chart-data="chartData" chart-labels="chartLbl" chart-series="chartseries" width="700" height="280" chart-colors="colr_nofill" chart-options="chartopt"></canvas>'
    };
});

Body:
In directive you can't access the scope variable of particular controllers.To know about scope access directive try this https://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-2-isolate-scope

You can also try the below code

demo.directive('chartdiv', function() {

return {
transclude: true,
restrict: 'E',
 scope: {
            chartLbl: "@",
            chartseries:"@",
            chartopt:"@",
            chartData:"@",
            colr_nofill:"@",

    },
template: '<canvas id="chartNew"
chart-data="chartData" chart-labels="chartLbl" chart-series="chartseries"
width="700" height="280" chart-colors="colr_nofill" chart-
options="chartopt">
</canvas>'

    link: function(scope){
    /*You can add css class here */
    chartNew.addClass("chart");
    }
};
});

In HTML you can pass the angularjs scope data in a variable on custom directive tag and get it in directive and use it in the template.

<chart chartData="{{chart_chartData}}"
chartLbl="{{chart_chartLbl}}" chartopt="{{chart_chartopt}}"
colr_nofill="{{chart_colr_nofill}}"
chartseries="{{chart_chartseries}}">
</chart>


问:
Ruby Datamapper connection with SSL to MariaDB on Amazon RDS
How do I establish a ruby Datamapper connection to MariaDB on Amazon RDS with SSL?

Here's what I did:

A non-SSL connection works when testing with:

uri = 'mysql://user:pass@host:port/db_name'
connection = DataObjects::Connection.new(uri)
=> #<DataObjects::Mysql::Connection:0x000056179a3a5921

connection.secure?
=> false
```

<p>According to the MySQL datamapper wiki, an ssl connection requires the following options: <code>:ssl_ca, :client_key, and :client_cert</code>.</p>

<p>This would result in the following code:</p>

<pre class="lang-rb prettyprint-override"><code>uri = 'mysql://user:pass@host:port/db_name?'
ssl_opts = 'ssl[ssl_ca]=file&ssl[client_key]=file&ssl[client_cert]=file'

connection = DataObjects::Connection.new(uri + ssl_opts)
connection.secure?
=> false
</code>```

However the only files get is the RDS combind CA bundle, refered from the RDS docs

I do not have a client_cert at all.

Connecting with the mysql client on cli works with SSL:

```<code>mysql --ssl -h host -u user -p pass db_name
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 1638
Server version: 10.1.26-MariaDB MariaDB Server
</code>```

答:
In doc

https://github.com/datamapper/do/wiki/MySQL

It also says

as tested only ca_cert was required to connect to RDS.

So try adding only ca_cert path and do a test

Body:
How do I establish a ruby Datamapper connection to MariaDB on Amazon RDS with SSL?

Here's what I did:

A non-SSL connection works when testing with:

uri = 'mysql://user:pass@host:port/db_name'
connection = DataObjects::Connection.new(uri)
=> #<DataObjects::Mysql::Connection:0x000056179a3a5921

connection.secure?
=> false

According to the MySQL datamapper wiki, an ssl connection requires the following options: :ssl_ca, :client_key, and :client_cert.

This would result in the following code:

uri = 'mysql://user:pass@host:port/db_name?'
ssl_opts = 'ssl[ssl_ca]=file&ssl[client_key]=file&ssl[client_cert]=file'

connection = DataObjects::Connection.new(uri + ssl_opts)
connection.secure?
=> false

However the only files get is the RDS combind CA bundle, refered from the RDS docs

I do not have a client_cert at all.

Connecting with the mysql client on cli works with SSL:

mysql --ssl -h host -u user -p pass db_name
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 1638
Server version: 10.1.26-MariaDB MariaDB Server


问:
Xamarin Forms error while writing anim R$anim.class
Hello i am update to visual studio community 2017 15.5 on debug i have this error</p>

```<code>obj\Debug\android\src\android\support\compat\R.java:11: error: error while writing anim: obj\Debug\android\bin\classes\android\support\compat\R$anim.class (El proceso no tiene acceso al archivo porque est├í siendo utilizado por otro proceso)
3>      public static final class anim {
3>                          ^
3>  Note: Some input files use or override a deprecated API.
3>  Note: Recompile with -Xlint:deprecation for details.
3>  Note: Some input files use unchecked or unsafe operations.
3>  Note: Recompile with -Xlint:unchecked for details.
3>  1 error
</code>```

答:
I can confirm that I am seeing the same error after the VS2017 15.5 upgrade. It appears that this issue has been filed with Xamarin support here.

I am running a Xamarin Forms app. While restarting VS does appear to resolve the issue, I am unable to deploy in debug mode. Even after a restart, when the app is deployed/launched into a device or emulator, it crashes immediately. However, the application can be launched in Release mode successfully.

Still searching for a fix. In the meantime, building a new dev VM with the 15.4 version of VS (available for download here).

Body:
Hello i am update to visual studio community 2017 15.5 on debug i have this error

obj\Debug\android\src\android\support\compat\R.java:11: error: error while writing anim: obj\Debug\android\bin\classes\android\support\compat\R$anim.class (El proceso no tiene acceso al archivo porque est├í siendo utilizado por otro proceso)
3>      public static final class anim {
3>                          ^
3>  Note: Some input files use or override a deprecated API.
3>  Note: Recompile with -Xlint:deprecation for details.
3>  Note: Some input files use unchecked or unsafe operations.
3>  Note: Recompile with -Xlint:unchecked for details.
3>  1 error


问:
Reference type of JVM
In some Java literature, The statement

The reference type of the Java virtual
  machine is cleverly named
  reference

is widely popular. However, authors tend not to explain more why such statement is valid. Another thing that would make me understand this more is

What does the reference type of the JVM means ? Does the JVM represent itself in the heap ?

Would appreciate a lot an explanation on this statement.

Thank you,

Ashmawy

答:
I think the cleverly part relates to the fact that a reference type is typically called a pointer, which necessitates the reader to learn two terms. The JVM terminology simply uses the term reference for this.

There's also a historical context.

When Java was introduced, its biggest competitor was C++. C++'s main problem was that it was deemed to be too difficult. Java initially positioned itself as the easy alternative to C++. It had a syntax very close to C++, but all the difficult stuff (operator overloading, templates, multiple pass-by mechanisms) etc were removed from the language.

And now comes the catch...

Java was initially marketed as not having pointers. The rationale for saying this was that pointers were deemed the most difficult thing of C++, so if Java would not have them, it had to be a simpler language.

The clever part thus comes from simply inventing another term for 'pointer'. Call them reference and you can state Java does not have pointers (but references).

This has lead to many debates and caused a good amount of confusion, especially since C++ already had the term 'reference' and uses it for something else (though conceptually a little related). The debate usually centers around two camps where one of them claims Java indeed does not have pointers, since you can't do pointer arithmetic with them and they don't directly represent memory addresses, while the other camp states that you don't have to be able to do arithmetic with a pointer to call it a pointer.

Put differently, whether it was clever to use the term reference is still open for debate.

Title: Reference type of JVM


问:
SAP business one and HANA studio
Good day, I have a trouble in SAP. I have to make automatic update World Exchanges currency in SAP studio. I can't ceate add on due it too. What can I do?</p>

答: Create your add-on and make it execute the method "update automatic exchanges" on start. From the add-on manager make the add-on start automatically. So when the b1 client is opened the add-on will start and execute your method. </p>

Title: SAP business one and HANA studio


问:
WordPress Custom php line code
I would like to add a small line of php to a post that already exists in WordPress im aded the code but after im publish it the code automatically convert to comment :

this that im add :

and this what i get :

答:
You can use the shortcodes, add some lines to the file functions then use the shortcode into your post

```<code>add_shortcode( 'php_code', function(){
echo "hello world";
} );
</code>```

then use the [php_code] into your post

Title: WordPress Custom php line code

Body:
You can use the shortcodes, add some lines to the file functions then use the shortcode into your post

add_shortcode( 'php_code', function(){
echo "hello world";
} );

then use the [php_code] into your post


问:
store positive number and negative in different vector
I am new to c++. I have a vector with size n. I want to search in the vector ad store positive and negative values in the new vectors. I don't know the number of positive and negative values.

Can anyone help me?

答:
A variation of @Shos's answer, involving less pointers, which might be easier to read:</p>

```<code>using std::vector;
vector<int> pos, neg;

for (auto& el : v)
{
    if (el >= 0)
        pos.push_back(el);
    else
        neg.push_back(el);
}
</code>```

Body:
A variation of @Shos's answer, involving less pointers, which might be easier to read:

using std::vector;
vector<int> pos, neg;

for (auto& el : v)
{
    if (el >= 0)
        pos.push_back(el);
    else
        neg.push_back(el);
}


问:
mappings on vim throwing an error (E10: \ should be followed by /, ? or &)
Hi I'm using MacVim 7.3
I'm following a PeepCode tutorial called smash into vim.

One of the topics is to assign various "mappings" (I think of them as shortcuts or aliases) for certain commands.

For example, here is part of my .vimrc file (see below)
The help files say that  is assigned as backslash (\) by default.  However, when I enter command-line mode and type :\tt I get the following error:

E10: \ should be followed by /, ? or &

Any thoughts on what I'm doing wrong?  I can tell that my .vimrc file is being used by macvim b/c I used the file to swap the semi-colon and colon bindings and now ; will cause the editor to enter command-line mode.

```<code>" Tab mappings.
map <leader>tt :tabnew<cr>
map <leader>te :tabedit
map <leader>tc :tabclose<cr>
map <leader>to :tabonly<cr>
map <leader>tn :tabnext<cr>
map <leader>tp :tabprevious<cr>
map <leader>tf :tabfirst<cr>
map <leader>tl :tablast<cr>
map <leader>tm :tabmove

" Controversial...swap colon and semicolon for easier commands
nnoremap ; :
nnoremap : ;

vnoremap ; :
vnoremap : ;
</code>```

答: You have two problems: one is that you are using map and then remap semicolon, so map <leader>tt :tabnew<CR> tries to execute ;tabnew<CR> (; repeats previous t/T/f/F motion, ta moves cursor to next a, n tries to repeat previous search and so on) and it won't work. You should use noremap where possible, do not use map without nore unless you know what you are doing (and I also suggest changing noremap to nnoremap here: I don't think you need to change tabs from visual and, especially, operator-pending modes). Second problem is that noremap remaps commands in normal mode, so you need to type \tt, not :\tt or ;\tt.

Body:
Hi I'm using MacVim 7.3
I'm following a PeepCode tutorial called smash into vim.

One of the topics is to assign various "mappings" (I think of them as shortcuts or aliases) for certain commands.

For example, here is part of my .vimrc file (see below)
The help files say that  is assigned as backslash (\) by default.  However, when I enter command-line mode and type :\tt I get the following error:

E10: \ should be followed by /, ? or &

Any thoughts on what I'm doing wrong?  I can tell that my .vimrc file is being used by macvim b/c I used the file to swap the semi-colon and colon bindings and now ; will cause the editor to enter command-line mode.

" Tab mappings.
map <leader>tt :tabnew<cr>
map <leader>te :tabedit
map <leader>tc :tabclose<cr>
map <leader>to :tabonly<cr>
map <leader>tn :tabnext<cr>
map <leader>tp :tabprevious<cr>
map <leader>tf :tabfirst<cr>
map <leader>tl :tablast<cr>
map <leader>tm :tabmove

" Controversial...swap colon and semicolon for easier commands
nnoremap ; :
nnoremap : ;

vnoremap ; :
vnoremap : ;


问:
Sharepoint list content from parent site to subsite
I have a list with multiple records in it. I want to filter some records from the list and display it on subsite web page. I goggled it and I found out that there is no direct way to use the list from parent site into subsite. I am using Sharepoint 2013 and I have full control access to site.</p>

答:
You have two options to display a SharePoint list from Parent site in a subsite:

Using Data View Web Part.

Using Content Query Web Part.

Check the details steps at

How to display a sharepoint list from parent site in subsite?

SP 2016 - Display list from Parent site in sub-site


问:
How to assign players to teams in a game
I'm creating a game with different participants that belong to different teams.
I having trouble assigned the players to the teams.
The players exist in an ArrayList, and i have created lists for each of the teams as well, but is it even possible to assign an element of one list to another list? So that the player exists in both lists?
Thanks </p>

答:
The list object contains an array of methods for adding and removing elements from lists: https://docs.oracle.com/javase/7/docs/api/java/util/List.html

I'd suggest something like :
teamList.add(playerList.get(playerIndex))

where playIndex is an integer of the player you want to add to the team. Assuming your players and teams are the same object type, the above code will retrieve a player from the player list and add that player to your team list.


问:
SLES 12 syntax error: '=~' unexpected operator/operand
i have developed a bigger script for SLES11 and everything is running fine.
But with SLES12 there are some syntax errors when starting the script.

ERROR: syntax error: '=~' unexpected operator/operand

```<code>#!/bin/ksh

while [[ ! $BIGTAB =~ ^-?[0-9* ]+$ ]] || [[ ! $BIGTAB -ge 1 ]]; do
echo "  Enter number of tables to display:"
read BIGTAB
...
</code>```

=~ seems to be not supported any more!?
Could you give me help, how to replace the syntax for SLES12 (and still also running under SLES11).

Thank you!

答:
I don't have SLES12 to test it, but it seems your problem is not the =~ operator, but your operand (it has one space in the middle of the regular expression).

Try this:

```<code>[[ ! $BIGTAB =~ ^-?[0-9]+$ ]]
</code>```

Body:
i have developed a bigger script for SLES11 and everything is running fine.
But with SLES12 there are some syntax errors when starting the script.

ERROR: syntax error: '=~' unexpected operator/operand

#!/bin/ksh

while [[ ! $BIGTAB =~ ^-?[0-9* ]+$ ]] || [[ ! $BIGTAB -ge 1 ]]; do
echo "  Enter number of tables to display:"
read BIGTAB
...

=~ seems to be not supported any more!?
Could you give me help, how to replace the syntax for SLES12 (and still also running under SLES11).

Thank you!

Body:
I don't have SLES12 to test it, but it seems your problem is not the =~ operator, but your operand (it has one space in the middle of the regular expression).

Try this:

[[ ! $BIGTAB =~ ^-?[0-9]+$ ]]


问:
Hibernate package scan in JavaConfig
I'm trying to configure Spring and Hibernate without xml. Here's my SessionFactory bean. When I add annotated class to configuration - it works properly. I want to do it automatically, but adding a package to configuration doesnt helps for some reason, I get "Identificator is not mapped" error</p>

```<code>    @Bean
public SessionFactory sessionFactory(){
    Properties hibernateProperties = new Properties();
    hibernateProperties.put("hibernate.connection.driver_class",ds_driver);
    hibernateProperties.put("hibernate.connection.url",ds_url);
    hibernateProperties.put("hibernate.connection.username",ds_username);
    hibernateProperties.put("hibernate.connection.password",ds_password);
    hibernateProperties.put("hibernate.show_sql", false);
    hibernateProperties.put("connection.pool_size", 1);
    hibernateProperties.put("current_session_context_class", "thread");
    hibernateProperties.put("hibernate.hbm2ddl.auto", "update");

    org.hibernate.cfg.Configuration configuration = new org.hibernate.cfg.Configuration();
    configuration.addPackage("app.entity"); // **doesnt work**
    configuration.addAnnotatedClass(Identificator.class); // **works fine**
    configuration.addProperties(hibernateProperties);

    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

    return sessionFactory;
}
</code>```

答:
```<code>   public SessionFactory getSessionFactory() {
    if (sessionFactory == null) {
        Configuration configuration = new Configuration()
                .configure(getMappedValue("Universal", "qb_hibernate"))
                .setProperty("hibernate.connection.autocommit", "true")
                .setProperty("connection.pool_size", "20000")
                .setProperty("hibernate.dialect", getMappedValue("Universal", "dialect"))
                .setProperty("hibernate.connection.driver_class", getMappedValue("Universal", "driver_class"))
                .setProperty("hibernate.connection.url", getMappedValue("Universal", "url"))
                .setProperty("hibernate.connection.username", getMappedValue("Universal", "userName"))
                .setProperty("hibernate.connection.password", getMappedValue("Universal", "password"))
                .setProperty("hibernate.show_sql", "false")
                .setProperty("hibernate.current_session_context_class", "thread")
                .setProperty("hibernate.query.factory_class", "org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory");
        ServiceRegistry serviceRegistry
                = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties()).build();
        LocalSessionFactoryBuilder builder
                = new LocalSessionFactoryBuilder(dataSource());
        builder.scanPackages("zw.co.techno.xxxxx.model").buildSettings(serviceRegistry);
        // builds a session factory from the service registry
        // sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        sessionFactory = builder.buildSessionFactory();
    }
    return sessionFactory;
}
</code>```

Title: Hibernate package scan in JavaConfig

Body:
I'm trying to configure Spring and Hibernate without xml. Here's my SessionFactory bean. When I add annotated class to configuration - it works properly. I want to do it automatically, but adding a package to configuration doesnt helps for some reason, I get "Identificator is not mapped" error

    @Bean
public SessionFactory sessionFactory(){
    Properties hibernateProperties = new Properties();
    hibernateProperties.put("hibernate.connection.driver_class",ds_driver);
    hibernateProperties.put("hibernate.connection.url",ds_url);
    hibernateProperties.put("hibernate.connection.username",ds_username);
    hibernateProperties.put("hibernate.connection.password",ds_password);
    hibernateProperties.put("hibernate.show_sql", false);
    hibernateProperties.put("connection.pool_size", 1);
    hibernateProperties.put("current_session_context_class", "thread");
    hibernateProperties.put("hibernate.hbm2ddl.auto", "update");

    org.hibernate.cfg.Configuration configuration = new org.hibernate.cfg.Configuration();
    configuration.addPackage("app.entity"); // **doesnt work**
    configuration.addAnnotatedClass(Identificator.class); // **works fine**
    configuration.addProperties(hibernateProperties);

    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
    SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

    return sessionFactory;
}