问:
How to generate more than one border radius
I am trying to make shapes with variable border radius.

Based on a modifier the shape should have a border radius of either 50 % (when Math.random() > 0.5), 20 % (when Math.random() > 0.8), and default to 0 % giving a plain square.

However, when you use the on-click function it will only give either the 20 % radius or the default shape, and not the 50 % radius.

Here is a simplified version of the key method:

function makeShapeAppear() {
    var top = Math.random() * 400;
    var left = Math.random() * 400;
    var width = (Math.random() * 100) + 100;

    if (Math.random() > 0.5) {
        document.getElementById("shape").style.borderRadius = "50%"
    } else {
        document.getElementById("shape").style.borderRadius = "0";
    }

    if (Math.random() > 0.8) {
        document.getElementById("shape").style.borderRadius = "20%"
    } else {
        document.getElementById("shape").style.borderRadius = "0";
    }
}
```

<p>The complete code snippet:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var bestTime = 0;

var start = new Date().getTime();

function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

function makeShapeAppear() {
    var top = Math.random() * 400;
    var left = Math.random() * 400;
    var width = (Math.random() * 100) + 100;
    if (Math.random() > 0.5) {
        document.getElementById("shape").style.borderRadius = "50%"
    } else {
        document.getElementById("shape").style.borderRadius = "0";
    }

    if (Math.random() > 0.8) {
        document.getElementById("shape").style.borderRadius = "20%"
    } else {
        document.getElementById("shape").style.borderRadius = "0";
    }

    document.getElementById("shape").style.backgroundColor = getRandomColor();
    document.getElementById("shape").style.width = width + "px";
    document.getElementById("shape").style.height = width + "px";
    document.getElementById("shape").style.top = top + "px";
    document.getElementById("shape").style.left = left + "px";
    document.getElementById("shape").style.display = "block";
    start = new Date().getTime();
}

function appearAfterDelay() {
    setTimeout(makeShapeAppear, Math.random() * 2000)
}

appearAfterDelay();

document.getElementById("shape").onclick = function() {
    document.getElementById("shape").style.display = "none";
    var end = new Date().getTime();
    var timeTaken = (end - start) / 1000;
    document.getElementById("timeTaken").innerHTML = timeTaken + "'s";
    if (timeTaken < bestTime || bestTime == 0) {
        bestTime = timeTaken;
        document.getElementById("best").innerHTML = bestTime + "s"
    }
    appearAfterDelay();
}</code>```

body {
    background-color: azure;
    margin: 0;
    padding: 0;
    font-family: sans-serif;
}

#shape {
    background-color: red;
    width: 200px;
    height: 200px;
    display: none;
    position: relative;
}

.bold {
    font-weight: bold;
}

#best {
    color: limegreen;
    font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
    <title>Javascript Test You Reactions</title>
</head>

<body>
    <h1>Test Your Reactions!</h1>
    <P>Click on the squares and circles as <em><ins>quickly</ins></em>as you can!</P>
    <p class="bold">Your time: <span id="timeTaken"></span></p>
    <p>Best time: <span id="best"></span></p>
    <div id="shape"></div>
</body></code>```

答:
As shown by UchihaItachi your main problem is in the ordering and separation of the conditional statements determining the right border radius; if the random number is over 0.5 but not over 0.8, the first conditional will set the radius to 50%, but the second will set it to 0.

Another little problem is recomputing the random value to test against, which will increase the probability of getting a border radius of 0.

This can all be improved like this

```<code>function makeShapeAppear() {
    var top = Math.random() * 400;
    var left = Math.random() * 400;
    var width = (Math.random() * 100) + 100;

    var factor = Math.random();
    var radius = "0";

    if (factor > 0.8) {
        radius = "20%"
    } else if (factor > 0.5) {
        radius = "50%"
    }

    document.getElementById("shape").style.borderRadius = radius;
}
</code>```

The complete code snippet, with a few other changes (e.g. only get the shape element once, structure code for readability, direct assignments when possible, etc.):

var bestTime = 0,
    shape = document.getElementById("shape"),
    start = new Date().getTime();

shape.onclick = click;
appearAfterDelay();

function appearAfterDelay() {
    setTimeout(makeShapeAppear, Math.random() * 2000)
}

function click() {
    var end = new Date().getTime(),
        timeTaken = (end - start) / 1000;

    shape.style.display = "none";

    if (timeTaken < bestTime || bestTime == 0) {
        bestTime = timeTaken;
    }

    document.getElementById("timeTaken").innerHTML = timeTaken + "s";
    document.getElementById("best").innerHTML = bestTime + "s"

    appearAfterDelay();
}

function makeShapeAppear() {
    var styles = shape.style,
        factor = Math.random(),
        radius = "0";

    styles.display = "block";
    styles.backgroundColor = getRandomColor();
    styles.top = Math.random() * 400 + "px";
    styles.left = Math.random() * 400 + "px";
    styles.width = styles.height = (Math.random() * 100) + 100 + "px";

    if (factor > 0.8) {
        radius = "20%"
    } else if (factor > 0.5) {
        radius = "50%"
    }
    styles.borderRadius = radius;

    start = new Date().getTime();
}

function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    background-color: azure;
    margin: 0;
    padding: 0;
    font-family: sans-serif;
}

#shape {
    display: none;
    position: relative;
}

.bold {
    font-weight: bold;
}

#best {
    color: limegreen;
}</code>```

    <title>Javascript Test You Reactions</title>

Test Your Reactions!

Click on the squares and circles as quickly as you can!

Your time:

Best time:

```

Body:
I am trying to make shapes with variable border radius.

Based on a modifier the shape should have a border radius of either 50 % (when Math.random() > 0.5), 20 % (when Math.random() > 0.8), and default to 0 % giving a plain square.

However, when you use the on-click function it will only give either the 20 % radius or the default shape, and not the 50 % radius.

Here is a simplified version of the key method:

function makeShapeAppear() {
    var top = Math.random() * 400;
    var left = Math.random() * 400;
    var width = (Math.random() * 100) + 100;

    if (Math.random() > 0.5) {
        document.getElementById("shape").style.borderRadius = "50%"
    } else {
        document.getElementById("shape").style.borderRadius = "0";
    }

    if (Math.random() > 0.8) {
        document.getElementById("shape").style.borderRadius = "20%"
    } else {
        document.getElementById("shape").style.borderRadius = "0";
    }
}

The complete code snippet:

var bestTime = 0;

var start = new Date().getTime();

function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

function makeShapeAppear() {
    var top = Math.random() * 400;
    var left = Math.random() * 400;
    var width = (Math.random() * 100) + 100;
    if (Math.random() > 0.5) {
        document.getElementById("shape").style.borderRadius = "50%"
    } else {
        document.getElementById("shape").style.borderRadius = "0";
    }

    if (Math.random() > 0.8) {
        document.getElementById("shape").style.borderRadius = "20%"
    } else {
        document.getElementById("shape").style.borderRadius = "0";
    }

    document.getElementById("shape").style.backgroundColor = getRandomColor();
    document.getElementById("shape").style.width = width + "px";
    document.getElementById("shape").style.height = width + "px";
    document.getElementById("shape").style.top = top + "px";
    document.getElementById("shape").style.left = left + "px";
    document.getElementById("shape").style.display = "block";
    start = new Date().getTime();
}

function appearAfterDelay() {
    setTimeout(makeShapeAppear, Math.random() * 2000)
}

appearAfterDelay();

document.getElementById("shape").onclick = function() {
    document.getElementById("shape").style.display = "none";
    var end = new Date().getTime();
    var timeTaken = (end - start) / 1000;
    document.getElementById("timeTaken").innerHTML = timeTaken + "'s";
    if (timeTaken < bestTime || bestTime == 0) {
        bestTime = timeTaken;
        document.getElementById("best").innerHTML = bestTime + "s"
    }
    appearAfterDelay();
}

body {
    background-color: azure;
    margin: 0;
    padding: 0;
    font-family: sans-serif;
}

#shape {
    background-color: red;
    width: 200px;
    height: 200px;
    display: none;
    position: relative;
}

.bold {
    font-weight: bold;
}

#best {
    color: limegreen;
    font-weight: bold;
}

    <title>Javascript Test You Reactions</title>

Test Your Reactions!

Click on the squares and circles as quicklyas you can!

Your time:

Best time:

Body:
As shown by UchihaItachi your main problem is in the ordering and separation of the conditional statements determining the right border radius; if the random number is over 0.5 but not over 0.8, the first conditional will set the radius to 50%, but the second will set it to 0.

Another little problem is recomputing the random value to test against, which will increase the probability of getting a border radius of 0.

This can all be improved like this

function makeShapeAppear() {
    var top = Math.random() * 400;
    var left = Math.random() * 400;
    var width = (Math.random() * 100) + 100;

    var factor = Math.random();
    var radius = "0";

    if (factor > 0.8) {
        radius = "20%"
    } else if (factor > 0.5) {
        radius = "50%"
    }

    document.getElementById("shape").style.borderRadius = radius;
}

The complete code snippet, with a few other changes (e.g. only get the shape element once, structure code for readability, direct assignments when possible, etc.):

var bestTime = 0,
    shape = document.getElementById("shape"),
    start = new Date().getTime();

shape.onclick = click;
appearAfterDelay();

function appearAfterDelay() {
    setTimeout(makeShapeAppear, Math.random() * 2000)
}

function click() {
    var end = new Date().getTime(),
        timeTaken = (end - start) / 1000;

    shape.style.display = "none";

    if (timeTaken < bestTime || bestTime == 0) {
        bestTime = timeTaken;
    }

    document.getElementById("timeTaken").innerHTML = timeTaken + "s";
    document.getElementById("best").innerHTML = bestTime + "s"

    appearAfterDelay();
}

function makeShapeAppear() {
    var styles = shape.style,
        factor = Math.random(),
        radius = "0";

    styles.display = "block";
    styles.backgroundColor = getRandomColor();
    styles.top = Math.random() * 400 + "px";
    styles.left = Math.random() * 400 + "px";
    styles.width = styles.height = (Math.random() * 100) + 100 + "px";

    if (factor > 0.8) {
        radius = "20%"
    } else if (factor > 0.5) {
        radius = "50%"
    }
    styles.borderRadius = radius;

    start = new Date().getTime();
}

function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

body {
    background-color: azure;
    margin: 0;
    padding: 0;
    font-family: sans-serif;
}

#shape {
    display: none;
    position: relative;
}

.bold {
    font-weight: bold;
}

#best {
    color: limegreen;
}

<head>
    <title>Javascript Test You Reactions</title>
</head>

<body>
    <h1>Test Your Reactions!</h1>
    <p>Click on the squares and circles as <em><ins>quickly</ins></em> as you can!</p>
    <p class="bold">Your time: <span id="timeTaken"></span></p>
    <p>Best time: <span id="best" class="bold"></span></p>
    <div id="shape"></div>
</body>


来源: stackexchange

问:
FirebaseUI Auth - Facebook Login error : Unsuccessful debug_token response from Facebook
I'm trying to integrate FirebaseUI Auth library. Google sign-in and Email sign-in are working fine but I have a problem setting up Facebook Login.
This is my code:

```<code>user = firebaseAuth.getCurrentUser();
            if (user != null) {
                   startMainActivity();
                   finish();
            } else {
                startActivityForResult(
                        AuthUI.getInstance()
                                .createSignInIntentBuilder()
                                .setIsSmartLockEnabled(!BuildConfig.DEBUG)
                                .setProviders(Arrays.asList(new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),
                                        new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build(),
                                        new AuthUI.IdpConfig.Builder(AuthUI.FACEBOOK_PROVIDER).build()))
                                .build(),
                        RC_SIGN_IN);
            }
