问:
Error when try to update text in French/English to mysql db
I have one page to edit data. In this case, I will show the page to edit French data. The problem is that, when I paste the text in French and click to edit and update, it assumes mysql_error. This just happens with French and English, I can do it right in Portuguese. I'm using only this tree languages.

I've tried some ways, but nothing happened...
What is commented is that what I tried.

When I press the button, that is what happens : "Ocorreu um erro, tente de novo! You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'ont forcé à travailler comme apprenti à l'usine d'orfèvrerie de son ' at line 1"

```<code><?php
    session_start();
    $cookie_name = "loggedin";
    if (isset($_COOKIE[$cookie_name])){
        $cookie_value = $_COOKIE[$cookie_name];
    }else {
        echo "O seu tempo expirou, inicie sessão novamente!";
        header("Refresh:2; url=/estagio/admin/login.php");
    }

    ini_set ('default_charset', 'UTF-8');

    mysql_set_charset('utf8');

    //header ("content-type: text/html; charset=utf-8");

    //mysql_query("SET NAMES 'utf8'");
    //mysql_query("SET character_set_connection=utf8");
    //mysql_query("SET character_set_client=utf8");
    //mysql_query("SET character_set_results=utf8");

    mysql_connect ("localhost", "root", "") or die ("Erro na conexão " .mysql_error());
    mysql_select_db ("casadoadro") or die ("Erro na seleção da base de dados " .mysql_error());

    $editid = $_GET['eid'];

    if (!isset($_GET['eid']) || empty($_GET['eid'])){
        header ("location: admin_biografia.php");
    }

    $editquery = mysql_query("select * from tb_biografia where id='{$editid}'") or die (mysql_error());
    $editdata = mysql_fetch_row($editquery);

    if ($_POST)
    {
        $id = htmlspecialchars ($_POST['id']);
        $title_fr = htmlspecialchars ($_POST['title_fr']);
        $subtitle_fr = htmlspecialchars ($_POST['subtitle_fr']);
        $text_fr = htmlspecialchars ($_POST['text_fr']);

        $q = mysql_query ("UPDATE tb_biografia SET title_fr='{$title_fr}', subtitle_fr='{$subtitle_fr}', text_fr='{$text_fr}'  WHERE id='{$id}'") or die ("Ocorreu um erro, tente de novo! " .mysql_error());

        if($q){
            echo "<script>alert ('Editado com sucesso'); window.location='admin_biografia.php'</script>";
        }
    }
?>

<html>
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
        <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
        <link rel="stylesheet" type="text/css" href="/estagio/css/styles.css">
        <title>Casa do adro</title>
    </head>
    <body>
        <div class="col-2"></div>
        <div class="col-8">
                <div class="col-12 w3-card-4 nopadding">
                    <form method="post" class="w3-container w3margin" enctype="multipart/form-data">
                        <input type="hidden" name="size" value="10000000" />
                        <div class="w3-row mtb">
                            <div class="w3-col" style="width:150px">ID</div>
                            <div class="w3-rest">
                                <?php echo $editdata[0]; ?>
                                <input class="w3-input w3-border" type="hidden" name="id"  value="<?php echo $editdata[0]; ?>">
                            </div>
                        </div>
                        <div class="w3-row mtb">
                            <div class="w3-col" style="width:150px">Título FR</div>
                            <div class="w3-rest">
                                <input class="w3-input w3-border" type="text" name="title_fr"  value="<?php echo $editdata[2]; ?>">
                            </div>
                        </div>
                        <div class="w3-row mtb">
                            <div class="w3-col" style="width:150px">Legenda FR</div>
                            <div class="w3-rest">
                                <input class="w3-input w3-border" type="text" name="subtitle_fr"  value="<?php echo $editdata[6]; ?>">
                            </div>
                        </div>
                        <div class="w3-row mtb">
                            <div class="w3-col" style="width:150px">Texto FR</div>
                            <div class="w3-rest">
                                <div class="w3-rest">
                                <textarea class="w3-input w3-border" rows="1" type="text" name="text_fr"><?php echo $editdata[9]; ?></textarea>
                            </div>
                            </div>
                        </div>

                        <button class="btnfbform w3-block mtb w3-ripple  w3-input w3-border" type="submit" name="upload"> Editar texto</button>
                    </form>
                </div>
            </div>
            <div class="col-2"></div>
        </body>
</html>
</code>```