</code>```

When I click the facebook button all the login process goes well (in my facebook profile I see the app in my apps list) but firebase doesn't create the user and I'm stuck on the login page.
In Android Monitor I have the following lines (the app doesn't crash):

```<code>E/CredentialSignInHandler: Unexpected exception when signing in with credential
                           com.google.firebase.FirebaseException: An internal error has occurred. [ Unsuccessful debug_token response from Facebook ]
                           at com.google.android.gms.internal.zzblv.zzce(Unknown Source)
                           at com.google.android.gms.internal.zzbls$zzj.zza(Unknown Source)
                           at com.google.android.gms.internal.zzbmd.zzcf(Unknown Source)
                           at com.google.android.gms.internal.zzbmd$zza.onFailure(Unknown Source)
                           at com.google.android.gms.internal.zzbly$zza.onTransact(Unknown Source)
                           at android.os.Binder.execTransact(Binder.java:453)
</code>```

The error that Firebase shows up is only "Unsuccessful debug_token response from Facebook" without any code or error message... I don't know what to do.

Thanks for the help!

答: Go to Facebook developers page and select your app from the dropdown menu. Then go to Settings -> Advanced and find Is App Secret embedded in the client? select No from the toggle button and done. Refer this image link if you face any difficulty finding the option. Facebook Login error : Unsuccessful debug_token response from Facebook

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to integrate FirebaseUI Auth library. Google sign-in and Email sign-in are working fine but I have a problem setting up Facebook Login.
This is my code:

user = firebaseAuth.getCurrentUser();
            if (user != null) {
                   startMainActivity();
                   finish();
            } else {
                startActivityForResult(
                        AuthUI.getInstance()
                                .createSignInIntentBuilder()
                                .setIsSmartLockEnabled(!BuildConfig.DEBUG)
                                .setProviders(Arrays.asList(new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),
                                        new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build(),
                                        new AuthUI.IdpConfig.Builder(AuthUI.FACEBOOK_PROVIDER).build()))
                                .build(),
                        RC_SIGN_IN);
            }

When I click the facebook button all the login process goes well (in my facebook profile I see the app in my apps list) but firebase doesn't create the user and I'm stuck on the login page.
In Android Monitor I have the following lines (the app doesn't crash):

E/CredentialSignInHandler: Unexpected exception when signing in with credential
                           com.google.firebase.FirebaseException: An internal error has occurred. [ Unsuccessful debug_token response from Facebook ]
                           at com.google.android.gms.internal.zzblv.zzce(Unknown Source)
                           at com.google.android.gms.internal.zzbls$zzj.zza(Unknown Source)
                           at com.google.android.gms.internal.zzbmd.zzcf(Unknown Source)
                           at com.google.android.gms.internal.zzbmd$zza.onFailure(Unknown Source)
                           at com.google.android.gms.internal.zzbly$zza.onTransact(Unknown Source)
                           at android.os.Binder.execTransact(Binder.java:453)

The error that Firebase shows up is only "Unsuccessful debug_token response from Facebook" without any code or error message... I don't know what to do.

Thanks for the help!


问:
Getting ngx-translate-messageformat-compiler to work with ionic
I'm trying to get an Ionic app to work with ICU messageformat translations. I'm not actually a "web" guy, I'm just trying to get a test frontend working as a proof-of-concept for my C# backend that delivers those ICU strings, so bear with me if I missed something obvious.

To start off I chose the template that already does "normal" translations: super.

```<code>C:\Users\N.Voigt>ionic start i18nTest

? What starter would you like to use: super
√ Creating directory .\i18nTest - done!
√ Downloading and extracting super starter - done!
√ Personalizing ionic.config.json and package.json - done!

Installing dependencies may take several minutes.

  *   IONIC  DEVAPP  *

 Speed up development with the Ionic DevApp, our fast, on-device testing mobile app

  -     Test on iOS and Android without Native SDKs
  -     LiveReload for instant style and JS updates

 -->    Install DevApp: link removed   <--

> npm i
√ Running command - done!
> git init

  *   IONIC  PRO  *

 Supercharge your Ionic development with the Ionic Pro SDK

  -     Track runtime errors in real-time, back to your original TypeScript
  -     Push remote updates and skip the app store queue

Learn more about Ionic Pro: https://ionicframework.com/products

? Install the free Ionic Pro SDK and connect your app? No

-----------------------------------

> git add -A
> git commit -m "Initial commit" --no-gpg-sign

Starter Welcome:
Welcome to the IONIC SUPER STARTER!

The Super Starter comes packed with ready-to-use page designs for common mobile designs like master detail,
login/signup, settings, tutorials, and more. Pick and choose which page types you want to use and remove the ones you
don't!

For more details, please see the project README:
https://github.com/ionic-team/starters/blob/master/ionic-angular/official/super/README.md

Next Steps:
* Go to your newly created project: cd .\i18nTest
* Get Ionic DevApp for easy device testing: link removed

C:\Users\N.Voigt>

C:\Users\N.Voigt>cd i18nTest
</code>```

I then followed the steps here to get ngx-translate-messageformat-compiler to work:

Made sure that @ngx-translate/core is already installed:

```<code>C:\Users\N.Voigt\i18nTest>npm ls @ngx-translate/core
i18nTest@0.0.1 C:\Users\N.Voigt\i18nTest
`-- @ngx-translate/core@8.0.0
</code>```

Installed ngx-translate-messageformat-compiler and messageformat

```<code>C:\Users\N.Voigt\i18nTest>npm install ngx-translate-messageformat-compiler messageformat --save
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ messageformat@1.0.2
+ ngx-translate-messageformat-compiler@2.0.1
added 121 packages in 27.242s
</code>```

Opened this folder in my favorite editor.

Added the example to the json files ./src/assets/i18n/de.json (this is my local language used).
Added the example to the json files ./src/assets/i18n/en.json (this is the fallback language... just in case...).

Added the suggested testing view template to ./src/pages/welcome/welcome.html

Starting it with ionic:serve works as one would imagine: the app starts, I click "Skip" to go to the welcome page and my text appears... translated, but not yet "messageformat"ed.

Now onto adding the actual messageformat:

In ./src/app/app.module.ts, I added the imports for TranslateCompiler and TranslateMessageFormatCompiler and added the configuration block for the compiler, so the whole configuration for the TranslateModule now reads:

```<code>TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: (createTranslateLoader),
        deps: [HttpClient]
      },
      // NEW:
      compiler: {
        provide: TranslateCompiler,
        useClass: TranslateMessageFormatCompiler
      }
    }),
</code>```

Upon starting the app, I immediately (before even clicking "Skip" to go to the welcome page) get the following error:

```<code>Runtime Error
Formatting function "plural" not found!
Stack
Error: Formatting function "plural" not found!
    at Compiler.token (http://localhost:8100/build/vendor.js:64971:42)
    at Compiler.<anonymous> (http://localhost:8100/build/vendor.js:65011:62)
    at Array.map (<anonymous>)
    at Compiler.compile (http://localhost:8100/build/vendor.js:65011:28)
    at Compiler.compile (http://localhost:8100/build/vendor.js:65017:26)
    at MessageFormat.compile (http://localhost:8100/build/vendor.js:120919:22)
    at TranslateMessageFormatCompiler.compileTranslations (http://localhost:8100/build/vendor.js:120440:35)
    at SafeSubscriber.loadingTranslations.take.subscribe._this.pending [as _next] (http://localhost:8100/build/vendor.js:39213:55)
    at SafeSubscriber.__tryOrUnsub (http://localhost:8100/build/vendor.js:21710:16)
    at SafeSubscriber.next (http://localhost:8100/build/vendor.js:21657:22)
Ionic Framework: 3.9.2
Ionic App Scripts: 3.1.2
Angular Core: 5.0.1
Angular Compiler CLI: 5.0.1
Node: 9.2.0
OS Platform: Windows 10
Navigator Platform: Win32
User Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36
</code>```

I checked that make-plural is installed:

```<code>C:\Users\N.Voigt\i18nTest>npm ls make-plural
i18nTest@0.0.1 C:\Users\N.Voigt\i18nTest
`-- messageformat@1.0.2
  `-- make-plural@3.0.6
</code>```

And now I'm kinda out of my depth. I did not get any errors or warnings during the whole process. What is wrong, how can I fix it? I'm not opposed to people telling me I do it wrong and I have to use a different package. I just need a way to translate and messageformat.

I removed the plural messageformat from the example texts and it works for non-plural texts:

But I still would like to have plural support... I mean it's their own example texts, that should work, right?

答:
Holy syntax error batman!

Figured it out. Their example is wrong. It has a syntax error.

```<code>"things": "There {count, plural, =0{is} one{is} other{are}} {count, plural, =0{} one{a} other{several}} {count, plural, =0{nothing} one{thing} other{things}",
</code>```

is simply missing a closing brace. It should be (see last character):

```<code>"things": "There {count, plural, =0{is} one{is} other{are}} {count, plural, =0{} one{a} other{several}} {count, plural, =0{nothing} one{thing} other{things}}",
</code>```

Works like a charm after fixing that.

Fixed it and sent a pull request so hopefully I'm the last person to trip on this.

Body:
I'm trying to get an Ionic app to work with ICU messageformat translations. I'm not actually a "web" guy, I'm just trying to get a test frontend working as a proof-of-concept for my C# backend that delivers those ICU strings, so bear with me if I missed something obvious.

To start off I chose the template that already does "normal" translations: super.

C:\Users\N.Voigt>ionic start i18nTest

? What starter would you like to use: super
√ Creating directory .\i18nTest - done!
√ Downloading and extracting super starter - done!
√ Personalizing ionic.config.json and package.json - done!

Installing dependencies may take several minutes.

  *   IONIC  DEVAPP  *

 Speed up development with the Ionic DevApp, our fast, on-device testing mobile app

  -     Test on iOS and Android without Native SDKs
  -     LiveReload for instant style and JS updates

 -->    Install DevApp: link removed   <--

> npm i
√ Running command - done!
> git init

  *   IONIC  PRO  *

 Supercharge your Ionic development with the Ionic Pro SDK

  -     Track runtime errors in real-time, back to your original TypeScript
  -     Push remote updates and skip the app store queue

Learn more about Ionic Pro: https://ionicframework.com/products

? Install the free Ionic Pro SDK and connect your app? No

-----------------------------------

> git add -A
> git commit -m "Initial commit" --no-gpg-sign

Starter Welcome:
Welcome to the IONIC SUPER STARTER!

The Super Starter comes packed with ready-to-use page designs for common mobile designs like master detail,
login/signup, settings, tutorials, and more. Pick and choose which page types you want to use and remove the ones you
don't!

For more details, please see the project README:
https://github.com/ionic-team/starters/blob/master/ionic-angular/official/super/README.md

Next Steps:
* Go to your newly created project: cd .\i18nTest
* Get Ionic DevApp for easy device testing: link removed

C:\Users\N.Voigt>

C:\Users\N.Voigt>cd i18nTest

I then followed the steps here to get ngx-translate-messageformat-compiler to work:

Made sure that @ngx-translate/core is already installed:

C:\Users\N.Voigt\i18nTest>npm ls @ngx-translate/core
i18nTest@0.0.1 C:\Users\N.Voigt\i18nTest
`-- @ngx-translate/core@8.0.0

Installed ngx-translate-messageformat-compiler and messageformat

C:\Users\N.Voigt\i18nTest>npm install ngx-translate-messageformat-compiler messageformat --save
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ messageformat@1.0.2
+ ngx-translate-messageformat-compiler@2.0.1
added 121 packages in 27.242s

Opened this folder in my favorite editor.

Added the example to the json files ./src/assets/i18n/de.json (this is my local language used).
Added the example to the json files ./src/assets/i18n/en.json (this is the fallback language... just in case...).

Added the suggested testing view template to ./src/pages/welcome/welcome.html

Starting it with ionic:serve works as one would imagine: the app starts, I click "Skip" to go to the welcome page and my text appears... translated, but not yet "messageformat"ed.

Now onto adding the actual messageformat:

In ./src/app/app.module.ts, I added the imports for TranslateCompiler and TranslateMessageFormatCompiler and added the configuration block for the compiler, so the whole configuration for the TranslateModule now reads:

TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: (createTranslateLoader),
        deps: [HttpClient]
      },
      // NEW:
      compiler: {
        provide: TranslateCompiler,
        useClass: TranslateMessageFormatCompiler
      }
    }),

Upon starting the app, I immediately (before even clicking "Skip" to go to the welcome page) get the following error:

Runtime Error
Formatting function "plural" not found!
Stack
Error: Formatting function "plural" not found!
    at Compiler.token (http://localhost:8100/build/vendor.js:64971:42)
    at Compiler.<anonymous> (http://localhost:8100/build/vendor.js:65011:62)
    at Array.map (<anonymous>)
    at Compiler.compile (http://localhost:8100/build/vendor.js:65011:28)
    at Compiler.compile (http://localhost:8100/build/vendor.js:65017:26)
    at MessageFormat.compile (http://localhost:8100/build/vendor.js:120919:22)
    at TranslateMessageFormatCompiler.compileTranslations (http://localhost:8100/build/vendor.js:120440:35)
    at SafeSubscriber.loadingTranslations.take.subscribe._this.pending [as _next] (http://localhost:8100/build/vendor.js:39213:55)
    at SafeSubscriber.__tryOrUnsub (http://localhost:8100/build/vendor.js:21710:16)
    at SafeSubscriber.next (http://localhost:8100/build/vendor.js:21657:22)
Ionic Framework: 3.9.2
Ionic App Scripts: 3.1.2
Angular Core: 5.0.1
Angular Compiler CLI: 5.0.1
Node: 9.2.0
OS Platform: Windows 10
Navigator Platform: Win32
User Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36

I checked that make-plural is installed:

C:\Users\N.Voigt\i18nTest>npm ls make-plural
i18nTest@0.0.1 C:\Users\N.Voigt\i18nTest
`-- messageformat@1.0.2
  `-- make-plural@3.0.6

And now I'm kinda out of my depth. I did not get any errors or warnings during the whole process. What is wrong, how can I fix it? I'm not opposed to people telling me I do it wrong and I have to use a different package. I just need a way to translate and messageformat.

I removed the plural messageformat from the example texts and it works for non-plural texts:

But I still would like to have plural support... I mean it's their own example texts, that should work, right?

Body:
Holy syntax error batman!

Figured it out. Their example is wrong. It has a syntax error.

"things": "There {count, plural, =0{is} one{is} other{are}} {count, plural, =0{} one{a} other{several}} {count, plural, =0{nothing} one{thing} other{things}",

is simply missing a closing brace. It should be (see last character):

"things": "There {count, plural, =0{is} one{is} other{are}} {count, plural, =0{} one{a} other{several}} {count, plural, =0{nothing} one{thing} other{things}}",

Works like a charm after fixing that.

Fixed it and sent a pull request so hopefully I'm the last person to trip on this.


问:
Format a date (string) with XSLT
There are a lot of questions/answers on this particular subject, but none seem to address the specific issue I have. I'm also a complete noob, so there's that ;-). I have the following XML being sent from an application to a piece of middleware. In that middleware, I'm capturing the XML and pulling out data. My last remaining challenge is to re-format a piece of string data that represents a date, that sits inside the <now></now> tags.

```<code><?xml version="1.0" encoding="UTF-8"?>
    <Body>
        <send_message xmlns="urn:xyztech:agent">
            <user>
                <now>2017-11-15T13:38:11+00:00</now>
                <company>xyz.demo</company>
            </user>
        </send_message>
    </Body>
</code>```

I'm using Apigee for the middleware, and need an XSL script to manipulate the date (to make it a bit cleaner - something like 15/11/2017 or 15.11.2017, and I don't want the time). I've tried several examples that I've seen, but none seem to work for me. Unfortunately, being the noob, I'm not really able to debug the errors that occur with those examples (e.g. failing to find the function from the namespace reference), and I'd really appreciate some assistance/guidance.

It would be pretty slick if I could use the XPath that I already have in the XSL that extracts the data:

```<code><Variable name="now" type="date">
    <XPath>//Envelope/Body/send_message/user/now</XPath>
</Variable>
</code>```

I've seen a solution for that, but I have a feeling that Apigee doesn't support XPath 2.0, so format-date($d,"[D]-[M]-[Y]") doesn't apper to be a viable option, either. Any/all help gratefully received...

答:
"I have a feeling" is not a proper approach to the issue. Just check whether Apigee "understands" XSLT 2.0.

If it does, use format-date function.
Note the way the format is given in the following example.
It provides proper size of day / month / year part.

Another important detail: Your source XML uses a namespace
and the script refers to an elements from it (now). So:

This namespace must be included in stylesheet tag, with
a namespace reference (I used xyz).

The now element must be given with this namespace reference.

So the whole script can be as follows:

```<code><xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:xyz="urn:xyztech:agent">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="xyz:now">
    <xsl:copy>
      <xsl:variable name="srcDate" select="substring-before(., 'T')" />
      <xsl:value-of select="format-date(xs:date($srcDate),'[D01].[M01].[Y0001]')"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="node()|@*">
    <xsl:copy><xsl:apply-templates select="node()|@*"/></xsl:copy>
  </xsl:template>
</xsl:stylesheet>
</code>```

I tested it on your source using http://xsltransform.net/ and it works.

Of course, the simplest way to check is to try this script in your environment.

Title: Format a date (string) with XSLT

Body:
There are a lot of questions/answers on this particular subject, but none seem to address the specific issue I have. I'm also a complete noob, so there's that ;-). I have the following XML being sent from an application to a piece of middleware. In that middleware, I'm capturing the XML and pulling out data. My last remaining challenge is to re-format a piece of string data that represents a date, that sits inside the <now></now> tags.

<?xml version="1.0" encoding="UTF-8"?>

        <send_message xmlns="urn:xyztech:agent">
            <user>
                <now>2017-11-15T13:38:11+00:00</now>
                <company>xyz.demo</company>
            </user>
        </send_message>

I'm using Apigee for the middleware, and need an XSL script to manipulate the date (to make it a bit cleaner - something like 15/11/2017 or 15.11.2017, and I don't want the time). I've tried several examples that I've seen, but none seem to work for me. Unfortunately, being the noob, I'm not really able to debug the errors that occur with those examples (e.g. failing to find the function from the namespace reference), and I'd really appreciate some assistance/guidance.

It would be pretty slick if I could use the XPath that I already have in the XSL that extracts the data:

<Variable name="now" type="date">
    <XPath>//Envelope/Body/send_message/user/now</XPath>
</Variable>

I've seen a solution for that, but I have a feeling that Apigee doesn't support XPath 2.0, so format-date($d,"[D]-[M]-[Y]") doesn't apper to be a viable option, either. Any/all help gratefully received...

Body:
"I have a feeling" is not a proper approach to the issue. Just check whether Apigee "understands" XSLT 2.0.

If it does, use format-date function.
Note the way the format is given in the following example.
It provides proper size of day / month / year part.

Another important detail: Your source XML uses a namespace
and the script refers to an elements from it (now). So:

This namespace must be included in stylesheet tag, with
a namespace reference (I used xyz).

The now element must be given with this namespace reference.

So the whole script can be as follows:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:xyz="urn:xyztech:agent">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="xyz:now">
    <xsl:copy>
      <xsl:variable name="srcDate" select="substring-before(., 'T')" />
      <xsl:value-of select="format-date(xs:date($srcDate),'[D01].[M01].[Y0001]')"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="node()|@*">
    <xsl:copy><xsl:apply-templates select="node()|@*"/></xsl:copy>
  </xsl:template>
</xsl:stylesheet>

I tested it on your source using http://xsltransform.net/ and it works.

Of course, the simplest way to check is to try this script in your environment.


问:
Copying different columns into one single column from different files and renaming them with the same filename
I have multiple files each with 5 columns and for each file I would like to stack each row on one another and then rename the files to their original names. Any idea how to proceed with that?
I am using awk to stack the rows:

```<code>awk '{ for(i=1;i<=NF;i++){ print $i}}' file > newfile
</code>```

And tried something like that to try the whole thing but doesn't work..

```<code>awk '{ for(i=1;i<=NF;i++){ print $i}}' *.data > testfile.tmp  && mv testfile.tmp *.data
</code>```

答:
If you're using GNU awk, you can edit files in-place with bundled inplace library:

```<code>gawk -i inplace '{for(i=1;i<=NF;i++) print $i}' *.data
</code>```

Body:
I have multiple files each with 5 columns and for each file I would like to stack each row on one another and then rename the files to their original names. Any idea how to proceed with that?
I am using awk to stack the rows:

awk '{ for(i=1;i<=NF;i++){ print $i}}' file > newfile

And tried something like that to try the whole thing but doesn't work..

awk '{ for(i=1;i<=NF;i++){ print $i}}' *.data > testfile.tmp  && mv testfile.tmp *.data

Body:
If you're using GNU awk, you can edit files in-place with bundled inplace library:

gawk -i inplace '{for(i=1;i<=NF;i++) print $i}' *.data


问:
Display images dynamically using map() in react not working
I want to display images in the sports array using map(). but not working</p>

```<code><div className="row">
   {this.state.sports.map(function(sport, index){
     return (
     <div className="col-md-3" key={index}>
       <h3 className="text-center">{this.state.sports.name}</h3>
       <img src={ require('./../assets/images/'+ {this.state.sports.name} +'.jpg') } width="300px" height="180px" />
       <button className="btn btn-info btn-sm" type="submit" onClick={this.join_in_sport} >JOIN</button>
     </div>
    )
  }.bind(this))}