答:
TL;DR use htmlspecialchars($_POST['text_fr]', ENT_QUOTES) or use some SQL library

The text in $title_fr, $text_fr or other siilar variable probably contains a single quote character (') that messes up your query.

Let's say the value of $_POST['text_fr'] is C'est la vie.

Then the resulting query will look somewhat like this:

```<code>UPDATE tb_biografia SET text_fr='C'est la vie'  WHERE id='10'
</code>```

As you see, the quote that should delimit the string and the quote in the string itself mixes together and the resulting query is completely invalid. Even the syntax highliter here on Stack overflow is confused by that.

This is a huge security flaw that enables SQL injection attacks. Never compose SQL queries from user input by yourself if you are not perfectly sure that you know what you are doing.

The problem in your case is behavior of function htmlspecialchars. It DOES NOT escape single quotes by default, only double quotes. See http://php.net/manual/en/function.htmlspecialchars.php. You need to supply second argument, ENT_QUOTES, so that it will encode also single quotes.

```<code>$text_fr = htmlspecialchars ($_POST['text_fr'], ENT_QUOTES);
</code>```

Viva la PHP!

However, I really recommend you to use some tool that helps with building the query and protects you from similar mistakes:

PDO and prepared statements (part of PHP core)

NotORM, Dibi, SQL query builder... lightweight libraries for easier manipulation with SQL databases

Doctrine or similar ORM framework - for heavy lifting on bigger projects.

Body:
I have one page to edit data. In this case, I will show the page to edit French data. The problem is that, when I paste the text in French and click to edit and update, it assumes mysql_error. This just happens with French and English, I can do it right in Portuguese. I'm using only this tree languages.

I've tried some ways, but nothing happened...
What is commented is that what I tried.

When I press the button, that is what happens : "Ocorreu um erro, tente de novo! You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'ont forcé à travailler comme apprenti à l'usine d'orfèvrerie de son ' at line 1"

<?php
    session_start();
    $cookie_name = "loggedin";
    if (isset($_COOKIE[$cookie_name])){
        $cookie_value = $_COOKIE[$cookie_name];
    }else {
        echo "O seu tempo expirou, inicie sessão novamente!";
        header("Refresh:2; url=/estagio/admin/login.php");
    }

    ini_set ('default_charset', 'UTF-8');

    mysql_set_charset('utf8');

    //header ("content-type: text/html; charset=utf-8");

    //mysql_query("SET NAMES 'utf8'");
    //mysql_query("SET character_set_connection=utf8");
    //mysql_query("SET character_set_client=utf8");
    //mysql_query("SET character_set_results=utf8");

    mysql_connect ("localhost", "root", "") or die ("Erro na conexão " .mysql_error());
    mysql_select_db ("casadoadro") or die ("Erro na seleção da base de dados " .mysql_error());

    $editid = $_GET['eid'];

    if (!isset($_GET['eid']) || empty($_GET['eid'])){
        header ("location: admin_biografia.php");
    }

    $editquery = mysql_query("select * from tb_biografia where id='{$editid}'") or die (mysql_error());
    $editdata = mysql_fetch_row($editquery);

    if ($_POST)
    {
        $id = htmlspecialchars ($_POST['id']);
        $title_fr = htmlspecialchars ($_POST['title_fr']);
        $subtitle_fr = htmlspecialchars ($_POST['subtitle_fr']);
        $text_fr = htmlspecialchars ($_POST['text_fr']);

        $q = mysql_query ("UPDATE tb_biografia SET title_fr='{$title_fr}', subtitle_fr='{$subtitle_fr}', text_fr='{$text_fr}'  WHERE id='{$id}'") or die ("Ocorreu um erro, tente de novo! " .mysql_error());

        if($q){
            echo "";
        }
    }
?>

        <meta charset="UTF-8">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
        <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
        <link rel="stylesheet" type="text/css" href="/estagio/css/styles.css">
        <title>Casa do adro</title>

                    <form method="post" class="w3-container w3margin" enctype="multipart/form-data">
                        <input type="hidden" name="size" value="10000000" />

ID

                                <?php echo $editdata[0]; ?>
                                <input class="w3-input w3-border" type="hidden" name="id"  value="<?php echo $editdata[0]; ?>">

Título FR

                                <input class="w3-input w3-border" type="text" name="title_fr"  value="<?php echo $editdata[2]; ?>">

Legenda FR

                                <input class="w3-input w3-border" type="text" name="subtitle_fr"  value="<?php echo $editdata[6]; ?>">

Texto FR

                                <textarea class="w3-input w3-border" rows="1" type="text" name="text_fr"><?php echo $editdata[9]; ?></textarea>

                        <button class="btnfbform w3-block mtb w3-ripple  w3-input w3-border" type="submit" name="upload"> Editar texto</button>
                    </form>

Body:
TL;DR use htmlspecialchars($_POST['text_fr]', ENT_QUOTES) or use some SQL library

The text in $title_fr, $text_fr or other siilar variable probably contains a single quote character (') that messes up your query.

Let's say the value of $_POST['text_fr'] is C'est la vie.

Then the resulting query will look somewhat like this:

UPDATE tb_biografia SET text_fr='C'est la vie'  WHERE id='10'

As you see, the quote that should delimit the string and the quote in the string itself mixes together and the resulting query is completely invalid. Even the syntax highliter here on Stack overflow is confused by that.

This is a huge security flaw that enables SQL injection attacks. Never compose SQL queries from user input by yourself if you are not perfectly sure that you know what you are doing.

The problem in your case is behavior of function htmlspecialchars. It DOES NOT escape single quotes by default, only double quotes. See http://php.net/manual/en/function.htmlspecialchars.php. You need to supply second argument, ENT_QUOTES, so that it will encode also single quotes.

$text_fr = htmlspecialchars ($_POST['text_fr'], ENT_QUOTES);

Viva la PHP!

However, I really recommend you to use some tool that helps with building the query and protects you from similar mistakes:

PDO and prepared statements (part of PHP core)

NotORM, Dibi, SQL query builder... lightweight libraries for easier manipulation with SQL databases

Doctrine or similar ORM framework - for heavy lifting on bigger projects.


来源: stackexchange

问:
Ionic2 google maps Execution failed for task ':transformClassesWithDexForDebug'
my project woks good without google maps plugin , when i install it and try to build i get:

```<code>* What went wrong:
Execution failed for task ':transformClassesWithDexForDebug'.
> com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException:
java.util.concurrent.ExecutionException: com.android.dex.DexException: Multiple dex files define
Lcom/google/android/gms/iid/zzc;
</code>```

when i create a new project and install the plugin it runs well so i think one of my plugins conflict with it

ionic info:

```<code>global packages:

    @ionic/cli-utils : 1.4.0
    Cordova CLI      : 7.0.1
    Ionic CLI        : 3.4.0

local packages:

    @ionic/app-scripts              : 1.3.6
    @ionic/cli-plugin-cordova       : 1.4.0
    @ionic/cli-plugin-ionic-angular : 1.3.1
    Cordova Platforms               : android 6.2.3
    Ionic Framework                 : ionic-angular 3.1.1

System:

    Node       : v6.10.3
    OS         : Windows 10
    Xcode      : not installed
    ios-deploy : not installed
    ios-sim    : not installed
    npm        : 3.10.10
</code>```

cordova plugin list:

```<code>cordova-plugin-console 1.0.5 "Console"
cordova-plugin-device 1.1.4 "Device"
cordova-plugin-splashscreen 4.0.3 "Splashscreen"
cordova-plugin-statusbar 2.2.3 "StatusBar"
cordova-plugin-whitelist 1.3.1 "Whitelist"
cordova-sqlite-storage 2.0.4 "Cordova sqlite storage plugin"
ionic-plugin-keyboard 2.2.1 "Keyboard"
phonegap-plugin-push 1.10.4 "PushPlugin"
plugin.google.maps 1.3.9 "phonegap-googlemaps-plugin"
{}
</code>```

答:
Try installing version 1.3.9. Worked for me:</p>

```<code>cordova plugin add cordova-plugin-googlemaps@1.3.9 --variable API_KEY_FOR_ANDROID="YOUR_ANDROID_API_KEY_IS_HERE" --variable API_KEY_FOR_IOS="YOUR_IOS_API_KEY_IS_HERE"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
my project woks good without google maps plugin , when i install it and try to build i get:

* What went wrong:
Execution failed for task ':transformClassesWithDexForDebug'.
> com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException:
java.util.concurrent.ExecutionException: com.android.dex.DexException: Multiple dex files define
Lcom/google/android/gms/iid/zzc;

when i create a new project and install the plugin it runs well so i think one of my plugins conflict with it

ionic info:

global packages:

    @ionic/cli-utils : 1.4.0
    Cordova CLI      : 7.0.1
    Ionic CLI        : 3.4.0

local packages:

    @ionic/app-scripts              : 1.3.6
    @ionic/cli-plugin-cordova       : 1.4.0
    @ionic/cli-plugin-ionic-angular : 1.3.1
    Cordova Platforms               : android 6.2.3
    Ionic Framework                 : ionic-angular 3.1.1

System:

    Node       : v6.10.3
    OS         : Windows 10
    Xcode      : not installed
    ios-deploy : not installed
    ios-sim    : not installed
    npm        : 3.10.10

cordova plugin list:

cordova-plugin-console 1.0.5 "Console"
cordova-plugin-device 1.1.4 "Device"
cordova-plugin-splashscreen 4.0.3 "Splashscreen"
cordova-plugin-statusbar 2.2.3 "StatusBar"
cordova-plugin-whitelist 1.3.1 "Whitelist"
cordova-sqlite-storage 2.0.4 "Cordova sqlite storage plugin"
ionic-plugin-keyboard 2.2.1 "Keyboard"
phonegap-plugin-push 1.10.4 "PushPlugin"
plugin.google.maps 1.3.9 "phonegap-googlemaps-plugin"
{}

Body:
Try installing version 1.3.9. Worked for me:

cordova plugin add cordova-plugin-googlemaps@1.3.9 --variable API_KEY_FOR_ANDROID="YOUR_ANDROID_API_KEY_IS_HERE" --variable API_KEY_FOR_IOS="YOUR_IOS_API_KEY_IS_HERE"


问:
Failing azure git deploys due to jquery typings errors
I'm building a scheduling application that uses the syncfusion scheduler component (an ng2 wrapper around a jquery plugin essentially). Following their documentation I've added both jquery and the associated TS typings, and everything is working fine locally after some upgrading of npm versions.

When git deploying to azure for testing and demoing, my builds are failing. Initially the error was as follows:

Cannot find module 'validate-npm-package-license'

This isn't a package I've had to install, but I presume it's necessary to prove that my company own a license for these controls (which we do). I've got an open support call with syncfusion but hoping to progress this without waiting too long! Not sure if it's a valid fix but adding a prepublish script of:

```<code>"prepublish": "npm install -g validate-npm-package-license"
</code>```

seems to have fixed this issue. However, the next build failed with no real reason given, other than the process exited. In past experiences the occasional azure git deploy has failed randomly like this before passing on a redeploy so I tried that, but now receive hundreds of jquery typings errors such as:

ERROR in [at-loader] ./node_modules/@types/jquery/index.d.ts:41:40
            TS1005: ',' expected.

ERROR in [at-loader] ./node_modules/@types/jquery/index.d.ts:4332:52
            TS1139: Type parameter declaration expected.

ERROR in [at-loader] ./node_modules/@types/jquery/index.d.ts:35:23
            TS2314: Generic type 'JQueryStatic' requires 2 type argument(s).

etc etc.

I've already had to downgrade to a much older version of these typings to fix local build errors, but I'm unsure as to why this is now failing in azure.

I've forced the azure node version to 8.0.0 with the environment variable, and this then yields an npm version of 5.0.0, and this is my current package.json file:

```<code>{
  "name": "scheduler",
  "version": "0.0.0",
  "scripts": {
    "prepublish": "npm install -g validate-npm-package-license",
    "build": "webpack",
    "copy-ej": "xcopy node_modules\\syncfusion-javascript\\Content\\ej wwwroot\\dist\\ej /y /s /i",
    "postinstall": "npm run copy-ej",
    "test": "karma start ClientApp/test/karma.conf.js"
  },
  "dependencies": {
    "@angular/common": "^2.4.5",
    "@angular/compiler": "^2.4.5",
    "@angular/core": "^2.4.5",
    "@angular/forms": "^2.4.5",
    "@angular/http": "^2.4.5",
    "@angular/platform-browser": "^2.4.5",
    "@angular/platform-browser-dynamic": "^2.4.5",
    "@angular/platform-server": "^2.4.5",
    "@angular/router": "^3.4.5",
    "@types/ej.web.all": "^15.2.3",
    "@types/jquery": "^2.0.42",
    "@types/node": "^6.0.42",
    "angular2-jwt": "^0.2.3",
    "angular2-platform-node": "~2.0.11",
    "angular2-template-loader": "^0.6.2",
    "angular2-universal": "^2.1.0-rc.1",
    "angular2-universal-patch": "^0.2.1",
    "angular2-universal-polyfills": "^2.1.0-rc.1",
    "aspnet-prerendering": "^2.0.0",
    "aspnet-webpack": "^1.0.17",
    "awesome-typescript-loader": "^3.0.0",
    "bootstrap": "^3.3.7",
    "css": "^2.2.1",
    "css-loader": "^0.25.0",
    "ej-angular2": "^15.2.43",
    "es6-shim": "^0.35.1",
    "event-source-polyfill": "^0.0.7",
    "expose-loader": "^0.7.1",
    "extract-text-webpack-plugin": "^2.0.0-rc",
    "file-loader": "^0.9.0",
    "html-loader": "^0.4.4",
    "isomorphic-fetch": "^2.2.1",
    "jquery": "^2.2.1",
    "json-loader": "^0.5.4",
    "ngx-bootstrap": "^1.7.0",
    "preboot": "^4.5.2",
    "raw-loader": "^0.5.1",
    "rxjs": "5.4.1",
    "style-loader": "^0.13.1",
    "syncfusion-javascript": "^15.2.43",
    "to-string-loader": "^1.1.5",
    "typescript": "2.2.1",
    "url-loader": "^0.5.7",
    "webpack": "^2.2.0",
    "webpack-hot-middleware": "^2.12.2",
    "webpack-merge": "^0.14.1",
    "zone.js": "0.8.12"
  },
  "devDependencies": {
    "@types/chai": "^3.4.34",
    "@types/jasmine": "^2.5.37",
    "chai": "^3.5.0",
    "jasmine-core": "^2.5.2",
    "karma": "^1.3.0",
    "karma-chai": "^0.1.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-webpack": "^1.8.0"
  }
}
</code>```

Any suggestions on what might be causing this?
Cheers

答:
Thanks for your interest in Syncfusion components.

We are unable to reproduce the reported issue “ERROR in [at-loader] ./node_modules/@types/jquery/index.d.ts:41:40 TS1005: ',' expected.”  at out end with jquery.d.ts@2.0.34. We have created the ASP .NET Core Angular sample using Visual Studio 2015 and published it using Azure app service. For your convenience we have attached sample in below link.

Sample

Refer to the below link for published above angular app.

http://aspnet-sample20170704125558.azurewebsites.net/

For your reference we have attached log file of published app.

log-file

If you are still facing the issues share the sample application that you have tried to published, which help use to investigate further and provide you solution at the earliest.

Body:
I'm building a scheduling application that uses the syncfusion scheduler component (an ng2 wrapper around a jquery plugin essentially). Following their documentation I've added both jquery and the associated TS typings, and everything is working fine locally after some upgrading of npm versions.

When git deploying to azure for testing and demoing, my builds are failing. Initially the error was as follows:

Cannot find module 'validate-npm-package-license'

This isn't a package I've had to install, but I presume it's necessary to prove that my company own a license for these controls (which we do). I've got an open support call with syncfusion but hoping to progress this without waiting too long! Not sure if it's a valid fix but adding a prepublish script of:

"prepublish": "npm install -g validate-npm-package-license"

seems to have fixed this issue. However, the next build failed with no real reason given, other than the process exited. In past experiences the occasional azure git deploy has failed randomly like this before passing on a redeploy so I tried that, but now receive hundreds of jquery typings errors such as:

ERROR in [at-loader] ./node_modules/@types/jquery/index.d.ts:41:40
            TS1005: ',' expected.

ERROR in [at-loader] ./node_modules/@types/jquery/index.d.ts:4332:52
            TS1139: Type parameter declaration expected.

ERROR in [at-loader] ./node_modules/@types/jquery/index.d.ts:35:23
            TS2314: Generic type 'JQueryStatic' requires 2 type argument(s).

etc etc.

I've already had to downgrade to a much older version of these typings to fix local build errors, but I'm unsure as to why this is now failing in azure.

I've forced the azure node version to 8.0.0 with the environment variable, and this then yields an npm version of 5.0.0, and this is my current package.json file:

{
  "name": "scheduler",
  "version": "0.0.0",
  "scripts": {
    "prepublish": "npm install -g validate-npm-package-license",
    "build": "webpack",
    "copy-ej": "xcopy node_modules\\syncfusion-javascript\\Content\\ej wwwroot\\dist\\ej /y /s /i",
    "postinstall": "npm run copy-ej",
    "test": "karma start ClientApp/test/karma.conf.js"
  },
  "dependencies": {
    "@angular/common": "^2.4.5",
    "@angular/compiler": "^2.4.5",
    "@angular/core": "^2.4.5",
    "@angular/forms": "^2.4.5",
    "@angular/http": "^2.4.5",
    "@angular/platform-browser": "^2.4.5",
    "@angular/platform-browser-dynamic": "^2.4.5",
    "@angular/platform-server": "^2.4.5",
    "@angular/router": "^3.4.5",
    "@types/ej.web.all": "^15.2.3",
    "@types/jquery": "^2.0.42",
    "@types/node": "^6.0.42",
    "angular2-jwt": "^0.2.3",
    "angular2-platform-node": "~2.0.11",
    "angular2-template-loader": "^0.6.2",
    "angular2-universal": "^2.1.0-rc.1",
    "angular2-universal-patch": "^0.2.1",
    "angular2-universal-polyfills": "^2.1.0-rc.1",
    "aspnet-prerendering": "^2.0.0",
    "aspnet-webpack": "^1.0.17",
    "awesome-typescript-loader": "^3.0.0",
    "bootstrap": "^3.3.7",
    "css": "^2.2.1",
    "css-loader": "^0.25.0",
    "ej-angular2": "^15.2.43",
    "es6-shim": "^0.35.1",
    "event-source-polyfill": "^0.0.7",
    "expose-loader": "^0.7.1",
    "extract-text-webpack-plugin": "^2.0.0-rc",
    "file-loader": "^0.9.0",
    "html-loader": "^0.4.4",
    "isomorphic-fetch": "^2.2.1",
    "jquery": "^2.2.1",
    "json-loader": "^0.5.4",
    "ngx-bootstrap": "^1.7.0",
    "preboot": "^4.5.2",
    "raw-loader": "^0.5.1",
    "rxjs": "5.4.1",
    "style-loader": "^0.13.1",
    "syncfusion-javascript": "^15.2.43",
    "to-string-loader": "^1.1.5",
    "typescript": "2.2.1",
    "url-loader": "^0.5.7",
    "webpack": "^2.2.0",
    "webpack-hot-middleware": "^2.12.2",
    "webpack-merge": "^0.14.1",
    "zone.js": "0.8.12"
  },
  "devDependencies": {
    "@types/chai": "^3.4.34",
    "@types/jasmine": "^2.5.37",
    "chai": "^3.5.0",
    "jasmine-core": "^2.5.2",
    "karma": "^1.3.0",
    "karma-chai": "^0.1.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-webpack": "^1.8.0"
  }
}

Any suggestions on what might be causing this?
Cheers


问:
Cucumber feature on form with Captcha
If you form has captcha (i'm using humanizer gem). How do you fill up form and send and get the expected result when writing cucumber feature.

```<code>Scenario: Sign Up with Valid Data
  Given I am not authenticated
  And I am on the sign in page
  When I follow "Sign up"
  And I fill in the following:
    | Name                   | Administrator            |
    | Email                  | admin@admin.com          |
    | Password               | 123456                   |
    | Password confirmation  | 123456                   |
  And I fill in the captcha correctly
  And I press "Sign Up"
  Then I should be on the new_company page
  And I should see "Hello Manoj"
</code>```

Now i can write a step definition matching /^I fill up catcha correctly$/ but what must be put there?

Be gentle, i'm new to cucumber and it's been frustrating so far. I'm not new to Rails or programming otherwise.

答:
So one solution i found out was to ensure Captcha is only added in Production environment.

To some extent i'm happy with that. But it would be ideal to reduce environment based branching in the app.

```<code>class User
  ...
  include Humanizer
  if Rails.env.production?
    require_human_on :create, :unless => :bypass_humanizer
  end
  ...
end
</code>```

ContentLicense: CC BY-SA 2.5

Title: Cucumber feature on form with Captcha

Body:
If you form has captcha (i'm using humanizer gem). How do you fill up form and send and get the expected result when writing cucumber feature.

Scenario: Sign Up with Valid Data
  Given I am not authenticated
  And I am on the sign in page
  When I follow "Sign up"
  And I fill in the following:
    | Name                   | Administrator            |
    | Email                  | admin@admin.com          |
    | Password               | 123456                   |
    | Password confirmation  | 123456                   |
  And I fill in the captcha correctly
  And I press "Sign Up"
  Then I should be on the new_company page
  And I should see "Hello Manoj"

Now i can write a step definition matching /^I fill up catcha correctly$/ but what must be put there?

Be gentle, i'm new to cucumber and it's been frustrating so far. I'm not new to Rails or programming otherwise.

Body:
So one solution i found out was to ensure Captcha is only added in Production environment.

To some extent i'm happy with that. But it would be ideal to reduce environment based branching in the app.

class User
  ...
  include Humanizer
  if Rails.env.production?
    require_human_on :create, :unless => :bypass_humanizer
  end
  ...
end


问:
Properties vs. Getters and Setters
It has been considered as a "horrible scenario" to update OurClass so that "OurAtt" is a value between 0 and 1000:

```<code>class OurClass:
    def __init__(self, a):
        self.OurAtt = a

x = OurClass(10)
print(x.OurAtt)
</code>```

Now, my question is why do we rely on the @property? Is it because of code legibility or there is some other reason; since we can well do the checks under the __init__() method?

```<code>class OurClass:
    def __init__(self, a):
        if a < 0:
            self.OurAtt = 0
        elif a > 1000:
            self.OurAtt = 1000
        else:
            self.OurAtt = a
</code>```

答:
The fact that you perform checks in the __init__ method does not guarantee that the value cannot be altered later to an invalid value.

For example:

```<code>x = OurClass(10)
x.OurAtt = -20
</code>```

We thus want to run the test every time the ourAtt value is set. We can do this with:

```<code>class OurClass:

    def __init__(self, a):
        self.OurAtt = a

    @property
    def OurAtt(self):
        return self._OurAtt

    @OurAtt.setter
    def OurAtt(self,a):
        if a < 0:
            self._OurAtt = 0
        elif a > 1000:
            self._OurAtt = 1000
        else:
            self._OurAtt = a
</code>```

Furthermore it allows to make the code more readable: every setter checks whether one specific value is valid. This is usually a better approach than checking all values in the same method, since if we alter the specifications of one value, we only have to modify the corresponding setter.

Another advantage is that validation is done in a transparent matter: you do not have to change an attribute into a "setter method": for the user, it just looks like he/she alters an attribute. You can thus later in the process - when users already make use of the attribute - decide to add some validation without changing the interface.

Finally it is more declarative and thus usually more "Pythonic".

Title: Properties vs. Getters and Setters

Body:
It has been considered as a "horrible scenario" to update OurClass so that "OurAtt" is a value between 0 and 1000:

class OurClass:
    def __init__(self, a):
        self.OurAtt = a

x = OurClass(10)
print(x.OurAtt)

Now, my question is why do we rely on the @property? Is it because of code legibility or there is some other reason; since we can well do the checks under the __init__() method?

class OurClass:
    def __init__(self, a):
        if a < 0:
            self.OurAtt = 0
        elif a > 1000:
            self.OurAtt = 1000
        else:
            self.OurAtt = a

Body:
The fact that you perform checks in the __init__ method does not guarantee that the value cannot be altered later to an invalid value.

For example:

x = OurClass(10)
x.OurAtt = -20

We thus want to run the test every time the ourAtt value is set. We can do this with:

class OurClass:

    def __init__(self, a):
        self.OurAtt = a

    @property
    def OurAtt(self):
        return self._OurAtt

    @OurAtt.setter
    def OurAtt(self,a):
        if a < 0:
            self._OurAtt = 0
        elif a > 1000:
            self._OurAtt = 1000
        else:
            self._OurAtt = a

Furthermore it allows to make the code more readable: every setter checks whether one specific value is valid. This is usually a better approach than checking all values in the same method, since if we alter the specifications of one value, we only have to modify the corresponding setter.

Another advantage is that validation is done in a transparent matter: you do not have to change an attribute into a "setter method": for the user, it just looks like he/she alters an attribute. You can thus later in the process - when users already make use of the attribute - decide to add some validation without changing the interface.

Finally it is more declarative and thus usually more "Pythonic".


问:
Convert std::string to boost::asio::streambuf
How do I convert the std::string  to boost::asio::streambuf?
Any lead is appreciated.

Initially I used boost::asio::read_until(pNetworkConnector->getSocket(), response, "\r\n"); which initialized boost::asio::streambuf response and I converted it to underlying stream i.e.

```<code>boost::asio::streambuf* responsePointer = &response;
iResponseStream.rdbuf(responsePointer);
</code>```

But now I directly get a std::string using curl like this

```<code>static size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp)
{
    ((std::string*)userp)->append((char*)contents, size * nmemb);
    return size * nmemb;
}
</code>```

and used it as

```<code>curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, &readBuffer);
</code>```

How can I convert std::string to boost::asio::streambuf or std::streambuf ?

答:
The following code shows how to convert between std::string and boost::asio::streambuf, see it online at ideone:

```<code>#include <iostream>
#include <boost/asio/streambuf.hpp>
#include <boost/asio/buffer.hpp>

int main()
{
   /* Convert std::string --> boost::asio::streambuf */
   boost::asio::streambuf sbuf;
   std::iostream os(&sbuf);
   std::string message("Teststring");
   os << message;

   /* Convert boost::asio::streambuf --> std::string */
   std::string str((std::istreambuf_iterator<char>(&sbuf)),
                    std::istreambuf_iterator<char>());

   std::cout << str << std::endl;
}
</code>```

Body:
How do I convert the std::string  to boost::asio::streambuf?
Any lead is appreciated.

Initially I used boost::asio::read_until(pNetworkConnector->getSocket(), response, "\r\n"); which initialized boost::asio::streambuf response and I converted it to underlying stream i.e.

boost::asio::streambuf* responsePointer = &response;
iResponseStream.rdbuf(responsePointer);

But now I directly get a std::string using curl like this

static size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp)
{
    ((std::string*)userp)->append((char*)contents, size * nmemb);
    return size * nmemb;
}

and used it as

curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, &readBuffer);

How can I convert std::string to boost::asio::streambuf or std::streambuf ?

Body:
The following code shows how to convert between std::string and boost::asio::streambuf, see it online at ideone:

#include <iostream>
#include <boost/asio/streambuf.hpp>
#include <boost/asio/buffer.hpp>

int main()
{
   /* Convert std::string --> boost::asio::streambuf */
   boost::asio::streambuf sbuf;
   std::iostream os(&sbuf);
   std::string message("Teststring");
   os << message;

   /* Convert boost::asio::streambuf --> std::string */
   std::string str((std::istreambuf_iterator<char>(&sbuf)),
                    std::istreambuf_iterator<char>());

   std::cout << str << std::endl;
}


问:
Convert Set<Map.Entry<K, V>> to HashMap<K, V>
At one point in my code, I created a Set<Map.Entry<K, V>> from a map. Now I want to recreate the same map form, so I want to convert the HashSet<Map.Entry<K, V>> back into a HashMap<K, V>. Does Java have a native call for doing this, or do I have to loop over the set elements and build the map up manually?

答: As of Guava 19 you can use ImmutableMap.copyOf(Iterable<Map.Entry<K,V>>)


问:
Casting an object to List<T> to be able to use extension methods
I have generated an extension method to display a IList<T> in a meaningful manner:

```<code>public static class IListExtension
{
  public static string ToDisplay<T>(this IList<T> source, string seperator = ",")
  {
    string display = string.Empty;
    // create the display string from the elements of this list
    return display;
  }
}
</code>```

To use this extension I can do this:

```<code>IList<someClass> myList = CreateList();
myList.ToDisplay();
</code>```

My problem is now, that I have a method that gets an object, which also can be a list. So, if the object is no list, I want to use the ToString() method, if it IS a list, I want to use my extension.

```<code>public string CreateDisplayString(object element)
{
  if (element == null)
    return string.Empty;

  if (element as IList<T> != null)
    return (element as IList<T>).ToDisplay();

  return element.ToString();
}
</code>```

Obviously, the code above does not work, because I cannot cast to the generic IList<T>. If I use an existing class, like IList<string> it works for lists of strings like I want it to, but of course I don't want to create a statement for each possible IList<[name of class]>. Is there a way to use the extension method or any other means to get a custom string from a list of any type?

答:
Well, you're basically looking for run-time overload resolution - dynamic does that. Have a separate method for the separate overloads you want, and it will pick the right one based on the usual overload resolution rules:

```<code>void Do<T>(IList<T> list) => ...
void Do(string someString) => ...
void Do(object somethingElse) => ...
</code>```

Then you can call the best overload (at run-time) just by doing

```<code>Do((dynamic)someObject);
</code>```

If you can afford to use dynamic, this is probably the simplest solution.

If not, you can exploit type variance. Instead of IList<T>, you can use IEnumerable<T> (which seems to be enough for the cases you've shown), which is covariant with respect to T. This allows you to do

```<code>if (someObject is IEnumerable<object> e)
{
  e.ToDisplay();
}
</code>```

This is only useful if the ToDisplay method doesn't actually use the type argument for something, of course.

Also, as InBetween correctly noted, value types do not support variance - so this will still fail for List<int>, for example - (new List<int>() is IEnumerable<object>) == false. It will only work correctly for reference types. You can still use the non-generic IList for that case, but you'll need a separate ToDisplay method for that. Alternatively, you could use reflection to invoke the correct method with the correct generic type arguments directly, but by that point you'd just have something that works pretty much like dynamic, but clunkier.

Body:
I have generated an extension method to display a IList<T> in a meaningful manner:

public static class IListExtension
{
  public static string ToDisplay<T>(this IList<T> source, string seperator = ",")
  {
    string display = string.Empty;
    // create the display string from the elements of this list
    return display;
  }
}

To use this extension I can do this:

IList<someClass> myList = CreateList();
myList.ToDisplay();

My problem is now, that I have a method that gets an object, which also can be a list. So, if the object is no list, I want to use the ToString() method, if it IS a list, I want to use my extension.

public string CreateDisplayString(object element)
{
  if (element == null)
    return string.Empty;

  if (element as IList<T> != null)
    return (element as IList<T>).ToDisplay();

  return element.ToString();
}

Obviously, the code above does not work, because I cannot cast to the generic IList<T>. If I use an existing class, like IList<string> it works for lists of strings like I want it to, but of course I don't want to create a statement for each possible IList<[name of class]>. Is there a way to use the extension method or any other means to get a custom string from a list of any type?

Body:
Well, you're basically looking for run-time overload resolution - dynamic does that. Have a separate method for the separate overloads you want, and it will pick the right one based on the usual overload resolution rules:

void Do<T>(IList<T> list) => ...
void Do(string someString) => ...
void Do(object somethingElse) => ...

Then you can call the best overload (at run-time) just by doing

Do((dynamic)someObject);

If you can afford to use dynamic, this is probably the simplest solution.

If not, you can exploit type variance. Instead of IList<T>, you can use IEnumerable<T> (which seems to be enough for the cases you've shown), which is covariant with respect to T. This allows you to do

if (someObject is IEnumerable<object> e)
{
  e.ToDisplay();
}

This is only useful if the ToDisplay method doesn't actually use the type argument for something, of course.

Also, as InBetween correctly noted, value types do not support variance - so this will still fail for List<int>, for example - (new List<int>() is IEnumerable<object>) == false. It will only work correctly for reference types. You can still use the non-generic IList for that case, but you'll need a separate ToDisplay method for that. Alternatively, you could use reflection to invoke the correct method with the correct generic type arguments directly, but by that point you'd just have something that works pretty much like dynamic, but clunkier.


问:
Crystal Reports Error in formula
I have a global variable which was declared in a formula in the Report Header section of my document.  I then try to reference that variable to use it in a for loop, and I get the error:

A number, currency amount, boolean,
  data, time, date-time, or string is
  expected here.

What is wrong here and how can I correct?  Code follows:

Header Formula:

```<code>Global StringVar Array items;
redim items [1];

Global StringVar Array jobs;
redim jobs [1];

Global StringVar Array POs;
redim POs [1];

Global StringVar Array Qty;
redim Qty [1];

Global NumberVar numRecordsPrinted;
numRecordsPrinted := 0;

""
</code>```

Detail Formula:

```<code>    Local NumberVar occurances;
    Local StringVar poTOuse;
    Local NumberVar i;

    if {%Line_PO_Test} <> ''
    and {PackingSlipHeader.CompanyCode} <> '10063'
    and {PackingSlipHeader.CompanyCode} <> '10017'
    then
        //Count the number of occurances
        For i := 0 To numRecordsPrinted Do       //Error on numRecordsPrinted
        (
            if items[i] = {PS_DETAIL_FOR_PRINT.DTSItemNumber}
                AND jobs[i] = {PS_DETAIL_FOR_PRINT.JobNumber}
                And Qty[i] = {PS_DETAIL_FOR_PRINT.Quantity_Shipped}
                THEN
                    occurances := occurances + 1
        )

        //Use the # of occurances to get the right PO number
Select occurances
        case 0: poTOuse := {@LinePOnum}
        case 1: poTOuse := {@Line_PO_3}
        case 2: poTOuse := {@Line_PO_2}

        default: poTOuse := "";

        //Save data into the array and increment for next time
        numRecordsPrinted := numRecordsPrinted + 1
        items[numRecordsPrinted] := {PS_DETAIL_FOR_PRINT.DTSItemNumber}
        jobs[numRecordsPrinted] := {PS_DETAIL_FOR_PRINT.JobNumber}
        Qty[numRecordsPrinted] :=   {PS_DETAIL_FOR_PRINT.Quantity_Shipped}

    //Print to the report
    'PO#: ' + poTOuse;
</code>```

答:
If you comment out the following section of code like so, do you still get an error?

```<code>For i := 0 To numRecordsPrinted Do       //Error on numRecordsPrinted
        (
//            if items[i] = {PS_DETAIL_FOR_PRINT.DTSItemNumber}
//                AND jobs[i] = {PS_DETAIL_FOR_PRINT.JobNumber}
//                And Qty[i] = {PS_DETAIL_FOR_PRINT.Quantity_Shipped}
//                THEN
                    occurances := occurances + 1
        )
</code>```

If yes, do you still get the error when you comment out occurances := occurances + 1?

Since the arrays are StringVars, you might need to wrap your database fields with cstr like this:

```<code>(
        if items[i] = cstr({PS_DETAIL_FOR_PRINT.DTSItemNumber})
            AND jobs[i] = cstr({PS_DETAIL_FOR_PRINT.JobNumber})
            And Qty[i] = cstr({PS_DETAIL_FOR_PRINT.Quantity_Shipped})
            THEN
                occurances := occurances + 1
    )
</code>```

If you want to remove the trailing decimals for the Quantity_Shipped, you can use cstr({PS_DETAIL_FOR_PRINT.Quantity_Shipped}, "0") instead.

Title: Crystal Reports Error in formula

Body:
I have a global variable which was declared in a formula in the Report Header section of my document.  I then try to reference that variable to use it in a for loop, and I get the error:

A number, currency amount, boolean,
  data, time, date-time, or string is
  expected here.

What is wrong here and how can I correct?  Code follows:

Header Formula:

Global StringVar Array items;
redim items [1];

Global StringVar Array jobs;
redim jobs [1];

Global StringVar Array POs;
redim POs [1];

Global StringVar Array Qty;
redim Qty [1];

Global NumberVar numRecordsPrinted;
numRecordsPrinted := 0;

""

Detail Formula:

    Local NumberVar occurances;
    Local StringVar poTOuse;
    Local NumberVar i;

    if {%Line_PO_Test} <> ''
    and {PackingSlipHeader.CompanyCode} <> '10063'
    and {PackingSlipHeader.CompanyCode} <> '10017'
    then
        //Count the number of occurances
        For i := 0 To numRecordsPrinted Do       //Error on numRecordsPrinted
        (
            if items[i] = {PS_DETAIL_FOR_PRINT.DTSItemNumber}
                AND jobs[i] = {PS_DETAIL_FOR_PRINT.JobNumber}
                And Qty[i] = {PS_DETAIL_FOR_PRINT.Quantity_Shipped}
                THEN
                    occurances := occurances + 1
        )

        //Use the # of occurances to get the right PO number
Select occurances
        case 0: poTOuse := {@LinePOnum}
        case 1: poTOuse := {@Line_PO_3}
        case 2: poTOuse := {@Line_PO_2}

        default: poTOuse := "";

        //Save data into the array and increment for next time
        numRecordsPrinted := numRecordsPrinted + 1
        items[numRecordsPrinted] := {PS_DETAIL_FOR_PRINT.DTSItemNumber}
        jobs[numRecordsPrinted] := {PS_DETAIL_FOR_PRINT.JobNumber}
        Qty[numRecordsPrinted] :=   {PS_DETAIL_FOR_PRINT.Quantity_Shipped}

    //Print to the report
    'PO#: ' + poTOuse;

Body:
If you comment out the following section of code like so, do you still get an error?

For i := 0 To numRecordsPrinted Do       //Error on numRecordsPrinted
        (
//            if items[i] = {PS_DETAIL_FOR_PRINT.DTSItemNumber}
//                AND jobs[i] = {PS_DETAIL_FOR_PRINT.JobNumber}
//                And Qty[i] = {PS_DETAIL_FOR_PRINT.Quantity_Shipped}
//                THEN
                    occurances := occurances + 1
        )

If yes, do you still get the error when you comment out occurances := occurances + 1?

Since the arrays are StringVars, you might need to wrap your database fields with cstr like this:

(
        if items[i] = cstr({PS_DETAIL_FOR_PRINT.DTSItemNumber})
            AND jobs[i] = cstr({PS_DETAIL_FOR_PRINT.JobNumber})
            And Qty[i] = cstr({PS_DETAIL_FOR_PRINT.Quantity_Shipped})
            THEN
                occurances := occurances + 1
    )

If you want to remove the trailing decimals for the Quantity_Shipped, you can use cstr({PS_DETAIL_FOR_PRINT.Quantity_Shipped}, "0") instead.


问:
Treat WHERE IN parameters as AND and not OR
I have this table structure/data :

I want to select the row_id(s) that have the combination of (97,6,2) AND (99,1,4) on (attribute_id,store_id,value) respectively.

In this example, we want to get the row_id 8664 as it respects this condition.

What I did is to use the where in statement like following :

```<code>SELECT DISTINCT row_id from catalog_product_entity_int
where row_id in
   (select row_id from catalog_product_entity_int
    WHERE (attribute_id, store_id,value)
    IN ( (99,1,4),(97,6,1) ))
</code>```

This outputs the lines that have (99,1,4) OR (97,6,1).

I tried this query :

```<code>SELECT DISTINCT row_id from catalog_product_entity_int
where row_id in
    (select row_id from catalog_product_entity_int
    WHERE (attribute_id, store_id,value) IN (99,1,4)
    AND (attribute_id, store_id,value) IN(97,6,1) )
</code>```

But I have #1241 - Operand should contain 3 column(s)

How do I manage to select the lines that validates the two conditions together ?

答:
It's easy.

Vectors (99, 1, 4) and (97, 6, 1) must be in parentheses: ((99, 1, 4)) and ((97, 6, 1)).

Try:

```<code>SELECT DISTINCT row_id
FROM catalog_product_entity_int
WHERE row_id IN (
    SELECT row_id
    FROM catalog_product_entity_int
    WHERE (attribute_id, store_id, value) IN ((99, 1, 4))
          OR (attribute_id, store_id, value) IN ((97, 6, 1))
)
</code>```

or even better:

```<code>SELECT DISTINCT row_id
FROM catalog_product_entity_int
WHERE row_id IN (
    SELECT row_id
    FROM catalog_product_entity_int
    WHERE (attribute_id, store_id, value) IN ((99, 1, 4), (97, 6, 1))
)
</code>```

Body:
I have this table structure/data :

I want to select the row_id(s) that have the combination of (97,6,2) AND (99,1,4) on (attribute_id,store_id,value) respectively.

In this example, we want to get the row_id 8664 as it respects this condition.

What I did is to use the where in statement like following :

SELECT DISTINCT row_id from catalog_product_entity_int
where row_id in
   (select row_id from catalog_product_entity_int
    WHERE (attribute_id, store_id,value)
    IN ( (99,1,4),(97,6,1) ))

This outputs the lines that have (99,1,4) OR (97,6,1).

I tried this query :

SELECT DISTINCT row_id from catalog_product_entity_int
where row_id in
    (select row_id from catalog_product_entity_int
    WHERE (attribute_id, store_id,value) IN (99,1,4)
    AND (attribute_id, store_id,value) IN(97,6,1) )

But I have #1241 - Operand should contain 3 column(s)

How do I manage to select the lines that validates the two conditions together ?

Body:
It's easy.

Vectors (99, 1, 4) and (97, 6, 1) must be in parentheses: ((99, 1, 4)) and ((97, 6, 1)).

Try:

SELECT DISTINCT row_id
FROM catalog_product_entity_int
WHERE row_id IN (
    SELECT row_id
    FROM catalog_product_entity_int
    WHERE (attribute_id, store_id, value) IN ((99, 1, 4))
          OR (attribute_id, store_id, value) IN ((97, 6, 1))
)

or even better:

SELECT DISTINCT row_id
FROM catalog_product_entity_int
WHERE row_id IN (
    SELECT row_id
    FROM catalog_product_entity_int
    WHERE (attribute_id, store_id, value) IN ((99, 1, 4), (97, 6, 1))
)


问:
RePost (bounce) received datas the same using curl
Does anyone knows How to bounce (RePost, exactly the same way) an array (datas) previously posted to my page ?

Here is how i do by now, guess it's not the best way :

Received datas

```<code>$_datas = $_REQUEST;
</code>```

and how i rePost ?

```<code> $ch = curl_init();
 curl_setopt($ch, CURLOPT_POST, 1);
 curl_setopt($ch, CURLOPT_URL, 'http://website.com/new_script.php');
 curl_setopt($ch, CURLOPT_POSTFIELDS, $_datas);
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
 $result = curl_exec($ch);
</code>```

Anyone has an idea ? Please ;)

答:
If you want to re-post data which comes in GET and POST, your code almost complete. Just need to add curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

So, code will be like this

```<code>$_datas = $_REQUEST;
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, 'http://website.com/new_script.php');
curl_setopt($ch, CURLOPT_POSTFIELDS, $_datas);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result     = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
</code>```

Body:
Does anyone knows How to bounce (RePost, exactly the same way) an array (datas) previously posted to my page ?

Here is how i do by now, guess it's not the best way :

Received datas

$_datas = $_REQUEST;

and how i rePost ?

 $ch = curl_init();
 curl_setopt($ch, CURLOPT_POST, 1);
 curl_setopt($ch, CURLOPT_URL, 'http://website.com/new_script.php');
 curl_setopt($ch, CURLOPT_POSTFIELDS, $_datas);
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
 $result = curl_exec($ch);

Anyone has an idea ? Please ;)

Body:
If you want to re-post data which comes in GET and POST, your code almost complete. Just need to add curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

So, code will be like this

$_datas = $_REQUEST;
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, 'http://website.com/new_script.php');
curl_setopt($ch, CURLOPT_POSTFIELDS, $_datas);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result     = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);


问:
How do I implement Authorization with a Single Page Application and REST Backend?
I'm using Node.js with Loopback (based on Express) for the REST API. It has an ACL implementation that allows you to give/prevent access from/to parts of the API to a Role.

The front-end of the application is written with React and Redux.

The app will have a public and a private part, and I want people to be able to log in to /admin.

Next to the ACL for the REST resources, should there be a separate Authorization mechanism for the front-end?

Say I want to be able to access the #/admin page and my user is part of a role that allows you to look up information about users; How do I decide that my user can access the admin dashboard and how do I decide that my user may add a widget that makes use of the users API, to which his Role has been granted access?

答:
Use flashboard for loopback admin dashboard.
Its automatically generate your admin panel based on your models configs.

vah7id.github.io/flashboard


问:
Significant new inventions in computing since 1980
This question arose from comments about different kinds of progress in computing over the last 50 years or so.

I was asked by some of the other participants to raise it as a question to the whole forum.

The basic idea here is not to bash the current state of things but to try to understand something about the progress of coming up with fundamental new ideas and principles.

I claim that we need really new ideas in most areas of computing, and I would like to know of any important and powerful ones that have been done recently. If we can't really find them, then we should ask "Why?" and "What should we be doing?"

答: I think part of the problem with these answers is they are either not well researched or are attempting to a new implementation or some technology that has seen significant "improvements." However, this is not a significant invention. For instance, any talking about functional programming or object oriented programming just fails; most of these ideas have been circulating since before most of the participants of SO were born.</p>

OwnerDisplayName: Alan Kay

LastEditorDisplayName: Out Into Space

OwnerDisplayName: BobbyShaftoe


问:
jQuery not working in IE 7 and Chrome
Okay, I have enough code that I probably shouldn't post the code directly, but I'm not sure where the problem lies within it.

The page in question is at letterlyyours.com/design.php.  How it's supposed to work is that you type in a word, press "Submit", and then little photos of each letter appear below--that you can scroll up and down.  In addition, if you click on a thumbnail, fancybox opens to show the full image.

The problem is that in Chrome, all the scrolling arrows are disabled.  Also in IE 6/7 (it works in IE 8), fancybox only works for the first thumbnail in the list.  Isn't that weird?

Anyway, I suspect the problem may be caused by something hackish I had to do to fix another problem.  For a list of photos, I had originally used 2D arrays, like photos[4][6], but this only worked in Firefox, so I changed it to something like eval('photos'+number+'[index]), which seemed to make it work in IE except for the aforementioned problems.

The link to the file with all the javascript code is: http://letterlyyours.com/jcarousel/design.js.php

Here's the code:

```<code>photos0 = [
{url: "photos/thumb_A 1.jpg", title: "A 1"},
{url: "photos/thumb_A 2.jpg", title: "A 2"},
...
];
...
...
photos25 = [
{url: "photos/thumb_Z 1.jpg", title: "Z 1"},
...
];

jQuery(document).ready(function() {

jQuery('#create').submit(function(event) {
    var word = jQuery('#word').val();
    event.preventDefault();
    jQuery('ul').unbind();
    jQuery("#creation").html('');
    jQuery('#creation').css('width', Math.max(122, 75*word.length));
    for (var a = 0; a < word.length; a++)
        {
        jQuery('#creation').append('<ul class="jcarousel jcarousel-skin-tango" id="carousel' + a + '"></ul>');
        var total = eval('photos' + parseInt(word.toUpperCase().charCodeAt(a)-65) + '.length');
        for (var b = 0; b < total; b++)
            {
            var url = eval('photos' + parseInt(word.toUpperCase().charCodeAt(a)-65) + '[b].url');
            var url_full = url.replace('thumb_', '');
            jQuery('#carousel' + a).append('<li><a id="thumb' + b + '" href="' + url_full + '"><div style="width: 75px; height: 113px; background-image: url(\'' + url + '\');"></div></a></li>');
            jQuery('a#thumb' + b).fancybox({
                'transitionIn': 'elastic',
                'transitionOut': 'elastic',
                'hideOnContentClick': true
            });
            }
        jQuery('#carousel' + a).jcarousel({
            vertical: true,
            scroll: 1,
            itemVisibleInCallback: function(carousel, li, index, state) {
                jQuery(li).parent().data('image', jQuery(li).children('a').children('div').css('background-image').replace(/"/g, ''));
            }
        });
        }
    jQuery('#creation').append('<a id="order" href="#orderform"><img width="122" height="24" src="images/button_order.png" tabindex="3" alt="Order Yours" /></a>');
    jQuery('a#order').fancybox({
    'hideOnContentClick': false,
    'transitionIn': 'fade',
    'frameWidth': 'auto',
    'title': 'Order \'' + word + '\'',
    'overlayShow': true,
    'overlayOpacity': 0.8,
    'overlayColor': 'black',
    'onStart': function() {
        jQuery('#list').html('');
        jQuery('#cost').html(word.length + ' photos at $6.00 per photo <br />Total: $' + word.length*6);
        jQuery('form#contact-form').unbind();
        jQuery('form#contact-form').submit(function(event) {
            jQuery.fancybox.showActivity();
            jQuery.post('contact.php', jQuery('form#contact-form').serialize(), function()
                {
                jQuery.fancybox(jQuery('div#thanks'));
                });
            event.preventDefault();
        });
        var photolist = '';
        for (a = 0; a < word.length; a++)
            {
            jQuery('#list').append('<div style="float: left; width: 75px; height: 113px; background-image: ' + jQuery('#carousel' + a).data('image') + '"/>');
            photolist += jQuery('#carousel' + a).data('image');
            }
        jQuery('#photonames').val(photolist);
        }
    });
});

jQuery('#word').keypress(function(event) {
    var letter = event.which;
    if ((letter != 8) && (letter != 0))
        {
        if (letter < 97)
            letter += 32;
        if (!((letter >= 97) && (letter <= 122)))
            {
            event.preventDefault();
            }
        }
});

jQuery('#word').select(function(event) {
    event.preventDefault();
});
});
</code>```

答: I think it might be a problem with children. it isnt working for me either on IE7</p>

Title: jQuery not working in IE 7 and Chrome

Body:
Okay, I have enough code that I probably shouldn't post the code directly, but I'm not sure where the problem lies within it.

The page in question is at letterlyyours.com/design.php.  How it's supposed to work is that you type in a word, press "Submit", and then little photos of each letter appear below--that you can scroll up and down.  In addition, if you click on a thumbnail, fancybox opens to show the full image.

The problem is that in Chrome, all the scrolling arrows are disabled.  Also in IE 6/7 (it works in IE 8), fancybox only works for the first thumbnail in the list.  Isn't that weird?

Anyway, I suspect the problem may be caused by something hackish I had to do to fix another problem.  For a list of photos, I had originally used 2D arrays, like photos[4][6], but this only worked in Firefox, so I changed it to something like eval('photos'+number+'[index]), which seemed to make it work in IE except for the aforementioned problems.

The link to the file with all the javascript code is: http://letterlyyours.com/jcarousel/design.js.php

Here's the code:

photos0 = [
{url: "photos/thumb_A 1.jpg", title: "A 1"},
{url: "photos/thumb_A 2.jpg", title: "A 2"},
...
];
...
...
photos25 = [
{url: "photos/thumb_Z 1.jpg", title: "Z 1"},
...
];

jQuery(document).ready(function() {

jQuery('#create').submit(function(event) {
    var word = jQuery('#word').val();
    event.preventDefault();
    jQuery('ul').unbind();
    jQuery("#creation").html('');
    jQuery('#creation').css('width', Math.max(122, 75*word.length));
    for (var a = 0; a < word.length; a++)
        {
        jQuery('#creation').append('

');
        var total = eval('photos' + parseInt(word.toUpperCase().charCodeAt(a)-65) + '.length');
        for (var b = 0; b < total; b++)
            {
            var url = eval('photos' + parseInt(word.toUpperCase().charCodeAt(a)-65) + '[b].url');
            var url_full = url.replace('thumb_', '');
            jQuery('#carousel' + a).append('

');
            jQuery('a#thumb' + b).fancybox({
                'transitionIn': 'elastic',
                'transitionOut': 'elastic',
                'hideOnContentClick': true
            });
            }
        jQuery('#carousel' + a).jcarousel({
            vertical: true,
            scroll: 1,
            itemVisibleInCallback: function(carousel, li, index, state) {
                jQuery(li).parent().data('image', jQuery(li).children('a').children('div').css('background-image').replace(/"/g, ''));
            }
        });
        }
    jQuery('#creation').append('');
    jQuery('a#order').fancybox({
    'hideOnContentClick': false,
    'transitionIn': 'fade',
    'frameWidth': 'auto',
    'title': 'Order \'' + word + '\'',
    'overlayShow': true,
    'overlayOpacity': 0.8,
    'overlayColor': 'black',
    'onStart': function() {
        jQuery('#list').html('');
        jQuery('#cost').html(word.length + ' photos at $6.00 per photo
Total: $' + word.length*6);
        jQuery('form#contact-form').unbind();
        jQuery('form#contact-form').submit(function(event) {
            jQuery.fancybox.showActivity();
            jQuery.post('contact.php', jQuery('form#contact-form').serialize(), function()
                {
                jQuery.fancybox(jQuery('div#thanks'));
                });
            event.preventDefault();
        });
        var photolist = '';
        for (a = 0; a < word.length; a++)
            {
            jQuery('#list').append('
');
            photolist += jQuery('#carousel' + a).data('image');
            }
        jQuery('#photonames').val(photolist);
        }
    });
});

jQuery('#word').keypress(function(event) {
    var letter = event.which;
    if ((letter != 8) && (letter != 0))
        {
        if (letter < 97)
            letter += 32;
        if (!((letter >= 97) && (letter <= 122)))
            {
            event.preventDefault();
            }
        }
});

jQuery('#word').select(function(event) {
    event.preventDefault();
});
});


问:
Packer waiting for SSH to become available
I am new to packer and vagrant and I am trying to build a brand new Windows OS Virtual box from Windows 10 disc image and packer. However, while doing build, packer never quits on the step "Waiting for SSH to become available". I have tried and followed multiple solutions from Stack overflow and Hashicorp but nothing fixed my issue.

My windows 10 JSON file:

```<code>{
  "builders": [
    {
      "type": "virtualbox-iso",
      "iso_url": "{{user `iso_url`}}",
      "iso_checksum_type": "{{user `iso_checksum_type`}}",
      "iso_checksum": "{{user `iso_checksum`}}",
      "headless": false,
      "boot_wait": "10m",
      "ssh_username": "vagrant",
      "ssh_password": "vagrant",
      "ssh_wait_timeout": "2h",
      "shutdown_command": "shutdown /s /t 10 /f /d p:4:1 /c \"Packer Shutdown\"",
      "guest_os_type": "Windows10_64",
      "disk_size": 61440,
      "vboxmanage": [
        [
          "modifyvm",
          "{{.Name}}",
          "--memory",
          "2048"
        ],
        [
          "modifyvm",
          "{{.Name}}",
          "--cpus",
          "2"
        ]
      ]
    }
  ],
  "post-processors":[
    {
      "type": "vagrant",
      "keep_input_artifact": false,
      "output": "windows_10_{{.Provider}}.box",
      "vagrantfile_template": "windows10.template"
    }
  ],
  "variables": {
    "iso_url": "C:/Ebe/Vagrant/Windows_10/SW_DVD5_Win_Pro_10_1511.1_64BIT_English_MLF_X20-93914.iso",
    "iso_checksum_type": "md5",
    "iso_checksum": "bd09dc56c51a6ce137b8c0eb7c4369ea",
    "autounattend": "./answer_files/10/Autounattend.xml"
  }
}
</code>```

My windows.template

```<code>Vagrant.require_version ">= 1.6.2"

Vagrant.configure("2") do |config|
    config.vm.define "vagrant-windows-10"
    config.vm.box = "windows_10"
    config.vm.communicator = "winrm"

    # Admin user name and password
    config.winrm.username = "vagrant"
    config.winrm.password = "vagrant"   config.vm.network :private_network, ip: "192.168.56.1"

    config.vm.guest = :windows
    config.windows.halt_timeout = 15

    config.vm.network :forwarded_port, guest: 3389, host: 3389, id: "rdp", auto_correct: true
    config.vm.network :forwarded_port, guest: 22, host: 2222, id: "ssh", auto_correct: true

    config.vm.provider :virtualbox do |v, override|
        #v.gui = true
        v.customize ["modifyvm", :id, "--memory", 2048]
        v.customize ["modifyvm", :id, "--cpus", 2]
        v.customize ["setextradata", "global", "GUI/SuppressMessages", "all" ]
    end

    config.vm.provider :vmware_fusion do |v, override|
        #v.gui = true
        v.vmx["memsize"] = "2048"
        v.vmx["numvcpus"] = "2"
        v.vmx["ethernet0.virtualDev"] = "vmxnet3"
        v.vmx["RemoteDisplay.vnc.enabled"] = "false"
        v.vmx["RemoteDisplay.vnc.port"] = "5900"
        v.vmx["scsi0.virtualDev"] = "lsisas1068"
    end

    config.vm.provider :vmware_workstation do |v, override|
        #v.gui = true
        v.vmx["memsize"] = "2048"
        v.vmx["numvcpus"] = "2"
        v.vmx["ethernet0.virtualDev"] = "vmxnet3"
        v.vmx["RemoteDisplay.vnc.enabled"] = "false"
        v.vmx["RemoteDisplay.vnc.port"] = "5900"

        v.vmx["scsi0.virtualDev"] = "lsisas1068"
    end end
</code>```

I am using below command to kick off the build

```<code>packer build windows10.json
</code>```

Below is the output of never ending build

```<code>virtualbox-iso output will be in this color.

==> virtualbox-iso: Downloading or copying Guest additions
    virtualbox-iso: Downloading or copying: file:///C:/Program%20Files/Oracle/VirtualBox/VBoxGuestAdditions.iso
==> virtualbox-iso: Downloading or copying ISO
    virtualbox-iso: Downloading or copying: file:///C:/Ebe/Vagrant/Windows_10/SW_DVD5_Win_Pro_10_1511.1_64BIT_English_MLF_X20-93914.iso
==> virtualbox-iso: Creating virtual machine...
==> virtualbox-iso: Creating hard drive...
==> virtualbox-iso: Creating forwarded port mapping for communicator (SSH, WinRM, etc) (host port 3527)
==> virtualbox-iso: Executing custom VBoxManage commands...
    virtualbox-iso: Executing: modifyvm packer-virtualbox-iso-1499123943 --memory 2048
    virtualbox-iso: Executing: modifyvm packer-virtualbox-iso-1499123943 --cpus 2
==> virtualbox-iso: Starting the virtual machine...
==> virtualbox-iso: Waiting 10m0s for boot...
==> virtualbox-iso: Typing the boot command...
==> virtualbox-iso: Waiting for SSH to become available...
</code>```

Please let me know if you have any suggestion to make this build work.

答:
Installing Windows automatically is a complicated matter. Instead of starting from scratch I recommend that you base your work on someone else, for example https://github.com/joefitzgerald/packer-windows

One basic problem with your packer template is that it should use WinRM and not SSH.

Body:
I am new to packer and vagrant and I am trying to build a brand new Windows OS Virtual box from Windows 10 disc image and packer. However, while doing build, packer never quits on the step "Waiting for SSH to become available". I have tried and followed multiple solutions from Stack overflow and Hashicorp but nothing fixed my issue.

My windows 10 JSON file:

{
  "builders": [
    {
      "type": "virtualbox-iso",
      "iso_url": "{{user `iso_url`}}",
      "iso_checksum_type": "{{user `iso_checksum_type`}}",
      "iso_checksum": "{{user `iso_checksum`}}",
      "headless": false,
      "boot_wait": "10m",
      "ssh_username": "vagrant",
      "ssh_password": "vagrant",
      "ssh_wait_timeout": "2h",
      "shutdown_command": "shutdown /s /t 10 /f /d p:4:1 /c \"Packer Shutdown\"",
      "guest_os_type": "Windows10_64",
      "disk_size": 61440,
      "vboxmanage": [
        [
          "modifyvm",
          "{{.Name}}",
          "--memory",
          "2048"
        ],
        [
          "modifyvm",
          "{{.Name}}",
          "--cpus",
          "2"
        ]
      ]
    }
  ],
  "post-processors":[
    {
      "type": "vagrant",
      "keep_input_artifact": false,
      "output": "windows_10_{{.Provider}}.box",
      "vagrantfile_template": "windows10.template"
    }
  ],
  "variables": {
    "iso_url": "C:/Ebe/Vagrant/Windows_10/SW_DVD5_Win_Pro_10_1511.1_64BIT_English_MLF_X20-93914.iso",
    "iso_checksum_type": "md5",
    "iso_checksum": "bd09dc56c51a6ce137b8c0eb7c4369ea",
    "autounattend": "./answer_files/10/Autounattend.xml"
  }
}

My windows.template

Vagrant.require_version ">= 1.6.2"

Vagrant.configure("2") do |config|
    config.vm.define "vagrant-windows-10"
    config.vm.box = "windows_10"
    config.vm.communicator = "winrm"

    # Admin user name and password
    config.winrm.username = "vagrant"
    config.winrm.password = "vagrant"   config.vm.network :private_network, ip: "192.168.56.1"

    config.vm.guest = :windows
    config.windows.halt_timeout = 15

    config.vm.network :forwarded_port, guest: 3389, host: 3389, id: "rdp", auto_correct: true
    config.vm.network :forwarded_port, guest: 22, host: 2222, id: "ssh", auto_correct: true

    config.vm.provider :virtualbox do |v, override|
        #v.gui = true
        v.customize ["modifyvm", :id, "--memory", 2048]
        v.customize ["modifyvm", :id, "--cpus", 2]
        v.customize ["setextradata", "global", "GUI/SuppressMessages", "all" ]
    end

    config.vm.provider :vmware_fusion do |v, override|
        #v.gui = true
        v.vmx["memsize"] = "2048"
        v.vmx["numvcpus"] = "2"
        v.vmx["ethernet0.virtualDev"] = "vmxnet3"
        v.vmx["RemoteDisplay.vnc.enabled"] = "false"
        v.vmx["RemoteDisplay.vnc.port"] = "5900"
        v.vmx["scsi0.virtualDev"] = "lsisas1068"
    end

    config.vm.provider :vmware_workstation do |v, override|
        #v.gui = true
        v.vmx["memsize"] = "2048"
        v.vmx["numvcpus"] = "2"
        v.vmx["ethernet0.virtualDev"] = "vmxnet3"
        v.vmx["RemoteDisplay.vnc.enabled"] = "false"
        v.vmx["RemoteDisplay.vnc.port"] = "5900"

        v.vmx["scsi0.virtualDev"] = "lsisas1068"
    end end

I am using below command to kick off the build

packer build windows10.json

Below is the output of never ending build

virtualbox-iso output will be in this color.

==> virtualbox-iso: Downloading or copying Guest additions
    virtualbox-iso: Downloading or copying: file:///C:/Program%20Files/Oracle/VirtualBox/VBoxGuestAdditions.iso
==> virtualbox-iso: Downloading or copying ISO
    virtualbox-iso: Downloading or copying: file:///C:/Ebe/Vagrant/Windows_10/SW_DVD5_Win_Pro_10_1511.1_64BIT_English_MLF_X20-93914.iso
==> virtualbox-iso: Creating virtual machine...
==> virtualbox-iso: Creating hard drive...
==> virtualbox-iso: Creating forwarded port mapping for communicator (SSH, WinRM, etc) (host port 3527)
==> virtualbox-iso: Executing custom VBoxManage commands...
    virtualbox-iso: Executing: modifyvm packer-virtualbox-iso-1499123943 --memory 2048
    virtualbox-iso: Executing: modifyvm packer-virtualbox-iso-1499123943 --cpus 2
==> virtualbox-iso: Starting the virtual machine...
==> virtualbox-iso: Waiting 10m0s for boot...
==> virtualbox-iso: Typing the boot command...
==> virtualbox-iso: Waiting for SSH to become available...

Please let me know if you have any suggestion to make this build work.


问:
Compiler does not identify class on the same package
I had some java classes a couple years ago, due to lack of use it all faded away. now ive been getting back into it. i was following a very simple tutorial building something using sublime (it was so simple i didn't bother on getting a proper IDE) the two files are:

```<code>package hello;

public class HelloWorld {
    public static void main(String[] args) {
        Greeter greeter = new Greeter();
        System.out.println(greeter.sayHello());
        System.out.println("random alt shift");
    }
}
</code>```

and

```<code>package hello;

public class Greeter {
    public String sayHello() {
        return "Hello world!";
    }
}
</code>```

Greeter compiles dine but HelloWorld gives me the following error:
javac HelloWorld.java

```<code>HelloWorld.java:6: error: cannot find symbol
        Greeter greeter = new Greeter();
        ^
  symbol:   class Greeter
  location: class HelloWorld
HelloWorld.java:6: error: cannot find symbol
        Greeter greeter = new Greeter();
                              ^
  symbol:   class Greeter
  location: class HelloWorld
2 errors
</code>```

and if i add "import hello.Greeter;" i get:

```<code>HelloWorld.java:2: error: cannot find symbol
import hello.Greeter;
            ^
  symbol:   class Greeter
  location: package hello
HelloWorld.java:6: error: cannot find symbol
        Greeter greeter = new Greeter();
        ^
  symbol:   class Greeter
  location: class HelloWorld
HelloWorld.java:6: error: cannot find symbol
        Greeter greeter = new Greeter();
                              ^
  symbol:   class Greeter
  location: class HelloWorld
3 errors
</code>```

On the IDE it runs fine, can anyone be so kind as to explain whats happening

答:
```<code>javac HelloWorld.java
</code>```

The problem is here. You're in the wrong directory. You should be up one level, where the package hierarchy starts, and you should be issuing

```<code>javac hello/HelloWorld.java
</code>```

Body:
I had some java classes a couple years ago, due to lack of use it all faded away. now ive been getting back into it. i was following a very simple tutorial building something using sublime (it was so simple i didn't bother on getting a proper IDE) the two files are:

package hello;

public class HelloWorld {
    public static void main(String[] args) {
        Greeter greeter = new Greeter();
        System.out.println(greeter.sayHello());
        System.out.println("random alt shift");
    }
}

and

package hello;

public class Greeter {
    public String sayHello() {
        return "Hello world!";
    }
}

Greeter compiles dine but HelloWorld gives me the following error:
javac HelloWorld.java

HelloWorld.java:6: error: cannot find symbol
        Greeter greeter = new Greeter();
        ^
  symbol:   class Greeter
  location: class HelloWorld
HelloWorld.java:6: error: cannot find symbol
        Greeter greeter = new Greeter();
                              ^
  symbol:   class Greeter
  location: class HelloWorld
2 errors

and if i add "import hello.Greeter;" i get:

HelloWorld.java:2: error: cannot find symbol
import hello.Greeter;
            ^
  symbol:   class Greeter
  location: package hello
HelloWorld.java:6: error: cannot find symbol
        Greeter greeter = new Greeter();
        ^
  symbol:   class Greeter
  location: class HelloWorld
HelloWorld.java:6: error: cannot find symbol
        Greeter greeter = new Greeter();
                              ^
  symbol:   class Greeter
  location: class HelloWorld
3 errors

On the IDE it runs fine, can anyone be so kind as to explain whats happening

Body:
javac HelloWorld.java

The problem is here. You're in the wrong directory. You should be up one level, where the package hierarchy starts, and you should be issuing

javac hello/HelloWorld.java


问:
Django, permission error saving on disk, why?
I'm getting a Permissions Error [Errno 13] Permission Denied when a workbook on disk using openpyxl:

```<code>wb.save(path)
</code>```

No file is uploaded. It's a request then the file is generated and delivered (downloaded), and that part works fine. What I'm trying to do is save a copy of that file on disk.

So far I have rw to both group and others. Same error.
Is this a Django or Linux permission issue?

答:
I think you do not have permissions on path directory, check permission on path
 directory

Body:
I'm getting a Permissions Error [Errno 13] Permission Denied when a workbook on disk using openpyxl:

wb.save(path)

No file is uploaded. It's a request then the file is generated and delivered (downloaded), and that part works fine. What I'm trying to do is save a copy of that file on disk.

So far I have rw to both group and others. Same error.
Is this a Django or Linux permission issue?


问:
Is complex formatting inside label of tab in Tkinter Notebook widget possible?
I've just finished adding some nice formatting to my logging console where based on the message type the prefix of the message is coloured differently:

In order to do that I used tags (tag_config()) along with Font() to make things bold:

```<code>from tkinter import font, Tk, END
from tkinter.scrolledtext import ScrolledText

def log_info(msg, widget):
  log(msg, "info", widget)

def log_error(msg, widget):
  log(msg, "error", widget)

def log_warn(msg, widget):
  log(msg, "warn", widget)

def log(msg, type, widget):
  msg_prefix = font.Font(widget, widget.cget("font"))
  msg_prefix.configure(weight="bold")
  if type == "info":
    widget.insert(END, "INFO: ", "info")
    widget.insert(END, msg + "\n")
  elif type == "error":
    widget.insert(END, "ERROR: ", "error")
    widget.insert(END, msg + "\n")
  elif type == "warn":
    widget.insert(END, "WARNING: ", "warn")
    widget.insert(END, msg + "\n")
  else:
    print("Unknown type of log message. Available types are 'info', 'error' and 'warn'")

  widget.tag_config("info", font=msg_prefix)
  widget.tag_config("error", foreground="red", font=msg_prefix)
  widget.tag_config("warn", foreground="orange", font=msg_prefix)

window = Tk()
window.geometry('970x45')
box = ScrolledText(window, width=70, height=7)
box.pack()
log_info("This is an information log message", box)
log_error("This is an error log message", box)
log_warn("This is a warning log message", box)

window.mainloop()
</code>```

However I am struggling to add a similar feature to the tab where this console is. Every time an error log message is logged in the console the tab where it is located gets updated to show the number of errors that are currently logged:

However I would like to make the (4) (from the screenshot above) coloured with red. I was unable to find font formatting for the tab label:

Reason: I've discovered that the logging console gets ignored quite often since the other tab in my widget is where the interaction happens. Since I want to keep things separated in order to prevent clustering too many things on the screen at the same time I'm trying to notify the user in an non-intrusive way that an error has occurred (other types of log messages are not that important).

答:
If you're using the ttk.Notebook, the answer is that you can only configure the tab text style for all tabs using styling. So you can make ALL tabs foreground red...

```<code>nb = ttk.Notebook(master, style='TNotebook')
...
style = ttk.Style()
# This will change the foreground color of ALL tabs to red.
style.configure('TNotebook.Tab', foreground='red')
</code>```

You could also use the tab compound option, which enables you to place both text and an image on the tab. You can change the text or image on a given tab separately. But to do what you are asking, your '(4)' would have to be an image, meaning you'd have to have a lot of pre-existing images waiting to be loaded depending on how many errors you anticipate.

Body:
I've just finished adding some nice formatting to my logging console where based on the message type the prefix of the message is coloured differently:

In order to do that I used tags (tag_config()) along with Font() to make things bold:

from tkinter import font, Tk, END
from tkinter.scrolledtext import ScrolledText

def log_info(msg, widget):
  log(msg, "info", widget)

def log_error(msg, widget):
  log(msg, "error", widget)

def log_warn(msg, widget):
  log(msg, "warn", widget)

def log(msg, type, widget):
  msg_prefix = font.Font(widget, widget.cget("font"))
  msg_prefix.configure(weight="bold")
  if type == "info":
    widget.insert(END, "INFO: ", "info")
    widget.insert(END, msg + "\n")
  elif type == "error":
    widget.insert(END, "ERROR: ", "error")
    widget.insert(END, msg + "\n")
  elif type == "warn":
    widget.insert(END, "WARNING: ", "warn")
    widget.insert(END, msg + "\n")
  else:
    print("Unknown type of log message. Available types are 'info', 'error' and 'warn'")

  widget.tag_config("info", font=msg_prefix)
  widget.tag_config("error", foreground="red", font=msg_prefix)
  widget.tag_config("warn", foreground="orange", font=msg_prefix)

window = Tk()
window.geometry('970x45')
box = ScrolledText(window, width=70, height=7)
box.pack()
log_info("This is an information log message", box)
log_error("This is an error log message", box)
log_warn("This is a warning log message", box)

window.mainloop()

However I am struggling to add a similar feature to the tab where this console is. Every time an error log message is logged in the console the tab where it is located gets updated to show the number of errors that are currently logged:

However I would like to make the (4) (from the screenshot above) coloured with red. I was unable to find font formatting for the tab label:

Reason: I've discovered that the logging console gets ignored quite often since the other tab in my widget is where the interaction happens. Since I want to keep things separated in order to prevent clustering too many things on the screen at the same time I'm trying to notify the user in an non-intrusive way that an error has occurred (other types of log messages are not that important).

Body:
If you're using the ttk.Notebook, the answer is that you can only configure the tab text style for all tabs using styling. So you can make ALL tabs foreground red...

nb = ttk.Notebook(master, style='TNotebook')
...
style = ttk.Style()
# This will change the foreground color of ALL tabs to red.
style.configure('TNotebook.Tab', foreground='red')

You could also use the tab compound option, which enables you to place both text and an image on the tab. You can change the text or image on a given tab separately. But to do what you are asking, your '(4)' would have to be an image, meaning you'd have to have a lot of pre-existing images waiting to be loaded depending on how many errors you anticipate.


问:
why does window object in javascript doesnt has this key but also console?
```<code>var varFunc = function declareFunc() {
  console.log(this); // window
  console.log(this.declareFunc); // undefined
  console.log(declareFunc); // function body
}
console.log(this) // window
varFunc();
</code>```

i know this in function direction to  window, but window doesn't has props declareFunc, but , finally this code still console [Function: declareFunc]  why?

and if i use Function.name :

```<code>var varFunc = function declareFunc() {
  console.log(this); // window
  console.log(declareFunc.name) // "declareFunc"
  console.log(varFunc.name); // "declareFunc". but why?
  console.log(this.declareFunc); // undefined
  console.log(declareFunc); // function body
}
console.log(varFunc.name) // "declareFunc". why?
var aa = function (){}
console.log(aa.name) // "aa"
console.log(this) // window
varFunc();
</code>```

答:
```<code>var varFunc = function declareFunc() {
  console.log(varFunc===declareFunc);//true
}
</code>```

This function has now two names: varFunc externally and declareFunc internally, so inside of it, you can access declareFunc,varFunc and window.varFunc , and outside:

```<code>console.log(varFunc,declareFunc);//function, undefined/error
</code>```

Body:
var varFunc = function declareFunc() {
  console.log(this); // window
  console.log(this.declareFunc); // undefined
  console.log(declareFunc); // function body
}
console.log(this) // window
varFunc();

i know this in function direction to  window, but window doesn't has props declareFunc, but , finally this code still console [Function: declareFunc]  why?

and if i use Function.name :

var varFunc = function declareFunc() {
  console.log(this); // window
  console.log(declareFunc.name) // "declareFunc"
  console.log(varFunc.name); // "declareFunc". but why?
  console.log(this.declareFunc); // undefined
  console.log(declareFunc); // function body
}
console.log(varFunc.name) // "declareFunc". why?
var aa = function (){}
console.log(aa.name) // "aa"
console.log(this) // window
varFunc();

Body:
var varFunc = function declareFunc() {
  console.log(varFunc===declareFunc);//true
}

This function has now two names: varFunc externally and declareFunc internally, so inside of it, you can access declareFunc,varFunc and window.varFunc , and outside:

console.log(varFunc,declareFunc);//function, undefined/error


问:
design element for chat box in xamarin.forms
How i can design chat Box UI in xamarin.forms with the small edge outside the box like in screenshot

答:
You will need to make renderer to create a bubble like that.

Here you can find an entire chat application made in Xamarin: https://github.com/EgorBo/CrossChat-Xamarin.Forms

Here you can find the Android renderer:
https://github.com/EgorBo/CrossChat-Xamarin.Forms/blob/master/Client/Crosschat.Client.Android/CustomRenderers/MessageRenderer.cs

IOS renderer:
https://github.com/EgorBo/CrossChat-Xamarin.Forms/blob/master/Client/Crosschat.Client.iOS/CustomRenderers/MessageRenderer.cs

And the winows renderer:
https://github.com/EgorBo/CrossChat-Xamarin.Forms/blob/master/Client/Crosschat.Client.WinPhone/CustomRenderers/MessageRenderer.cs

GOod luck


问:
excel: vba type mismatch comparing dates
I'm trying to make a comparison between years from two dates (in different columns) and the current year date. If the year is the same then it should write on the corresponding row at column 13 the word "ATUAL", if the year is different then it should write nothing.

This is what I've tried so far.

```<code>Sub CopyColumn2()

Dim i As Long
Dim j As Long
Dim lastrow As Long
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim wbk As Workbook
Dim wb As Worksheet

Set wbk = Workbooks.Open("I:\CGP\DEOPEX\01 - Supervisão\01 - Administrativo\06- ADM - Taís e Natalia\Férias - Aprovadas\FÉRIAS TÉCNICOS EXTERNAS.xlsx")
Set ws1 = ThisWorkbook.Sheets("BASE_TOTAL")
Set ws2 = wbk.Worksheets("FUNCIONÁRIOS")

lastrow = ws2.Range("A" & Rows.Count).End(xlUp).Row

For j = 2 To lastrow
    If Year(ws1.Cells(j, 9)) = Year(Date) Or Year(ws1.Cells(j, 12)) = Year(Date) Then
        ws1.Cells(j, 13) = "ATUAL"
    Else
        ws1.Cells(j, 13) = ""
    End If
Next j

End Sub
</code>```

The dates are placed in columns I and L and all column is set as Date. My Excel is in portuguese so my date format is dd/mm/yyyy.

When I run my code, I receive this message:

Run-time error 13: Type mismatch

And this part is highlighted:

```<code>If Year(ws1.Cells(j, 9)) = Year(Date) Or Year(ws1.Cells(j, 12)) = Year(Date) Then
</code>```

Is anyone knows what is the problem here? It should work since all my dates are formatted the same way.

答:
Try this:

Declare date variables Dim date1 As Date, date2 As Date

Set value for variable

date1 = ws1.Cells(j, 9)
date2 = ws1.Cells(j, 12)

Use variable in your If statement

If Year(date1) = Year(Date) Or Year(date2) = Year(Date) Then

Body:
I'm trying to make a comparison between years from two dates (in different columns) and the current year date. If the year is the same then it should write on the corresponding row at column 13 the word "ATUAL", if the year is different then it should write nothing.

This is what I've tried so far.

Sub CopyColumn2()

Dim i As Long
Dim j As Long
Dim lastrow As Long
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim wbk As Workbook
Dim wb As Worksheet

Set wbk = Workbooks.Open("I:\CGP\DEOPEX\01 - Supervisão\01 - Administrativo\06- ADM - Taís e Natalia\Férias - Aprovadas\FÉRIAS TÉCNICOS EXTERNAS.xlsx")
Set ws1 = ThisWorkbook.Sheets("BASE_TOTAL")
Set ws2 = wbk.Worksheets("FUNCIONÁRIOS")

lastrow = ws2.Range("A" & Rows.Count).End(xlUp).Row

For j = 2 To lastrow
    If Year(ws1.Cells(j, 9)) = Year(Date) Or Year(ws1.Cells(j, 12)) = Year(Date) Then
        ws1.Cells(j, 13) = "ATUAL"
    Else
        ws1.Cells(j, 13) = ""
    End If
Next j

End Sub

The dates are placed in columns I and L and all column is set as Date. My Excel is in portuguese so my date format is dd/mm/yyyy.

When I run my code, I receive this message:

Run-time error 13: Type mismatch

And this part is highlighted:

If Year(ws1.Cells(j, 9)) = Year(Date) Or Year(ws1.Cells(j, 12)) = Year(Date) Then

Is anyone knows what is the problem here? It should work since all my dates are formatted the same way.


问:
How to create a textbox inside gridstack so that it fits the entire grid-item-content?
I am using the following:

```<code>https://troolee.github.io/gridstack.js/
</code>```

For each grid-stack-item, I have a grid-stack-item-content div. Within each, I have 2 divs with class .panel-header that has the title of the box/panel and a textarea under that. The issue is, the textarea is never fitting the whole height of the panel even when I set the height of the textarea to be 100% in both width and height.

答:
textarea doesnt work with regular height style, it has the rows attribute

```<code><textarea cols="30" rows="10" class="form-control"></textarea>
</code>```

if you increase or decrease the rows it will get bigger or smaller
to do this automatically you need to combine the resize event of gridstack with some solution already answered here

Body:
I am using the following:

https://troolee.github.io/gridstack.js/

For each grid-stack-item, I have a grid-stack-item-content div. Within each, I have 2 divs with class .panel-header that has the title of the box/panel and a textarea under that. The issue is, the textarea is never fitting the whole height of the panel even when I set the height of the textarea to be 100% in both width and height.

Body:
textarea doesnt work with regular height style, it has the rows attribute

<textarea cols="30" rows="10" class="form-control"></textarea>

if you increase or decrease the rows it will get bigger or smaller
to do this automatically you need to combine the resize event of gridstack with some solution already answered here


问:
LXC run command on containers
Is there a way to run a command for example fdisk -l on all the running LXC containers from the host?</p>

```<code>lxc-execute requires --name option
</code>```

答:
if you have an php interpreter on host node, you can use this snippet</p>

```<code>#!/usr/bin/env php
<?php

if(!@is_executable('/usr/bin/lxc-attach'))
{
    print "This host is probably not an LXC host.\n";
    exit;

$ret=@exec('/usr/bin/lxc-ls');
$vzs=explode(' ',$ret);

exec('clear');

print "Executing \"".$argv[1]."\" command on all containers...\n";
sleep(1);

foreach($vzs as $k)
{
    print "Executing \"".$argv[1]."\" command on $k...\n";
    passthru('/usr/bin/lxc-attach -n '.$k.' -- '.$argv[1]);
    echo PHP_EOL;
}

echo PHP_EOL;
</code>```

Title: LXC run command on containers

Body:
Is there a way to run a command for example fdisk -l on all the running LXC containers from the host?

lxc-execute requires --name option

Body:
if you have an php interpreter on host node, you can use this snippet

#!/usr/bin/env php
<?php

if(!@is_executable('/usr/bin/lxc-attach'))
{
    print "This host is probably not an LXC host.\n";
    exit;

$ret=@exec('/usr/bin/lxc-ls');
$vzs=explode(' ',$ret);

exec('clear');

print "Executing \"".$argv[1]."\" command on all containers...\n";
sleep(1);

foreach($vzs as $k)
{
    print "Executing \"".$argv[1]."\" command on $k...\n";
    passthru('/usr/bin/lxc-attach -n '.$k.' -- '.$argv[1]);
    echo PHP_EOL;
}

echo PHP_EOL;


问:
how can I access to reactive formgroup validations?
I want to validate my form field, but I have a formgroup inside it like this:

```<code><form novalidate (ngSubmit)="onSubmit(user)" [formGroup]="user">
      <label>
        <span>Full name</span>
        <input type="text" placeholder="Name" formControlName="name">
      </label>
      <div class="error" *ngIf="!user.controls.name.valid && user.controls.name.touched">
        Name is required
      </div>
      <div formGroupName="account">
        <label>
          <span>Email address</span>
          <input type="email" placeholder="Email" formControlName="email">
        </label>
        <div
          class="error"
          *ngIf="!user.controls.address.email.valid">
          Email is required
        </div>
        <button type="submit" [disabled]="user.invalid">Sign up</button>
    </form>
</code>```

but at email field it is not working this

```<code>!user.controls.address.email.valid
</code>```

how can I get if that field is valid or not to show the message?

答:
Suppose my structure would be

```<code> this.UserForm = this.fb.group({
            id: [this.userobj.id],
            addresses: this.fb.group({
                street: [this.addrssobj.street, Validators.required],
            })
});
</code>```

My addresses.street validation would be like this (html)

```<code><div formGroupName="addresses">
            <div>
                <label class="center-block"> Street: </label>
                <input type="text" class="form-group" formControlName="street" required>
                <div *ngIf="UserForm.get('addresses').get('street').hasError('required') && UserForm.get('addresses').get('street').touched" class="text-danger">
                    Street is required
                </div>
            </div>
</code>```

Body:
I want to validate my form field, but I have a formgroup inside it like this:

<form novalidate (ngSubmit)="onSubmit(user)" [formGroup]="user">

        Full name
        <input type="text" placeholder="Name" formControlName="name">

        Name is required

          Email address
          <input type="email" placeholder="Email" formControlName="email">

          Email is required

        <button type="submit" [disabled]="user.invalid">Sign up</button>
    </form>

but at email field it is not working this

!user.controls.address.email.valid

how can I get if that field is valid or not to show the message?

Body:
Suppose my structure would be

 this.UserForm = this.fb.group({
            id: [this.userobj.id],
            addresses: this.fb.group({
                street: [this.addrssobj.street, Validators.required],
            })
});

My addresses.street validation would be like this (html)

<div formGroupName="addresses">
            <div>
                <label class="center-block"> Street: </label>
                <input type="text" class="form-group" formControlName="street" required>
                <div *ngIf="UserForm.get('addresses').get('street').hasError('required') && UserForm.get('addresses').get('street').touched" class="text-danger">
                    Street is required
                </div>
            </div>