</div>
</code>```

答:
The problem seems to lie in how you are building the pathname for your image. Same for your
 tag.

```<code>src={ require('./../assets/images/'+ {this.state.sports.name} +'.jpg') }
</code>```

If this.state.sports is an array, and not an object, then it can't possibly have a name key. I think you meant to print the current objects name for each iteration in your map().

So try:

```<code><h3 className="text-center">{this.state.sports.name}</h3>
<img src={ require('./../assets/images/'+ {sport.name} +'.jpg') } width="300px" height="180px" />
</code>```

This is assuming your array looks something like:

```<code>[
  {name: "foo"},
  {name: "bar"}
]
</code>```

Body:
I want to display images in the sports array using map(). but not working

   {this.state.sports.map(function(sport, index){
     return (

{this.state.sports.name}

       <button className="btn btn-info btn-sm" type="submit" onClick={this.join_in_sport} >JOIN</button>

    )
  }.bind(this))}

Body:
The problem seems to lie in how you are building the pathname for your image. Same for your <h3> tag.

src={ require('./../assets/images/'+ {this.state.sports.name} +'.jpg') }

If this.state.sports is an array, and not an object, then it can't possibly have a name key. I think you meant to print the current objects name for each iteration in your map().

So try:

<h3 className="text-center">{this.state.sports.name}</h3>
<img src={ require('./../assets/images/'+ {sport.name} +'.jpg') } width="300px" height="180px" />

This is assuming your array looks something like:

[
  {name: "foo"},
  {name: "bar"}
]


问:
How to use assertion with test while executing tests in testlink
I am creating test in selenium with java and using testlink for test execution and result.Without assertion tests are working fine with testlink and showing result but when I am using assertion to verify expected and actual result like this:

```<code>try {

        driver.get("http://www.software-testing-tutorials-automation.com");
        String ExpextedTitle="Software testing tutorials and automatio";
        String ActualTitle=driver.findElement(By.xpath("//h1[@class='title']")).getText();
        Assert.assertEquals(ActualTitle, ExpextedTitle);
        IntegrationWithTestLink.updateResult("GR-1", null, TestLinkAPIResults.TEST_PASSED);
     }catch(Exception e){
         System.out.println("Hiiiii");
         IntegrationWithTestLink.updateResult("GR-1", e.getMessage(), TestLinkAPIResults.TEST_FAILED);
     }
 }
</code>```

I don't know why result are not showing in testlink in case for
       exception. Can anyone suggest me better approach to use Assertion here.

答:
Assertion Error is not caught by catch block as your are catching exception not the error. To catch the Error change the code as given below.

try {

```<code>    driver.get("http://www.software-testing-tutorials-automation.com");
    String ExpextedTitle="Software testing tutorials and automatio";
    String ActualTitle=driver.findElement(By.xpath("//h1[@class='title']")).getText();
    Assert.assertEquals(ActualTitle, ExpextedTitle);
    IntegrationWithTestLink.updateResult("GR-1", null, TestLinkAPIResults.TEST_PASSED);
 }catch(AssertionError e){
     System.out.println("Hiiiii");
     IntegrationWithTestLink.updateResult("GR-1", e.getMessage(), TestLinkAPIResults.TEST_FAILED);
 }
</code>```

}

It may work for you.

ContentLicense: CC BY-SA 4.0

Body:
I am creating test in selenium with java and using testlink for test execution and result.Without assertion tests are working fine with testlink and showing result but when I am using assertion to verify expected and actual result like this:

try {

        driver.get("http://www.software-testing-tutorials-automation.com");
        String ExpextedTitle="Software testing tutorials and automatio";
        String ActualTitle=driver.findElement(By.xpath("//h1[@class='title']")).getText();
        Assert.assertEquals(ActualTitle, ExpextedTitle);
        IntegrationWithTestLink.updateResult("GR-1", null, TestLinkAPIResults.TEST_PASSED);
     }catch(Exception e){
         System.out.println("Hiiiii");
         IntegrationWithTestLink.updateResult("GR-1", e.getMessage(), TestLinkAPIResults.TEST_FAILED);
     }
 }

I don't know why result are not showing in testlink in case for
       exception. Can anyone suggest me better approach to use Assertion here.

Body:
Assertion Error is not caught by catch block as your are catching exception not the error. To catch the Error change the code as given below.

try {

    driver.get("http://www.software-testing-tutorials-automation.com");
    String ExpextedTitle="Software testing tutorials and automatio";
    String ActualTitle=driver.findElement(By.xpath("//h1[@class='title']")).getText();
    Assert.assertEquals(ActualTitle, ExpextedTitle);
    IntegrationWithTestLink.updateResult("GR-1", null, TestLinkAPIResults.TEST_PASSED);
 }catch(AssertionError e){
     System.out.println("Hiiiii");
     IntegrationWithTestLink.updateResult("GR-1", e.getMessage(), TestLinkAPIResults.TEST_FAILED);
 }

}

It may work for you.


问:
Assigning a struct using similar struct of pointers in Go
I have two structures that are similar and I want to assign one to the other.
The first one "Equipment" is the structure used to match the database. The second one "JsonEquipment" is the helper structure to parse JSON data.

Here is the example:

```<code>type Equipment struct {
    ID         uint
    CategoryID uint
    Ip         string
    Login      string
    Password   string
}

type JsonEquipment struct {
    ID           *uint
    Category     *string
    Ip           *string
    Login        *string
    Password     *string
}
</code>```

The pointers are there to check if the field is present or not in the JSON. More info: How to recognize void value and unspecified field when unmarshaling in Go?

So for the moment I created a function with many "if" to check and assign to the Equipment but I wonder if there is a better & cleaner solution.

```<code>func CreateEquipment(item JsonEquipment) (Equipment) {
    e := Equipment{}

    if item.ID != nil && !previousEquipment.Auto { // Is the field present & not automatic equipment
        e.ID = *item.ID
    }

    if item.Ip != nil { // Is the field present ?
        e.Ip = *item.Ip
    }

    if item.Login != nil { // Is the field present ?
        e.Login = *item.Login
    }

    [...]
    return e
}
</code>```

I hope you grasp the idea.

This question is similar to
  Assign struct with another struct but is different because of the pointers => non pointers struct

答:
Im not sure if understood your question correctly but wouldn't something like this do the job:

```<code>type Equipment struct {
    ID         uint
    CategoryID uint
    Ip         string
    Login      string
    Password   string
}

func main(){
    // Grabing the equipment.
    equips := getEquipment()

    // Checking each equipment for its validity.
    for _, e := range equips {
        if (e.isValid()) {
            fmt.Println(e, "is OK!")
        } else {
            fmt.Println(e, "is NOT OK!")
        }
    }
}

// getEquipment fetches the json from the file.
func getEquipment() (e []Equipment) {
    raw, err := ioutil.ReadFile("./equipment.json")
    if err != nil {
        fmt.Println(err.Error())
        os.Exit(1)
    }

    json.Unmarshal(raw, &e)

    return
}

// isValid checks if the equipment has all the required fields.
func (e *Equipment) isValid() bool {
    if (e.Ip == "" || e.Login == "") { // You might add more validation rules
        return false
    }

    return true
}
</code>```

Its pretty straightforward but I'm not sure what more would you want to do here.

This way you have one Equipment struct and there's no need of the other "copy" of it containing the pointers.

You can try this code out here.

Body:
I have two structures that are similar and I want to assign one to the other.
The first one "Equipment" is the structure used to match the database. The second one "JsonEquipment" is the helper structure to parse JSON data.

Here is the example:

type Equipment struct {
    ID         uint
    CategoryID uint
    Ip         string
    Login      string
    Password   string
}

type JsonEquipment struct {
    ID           *uint
    Category     *string
    Ip           *string
    Login        *string
    Password     *string
}

The pointers are there to check if the field is present or not in the JSON. More info: How to recognize void value and unspecified field when unmarshaling in Go?

So for the moment I created a function with many "if" to check and assign to the Equipment but I wonder if there is a better & cleaner solution.

func CreateEquipment(item JsonEquipment) (Equipment) {
    e := Equipment{}

    if item.ID != nil && !previousEquipment.Auto { // Is the field present & not automatic equipment
        e.ID = *item.ID
    }

    if item.Ip != nil { // Is the field present ?
        e.Ip = *item.Ip
    }

    if item.Login != nil { // Is the field present ?
        e.Login = *item.Login
    }

    [...]
    return e
}

I hope you grasp the idea.

This question is similar to
  Assign struct with another struct but is different because of the pointers => non pointers struct

Body:
Im not sure if understood your question correctly but wouldn't something like this do the job:

type Equipment struct {
    ID         uint
    CategoryID uint
    Ip         string
    Login      string
    Password   string
}

func main(){
    // Grabing the equipment.
    equips := getEquipment()

    // Checking each equipment for its validity.
    for _, e := range equips {
        if (e.isValid()) {
            fmt.Println(e, "is OK!")
        } else {
            fmt.Println(e, "is NOT OK!")
        }
    }
}

// getEquipment fetches the json from the file.
func getEquipment() (e []Equipment) {
    raw, err := ioutil.ReadFile("./equipment.json")
    if err != nil {
        fmt.Println(err.Error())
        os.Exit(1)
    }

    json.Unmarshal(raw, &e)

    return
}

// isValid checks if the equipment has all the required fields.
func (e *Equipment) isValid() bool {
    if (e.Ip == "" || e.Login == "") { // You might add more validation rules
        return false
    }

    return true
}

Its pretty straightforward but I'm not sure what more would you want to do here.

This way you have one Equipment struct and there's no need of the other "copy" of it containing the pointers.

You can try this code out here.


问:
How to increase font size in javascript?
I'm trying to increase the font size for the title of a GUI that was made using javascript. I'm a java script noob but i just wanted to make a few adjustments to the pre-made GUI in a short amount of time. Any help would be appreciated.

```<code>templateObj.$.ti_widget_plot1.layout.title = 'X-Y Scatter Plot';
</code>```

The code above is what allows me access the title and change the name.

Thanks

答:
var a = document.getElementById('text');
var btn1 = document.getElementById('btn1');
var btn2 = document.getElementById('btn2');

btn1.addEventListener('click',function(){
x = window.getComputedStyle(a, null).getPropertyValue('font-size');
currentsize = parseFloat(x)
a.style.fontSize = (currentsize + 5) + 'px';
})
btn2.addEventListener('click',function(){
x = window.getComputedStyle(a, null).getPropertyValue('font-size');
currentsize = parseFloat(x)
a.style.fontSize = (currentsize - 5) + 'px';
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id='btn1'>+</button>
<button id='btn2'>-</button>
<div>
<p id='text'>text content</p>
</div></code>```

Body:
I'm trying to increase the font size for the title of a GUI that was made using javascript. I'm a java script noob but i just wanted to make a few adjustments to the pre-made GUI in a short amount of time. Any help would be appreciated.

templateObj.$.ti_widget_plot1.layout.title = 'X-Y Scatter Plot';

The code above is what allows me access the title and change the name.

Thanks

Body:
var a = document.getElementById('text');
var btn1 = document.getElementById('btn1');
var btn2 = document.getElementById('btn2');

btn1.addEventListener('click',function(){
x = window.getComputedStyle(a, null).getPropertyValue('font-size');
currentsize = parseFloat(x)
a.style.fontSize = (currentsize + 5) + 'px';
})
btn2.addEventListener('click',function(){
x = window.getComputedStyle(a, null).getPropertyValue('font-size');
currentsize = parseFloat(x)
a.style.fontSize = (currentsize - 5) + 'px';
})

<button id='btn1'>+</button>
<button id='btn2'>-</button>
<div>
<p id='text'>text content</p>
</div>


问:
Border Disappears on Zoom Out/in In all Browser
I am working on a project with different browsers.

I am having a table with borders and when I zoom out my page border disappears.

This happens in all browsers like IE, EDGE, and Chrome Browser.

Is it the DOM structure problem?

It needs to supports with zoom level 75% to 125%. To be specific set zoom to 67% in Chrome and see the change

Please provide the possible solution to this question.

.mEditor {
  display: flex;
  border-bottom: 1px solid #d7d7d7;
}

.m-label {
  width: 30%;
  display: flex;
  background-color: #f2f2f2;
}

.m-editor-noc {
  flex: 1;
  display: flex;
  background-color: #FFFFFF;
  border-left: 1px solid #d7d7d7;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.mfEditor {
  display: flex;
  flex: 1 0 auto;
}

.mEditor-li {
  vertical-align: middle;
  border-left: 1px solid #d7d7d7;
  height: 18px;
  display: inline-block;
  margin-top: 3px;
}

.mEditor .tEditor {
  border: none;
  flex: 1;
  padding-right: 6px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="m-group">

  <div id="id251" class="mEditor">

    <div class="m-label">
      <label for="id223" title="Address">Address</label>
    </div>
    <div class="m-editor-noc">
      <div id="id252" class="mfEditor">

        <input type="text" class="tEditor" value="Address" name="" id="id223" maxlength="255" tabindex="0">

      </div>
      <div class="editor-links"></div>
    </div>
  </div>

  <div id="id254" class="mEditor">

    <div class="m-label">
      <label for="id224" title="Address 2">Address 2</label>
    </div>
    <div class="m-editor-noc">
      <div id="id255" class="mfEditor">

        <input type="text" class="tEditor" value="16" name="" id="id224" maxlength="30" tabindex="0">

      </div>
      <div class="editor-links"></div>
    </div>
  </div>

  <div id="id257" class="mEditor">

    <div class="m-label">
      <label for="id225" title="Postcode">Postcode</label>
    </div>
    <div class="m-editor-noc">
      <div id="id258" class="mfEditor">

        <input type="text" class="tEditor" value="Post Code" name="" id="id225" maxlength="10" tabindex="0">

      </div>
      <div class="editor-links"></div>
    </div>
  </div>

  <div id="id25a" class="mEditor ">

    <div class="m-label">
      <label for="id20f" title="City">City</label>
    </div>
    <div class="m-editor-noc">
      <div id="id25b" class="mfEditor">

        <input type="text" class="tEditor" value="City" name="" id="id20f" autocomplete="off" maxlength="50" tabindex="0">

      </div>
      <div class="editor-links">

      </div>

    </div>
  </div>

  <div id="id25d" class="mEditor">

    <div class="m-label">
      <label for="id228" title="District">District</label>
    </div>
    <div class="m-editor-noc">
      <div id="id25e" class="mfEditor">

        <input type="text" class="tEditor" value="" name="" id="id228" maxlength="100" tabindex="0">

      </div>
      <div class="editor-links"></div>
    </div>
  </div>

  <div id="id260" class="mEditor ">

    <div class="m-label">
      <label for="id210" title="Country">Country</label>
    </div>
    <div class="m-editor-noc">
      <div id="id261" class="mfEditor">

        <input type="text" class="tEditor" value="Country" name="" id="id210" autocomplete="off" maxlength="50" tabindex="0">

      </div>
      <div class="editor-links">

      </div>
    </div>
  </div>

</div></code>```

答:
If by "We supporting all browser and Zoom level 75% - 125%" you mean you  want a border to have the same size in actual pixels regardless of zoom level, you're out of luck. It's not technically possible.

You should only develop for zoom level of 100%.
There is no reliable cross-browser method to know the zoom level, which means this information is not available inside your Window object, so you can't use it to adjust values of properties on your elements.

As a fallback, you could just make the border thicker, so it will be visible even when zoomed. Now it's not displayed because it probably gets a sub-pixel size and estimated by the browser into non-renderable.

Do note everything you that's rendered at zoom levels other than 100% is entirely at the whim of how each browser internally chooses to estimate and render, which you:

have no control on

could change without notice.

In other words, your initial statement should have a minor footnote:

* Within reasonable limits. Rendering while zoomed is browser dependent.

Body:
I am working on a project with different browsers.

I am having a table with borders and when I zoom out my page border disappears.

This happens in all browsers like IE, EDGE, and Chrome Browser.

Is it the DOM structure problem?

It needs to supports with zoom level 75% to 125%. To be specific set zoom to 67% in Chrome and see the change

Please provide the possible solution to this question.

.mEditor {
  display: flex;
  border-bottom: 1px solid #d7d7d7;
}

.m-label {
  width: 30%;
  display: flex;
  background-color: #f2f2f2;
}

.m-editor-noc {
  flex: 1;
  display: flex;
  background-color: #FFFFFF;
  border-left: 1px solid #d7d7d7;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.mfEditor {
  display: flex;
  flex: 1 0 auto;
}

.mEditor-li {
  vertical-align: middle;
  border-left: 1px solid #d7d7d7;
  height: 18px;
  display: inline-block;
  margin-top: 3px;
}

.mEditor .tEditor {
  border: none;
  flex: 1;
  padding-right: 6px;
}

      Address

        <input type="text" class="tEditor" value="Address" name="" id="id223" maxlength="255" tabindex="0">

      Address 2

        <input type="text" class="tEditor" value="16" name="" id="id224" maxlength="30" tabindex="0">

      Postcode

        <input type="text" class="tEditor" value="Post Code" name="" id="id225" maxlength="10" tabindex="0">

      City

        <input type="text" class="tEditor" value="City" name="" id="id20f" autocomplete="off" maxlength="50" tabindex="0">

      District

        <input type="text" class="tEditor" value="" name="" id="id228" maxlength="100" tabindex="0">

      Country

        <input type="text" class="tEditor" value="Country" name="" id="id210" autocomplete="off" maxlength="50" tabindex="0">


问:
how to redirect another jsp page in controller using spring MVC?
in WEB-INF having a Jsp File pls see image   I am using Spring mvc with Hibernate Database connection,in my controller having data from database in variable val  now how can i redirect to another jsp page with data's

Controller Part:

```<code>@RequestMapping(value = "/EditShop" , method = RequestMethod.POST)
          public String editShop(HttpServletRequest request,HttpServletResponse response) throws IOException
          {
              String id=request.getParameter("Id");
              try
              {
                  String val=shopService1.editShopinfo(id);
                  System.out.println("Edit Shop : "+val);
              }
              catch(Exception e)
              {

                  System.out.println("Edit Shop : "+e );
              }
               return "redirect:/EditShop.jsp";
          }
</code>```

答:
return "redirect:/EditShop.jsp";

Insted of this you have return View Name like
return "EditShop";

In Spring Execution Flow InternalResourceViewResolver will Take Care to Call Jsp.

you have to set val to HttpSession Object like session.setAttribut("val",valueofField);

Then you get that value In your jsp
session.getAttribute("val");

I Hope it helps.

Body:
in WEB-INF having a Jsp File pls see image   I am using Spring mvc with Hibernate Database connection,in my controller having data from database in variable val  now how can i redirect to another jsp page with data's

Controller Part:

@RequestMapping(value = "/EditShop" , method = RequestMethod.POST)
          public String editShop(HttpServletRequest request,HttpServletResponse response) throws IOException
          {
              String id=request.getParameter("Id");
              try
              {
                  String val=shopService1.editShopinfo(id);
                  System.out.println("Edit Shop : "+val);
              }
              catch(Exception e)
              {

                  System.out.println("Edit Shop : "+e );
              }
               return "redirect:/EditShop.jsp";
          }


问:
How to write into APCu from CLI-call?
I want to prefill my APCu-Cache with translation and there is already a job that does this called "SeedTranslationCacheJob".
All jobs are only available in our "CRM" so a user that visits our website cannot start such jobs.

I call this job on each website-server-node to prefill the translations each node needs by cli:

```<code>php index.php job DeploymentJob --deploymentJobList="SeedTranslationCacheJob,TestTranslationCacheJob"
</code>```

But this job does not fill the APCu even i have enabled CLI-Caching https://secure.php.net/manual/en/apcu.configuration.php#ini.apcu.enable-cli

Is there a way to fill the APCu that a web-request uses by a script called from cli? Or are these 2 complete different caches?

Is there perhaps a way to configure APCu that i can store data from cli-calls into it and that read them from web-request?

答: This not possible to access the APCu data from a web-request that a cli script has written in. Even different cli calls cannot share data using APCu.</p>

Title: How to write into APCu from CLI-call?

Body:
I want to prefill my APCu-Cache with translation and there is already a job that does this called "SeedTranslationCacheJob".
All jobs are only available in our "CRM" so a user that visits our website cannot start such jobs.

I call this job on each website-server-node to prefill the translations each node needs by cli:

php index.php job DeploymentJob --deploymentJobList="SeedTranslationCacheJob,TestTranslationCacheJob"

But this job does not fill the APCu even i have enabled CLI-Caching https://secure.php.net/manual/en/apcu.configuration.php#ini.apcu.enable-cli

Is there a way to fill the APCu that a web-request uses by a script called from cli? Or are these 2 complete different caches?

Is there perhaps a way to configure APCu that i can store data from cli-calls into it and that read them from web-request?


问:
regex url to image in php
I am making a profile page where users can set an url to their profile image. How do I check this with regex for example?</p>

答:
First test that is a valid url with filter_var()

```<code>$url = filter_var($variable, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED);
</code>```

Then you'll need to download the resource, and test locally if it's an image.

ContentLicense: CC BY-SA 2.5

Title: regex url to image in php

Body:
First test that is a valid url with filter_var()

$url = filter_var($variable, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED);

Then you'll need to download the resource, and test locally if it's an image.


问:
How to play a recorded video using HTML and JavaScript
I had done video recording using  html.I had recorded and play a video in the same tag itself using autoplay with HTML and JavaScript .I want to play that video in separate tag below recording.please can anyone help me.Thanks in Advance:)

main.js:

```<code>    mediaRecorder.onstop = function(){
        log('Stopped  & state = ' + mediaRecorder.state);

        var blob = new Blob(chunks, {type: "video/mp4"});
        chunks = [];

        var videoURL = window.URL.createObjectURL(blob);

        downloadLink.href = videoURL;
        videoElement.src = videoURL;
        downloadLink.innerHTML = 'Download video file';

        var rand =  Math.floor((Math.random() * 10000000));
        var name  = "video_"+rand+".webm" ;

        downloadLink.setAttribute( "download", name);
        downloadLink.setAttribute( "name", name);
    };
function onBtnStopClicked(){
    mediaRecorder.stop();
    videoElement.controls = true;

}
</code>```

HTML:

```<code><video controls autoplay></video><br>
    <button id="rec" onclick="onBtnRecordClicked()">Record</button>
    <button id="pauseRes"   onclick="onPauseResumeClicked()" disabled>Pause</button>
    <button id="stop"  onclick="onBtnStopClicked()" disabled>Stop</button>
</code>```

答:
let onBtnStopClicked = function (e) {
    mediaRecorder.stop();
};

mediaRecorder.onstop = function () {
    // log('Stopped  & state = ' + mediaRecorder.state);

    let blob = new Blob(chunks, {type: "video/mp4"});
    let chunks = [];
    let videoURL = window.URL.createObjectURL(blob);
    let rand =  Math.floor((Math.random() * 10000000));
    let name  = "video_" + rand + ".webm" ;

    let videoElement = document.createElement("video");
    videoElement.controls = true;
    videoElement.src = videoURL;

    let downloadLink = document.createElement("button");
    downloadLink.href = videoURL;
    downloadLink.innerHTML = "Download video file";
    downloadLink.setAttribute("download", name);
    downloadLink.setAttribute("name", name);

    document.body.appendChild(videoElement);
    document.body.appendChild(downloadLink);
};```

put all your code in the sandbox

Body:
I had done video recording using  html.I had recorded and play a video in the same tag itself using autoplay with HTML and JavaScript .I want to play that video in separate tag below recording.please can anyone help me.Thanks in Advance:)

main.js:

    mediaRecorder.onstop = function(){
        log('Stopped  & state = ' + mediaRecorder.state);

        var blob = new Blob(chunks, {type: "video/mp4"});
        chunks = [];

        var videoURL = window.URL.createObjectURL(blob);

        downloadLink.href = videoURL;
        videoElement.src = videoURL;
        downloadLink.innerHTML = 'Download video file';

        var rand =  Math.floor((Math.random() * 10000000));
        var name  = "video_"+rand+".webm" ;

        downloadLink.setAttribute( "download", name);
        downloadLink.setAttribute( "name", name);
    };
function onBtnStopClicked(){
    mediaRecorder.stop();
    videoElement.controls = true;

}

HTML:

<video controls autoplay></video>

    <button id="rec" onclick="onBtnRecordClicked()">Record</button>
    <button id="pauseRes"   onclick="onPauseResumeClicked()" disabled>Pause</button>
    <button id="stop"  onclick="onBtnStopClicked()" disabled>Stop</button>

Body:
let onBtnStopClicked = function (e) {
    mediaRecorder.stop();
};

mediaRecorder.onstop = function () {
    // log('Stopped  & state = ' + mediaRecorder.state);

    let blob = new Blob(chunks, {type: "video/mp4"});
    let chunks = [];
    let videoURL = window.URL.createObjectURL(blob);
    let rand =  Math.floor((Math.random() * 10000000));
    let name  = "video_" + rand + ".webm" ;

    let videoElement = document.createElement("video");
    videoElement.controls = true;
    videoElement.src = videoURL;

    let downloadLink = document.createElement("button");
    downloadLink.href = videoURL;
    downloadLink.innerHTML = "Download video file";
    downloadLink.setAttribute("download", name);
    downloadLink.setAttribute("name", name);

    document.body.appendChild(videoElement);
    document.body.appendChild(downloadLink);
};

put all your code in the sandbox


问:
Limiting lines per page in BI Publisher
I'm using RTF template to create a BI report. I need to limit the number of rows into 3 records on the 1st page only. The remaining records/rows will continue to fill the next pages. I'm also required to print the page total. I used the code below to limit the number of records, however it prints only 1 row. Any help will be appreciated. thanks</p>

```<code><?xdoxslt:set_variable($_XDOCTX, ‘counter’, 0)?>
<?xdoxslt:set_variable($_XDOCTX, ‘lines_page’, 3)?>
<?xdoxslt:set_variable($_XDOCTX, ‘tot_lines’, count(.//PdfDraftPurchaseOrderHeaderVORow))?>
<?xdoxslt:set_variable($_XDOCTX,’remainder’,0)?>

<?for-each:PdfDraftPurchaseOrderHeaderVORow?>
<?xdoxslt:set_variable($_XDOCTX, ‘counter’, xdoxslt:get_variable($_XDOCTX, ‘counter’)+1)?>
<?if@row:xdoxslt:get_variable($_XDOCTX,’counter’) != xdoxslt:get_variable($_XDOCTX,’tot_lines’)?>
<?if@row:position() mod xdoxslt:get_variable($_XDOCTX, ‘lines_page’) = 0?><?call:breaking?><?end if?><?end if?>
<?end for-each?>
</code>```

答:
you can use this syntax, if you want to break a page after n number of rows:

```<code><? if position() mod 3 = 0?>
<?split-by-page-break:?>
<?end if?>
</code>```

this will break the page after 3 rows, then after 6 rows and so on for every 3 multiple. You can replace 3 with your desired row count.

By the way position() is the row number in your xml data source.

Title: Limiting lines per page in BI Publisher

Body:
I'm using RTF template to create a BI report. I need to limit the number of rows into 3 records on the 1st page only. The remaining records/rows will continue to fill the next pages. I'm also required to print the page total. I used the code below to limit the number of records, however it prints only 1 row. Any help will be appreciated. thanks

<?xdoxslt:set_variable($_XDOCTX, ‘counter’, 0)?>
<?xdoxslt:set_variable($_XDOCTX, ‘lines_page’, 3)?>
<?xdoxslt:set_variable($_XDOCTX, ‘tot_lines’, count(.//PdfDraftPurchaseOrderHeaderVORow))?>
<?xdoxslt:set_variable($_XDOCTX,’remainder’,0)?>

<?for-each:PdfDraftPurchaseOrderHeaderVORow?>
<?xdoxslt:set_variable($_XDOCTX, ‘counter’, xdoxslt:get_variable($_XDOCTX, ‘counter’)+1)?>
<?if@row:xdoxslt:get_variable($_XDOCTX,’counter’) != xdoxslt:get_variable($_XDOCTX,’tot_lines’)?>
<?if@row:position() mod xdoxslt:get_variable($_XDOCTX, ‘lines_page’) = 0?><?call:breaking?><?end if?><?end if?>
<?end for-each?>

Body:
you can use this syntax, if you want to break a page after n number of rows:

<? if position() mod 3 = 0?>
<?split-by-page-break:?>
<?end if?>

this will break the page after 3 rows, then after 6 rows and so on for every 3 multiple. You can replace 3 with your desired row count.

By the way position() is the row number in your xml data source.


问:
Xamarin.Forms.Switch sends Toggled event when value is updated
So I'm still debuting with Xamarin.Forms. So far so good, if I put aside a few pesky bugs I encountered. Here's the new guy. Maybe one of you could tell me if I'm doing something wrong.

Basically, I have a Xamarin.Forms.Switch on my interface, and I'm listening for changes in its state with the Toggled event. The doc says about this event: "Event that is raised when this Switch is toggled by the user."

Unfortunately, when I update the value of the switch programmatically, the event fires.

```<code>var mySwitch = new Switch ();
mySwitch.Toggled += (object sender, ToggledEventArgs e) => {
    Console.WriteLine ("Switch.Toggled event sent");
};
mySwitch.IsToggled = true;
</code>```

Any way to prevent the event from firing / to know that it's not the user who triggered it?

答:
Toggled event will every-time called, when you manually change the toggle that time also Toggled event will fire.

The solution is just set

```<code>mySwitch.Toggled -= HandleSwitchToggledByUser;
</code>```

before you manually change toggle value, and write

```<code>mySwitch.Toggled += HandleSwitchToggledByUser;
</code>```

after you manual change of toggle,

Hope, this will help you

Body:
So I'm still debuting with Xamarin.Forms. So far so good, if I put aside a few pesky bugs I encountered. Here's the new guy. Maybe one of you could tell me if I'm doing something wrong.

Basically, I have a Xamarin.Forms.Switch on my interface, and I'm listening for changes in its state with the Toggled event. The doc says about this event: "Event that is raised when this Switch is toggled by the user."

Unfortunately, when I update the value of the switch programmatically, the event fires.

var mySwitch = new Switch ();
mySwitch.Toggled += (object sender, ToggledEventArgs e) => {
    Console.WriteLine ("Switch.Toggled event sent");
};
mySwitch.IsToggled = true;

Any way to prevent the event from firing / to know that it's not the user who triggered it?

Body:
Toggled event will every-time called, when you manually change the toggle that time also Toggled event will fire.

The solution is just set

mySwitch.Toggled -= HandleSwitchToggledByUser;

before you manually change toggle value, and write

mySwitch.Toggled += HandleSwitchToggledByUser;

after you manual change of toggle,

Hope, this will help you


问:
"Execution Failed" error In Xamarin Studio
When I'm running app in Xamarin Studio I got an error "Execution Failed"
How to fix it?  </p>

答: The problem is your emulator, please try close the emulator and re-run your project. The problem occurs sometimes when you use your emulator for so long in Xamarin Studio.</p>


问:
HTMLElement focus() method Uncaught TypeError
I have come across an issue which i feel is rather odd though I'm still learning javascript. I want to do some calculations only when a value for a state is set, if the state isn't set then I want the form field focused.

Now the issue is that the code below doesn't work

```<code>document.getElementById('cart-hplus').addEventListener('submit', estimateTotal);

function estimateTotal(event) {
    event.preventDefault();

    var state = document.getElementById('s-state').value;
    if (state === '') {
        alert("Please choose your preferred shipping state.");

        state.focus();
    }
}
</code>```

Uncaught TypeError: state.focus is not a function

But this works but i don't think it's good habit declaring a variable then using the document object again inside my if statement

```<code>function estimateTotal(event) {
    event.preventDefault();

    var state = document.getElementById('s-state').value;
    if (state === '') {
        alert("Please choose your preferred shipping state.");

        document.getElementById('s-state').focus();
    }
}
</code>```

What is wrong with the first code?

答:
In your first code make following change,</p>

```<code>document.getElementById('cart-hplus').addEventListener('submit', estimateTotal);

function estimateTotal(event) {
    event.preventDefault();

    var state = document.getElementById('s-state');
    if (state.value === '') {
        alert("Please choose your preferred shipping state.");

        state.focus();
    }
}
</code>```

Body:
I have come across an issue which i feel is rather odd though I'm still learning javascript. I want to do some calculations only when a value for a state is set, if the state isn't set then I want the form field focused.

Now the issue is that the code below doesn't work

document.getElementById('cart-hplus').addEventListener('submit', estimateTotal);

function estimateTotal(event) {
    event.preventDefault();

    var state = document.getElementById('s-state').value;
    if (state === '') {
        alert("Please choose your preferred shipping state.");

        state.focus();
    }
}

Uncaught TypeError: state.focus is not a function

But this works but i don't think it's good habit declaring a variable then using the document object again inside my if statement

function estimateTotal(event) {
    event.preventDefault();

    var state = document.getElementById('s-state').value;
    if (state === '') {
        alert("Please choose your preferred shipping state.");

        document.getElementById('s-state').focus();
    }
}

What is wrong with the first code?

Body:
In your first code make following change,

document.getElementById('cart-hplus').addEventListener('submit', estimateTotal);

function estimateTotal(event) {
    event.preventDefault();

    var state = document.getElementById('s-state');
    if (state.value === '') {
        alert("Please choose your preferred shipping state.");

        state.focus();
    }
}


问:
how to pass backslash in html form
I know very little html, I have a backend application that does a mongodb lookup. I am building a simple html screen with forms to accept value to a web service which will run the mongo query and reply on the screen.

When I pass a filename path field in my form like this

```<code>\\test.server.com\filetest\test
</code>```

in my web service app, I see the value coming in as

```<code>%5c%5Ctest.server.com%5cfiletest%5ctest
</code>```

how can I get the value without this translation.

Matter fact I was hoping it would come in like this

```<code>\\\\test.server.com\\filetest\\test
</code>```

as that is how things got stored in mongo.

答:
You cannot pass a backslash directly as it is. That's because URLs can only be ASCII encoded. What this means is, that when you need to pass some special characters like Ü, as well as characters that need to be escaped in URLs (as spaces, backslashes, etc.) you need a way to represent them with ASCII symbols.

In your case the URL is getting encoded and backslashes are converted to %5c. To have them revert to '\' you need to either:

Decode them back in your server-side code. This is your best bet. This is done in different ways, depending on the technology your backend uses. In PHP, for example, you can use urldecode function - here.

Decode characters before querying in mongodb itself. This you will need to work on, because I'm not aware of a functionality that does this for you out of the box.

More info on URL encoding can be found here.

Hope this helps!

Title: how to pass backslash in html form

Body:
I know very little html, I have a backend application that does a mongodb lookup. I am building a simple html screen with forms to accept value to a web service which will run the mongo query and reply on the screen.

When I pass a filename path field in my form like this

\\test.server.com\filetest\test

in my web service app, I see the value coming in as

%5c%5Ctest.server.com%5cfiletest%5ctest

how can I get the value without this translation.

Matter fact I was hoping it would come in like this

\\\\test.server.com\\filetest\\test

as that is how things got stored in mongo.


问:
Show all errors above a form with bassistance plugin
So I am using this plugin for form validation:

http://bassistance.de/jquery-plugins/jquery-plugin-validation/

The problem is, it displays validation error next to each form field. I would like to display all errors above the form fields.

Is that possible? I cannot find this possibility mentioned in the documentation.

答:
Indeed it is, the option you are looking for is errorLabelContainer (used in combination with wrapper).

The example given there is:

```<code>$("#myform").validate({
   errorLabelContainer: "#messageBox",
   wrapper: "li",
   submitHandler: function() { alert("Submitted!") }
});
</code>```

So in the div (or whatever element has the id "messageBox"), you will get a
 with all the errors listed, wrapped in
 which you can then style as you want with an external css.

Body:
Indeed it is, the option you are looking for is errorLabelContainer (used in combination with wrapper).

The example given there is:

$("#myform").validate({
   errorLabelContainer: "#messageBox",
   wrapper: "li",
   submitHandler: function() { alert("Submitted!") }
});

So in the div (or whatever element has the id "messageBox"), you will get a <ul> with all the errors listed, wrapped in <li> which you can then style as you want with an external css.


问:
Image/File upload doesn't work with materializecss framework
I want to create a post creator which works with a database, but I can't upload an image or a file. My web-page is using the materialize framework. This code is mostly shrunk down to the important parts.</p>

```<code><?php
require_once 'include/Database.php';
require_once 'include/Sessions.php';
require_once 'include/Functions.php';

if (isset($_POST['addPostButton']) || isset($_FILES['image'])) {

    $imageName = $_POST['image'];
    $imageDirectory = 'uploads/' . basename($_FILES['image']['name']);

    if (!move_uploaded_file($_FILES['image']['tmp_name'], $imageDirectory)) {
        $_SESSION['ErrorMessage'] = 'File is invalid!';
    } else {
        global $ConnectingDB;
        $stmt = $ConnectingDB->prepare("INSERT INTO posts(image) VALUES('$imageName')");
        if ($stmt->execute()) {
            $_SESSION['SuccessMessage'] = 'Post created';
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Admin Dashboard</title>
    <link type="text/css" rel="stylesheet" href="css/materialize.css">
    <link type="text/css" rel="stylesheet" href="css/styles.css">
</head>
<body>
    <form action="add-post.php" method="post">
        <div class="row">
            <div class="file-field input-field">
                <div class="btn green">
                    <span>File</span>
                    <input type="file" name="image">
                </div>
                <div class="file-path-wrapper">
                    <input type="text" class="file-path" placeholder="Choose an image">
                </div>
            </div>
        </div>
    </form>
</body>
</html>
</code>```

答:
From

```<code><form action="add-post.php" method="post">
</code>```

To

```<code><form action="add-post.php" method="post" enctype="multipart/form-data">
</code>```

Here need to add a form attribute enctype to send files.

Body:
I want to create a post creator which works with a database, but I can't upload an image or a file. My web-page is using the materialize framework. This code is mostly shrunk down to the important parts.

<?php
require_once 'include/Database.php';
require_once 'include/Sessions.php';
require_once 'include/Functions.php';

if (isset($_POST['addPostButton']) || isset($_FILES['image'])) {

    $imageName = $_POST['image'];
    $imageDirectory = 'uploads/' . basename($_FILES['image']['name']);

    if (!move_uploaded_file($_FILES['image']['tmp_name'], $imageDirectory)) {
        $_SESSION['ErrorMessage'] = 'File is invalid!';
    } else {
        global $ConnectingDB;
        $stmt = $ConnectingDB->prepare("INSERT INTO posts(image) VALUES('$imageName')");
        if ($stmt->execute()) {
            $_SESSION['SuccessMessage'] = 'Post created';
        }
    }
}
?>

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Admin Dashboard</title>
    <link type="text/css" rel="stylesheet" href="css/materialize.css">
    <link type="text/css" rel="stylesheet" href="css/styles.css">

    <form action="add-post.php" method="post">

                    File
                    <input type="file" name="image">

                    <input type="text" class="file-path" placeholder="Choose an image">

    </form>

Body:
From

<form action="add-post.php" method="post">

To

<form action="add-post.php" method="post" enctype="multipart/form-data">

Here need to add a form attribute enctype to send files.


问:
What algorithm is used in Set to avoid duplicates?
May I know What algorithm is used in Set to avoid duplicates ?<br>
I want to know just What is the name of the algorithm used to avoid the duplicates and If possible the same algorithm implementation as well. </p>

答:
This depends on the Set implementation. Set is just an interface that defines the methods and general behavior of implementing classes. How this classes ensure the uniqueness of the entries depends on the implementation of this classes and can be quite different.

Some implementation could use an sorted list to quickly find an existing entry by using a binary search, some other class might be stupid and will just iterate over every entry to find out if an entry already exists or not.

Body:
May I know What algorithm is used in Set to avoid duplicates ?

I want to know just What is the name of the algorithm used to avoid the duplicates and If possible the same algorithm implementation as well.


问:
How to Launch specific activity when my Application is in Recent Apps List?
in my android application 3 activities are there.those are A,B&C.
Initial landing screen is A.then navigate to B.
But I want to display Activity C when this app is in recent appslist kind of App Masking.
Any one have idea please share me.
Thanks in Advance!!!</p>

答:
Well it's easy you can use the savedInstanceState Bundle to save a boolean flag(lest say isAppCameFromRecent) in onSavedInstanceState method when app minimised then use onRestoreInstanceState to extract that boolean when app returns from recent apps list if boolean is set to true then navigate to activity C.

@

```<code>Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
     super.onSaveInstanceState(savedInstanceState);
     ...
    }

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
...
}
</code>```

Body:
Well it's easy you can use the savedInstanceState Bundle to save a boolean flag(lest say isAppCameFromRecent) in onSavedInstanceState method when app minimised then use onRestoreInstanceState to extract that boolean when app returns from recent apps list if boolean is set to true then navigate to activity C.

@

Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
     super.onSaveInstanceState(savedInstanceState);
     ...
    }

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
...
}


问:
How to disable automatic import statements in VsCode October 2017
The latest version of VS Code installed a few days ago (the October 2017 update) keeps adding all kinds of strange import statements to the top of the .ts code file.

For example, as I was editing a file, VsCode suddenly added a line like this to the top of the file:

```<code>import { Stack } from "../../../../../../../../../Repos/Web/node_modules/@types/d3";
</code>```

How do I disable this behavior?

答:
You can disable it by adding this line to your user or workspace settings (File>Preferences>Settings, or Code>Preferences>Settings).

```<code>"typescript.autoImportSuggestions.enabled": false
</code>```

Ref.: https://github.com/Microsoft/vscode/issues/38551

Body:
The latest version of VS Code installed a few days ago (the October 2017 update) keeps adding all kinds of strange import statements to the top of the .ts code file.

For example, as I was editing a file, VsCode suddenly added a line like this to the top of the file:

import { Stack } from "../../../../../../../../../Repos/Web/node_modules/@types/d3";

How do I disable this behavior?

Body:
You can disable it by adding this line to your user or workspace settings (File>Preferences>Settings, or Code>Preferences>Settings).

"typescript.autoImportSuggestions.enabled": false

Ref.: https://github.com/Microsoft/vscode/issues/38551


问:
angularjs $boadcast and $on doesn´t work from angular.injector
I´m trying to call a function into a Controller when received a Push Notification, passing for a $broadcast / factory, but the broadcast doesn´t work when calling by the angular.injector, here a peace of my code:

push.js

```<code>window.onNotification = function(data) {
        angular.injector(['ng', 'myApp']).get("laFactory").PushReceived(data.additionalData); // --> work fine
    };
         window.push = PushNotification.init({
             "android": {
                 "senderID": "123456789",
                 "icon": "system",
                 "forceShow": true
             }
         });

         window.push.on('notification', window.onNotification);
</code>```

laFactory.js

```<code>.factory('laFactory', ['$http', '$rootScope', function ($http, $rootScope) {
    var laFactory = {};

    laFactory.PushReceived = function(data) {
       $rootScope.$broadcast('handleNotify', {}); // --> don´t work when called by angular.injector!!! why not?!
    };

    $rootScope.$broadcast('handleNotify', {}); // this work fine

    return laFactory;
}
</code>```

myController.js

```<code>.controller('NotificacoesController', function($scope, $rootScope, laFactory) {
    var handler = $scope.$on('handleNotify', function () {
            alert('broadcast - on');
    });
</code>```

}

答:
It's not clear why you are trying to get the service this way?

Pretty sure the syntax you're using is creating a new injector if you want to get the existing one then you would use something like:

angular.element(document).injector()

Even still I wonder why you wouldn't just inject the services normally.  https://docs.angularjs.org/api/ng/function/angular.injector

Ah I see now you're trying to get this outside of angular context... the above snippet will work but think you're better off typically just wrapping the notification code in a service instead of trying to use angular stuff outside of angular bring the other stuff "into the fold"  or search for existing modules that do this work for you.

Body:
I´m trying to call a function into a Controller when received a Push Notification, passing for a $broadcast / factory, but the broadcast doesn´t work when calling by the angular.injector, here a peace of my code:

push.js

window.onNotification = function(data) {
        angular.injector(['ng', 'myApp']).get("laFactory").PushReceived(data.additionalData); // --> work fine
    };
         window.push = PushNotification.init({
             "android": {
                 "senderID": "123456789",
                 "icon": "system",
                 "forceShow": true
             }
         });

         window.push.on('notification', window.onNotification);

laFactory.js

.factory('laFactory', ['$http', '$rootScope', function ($http, $rootScope) {
    var laFactory = {};

    laFactory.PushReceived = function(data) {
       $rootScope.$broadcast('handleNotify', {}); // --> don´t work when called by angular.injector!!! why not?!
    };

    $rootScope.$broadcast('handleNotify', {}); // this work fine

    return laFactory;
}

myController.js

.controller('NotificacoesController', function($scope, $rootScope, laFactory) {
    var handler = $scope.$on('handleNotify', function () {
            alert('broadcast - on');
    });

}


问:
Python style question: Support class as inner class?
I like to use the structures built into the language to organize my code. But there is one situation where I can't stay consistent, simply because I don't see a definitive best way of doing it. It's regarding support classes, that is, classes that are exclusively used internally by another class: Do I make them inner classes, or separate classes.

Inner classes:

```<code>class Complicated:
    class Utility1:
        pass
    class Utility2:
        pass
    pass
</code>```

Separate classes:

```<code>class Complicated:
    pass

class Utility1:
    pass

class Utility2:
    pass
</code>```

Inner classes has the advantage of being scoped inside the only class that uses them. But the problem is that I get less space to write code due to indentation.

Outer classes have neither the advantage nor the disadvantage. I am tired of always spending some mental energy whenever I write support classes, wondering about this silly issue.

My question is whether anyone with a substantial python experience on their back can advise as to whether there is a best practice regarding this? Even if the answer is that "it depends", it is appreciated if it comes with someone more experienced than myself.

答:
I would suggest

```<code>class Complicated:
    pass

class _Utility1:
    pass

class _Utility2:
    pass
</code>```

and put all this in a module of its own.  The leading _ indicates that the utility classes are meant for internal use only (and for what it's woth, they won't get imported by from module import *; but I don't like this anyway).

Edit: Citing from PEP 8:

Classes for internal use have a leading underscore in addition.

Body:
I like to use the structures built into the language to organize my code. But there is one situation where I can't stay consistent, simply because I don't see a definitive best way of doing it. It's regarding support classes, that is, classes that are exclusively used internally by another class: Do I make them inner classes, or separate classes.

Inner classes:

class Complicated:
    class Utility1:
        pass
    class Utility2:
        pass
    pass

Separate classes:

class Complicated:
    pass

class Utility1:
    pass

class Utility2:
    pass

Inner classes has the advantage of being scoped inside the only class that uses them. But the problem is that I get less space to write code due to indentation.

Outer classes have neither the advantage nor the disadvantage. I am tired of always spending some mental energy whenever I write support classes, wondering about this silly issue.

My question is whether anyone with a substantial python experience on their back can advise as to whether there is a best practice regarding this? Even if the answer is that "it depends", it is appreciated if it comes with someone more experienced than myself.

Body:
I would suggest

class Complicated:
    pass

class _Utility1:
    pass

class _Utility2:
    pass

and put all this in a module of its own.  The leading _ indicates that the utility classes are meant for internal use only (and for what it's woth, they won't get imported by from module import *; but I don't like this anyway).

Edit: Citing from PEP 8:

Classes for internal use have a leading underscore in addition.


问:
Why datetime in MATLAB is giving weird result?
I am trying to convert datenum values from double array. But conversion is leading to weird values in 'year'.

e.g.

     t(1)=23823.1076388889;
      d=datetime(t,'ConvertFrom','datenum');
      d(1) = '22-Mar-0065 02:35:00'

What am I doing wrong?

Thanks for your help.

答:
MATLAB date numbers count the number of days since midnight, Jan 1st of the fictitious year 0 (counting backward from today using the Gregorian system with leap years).

You have a different offset, so you simply need to add that:

```<code>t  = 23823.1076388889;
t0 = datenum('1950-01-01 00:00:00', 'yyyy-mm-dd HH:MM:SS');
d  = datestr(t + t0)
</code>```

which gives:

```<code>d =
    24-Mar-2015 02:35:00
</code>```

Body:
MATLAB date numbers count the number of days since midnight, Jan 1st of the fictitious year 0 (counting backward from today using the Gregorian system with leap years).

You have a different offset, so you simply need to add that:

t  = 23823.1076388889;
t0 = datenum('1950-01-01 00:00:00', 'yyyy-mm-dd HH:MM:SS');
d  = datestr(t + t0)

which gives:

d =
    24-Mar-2015 02:35:00


问:
Connecting Hive with python
I want to connect hive using python.

I am using Anaconda to get the module. Can anyone suggest me the correct syntax for connecting hive with python, I have the username and password for the hive database I wish to pick data from.

答:
You need to import Pyhive module

The command to connect is :-

```<code>from pyhive import hive
conn = hive.Connection(host="YOUR_HIVE_HOST", port=PORT, username="YOU")
</code>```

Hope this helps with the error you are still getting - Git link

Title: Connecting Hive with python

Body:
You need to import Pyhive module

The command to connect is :-

from pyhive import hive
conn = hive.Connection(host="YOUR_HIVE_HOST", port=PORT, username="YOU")

Hope this helps with the error you are still getting - Git link


问:
send selected values from JavaScript to Controller in CodeIgniter?
this is my view from which i want to send the data. when i select class name i want to send it to Controller by Ajax

```<code><select class="form-control" name="persent_class" id="class">
<?php foreach ($all_classes as $class) : ?>
  <option value="<?php echo $class['class_name']?>"><?php echo
  $class['class_name']?></option>
  <?php endforeach; ?>
          </select>
</code>```

this is my ajax function:

```<code><script type="text/javascript">
    $(document).ready(function () {
        $("#class").change(function () {
            var c = $("#class").val();
            $.ajax({
                type: "POST",
                url: "<?=base_url()?>index.php/Welcome/get_class_name",
                data: {"c":c},
                dataType:"json",
                cache: "false",

            });
        });
    });
</script>
</code>```

and this is my controller function:

```<code>public function get_class_name()
        {
            $id=$this->input->post('c');
            echo json_encode($id);

        }
</code>```

答:
Try it with this script, some line changed and you forget echo base_url:</p>

```<code><script type="text/javascript">
    $(document).ready(function () {
        $("#class").change(function () {
            var optionSelected = $(this).find("option:selected");
            var valueSelected  = optionSelected.val();
            $.ajax({
                type: "POST",
                url: "<?php echo base_url(); ?>index.php/Welcome/get_class_name",
                data: {"c":valueSelected},
                dataType:"json",
                cache: "false",

            });
        });
    });
</script>
</code>```

Body:
this is my view from which i want to send the data. when i select class name i want to send it to Controller by Ajax

<select class="form-control" name="persent_class" id="class">
<?php foreach ($all_classes as $class) : ?>
  <option value="<?php echo $class['class_name']?>"><?php echo
  $class['class_name']?></option>
  <?php endforeach; ?>
          </select>

this is my ajax function:

and this is my controller function:

public function get_class_name()
        {
            $id=$this->input->post('c');
            echo json_encode($id);

        }

Body:
Try it with this script, some line changed and you forget echo base_url:

<script type="text/javascript">
    $(document).ready(function () {
        $("#class").change(function () {
            var optionSelected = $(this).find("option:selected");
            var valueSelected  = optionSelected.val();
            $.ajax({
                type: "POST",
                url: "<?php echo base_url(); ?>index.php/Welcome/get_class_name",
                data: {"c":valueSelected},
                dataType:"json",
                cache: "false",

            });
        });
    });
</script>