问:
Jsoup. Print all text nodes in order
I want to parse this with Jsoup (this is a simplification, I would be parsing entire web pages)

```<code><html><body><p>A<strong>B</strong>C<strong>D</strong>E</p></body></html>
</code>```

to obtain all text elements in the order they appear, this is:

```<code>A B C D E
</code>```

I have tried two approaches:

```<code>Elements elements = doc.children().select("*");
for (Element el : elements)
    System.out.println(el.ownText());
</code>```

which returns:

```<code>A C E B D
</code>```

This is, the elements between "strong" tags go at the end.

I have also tried a recursive version:

```<code>myfunction(doc.children());

private void myfunction(Elements elements) {
  for (Element el : elements){
    List<Node> nodos = el.childNodes();
    for (Node nodo : nodos) {
      if (nodo instanceof TextNode && !((TextNode) nodo).isBlank()) {
      System.out.println(((TextNode) nodo).text());
    }
  }
  myfunction(el.children());
}
</code>```

But the result is the same as before.

How can this be accomplished? I feel I am making difficult something simple ...

答:
How about:

```<code>private static void myfunction(Node element) {
    for (Node n : element.childNodes()) {
        if (n instanceof TextNode && !((TextNode) n).isBlank()) {
            System.out.println(((TextNode) n).text());
        } else {
            myfunction(n);
        }
    }
}
</code>```

Demo:

```<code>String html = "<html><body><p>A<strong>B</strong>C<strong>D</strong>E</p></body></html>";
Document doc = Jsoup.parse(html);
myfunction(doc.body());
</code>```

Output:

```<code>A
B
C
D
E
</code>```

Java 15 update to avoid casting (TextNode) n (for more details see JEP 375: Pattern Matching for instanceof (Second Preview))

```<code>private static void myfunction(Node element) {
    for (Node n : element.childNodes()) {
        if (n instanceof TextNode tNode && !tNode.isBlank()) {
            System.out.println(tNode.text());
        } else {
            myfunction(n);
        }
    }
}
</code>```

Title: Jsoup. Print all text nodes in order

Body:
I want to parse this with Jsoup (this is a simplification, I would be parsing entire web pages)

ABCDE

to obtain all text elements in the order they appear, this is:

A B C D E

I have tried two approaches:

Elements elements = doc.children().select("*");
for (Element el : elements)
    System.out.println(el.ownText());

which returns:

A C E B D

This is, the elements between "strong" tags go at the end.

I have also tried a recursive version:

myfunction(doc.children());

private void myfunction(Elements elements) {
  for (Element el : elements){
    List<Node> nodos = el.childNodes();
    for (Node nodo : nodos) {
      if (nodo instanceof TextNode && !((TextNode) nodo).isBlank()) {
      System.out.println(((TextNode) nodo).text());
    }
  }
  myfunction(el.children());
}

But the result is the same as before.

How can this be accomplished? I feel I am making difficult something simple ...

Body:
How about:

private static void myfunction(Node element) {
    for (Node n : element.childNodes()) {
        if (n instanceof TextNode && !((TextNode) n).isBlank()) {
            System.out.println(((TextNode) n).text());
        } else {
            myfunction(n);
        }
    }
}

Demo:

String html = "<html><body><p>A<strong>B</strong>C<strong>D</strong>E</p></body></html>";
Document doc = Jsoup.parse(html);
myfunction(doc.body());

Output:

A
B
C
D
E

Java 15 update to avoid casting (TextNode) n (for more details see JEP 375: Pattern Matching for instanceof (Second Preview))

private static void myfunction(Node element) {
    for (Node n : element.childNodes()) {
        if (n instanceof TextNode tNode && !tNode.isBlank()) {
            System.out.println(tNode.text());
        } else {
            myfunction(n);
        }
    }
}


来源: stackexchange

问:
Visual Studio Ionic App Packaging for iOS
I have an Ionic app I've developed using Visual Studio on a Windows machine.  I now want to package the app for iOS deployment and I can't get the remote build on the Mac to work to save my life.  I've wasted 3 days on this problem.

My build.json in my app is:

```<code>  "ios": {
    "release": {
      "developmentTeam": "XXXXXXXXXX",
      "codeSignIdentity": "iPhone Distribution",
      "packageType": "app-store",
      "provisioningProfile": "XXXXXXXX-XXXXX-XXXX-XXXX-XXXXXXXXXXXX",
      "buildFlag": [
        "EMBEDDED_CONTENT_CONTAINS_SWIFT = YES",
        "ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES=NO",
        "LD_RUNPATH_SEARCH_PATHS = \"@executable_path/Frameworks\""
      ]
    }
  }
</code>```

I created an iOS distribution certificate using the latest XCODE on my MacInCloud:

Here is the certificate in the developer portal:

And then in the developer portal, I created Provisioning Profile, then downloaded it to my PC, opened it, extracted the Provisioning Profile UUID and put it into my build.json:

So then I do a remote build using my Mac in Cloud and I can watch the build take place but then by the end of the long build process, I eventually get this error:

Error Domain=IDEProvisioningErrorDomain Code=9 ""Cincy Christmas.app"
  requires a provisioning profile."
  UserInfo={NSLocalizedDescription="Cincy Christmas.app" requires a
  provisioning profile., NSLocalizedRecoverySuggestion=Add a profile to
  the "provisioningProfiles" dictionary in your Export Options property
  list.}

I tried many different codeSignIdentity (iOS Distribution, iPhone Developer, etc...) and gotten multiple different errors (conflicting provisions, change to iPhone Developer, etc...)  I've also updated Cordova (7.0) and Cordova-ios (4.5.3) to see if that would fix it.  No dice.

What am I doing wrong?  Any ideas?  I'm at my wit's end!

答:
I suspect the provisioning profile isn't installed on the Mac you're using to build the app with. There are two ways to install profiles:

Launch Xcode and navigate to Xcode > Preferences > Accounts, then click on "Download Manual Profiles" or "Download All Profiles" (depending on whether you're using Xcode 9 or an older version).

You can download the profile from the Apple Developer portal to that Mac, then double-click the profile. This will launch Xcode and, unfortunately, you don't get any further UI feedback.

Next, open your project in Xcode and inspect the the "Signing" group under "General" and verify that the correct profile is selected.

ContentLicense: CC BY-SA 3.0

Body:
I have an Ionic app I've developed using Visual Studio on a Windows machine.  I now want to package the app for iOS deployment and I can't get the remote build on the Mac to work to save my life.  I've wasted 3 days on this problem.

My build.json in my app is:

  "ios": {
    "release": {
      "developmentTeam": "XXXXXXXXXX",
      "codeSignIdentity": "iPhone Distribution",
      "packageType": "app-store",
      "provisioningProfile": "XXXXXXXX-XXXXX-XXXX-XXXX-XXXXXXXXXXXX",
      "buildFlag": [
        "EMBEDDED_CONTENT_CONTAINS_SWIFT = YES",
        "ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES=NO",
        "LD_RUNPATH_SEARCH_PATHS = \"@executable_path/Frameworks\""
      ]
    }
  }

I created an iOS distribution certificate using the latest XCODE on my MacInCloud:

Here is the certificate in the developer portal:

And then in the developer portal, I created Provisioning Profile, then downloaded it to my PC, opened it, extracted the Provisioning Profile UUID and put it into my build.json:

So then I do a remote build using my Mac in Cloud and I can watch the build take place but then by the end of the long build process, I eventually get this error:

Error Domain=IDEProvisioningErrorDomain Code=9 ""Cincy Christmas.app"
  requires a provisioning profile."
  UserInfo={NSLocalizedDescription="Cincy Christmas.app" requires a
  provisioning profile., NSLocalizedRecoverySuggestion=Add a profile to
  the "provisioningProfiles" dictionary in your Export Options property
  list.}

I tried many different codeSignIdentity (iOS Distribution, iPhone Developer, etc...) and gotten multiple different errors (conflicting provisions, change to iPhone Developer, etc...)  I've also updated Cordova (7.0) and Cordova-ios (4.5.3) to see if that would fix it.  No dice.

What am I doing wrong?  Any ideas?  I'm at my wit's end!


问:
constant variables that are used only in one cpp file - where to declare them
I have a small project and all its code is in one namespace (multiple files), in certain file I need to use multiple constants.

Only this one file will use those constant variables.

Which one is the right way to go and what's the difference (I'm familiar with static and const but still don't know the difference)

declare static const in the header, define in the source file

define const in source file in the namespace scope

define static const in source file in the namespace scope

答:
Only this one file will use those constant variables.

If I understood correctly, that sentence automatically excludes the first option:

declare static const in the header, define in the source file

You don't need to expose the declaration in other compilation units (cpp files), so you don't need a header file includable in different cpp files.

At this point the following options:

define const in source file in the namespace scope

define static const in source file in the namespace scope

In your situation, the correct answer should be (3).

Why?

The answer is simply the correlation with the meaning of static variable outside function block.

From here:

The static specifier [...]. When used in a declaration at namespace scope, it specifies internal linkage.

So when you need to declare a constant variable which will be used only in that single compilation unit (cpp file), you should declare it as static const in order to express the internal linkage more explicit in the reading.

Extra

In general is a good point to use, instead, an anonymous namespace in your compilation unit.

In your .cpp file:

```<code> namespace {
    const int kVariable = 12;
 }

 // no more static const int kVariable = 12;

 void foo() {
   std::cout << kVariable << '\n';
 }
</code>```

The purpose is practically the same.

Conclusions

All those information give you a general idea about static keyword in the constant declarations.

Anyway, it is often a matter of style.

Body:
Only this one file will use those constant variables.

If I understood correctly, that sentence automatically excludes the first option:

declare static const in the header, define in the source file

You don't need to expose the declaration in other compilation units (cpp files), so you don't need a header file includable in different cpp files.

At this point the following options:

define const in source file in the namespace scope

define static const in source file in the namespace scope

In your situation, the correct answer should be (3).

Why?

The answer is simply the correlation with the meaning of static variable outside function block.

From here:

The static specifier [...]. When used in a declaration at namespace scope, it specifies internal linkage.

So when you need to declare a constant variable which will be used only in that single compilation unit (cpp file), you should declare it as static const in order to express the internal linkage more explicit in the reading.

Extra

In general is a good point to use, instead, an anonymous namespace in your compilation unit.

In your .cpp file:

 namespace {
    const int kVariable = 12;
 }

 // no more static const int kVariable = 12;

 void foo() {
   std::cout << kVariable << '\n';
 }

The purpose is practically the same.

Conclusions

All those information give you a general idea about static keyword in the constant declarations.

Anyway, it is often a matter of style.


问:
nested has_many :through in rails 3
I know Rails doesn't support nested has_many :through relationships, though there's been talk and an open ticket about a patch since as early as Rails 2.

I did come across a plugin that's pretty slick, but the master branches don't work with Rails 3 and I'm hesitant to use it for mission critical tasks in the app hence the lack of active recent development. So -- what's the best way to deal with these relations.

```<code>class Author < ActiveRecord::Base
  has_many :contracts
  has_many :products, :through => :contracts

class Product < ActiveRecord::Base
  has_many :contracts
  has_many :orders
  has_many :authors, :through => :contracts

class Contracts < ActiveRecord::Base
  belongs_to :author
  belongs_to :product
</code>```

So, all the being what it is it would be great to be able to get at orders this by adding this to the Author model:

```<code>has_many :orders, :through => :products
</code>```

But alas, you cannot -- at least without the plugin. So, my question is what's the best approach to accessing all of an author's orders when the only association is between the join model, Contracts?

答:
If you're not trying to create objects through the nested association, and you want to use it for lookup only, then scopes in Rails 3 are a great way to do this. Alternatively you could implement a class method.

I've had this kind of thing as an example in a class I taught recently, the Rails 3 version of the code is here:
https://github.com/wolframarnold/Efficient-TDD-Rails3/blob/master/app/models/user.rb

See the definition of the items method. The specs are here:
https://github.com/wolframarnold/Efficient-TDD-Rails3/blob/master/spec/models/user_orders_spec.rb

Rails 3.1 update: As one commenter already noted, Rails 3.1 does support has_many :through associations more than one level deep.

ContentLicense: CC BY-SA 2.5

Title: nested has_many :through in rails 3

Body:
I know Rails doesn't support nested has_many :through relationships, though there's been talk and an open ticket about a patch since as early as Rails 2.

I did come across a plugin that's pretty slick, but the master branches don't work with Rails 3 and I'm hesitant to use it for mission critical tasks in the app hence the lack of active recent development. So -- what's the best way to deal with these relations.

class Author < ActiveRecord::Base
  has_many :contracts
  has_many :products, :through => :contracts

class Product < ActiveRecord::Base
  has_many :contracts
  has_many :orders
  has_many :authors, :through => :contracts

class Contracts < ActiveRecord::Base
  belongs_to :author
  belongs_to :product

So, all the being what it is it would be great to be able to get at orders this by adding this to the Author model:

has_many :orders, :through => :products

But alas, you cannot -- at least without the plugin. So, my question is what's the best approach to accessing all of an author's orders when the only association is between the join model, Contracts?


问:
NPM Invalid Package during deployment found @types
I'm trying to run my first application with azure's continuous development, this is app from standard template from Visual Studio 2017 MVC net core 2.0, using React. I just pushed this app to my github, on branch configured with azure to auto deploy, and deploy log i can see this:

```<code>Command: "D:\home\site\deployments\tools\deploy.cmd"
Handling ASP.NET Core Web Application deployment.
  Restore completed in 680.87 ms for D:\home\site\repository\PortfolioKJ\PortfolioKJ.csproj.
  Restore completed in 1.08 sec for D:\home\site\repository\PortfolioKJ\PortfolioKJ.csproj.
Microsoft (R) Build Engine version 15.3.409.57025 for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.

  PortfolioKJ -> D:\home\site\repository\PortfolioKJ\bin\Release\netcoreapp2.0\PortfolioKJ.dll
EXEC : npm ERR! error : Invalid Package: expected types/react-hot-loader but found @types/react-hot-loader [D:\home\site\repository\PortfolioKJ\PortfolioKJ.csproj]
  npm ERR!     at D:\Program Files (x86)\npm\1.4.28\node_modules\npm\lib\cache\add-local-tarball.js:161:14
  npm ERR!     at process._tickCallback (node.js:448:13)
  npm ERR! If you need help, you may report this *entire* log,
  npm ERR! including the npm and node versions, at:
  npm ERR!     <http://github.com/npm/npm/issues>

  npm ERR! System Windows_NT 6.2.9200
  npm ERR! command "node" "D:\\Program Files (x86)\\npm\\1.4.28\\node_modules\\npm\\bin\\npm-cli.js" "install"
  npm ERR! cwd D:\home\site\repository\PortfolioKJ
  npm ERR! node -v v0.10.40
  npm ERR! npm -v 1.4.28
  npm
D:\home\site\repository\PortfolioKJ\PortfolioKJ.csproj(39,5): error MSB3073: The command "npm install" exited with code 1.
Failed exitCode=1, command=dotnet publish "D:\home\site\repository\PortfolioKJ\PortfolioKJ.csproj" --output "D:\local\Temp\8d52bb32bb3bc7e" --configuration Release
An error has occurred during web site deployment.
\r\nD:\Program Files (x86)\SiteExtensions\Kudu\67.61109.3117\bin\Scripts\starter.cmd "D:\home\site\deployments\tools\deploy.cmd"
</code>```

I realy don't know what i can do now. I was hoping that if everything is standard, it could run without issues.

Here is tsconfig.json

```<code>{
  "compilerOptions": {
    "baseUrl": ".",
    "module": "es2015",
    "moduleResolution": "node",
    "target": "es5",
    "jsx": "react",
    "experimentalDecorators": true,
    "sourceMap": true,
    "skipDefaultLibCheck": true,
    "strict": true,
    "lib": ["es6", "dom"],
    "types": ["webpack-env"]
  },
  "exclude": [
      "bin",
      "node_modules"
  ]
}
</code>```

On my local PC everything works great.

答: I found my issue. Problem was with line  npm ERR! node -v v0.10.40, default version of node, on azure server was 0.10, which couldn't resolve what @types mean. To solve this, I had to add line WEBSITE_NODE_DEFAULT_VERSION, and value 4.2.3, to my Application's settings on Azure.

Body:
I'm trying to run my first application with azure's continuous development, this is app from standard template from Visual Studio 2017 MVC net core 2.0, using React. I just pushed this app to my github, on branch configured with azure to auto deploy, and deploy log i can see this:

Command: "D:\home\site\deployments\tools\deploy.cmd"
Handling ASP.NET Core Web Application deployment.
  Restore completed in 680.87 ms for D:\home\site\repository\PortfolioKJ\PortfolioKJ.csproj.
  Restore completed in 1.08 sec for D:\home\site\repository\PortfolioKJ\PortfolioKJ.csproj.
Microsoft (R) Build Engine version 15.3.409.57025 for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.

  PortfolioKJ -> D:\home\site\repository\PortfolioKJ\bin\Release\netcoreapp2.0\PortfolioKJ.dll
EXEC : npm ERR! error : Invalid Package: expected types/react-hot-loader but found @types/react-hot-loader [D:\home\site\repository\PortfolioKJ\PortfolioKJ.csproj]
  npm ERR!     at D:\Program Files (x86)\npm\1.4.28\node_modules\npm\lib\cache\add-local-tarball.js:161:14
  npm ERR!     at process._tickCallback (node.js:448:13)
  npm ERR! If you need help, you may report this *entire* log,
  npm ERR! including the npm and node versions, at:
  npm ERR!     <http://github.com/npm/npm/issues>

  npm ERR! System Windows_NT 6.2.9200
  npm ERR! command "node" "D:\\Program Files (x86)\\npm\\1.4.28\\node_modules\\npm\\bin\\npm-cli.js" "install"
  npm ERR! cwd D:\home\site\repository\PortfolioKJ
  npm ERR! node -v v0.10.40
  npm ERR! npm -v 1.4.28
  npm
D:\home\site\repository\PortfolioKJ\PortfolioKJ.csproj(39,5): error MSB3073: The command "npm install" exited with code 1.
Failed exitCode=1, command=dotnet publish "D:\home\site\repository\PortfolioKJ\PortfolioKJ.csproj" --output "D:\local\Temp\8d52bb32bb3bc7e" --configuration Release
An error has occurred during web site deployment.
\r\nD:\Program Files (x86)\SiteExtensions\Kudu\67.61109.3117\bin\Scripts\starter.cmd "D:\home\site\deployments\tools\deploy.cmd"

I realy don't know what i can do now. I was hoping that if everything is standard, it could run without issues.

Here is tsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "module": "es2015",
    "moduleResolution": "node",
    "target": "es5",
    "jsx": "react",
    "experimentalDecorators": true,
    "sourceMap": true,
    "skipDefaultLibCheck": true,
    "strict": true,
    "lib": ["es6", "dom"],
    "types": ["webpack-env"]
  },
  "exclude": [
      "bin",
      "node_modules"
  ]
}

On my local PC everything works great.


问:
Why is my image_path undefined when using export_graphviz? - Python 3
I'm trying to run this machine learning tree algorithm code in IPython:

```<code>from sklearn.datasets import load_iris

from sklearn.tree import DecisionTreeClassifier

iris = load_iris()
X = iris.data[:, 2:] # petal length and width
y = iris.target

tree_clf = DecisionTreeClassifier(max_depth=2)
tree_clf.fit(X, y)

from sklearn.tree import export_graphviz
export_graphviz(tree_clf, out_file=image_path("iris_tree.dot"),
    feature_names=iris.feature_names[2:],
    class_names=iris.target_names,
    rounded=True,
    filled=True
)
</code>```

But I get this error when run in IPython:

I'm unfamiliar with export_graphviz, does anyone have any idea how to correct this?

答:
you must correct

out_file=image_path("iris_tree.dot"),

in below code line:

out_file="C:/Users/VIDA/Desktop/python/iris_tree.dot",

Body:
I'm trying to run this machine learning tree algorithm code in IPython:

from sklearn.datasets import load_iris

from sklearn.tree import DecisionTreeClassifier

iris = load_iris()
X = iris.data[:, 2:] # petal length and width
y = iris.target

tree_clf = DecisionTreeClassifier(max_depth=2)
tree_clf.fit(X, y)

from sklearn.tree import export_graphviz
export_graphviz(tree_clf, out_file=image_path("iris_tree.dot"),
    feature_names=iris.feature_names[2:],
    class_names=iris.target_names,
    rounded=True,
    filled=True
)

But I get this error when run in IPython:

I'm unfamiliar with export_graphviz, does anyone have any idea how to correct this?


问:
include leading zeros while exporting to csv in ssis
I have a package which exports data from table to .csv file, it exports 600 000 records.

I have few columns which has leading zeros and trailing zeros, while exporting the data both leading and trailing zeros are missing.

EX: actual data coming from source

```<code> column1   column2
 001       67.50
</code>```

exported data in csv file

```<code> column1   column2
 1         67.5
</code>```

I tried many methods like placing data conversion, and also Replicate function in derived column.

i also tried by exporting the data to .txt file and use .cmd file to change the .txt file .csv file, all these methods yielded no results.

is there a way to achieve this?

答:
When exporting to text- or csv-formatted files numeric values that need to retain leading and/or trailing zeros, a combination of the following is required.

1) Using a derived column or conversion task under Data Flow, convert the numeric field to a text or varchar.

2) Be sure the destination CSV file has the field defined as a text of sufficient character length.

Lastly, if you are in a situation where a numerical value is required (NULL or blank are not acceptable) in the output file, then take a look at the following link.  This is where a "0.00" must be provided instead of a NULL or blank.

How do I get SSIS Data Flow to put '0.00' in a flat file?

Hope this helps.

Body:
I have a package which exports data from table to .csv file, it exports 600 000 records.

I have few columns which has leading zeros and trailing zeros, while exporting the data both leading and trailing zeros are missing.

EX: actual data coming from source

 column1   column2
 001       67.50

exported data in csv file

 column1   column2
 1         67.5

I tried many methods like placing data conversion, and also Replicate function in derived column.

i also tried by exporting the data to .txt file and use .cmd file to change the .txt file .csv file, all these methods yielded no results.

is there a way to achieve this?


问:
Uncaught Error: Call to undefined function mysql_query()
When I run my code, the navegator show me that:

Notice: Use of undefined constant datos1 - assumed 'datos1' in C:\xampp\htdocs\formulario\conexion1.php on line 8

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\xampp\htdocs\formulario\conexion1.php on line 8
No se pudo conectar a la base de datos
Notice: Undefined index: Teachers_Name in C:\xampp\htdocs\formulario\conexion1.php on line 13

Notice: Undefined index: School_Name in C:\xampp\htdocs\formulario\conexion1.php on line 14

Notice: Undefined variable: Implementation_Quality in C:\xampp\htdocs\formulario\conexion1.php on line 15

Notice: Undefined variable: Implementation_Quality in C:\xampp\htdocs\formulario\conexion1.php on line 17

Fatal error: Uncaught Error: Call to undefined function mysql_query() in C:\xampp\htdocs\formulario\conexion1.php:19 Stack trace: #0 {main} thrown in C:\xampp\htdocs\formulario\conexion1.php on line 19

What I do?

```<code><?php
$conexion = new mysqli("localhost", "root", "");

if(!$conexion){
echo "Conexión no exitosa";
} else {

$base= mysqli_select_db(datos1);
    if(!$base){
        echo "No se pudo conectar a la base de datos";
    }
 }
$Teachers_Name=$_POST['Teachers_Name'];
$School_Name=$_POST['School_Name'];
$Implementation_Quality['Implementation_Quality'];

$sql= "INSERT INTO datos_1 VALUES('$Teachers_Name', 'School_Name',
'$Implementation_Quality')";

$ejecutar = mysql_query($sql);

if(!$ejecutar){
echo "Hubo algun error";
} else {
 echo "Datos guardados correctamente<br><a href='index.html'>Volver</a>";
}
?>
</code>```

答:
Replace this:

```<code>$base= mysqli_select_db(datos1);
</code>```

With this:

```<code>$base= mysqli_select_db($conexion,'datos1');
</code>```

replace this:

```<code>$sql= "INSERT INTO datos_1 VALUES('$Teachers_Name', 'School_Name', '$Implementation_Quality')";
</code>```

With this:

```<code>$sql= 'INSERT INTO datos_1 (col1, col2, col3) VALUES ( ?, ?, ? )';
</code>```

Replace col1,col2 and col3 with the names of columns in the datos_1 table.

e.g. ... datos_1 (teacher_name, school_name, implementation_quality) VALUES ...

Note that this is a static string literal. There's no variable substitution. The question marks are bind placeholders which we will reference later.

Replace this:

```<code>$ejecutar = mysql_query($sql);
</code>```

With this:

```<code>$sth = mysqli_prepare($conexion,$sql);
mysqli_stmt_bind_param($sth,'sss', $Teachers_Name, $School_Name, $Implementation_Quality);
$ejecutar = mysqli_stmt_execute($sth);
</code>```

Don't mix mysql_ functions with mysqli_ functions. That won't work. (We shouldn't be using any mysql_ functions in new development; the mysql_ interface functions have been deprecated a long time ago, and are finally removed in newest versions of PHP.

Do NOT incorporate potentially unsafe values in SQL text. Use prepared statements with bind placeholders. (Or less optimally, properly escape any values that are incorporated into the text.)

Recommended:

Little Bobby Tables - Exploits of a Mom  https://xkcd.com/327/

OWASP SQL Injection https://www.owasp.org/index.php/SQL_Injection

ContentLicense: CC BY-SA 4.0

Body:
When I run my code, the navegator show me that:

Notice: Use of undefined constant datos1 - assumed 'datos1' in C:\xampp\htdocs\formulario\conexion1.php on line 8

Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\xampp\htdocs\formulario\conexion1.php on line 8
No se pudo conectar a la base de datos
Notice: Undefined index: Teachers_Name in C:\xampp\htdocs\formulario\conexion1.php on line 13

Notice: Undefined index: School_Name in C:\xampp\htdocs\formulario\conexion1.php on line 14

Notice: Undefined variable: Implementation_Quality in C:\xampp\htdocs\formulario\conexion1.php on line 15

Notice: Undefined variable: Implementation_Quality in C:\xampp\htdocs\formulario\conexion1.php on line 17

Fatal error: Uncaught Error: Call to undefined function mysql_query() in C:\xampp\htdocs\formulario\conexion1.php:19 Stack trace: #0 {main} thrown in C:\xampp\htdocs\formulario\conexion1.php on line 19

What I do?

<?php
$conexion = new mysqli("localhost", "root", "");

if(!$conexion){
echo "Conexión no exitosa";
} else {

$base= mysqli_select_db(datos1);
    if(!$base){
        echo "No se pudo conectar a la base de datos";
    }
 }
$Teachers_Name=$_POST['Teachers_Name'];
$School_Name=$_POST['School_Name'];
$Implementation_Quality['Implementation_Quality'];

$sql= "INSERT INTO datos_1 VALUES('$Teachers_Name', 'School_Name',
'$Implementation_Quality')";

$ejecutar = mysql_query($sql);

if(!$ejecutar){
echo "Hubo algun error";
} else {
 echo "Datos guardados correctamente
Volver";
}
?>

Body:
Replace this:

$base= mysqli_select_db(datos1);

With this:

$base= mysqli_select_db($conexion,'datos1');

replace this:

$sql= "INSERT INTO datos_1 VALUES('$Teachers_Name', 'School_Name', '$Implementation_Quality')";

With this:

$sql= 'INSERT INTO datos_1 (col1, col2, col3) VALUES ( ?, ?, ? )';

Replace col1,col2 and col3 with the names of columns in the datos_1 table.

e.g. ... datos_1 (teacher_name, school_name, implementation_quality) VALUES ...

Note that this is a static string literal. There's no variable substitution. The question marks are bind placeholders which we will reference later.

Replace this:

$ejecutar = mysql_query($sql);

With this:

$sth = mysqli_prepare($conexion,$sql);
mysqli_stmt_bind_param($sth,'sss', $Teachers_Name, $School_Name, $Implementation_Quality);
$ejecutar = mysqli_stmt_execute($sth);

Don't mix mysql_ functions with mysqli_ functions. That won't work. (We shouldn't be using any mysql_ functions in new development; the mysql_ interface functions have been deprecated a long time ago, and are finally removed in newest versions of PHP.

Do NOT incorporate potentially unsafe values in SQL text. Use prepared statements with bind placeholders. (Or less optimally, properly escape any values that are incorporated into the text.)

Recommended:

Little Bobby Tables - Exploits of a Mom  https://xkcd.com/327/

OWASP SQL Injection https://www.owasp.org/index.php/SQL_Injection


问:
WPF Storyboard.Completed event is not immediate
In WPF, a Storyboard can be stopped by Storyboard.SkipToFill(), but the Completed event will not be fired immediately. Just as the following demo code showing:

```<code>public partial class MainWindow : Window
{
    private Storyboard _storyboard = new Storyboard();

    public MainWindow()
    {
        InitializeComponent();
        InitializeStoryboard();
    }

    private void InitializeStoryboard()
    {
        var animation = new DoubleAnimation
        {
            Duration = TimeSpan.FromSeconds(3),
            From = 0,
            To = 300
        };

        Storyboard.SetTarget(animation, MyRectangle);
        Storyboard.SetTargetProperty(animation, new PropertyPath(WidthProperty));

        _storyboard = new Storyboard();
        _storyboard.Children.Add(animation);

        _storyboard.Completed += StoryboardOnCompleted;
    }

    private void StartButton_OnClick(object sender, RoutedEventArgs e)
    {
        _storyboard.Begin(this, true);
    }

    private void StopButton_OnClick(object sender, RoutedEventArgs e)
    {
        _storyboard.SkipToFill(this);
        Debug.WriteLine(@"SkipToFill");
    }

    private void StoryboardOnCompleted(object sender, EventArgs eventArgs)
    {
        Debug.WriteLine(@"Completed");
    }
}
</code>```

Click the StartButton to begin the Storyboard, and then click the StopButton to stop it. The output will be:

SkipToFill

Completed

So, my question: How to make the Completed event fired immediately? i.e. to make the output be:

Completed

SkipToFill

答:
You can't control when the Storyboard raises the Completed event but you could handle the event whenever it occurs.

So you could hook up another event handler to the Completed event and do whatever you want in there after the Completed event has been raised.

This will print the output in the expected order, i.e. the event handlers will be invoked in the order you register them:

```<code>private void StopButton_OnClick(object sender, RoutedEventArgs e)
{
    _storyboard.Completed += _storyboard_Completed;
    _storyboard.SkipToFill(this);
}

private void _storyboard_Completed(object sender, EventArgs e)
{
    Debug.WriteLine(@"SkipToFill");
    _storyboard.Completed -= _storyboard_Completed;
}

private void StoryboardOnCompleted(object sender, EventArgs eventArgs)
{
    Debug.WriteLine(@"Completed");
}
</code>```

If you want to actually block (asynchronously) in the StopButton_OnClick method until the Completed has been raised, you could use a SemaphoreSlim:

```<code>private readonly System.Threading.SemaphoreSlim _semaphore = new System.Threading.SemaphoreSlim(0, 1);
private async void StopButton_OnClick(object sender, RoutedEventArgs e)
{
    _storyboard.Completed += (ss, ee) => _semaphore.Release();
    _storyboard.SkipToFill(this);
    await _semaphore.WaitAsync(); //wait here...

    Debug.WriteLine(@"SkipToFill");

}

private void StoryboardOnCompleted(object sender, EventArgs eventArgs)
{
    Debug.WriteLine(@"Completed");
}
</code>```

Body:
In WPF, a Storyboard can be stopped by Storyboard.SkipToFill(), but the Completed event will not be fired immediately. Just as the following demo code showing:

public partial class MainWindow : Window
{
    private Storyboard _storyboard = new Storyboard();

    public MainWindow()
    {
        InitializeComponent();
        InitializeStoryboard();
    }

    private void InitializeStoryboard()
    {
        var animation = new DoubleAnimation
        {
            Duration = TimeSpan.FromSeconds(3),
            From = 0,
            To = 300
        };

        Storyboard.SetTarget(animation, MyRectangle);
        Storyboard.SetTargetProperty(animation, new PropertyPath(WidthProperty));

        _storyboard = new Storyboard();
        _storyboard.Children.Add(animation);

        _storyboard.Completed += StoryboardOnCompleted;
    }

    private void StartButton_OnClick(object sender, RoutedEventArgs e)
    {
        _storyboard.Begin(this, true);
    }

    private void StopButton_OnClick(object sender, RoutedEventArgs e)
    {
        _storyboard.SkipToFill(this);
        Debug.WriteLine(@"SkipToFill");
    }

    private void StoryboardOnCompleted(object sender, EventArgs eventArgs)
    {
        Debug.WriteLine(@"Completed");
    }
}

Click the StartButton to begin the Storyboard, and then click the StopButton to stop it. The output will be:

SkipToFill

Completed

So, my question: How to make the Completed event fired immediately? i.e. to make the output be:

Completed

SkipToFill

Body:
You can't control when the Storyboard raises the Completed event but you could handle the event whenever it occurs.

So you could hook up another event handler to the Completed event and do whatever you want in there after the Completed event has been raised.

This will print the output in the expected order, i.e. the event handlers will be invoked in the order you register them:

private void StopButton_OnClick(object sender, RoutedEventArgs e)
{
    _storyboard.Completed += _storyboard_Completed;
    _storyboard.SkipToFill(this);
}

private void _storyboard_Completed(object sender, EventArgs e)
{
    Debug.WriteLine(@"SkipToFill");
    _storyboard.Completed -= _storyboard_Completed;
}

private void StoryboardOnCompleted(object sender, EventArgs eventArgs)
{
    Debug.WriteLine(@"Completed");
}

If you want to actually block (asynchronously) in the StopButton_OnClick method until the Completed has been raised, you could use a SemaphoreSlim:

private readonly System.Threading.SemaphoreSlim _semaphore = new System.Threading.SemaphoreSlim(0, 1);
private async void StopButton_OnClick(object sender, RoutedEventArgs e)
{
    _storyboard.Completed += (ss, ee) => _semaphore.Release();
    _storyboard.SkipToFill(this);
    await _semaphore.WaitAsync(); //wait here...

    Debug.WriteLine(@"SkipToFill");

}

private void StoryboardOnCompleted(object sender, EventArgs eventArgs)
{
    Debug.WriteLine(@"Completed");
}


问:
DDD change aggregate root id
In a discussion I got the following question. In a banking domain there is a aggregate root, Account, identified by Account Number. Assume at some point in time the bank has decided to change all the account from 8 digits to 12 digits due to some reasons and the account is accessible with both the numbers for a year and after that only new number will be used, how this should be handled in a DDD way, I was wondering whether it will create a new bounded context</p>

答:
With an entity you always want to have a technical id i.e an Id (UUID) property that's immutable and that your app controls. The natural id AccountNumber is a Value Object only. Basically, in your app for technical reasons only use the Id, the AccountNumber is just another VO/detail of the aggregate.

Changing the account number format shouldn't create a new bounded context, it's just a change inside a Value Object. But all the problems you have because of the change, stem from the implementation, not from the domain modelling (unless it's a wrong model :D) . If you're using Event Sourcing and CQRS, things should be simple enough, relatively speaking. If you're using an ORM who restores state, things will be more complicated.

The DDD way means you have to understand the nature of concepts, the actual implementation depends on many things.

Title: DDD change aggregate root id


问:
Skype For Business not showing HTML in conversations on Android
I've got the bot application set up to send certain messages as text/html and some as text/plain.  Only the text/plain messages are displayed by the mobile phone SfB client application, but both types are displayed by the SfB desktop client.  I'm wondering if the issue is with the type of client receiving the message or if there is a setting somewhere in SfB Server that needs to be modified so that text/html can be displayed on mobile phones. </p>

答: I've done some research on this issue, and it seems the mobile client only accepts plain text. Even if you send a multipart/alternative package with both text/plain and text/html versions of the message, it will not display on mobile clients. I encountered this while developing a UCMA application. My solution was to use the user agent header for the call to determine if the user was calling from a PC or not, and to convert any HTML to plain text before sending if they were not calling from a PC.</p>


问:
AngularJS with jQuery for selecting parent element
I'm posting my html and directive code. I have two spans, which I have attached ng-click to. On ng-click I want to check the classes of their parents parent item (.parent-portlet), but what I have so far is not working correctly as all of the parent portlets get selected instead of only the current one.

     Remove

     Add Back

```

<p>this is what I have in my directive: </p>

<pre class="lang-js prettyprint-override"><code>scope.removePortlet = function(portlet) {
  var port = $('.remove').parent().parent();
  port.addClass('removed');
  port.addClass('edit-portlet');
};

scope.addPortlet = function(portlet) {
  var port = $('.add-back').parent().parent();
  if (portlet.hasClass('removed')) {
    port.removeClass('removed');
    port.removeClass('edit-portlet');
  }
};
</code>```

The problem with this code is that var portlet catches all of the portlets(parents) and I want to catch only the one related to the click action. How can I achieve that? I tried to pass this to my jquery select like so:

```<code>var portlet = $('.add-back', this).parent().parent();
</code>```

but that didn't work. Any ideas how this can be achieved?

Thanks in advance.

答:
Use ng-class instead. Here's an example of changing background colors with classes:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.portlet = {
    classes: {
      "parent-portlet": true,
      "edit-portlet": false,
      "removed": false
    }
  }

  $scope.removePortlet = function(portlet) {
    portlet.classes.removed = true;
    portlet.classes["edit-portlet"] = true;
  };

  $scope.addPortlet = function(portlet) {
    portlet.classes.removed = false;
    portlet.classes["edit-portlet"] = false;
  };
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Put your css in here */

.parent-portlet {
  background-color: #ccc;
  padding: 20px;
}

.parent-portlet.removed {
  background-color: #c00;
}

.parent-portlet button {
  padding: 10px;
  margin: 0 10px;
}</code>```

<!DOCTYPE html>

      <button class="remove" ng-click="removePortlet(portlet)">
        Remove
      </button>
      <button class="add-back" ng-click="addPortlet(portlet)">
        Add Back
      </button>

```

Body:
I'm posting my html and directive code. I have two spans, which I have attached ng-click to. On ng-click I want to check the classes of their parents parent item (.parent-portlet), but what I have so far is not working correctly as all of the parent portlets get selected instead of only the current one.

     Remove

     Add Back

this is what I have in my directive:

scope.removePortlet = function(portlet) {
  var port = $('.remove').parent().parent();
  port.addClass('removed');
  port.addClass('edit-portlet');
};

scope.addPortlet = function(portlet) {
  var port = $('.add-back').parent().parent();
  if (portlet.hasClass('removed')) {
    port.removeClass('removed');
    port.removeClass('edit-portlet');
  }
};

The problem with this code is that var portlet catches all of the portlets(parents) and I want to catch only the one related to the click action. How can I achieve that? I tried to pass this to my jquery select like so:

var portlet = $('.add-back', this).parent().parent();

but that didn't work. Any ideas how this can be achieved?

Thanks in advance.

Body:
Use ng-class instead. Here's an example of changing background colors with classes:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.portlet = {
    classes: {
      "parent-portlet": true,
      "edit-portlet": false,
      "removed": false
    }
  }

  $scope.removePortlet = function(portlet) {
    portlet.classes.removed = true;
    portlet.classes["edit-portlet"] = true;
  };

  $scope.addPortlet = function(portlet) {
    portlet.classes.removed = false;
    portlet.classes["edit-portlet"] = false;
  };
});

/* Put your css in here */

.parent-portlet {
  background-color: #ccc;
  padding: 20px;
}

.parent-portlet.removed {
  background-color: #c00;
}

.parent-portlet button {
  padding: 10px;
  margin: 0 10px;
}

<!DOCTYPE html>
<html ng-app="plunker">
<head>
  <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>

</head>

<body ng-controller="MainCtrl">
  <div ng-class="portlet.classes">
    <div class="portlet-titlebar">
      <button class="remove" ng-click="removePortlet(portlet)">
        Remove
      </button>
      <button class="add-back" ng-click="addPortlet(portlet)">
        Add Back
      </button>
    </div>
  </div>
</body>

</html>


问:
collecting data from running program
I am working on a problem where i should collect data from running program numerous times. For example, every time the program finishes commands, it give certain value t, which is different every time run it. My task is to collect t from N runs of the program. t is going to be different every run. here is the program:

```<code>import random
th=0
t=0
tr=0
result=[]
for i in range(7):
  i=random.randint(0,1)
  result.append(i)
print(result)
a=0
b=len(result)-1
while th<50:

  j=random.randint(a,b)
  i=j-1
  k=j+1
if k<b
   k=0
if result[i]==result[k]:
    if result[j]!=result[i]:
        result[j]==result[i]
         th=0
        t+=1
   else:
        th+=1
        t+=1
   else:
    th+=1
    t+=1

   tr= t-th
print(tr)
print (result)
</code>```

In this program every run gives you new result. In this generated array there will be obviously every time different arrangement of 0 and 1 and therefore, different t. So resulting t, tr, will be ofcourse different.
I don't know wheter i should do it in new window, or there is a certain function that can do this. Also, if this question is to easy, and there is literature for it, please write what is the name of this kind of problem. thanks :)

btw, im working in python 3.6

答:
See how to make one Python script launch another: you can write a Python script to run the other script and gather the output.  You can receive the output as return value from a function call, and tally it just as you would from any function.

Note that your "running program" and your master script need to agree on the form of the information returned: know the data types you're receiving.  If you're in doubt, start by having your master script print out what it receives, and the type of each returned value.

Title: collecting data from running program

Body:
I am working on a problem where i should collect data from running program numerous times. For example, every time the program finishes commands, it give certain value t, which is different every time run it. My task is to collect t from N runs of the program. t is going to be different every run. here is the program:

import random
th=0
t=0
tr=0
result=[]
for i in range(7):
  i=random.randint(0,1)
  result.append(i)
print(result)
a=0
b=len(result)-1
while th<50:

  j=random.randint(a,b)
  i=j-1
  k=j+1
if k<b
   k=0
if result[i]==result[k]:
    if result[j]!=result[i]:
        result[j]==result[i]
         th=0
        t+=1
   else:
        th+=1
        t+=1
   else:
    th+=1
    t+=1

   tr= t-th
print(tr)
print (result)

In this program every run gives you new result. In this generated array there will be obviously every time different arrangement of 0 and 1 and therefore, different t. So resulting t, tr, will be ofcourse different.
I don't know wheter i should do it in new window, or there is a certain function that can do this. Also, if this question is to easy, and there is literature for it, please write what is the name of this kind of problem. thanks :)

btw, im working in python 3.6


问:
why use xcode if monotouch is available?
if mono touch is available than why we should use mac environment(sdk,xcode+Interface Builder)?

what are the disadvantage of monotouch compare to xcode?

答:
Hello here is my personal opinion,

I've also been on .Net world for a while, when iPhone launched the ability to create native apps, it called my whole attention and i really tried to learn objc, i took 2 books and started trying and trying and trying like for a month and then I left iPHone programming due to you had to make tons of things than on .NET was a line away for example the GC.

When Miguel de Icaza launched MonoTouch i gave it a try and i realized that most of my previously done code was fully funcional (i've always tried to separate ui code from business code) and this is really the point of .NET on the iPhone, to bring most of your already done business logic to the device.

Also on objc you wont find anything like LINQ or var keyword, consuming web services on MonoTouch its just a few clicks away etc.

If you want to target the Android platform there is also MonoDroid (monodroid.net) wich its coming out later this year the stable release, you can give it a try right now on the beta state. Also if you want to target Mac OSX there is MonoMac. So you can share class libs between all this 3 platforms (also al mono/.net supported ones) without hassle not to mention it will work on windows too and viceversa (when possible) (Also dont forget about WP7).

The only thing you will need to worry about its the UI but most of your business logic should work. here is a complete list of .NET Assemblies supported in MonoTouch http://monotouch.net/Documentation/Assemblies and also MonoTouch exposes a C#/CIL binding to all the CocoaTouch APIs.

Also the support of the MonoTouch team is awesome you can just get on IRC ans ask a question and it will be answered right away, mailing list too :)

I really enjoy MonoTouch, i know that no language is perfect for all tasks, and Objective-C is no exception.


问:
Synchronize database of Firebase with Swift 4 language
I am new at swift 4 programming. I try to show some data(actually they are child names) from database of firebase. When view did load, I can take them and show on tableView but it is not working real time. When I delete some data from firebase, I need to refresh(go back and load again) the viewController. If I refresh the tableView with timer, all data append from its end. If I, firstly, delete after append new data to tableView. It is jittering. Is there anyway to synchronize this tableView with firebase, without these problems? </p>

```<code>override func viewDidLoad() {
        super.viewDidLoad()

        ref = Database.database().reference()
        ref.keepSynced(true)

        let userRef = self.ref.child("Users").child(Username).child("Schedule")
        userRef.observeSingleEvent(of: .value, with: { snapshot in
            for child in snapshot.children {
                let snap = child as! DataSnapshot
                let key = snap.key
                self.myList.append(key)
                self.CourseList.append(key)
                self.LessonsTableView.reloadData()
            }
            // Lessons are taking and after, they are locating under phone's memory!
            UserDefaults.standard.set(self.CourseList, forKey: "LessonsArray")
            UserDefaults.standard.synchronize()
        })
}

//Setting up our table
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myList.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = LessonsTableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! LessonsTableViewCell
        cell.myLabell.text = myList[indexPath.row]
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let Dummy:String = myList[indexPath.row] as Any as! String
        let Selected:String = (Dummy as NSString) as Any as! String
        UserDefaults.standard.set(Selected, forKey: "Selected")
        self.performSegue(withIdentifier: "NextPage", sender: self)
    }
</code>```

答:
it is giving an error like this, </p>

```<code>    let userRef = self.ref.child("Users").child(Username).child("Schedule")
    userRef.observeSingleEvent(of: .value, with: { snapshot in
        DispatchQueue.main.sync {
            let snap = child as! DataSnapshot
            let key = snap.key
            self.myList.append(key)
            self.CourseList.append(key)
            self.LessonsTableView.reloadData()
        }
        UserDefaults.standard.set(self.CourseList, forKey: "LessonsArray")
        UserDefaults.standard.synchronize()
    })
</code>```

Body:
I am new at swift 4 programming. I try to show some data(actually they are child names) from database of firebase. When view did load, I can take them and show on tableView but it is not working real time. When I delete some data from firebase, I need to refresh(go back and load again) the viewController. If I refresh the tableView with timer, all data append from its end. If I, firstly, delete after append new data to tableView. It is jittering. Is there anyway to synchronize this tableView with firebase, without these problems?

override func viewDidLoad() {
        super.viewDidLoad()

        ref = Database.database().reference()
        ref.keepSynced(true)

        let userRef = self.ref.child("Users").child(Username).child("Schedule")
        userRef.observeSingleEvent(of: .value, with: { snapshot in
            for child in snapshot.children {
                let snap = child as! DataSnapshot
                let key = snap.key
                self.myList.append(key)
                self.CourseList.append(key)
                self.LessonsTableView.reloadData()
            }
            // Lessons are taking and after, they are locating under phone's memory!
            UserDefaults.standard.set(self.CourseList, forKey: "LessonsArray")
            UserDefaults.standard.synchronize()
        })
}

//Setting up our table
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myList.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = LessonsTableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! LessonsTableViewCell
        cell.myLabell.text = myList[indexPath.row]
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let Dummy:String = myList[indexPath.row] as Any as! String
        let Selected:String = (Dummy as NSString) as Any as! String
        UserDefaults.standard.set(Selected, forKey: "Selected")
        self.performSegue(withIdentifier: "NextPage", sender: self)
    }

Body:
it is giving an error like this,

    let userRef = self.ref.child("Users").child(Username).child("Schedule")
    userRef.observeSingleEvent(of: .value, with: { snapshot in
        DispatchQueue.main.sync {
            let snap = child as! DataSnapshot
            let key = snap.key
            self.myList.append(key)
            self.CourseList.append(key)
            self.LessonsTableView.reloadData()
        }
        UserDefaults.standard.set(self.CourseList, forKey: "LessonsArray")
        UserDefaults.standard.synchronize()
    })


问:
Error attempting to load and run jmeter 3.3 script with java
I'm attempting to run a jmeter script with java code.

I've followed the instructions, but when attempting to call SaveService.loadTree(file), I get an error:

```<code>java.lang.IllegalArgumentException: Problem loading XML from:'file path/file.jmx', missing class com.thoughtworks.xstream.converters.ConversionException:
---- Debugging information ----
cause-exception     : com.thoughtworks.xstream.converters.ConversionException
cause-message       :
first-jmeter-class  : org.apache.jmeter.save.converters.HashTreeConverter.unmarshal(HashTreeConverter.java:67)
class               : org.apache.jmeter.save.ScriptWrapper
required-type       : org.apache.jorphan.collections.ListedHashTree
converter-type      : org.apache.jmeter.save.ScriptWrapperConverter
path                : /jmeterTestPlan/hashTree/hashTree/hashTree/hashTree/HTTPSamplerProxy
line number         : 31
version             : 3.3 r1808647
-------------------------------
</code>```

答: I found that the "ApacheJMeter_http" dependency was not in my pom.xml file. "ApacheJMeter_core" does not include all of the needed files for a basic test run.</p>

Body:
I'm attempting to run a jmeter script with java code.

I've followed the instructions, but when attempting to call SaveService.loadTree(file), I get an error:

java.lang.IllegalArgumentException: Problem loading XML from:'file path/file.jmx', missing class com.thoughtworks.xstream.converters.ConversionException:
---- Debugging information ----
cause-exception     : com.thoughtworks.xstream.converters.ConversionException
cause-message       :
first-jmeter-class  : org.apache.jmeter.save.converters.HashTreeConverter.unmarshal(HashTreeConverter.java:67)
class               : org.apache.jmeter.save.ScriptWrapper
required-type       : org.apache.jorphan.collections.ListedHashTree
converter-type      : org.apache.jmeter.save.ScriptWrapperConverter
path                : /jmeterTestPlan/hashTree/hashTree/hashTree/hashTree/HTTPSamplerProxy
line number         : 31
version             : 3.3 r1808647
-------------------------------


问:
How to give a custom angle to a gradient?
when creating a background with a gradient, it is possible to set the gradient in multiplications of 45

how can I set the gradient angle to 60 for instance?

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <shape>
        <gradient
            android:angle="45"
            android:startColor="@color/gradient_bottom"
            android:endColor="@color/gradient_top"
            android:type="linear" />
    </shape>
</item>
</selector>
</code>```

答:
You can use like this.

```<code> <shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"
  >
   <gradient
      android:startColor="@color/purple"
       android:endColor="@color/pink"
       android:angle="60" />
 </shape>
</code>```

If you use shape then it's working fine.

Body:
when creating a background with a gradient, it is possible to set the gradient in multiplications of 45

how can I set the gradient angle to 60 for instance?

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <shape>
        <gradient
            android:angle="45"
            android:startColor="@color/gradient_bottom"
            android:endColor="@color/gradient_top"
            android:type="linear" />
    </shape>
</item>
</selector>

Body:
You can use like this.

 <shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"
  >
   <gradient
      android:startColor="@color/purple"
       android:endColor="@color/pink"
       android:angle="60" />
 </shape>

If you use shape then it's working fine.


答:
I'd select option #3.  It is a little more typing, and means the same thing as #2.

But people (myself included!) can easily forget that a const will have internal linkage unless declared extern const.  So putting static const helps with self-documenting code, in my opinion.

If you like anonymous namespaces, you could put them in one to help clarify that they are internal to that translation unit.  That is a matter of preference.

Title: constant variables that are used only in one cpp file - where to declare them

Body:
I have a small project and all its code is in one namespace (multiple files), in certain file I need to use multiple constants.

Only this one file will use those constant variables.

Which one is the right way to go and what's the difference (I'm familiar with static and const but still don't know the difference)

declare static const in the header, define in the source file

define const in source file in the namespace scope

define static const in source file in the namespace scope


问:
In a multithreaded (Java or .Net) program, can I assume that copying a variable is atomic?
I was worrying about race conditions in an application I'm designing, when I was wondering about this question.

Let's say I have a large array or collection of some sort that is managed by one component of my program, let's call that component Monitor. Its job is to regularly check if the collection is "dirty", i. e. has changed recently, and if so, write a snapshot to disk (this is to checkpoint the application in case a crash occurs) and mark it as clean again.

Other components of the same program, running in a different thread, call the Monitor's methods to add data to or modify data in the array/collection. Those methods mark the collection as dirty.

Now, the altering methods run in the other components' threads, right? And if I'm not so lucky, they might be called while the snapshot is written to disk, change data that has already been written, set the dirty flag and the Monitor's thread unsets it just after that, without having saved the changes (it was already past the element when it changed). So I have a dirty collection that's marked as clean.

For a while, I thought that I could maybe solve the problem by making a temporary copy of the collection, mark it clean and then go and serialize the copy. But would the copying be atomic, i. e. can I be sure that the collection will not change while I'm copying it?

Meanwhile, I think I have found better solutions, like

setting a lock flag before beginning the write to disk and make the data altering methods wait until the flag is unset

have the data altering methods write to a "change queue" instead of directly to the collection and have the thread that does the disk writing process that queue

and I think the lock flag might be the best way to go. But I'm still curious: Is copying a variable atomic?

Follow-up: Maybe this should go in a question of its own, but actually it's very much the same. According to the answers below, my "lock flag" approach might also not work, right? Because the data altering method might check the lock flag while it is being set to the "locked" value and decide it's not locked. So I need a special construction like a mutex if I really want to do this right, correct?

Kudos to erickson for his very helpful answer on my follow-up. I really should have made this two questions so I could have accepted two answers. Please, vote him up, too.

答:
Setting a 32-bit (at least in .NET) is atomic, but it does you no good.  You have to read it to know if it's locked, so you might read it, and after the read, someone else reads it before you can set it, so two threads end up inside the "protected" code.  THis is exactly what actual synchronization objects (like the .NET Monitor class) are for.  You could use an Interlocked to check and increment the lock variable as well.

See also: Is accessing a variable in C# an atomic operation?

OwnerDisplayName: Hanno

LastEditorDisplayName: Hanno

OwnerDisplayName: ctacke


问:
How to secure Silverlight app with Login screen/custom form
I'm sure there must be a simple answer for this but I can't figure it out -

I have a Silverlight 4 OOB application that requires a login screen/security. The View shows a LoginView (Username/pw) which then passes the details to a WCF service and checks it against a database. It will return a result to the client to say if their details were valid or not. This part works fine.

Where I need some guidance is the best way of storing the fact that the user is logged on/authenticated for the current Silverlight session.

It's OOB so we can't use any web cookies/session stuff as far as I know. I assume we have to store some sort of Identity in the thread but I need some pointers please.

The other caveat is that I would like to secure all other pages to check if the user is authenticated and redirect to the login screen if not. I use the Navigation framework so I have a Frame - this may make it easier...

Any tips or pointers appreciated - I just need some ideas to get started please.

答:
Just store the fact that the user is authenticated anywhere you like - I tend to like the Application object since it's an app-wide setting, but you can stick your "IsAuthenticaed" and/or "Roles" properties anywhere, really.

Take a look at WCF RIA Services - even if you don't want to use their solution, you can take a look at the generated authentication code it makes and see a good real-world example of how this can all work.

As for redirecting if the user is not logged in, I suggest using an INavigationContentLoader on your Frame, which can implement this logic in a central location.  See these two excellent posts by David Poll on the subject of INavigationContentLoader and authentication/authorization:

http://www.davidpoll.com/2010/01/01/opening-up-silverlight-4-navigation-authenticationauthorization-in-an-inavigationcontentloader/

http://www.davidpoll.com/2010/05/10/common-navigation-ui-and-authorization-driven-sitemaps/


问:
threejs gl.readPixels alpha always return 255
I want to read the pixel values from a threejs application.

```<code>const gl = renderer.context;
const currentFrame = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4);
// read image data from gl
gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, currentFrame);
</code>```

Threejs code

```<code>const renderer = new THREE.WebGLRenderer({preserveDrawingBuffer: true});

renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight );

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.z = 6;

const geometry = new THREE.BoxGeometry(10, 10, 10);
const cube = new THREE.Mesh(geometry);
scene.add(cube);
</code>```

The RBG values return correct but the alpha value always return 255.

答:
There are 2 possibilities.

Either the internal buffer contains 1.0 (255) for the alpha channel of all texels.

Or the buffer where you read from has no alpha channel at all, in its internal format. This means the internal buffer format is e.g. RGB.

The WebGL 1.0 Specifications - 5.13.12 Reading back pixels refers to OpenGL ES 2.0 Specification.

See OpenGL ES 2.0 Specification - 3.6.2 Transfer of Pixel Rectangles:

Final Expansion to RGBA

Each group is converted to a group of 4 elements as follows: if a group does not contain an A element, then A is added and set to 1.0. If any of R, G, or B is missing from the group, each missing element is added and assigned a value of 0.0.

Note, if you do not set the alpha channel of the vertex attribute which is writen to the fragment color, then the alpha channel will be 1.0 (255 in RGBA8 buffer), beacuse all vertex attributes are initilized with (0, 0, 0, 1):

The WebGL 1.0 Specifications - 5.13.10 Uniforms and attributes refers to OpenGL ES 2.0 Specification.

See OpenGL ES 2.0 Specification - See 2.7 Current Vertex State:

The state required to support vertex specification consists of MAX_VERTEX_ATTRIBS four-component floating-point vectors to store generic vertex attributes. The initial values for all generic vertex attributes are (0, 0, 0, 1).

If you want to set the alpha channel on the geometry of a THREE.mesh, then you have to attach a transparent material to the mesh with an opacity less then 1.0. See THREE.material:

```<code>var geometry = new THREE.BoxGeometry( 10, 10, 10 );
var material = new THREE.MeshBasicMaterial( {
    color: 0xff0000,
    transparent: true,
    opacity: 0.5,
} );
const cube = new THREE.Mesh(geometry, material);
</code>```

To be able to read an alpha channel, you have to ensure that the canvas contains an alpha (transparency) buffer. This can be don by setting the alpha attribute of the THREE.WebGLRenderer:

```<code>renderer = new THREE.WebGLRenderer( {
    alpha: true
});
</code>```

Body:
I want to read the pixel values from a threejs application.

const gl = renderer.context;
const currentFrame = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4);
// read image data from gl
gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, currentFrame);

Threejs code

const renderer = new THREE.WebGLRenderer({preserveDrawingBuffer: true});

renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight );

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.z = 6;

const geometry = new THREE.BoxGeometry(10, 10, 10);
const cube = new THREE.Mesh(geometry);
scene.add(cube);

The RBG values return correct but the alpha value always return 255.

Body:
There are 2 possibilities.

Either the internal buffer contains 1.0 (255) for the alpha channel of all texels.

Or the buffer where you read from has no alpha channel at all, in its internal format. This means the internal buffer format is e.g. RGB.

The WebGL 1.0 Specifications - 5.13.12 Reading back pixels refers to OpenGL ES 2.0 Specification.

See OpenGL ES 2.0 Specification - 3.6.2 Transfer of Pixel Rectangles:

Final Expansion to RGBA

Each group is converted to a group of 4 elements as follows: if a group does not contain an A element, then A is added and set to 1.0. If any of R, G, or B is missing from the group, each missing element is added and assigned a value of 0.0.

Note, if you do not set the alpha channel of the vertex attribute which is writen to the fragment color, then the alpha channel will be 1.0 (255 in RGBA8 buffer), beacuse all vertex attributes are initilized with (0, 0, 0, 1):

The WebGL 1.0 Specifications - 5.13.10 Uniforms and attributes refers to OpenGL ES 2.0 Specification.

See OpenGL ES 2.0 Specification - See 2.7 Current Vertex State:

The state required to support vertex specification consists of MAX_VERTEX_ATTRIBS four-component floating-point vectors to store generic vertex attributes. The initial values for all generic vertex attributes are (0, 0, 0, 1).

If you want to set the alpha channel on the geometry of a THREE.mesh, then you have to attach a transparent material to the mesh with an opacity less then 1.0. See THREE.material:

var geometry = new THREE.BoxGeometry( 10, 10, 10 );
var material = new THREE.MeshBasicMaterial( {
    color: 0xff0000,
    transparent: true,
    opacity: 0.5,
} );
const cube = new THREE.Mesh(geometry, material);

To be able to read an alpha channel, you have to ensure that the canvas contains an alpha (transparency) buffer. This can be don by setting the alpha attribute of the THREE.WebGLRenderer:

renderer = new THREE.WebGLRenderer( {
    alpha: true
});


问:
How to center text in
 when there is also a button on the right of

The text in the span is not exactly in the middle due to the button on the right. Any help in centering it would be very much appreciated. I've tried adding divs and changing the display property to no avail.

https://jsfiddle.net/9nvukjxa/17/

HTML (uses Bootstrap):

```<code><div class="wrapper">
    <div class="myflash  alert alert-dismissable speechwarning">
        <div class="container">
            <span>This is not exactly centered</span>
            <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
        </div>
    </div>
</div>
</code>```

CSS:

```<code>.container {
    text-align: center;
}
</code>```

答:
Take the button element out of the natural flow of the document by declaring its position absolute.

With a few other minor adjustments, like declaring position: relative on the containing parent element .container, you should find the text in question now precisely horizontally centered since the button element is no longer occupying space in the document flow.

.container {
  text-align: center;
}

/* Additional */

.alert-dismissable .close.pos-absolute {
    position: absolute;
    right: -7px;
}

.container {
    position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="wrapper">
  <div class="myflash  alert alert-dismissable speechwarning">
    <div class="container">
      <span>This is not exactly centered</span>
      <button type="button" class="close pos-absolute" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
    </div>
  </div>
</div></code>```

Updated Fiddle

Title: How to center text in <div> when there is also a button on the right of <div>

Body:
The text in the span is not exactly in the middle due to the button on the right. Any help in centering it would be very much appreciated. I've tried adding divs and changing the display property to no avail.

https://jsfiddle.net/9nvukjxa/17/

HTML (uses Bootstrap):

            This is not exactly centered
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

CSS:

.container {
    text-align: center;
}

Body:
Take the button element out of the natural flow of the document by declaring its position absolute.

With a few other minor adjustments, like declaring position: relative on the containing parent element .container, you should find the text in question now precisely horizontally centered since the button element is no longer occupying space in the document flow.

.container {
  text-align: center;
}

/* Additional */

.alert-dismissable .close.pos-absolute {
    position: absolute;
    right: -7px;
}

.container {
    position: relative;
}

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="wrapper">
  <div class="myflash  alert alert-dismissable speechwarning">
    <div class="container">
      <span>This is not exactly centered</span>
      <button type="button" class="close pos-absolute" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
    </div>
  </div>
</div>

Updated Fiddle


问:
Android Error: failed to find target with hash string android-26 and similar
I have an error when I wanted to try it first google firebase android quickstart.
The gradle build is failed with the reason "failed to find target with hash string android-26". Despite I installed the required version.

答:
In the SDK Manager, make sure SDK version 26 is installed.

Make sure that the app/build.gradle file has this line:

```<code>android {
compileSdkVersion 26
...
}
</code>```

You might also want to set the targetSdkVersion to the same number, and check if intalled Build Tools version matches the one denoted in the build.gradle file. If none is there, add it, i.e.:

```<code>android {
buildToolsVersion '26.0.3'
}
</code>```

Then press "Try again" at the top border of the window and wait.

Of course the same works for SDK version 27 and buildToolsVersion 27.0.1 and so forth. Just make sure installed version and referenced version do match.

Body:
In the SDK Manager, make sure SDK version 26 is installed.

Make sure that the app/build.gradle file has this line:

android {
compileSdkVersion 26
...
}

You might also want to set the targetSdkVersion to the same number, and check if intalled Build Tools version matches the one denoted in the build.gradle file. If none is there, add it, i.e.:

android {
buildToolsVersion '26.0.3'
}

Then press "Try again" at the top border of the window and wait.

Of course the same works for SDK version 27 and buildToolsVersion 27.0.1 and so forth. Just make sure installed version and referenced version do match.


问:
Python/Sklearn - Value Error: could not convert string to float
I'm trying to run a kNN classifier across my dataset using 10-fold CV. I have some experience with models in WEKA but struggling to transfer this over to Sklearn.

Below is my code

```<code>filename = 'train4.csv'
names = ['attribute names are here']

df = pandas.read_csv(filename, names=names)

num_folds = 10
kfold = KFold(n_splits=10, random_state=7)
model = KNeighborsClassifier()
results = cross_val_score(model, df.drop('mix1_instrument', axis=1), df['mix1_instrument'], cv=kfold)
print(results.mean())
</code>```

I am receiving this error

```<code> ValueError: could not convert string to float: ''
</code>```

How can I convert this attribute? And this contains useful information for classifying my instances would a conversion impact this?

There are two attributes that are 'object' that I believe need converting named 'class1' and class2'

Sample data below...

```<code>{
    'temporalCentroid': {
        0: 'temporalCentroid',
        1: '1.67324',
        2: '1.330722',
        3: '0.786984',
        4: '1.850129'
    },
    'LogSpecCentroid': {
        0: 'LogSpecCentroid',
        1: '-1.043802',
        2: '-0.82943',
        3: '-2.441297',
        4: '-0.837145'
    },
    'LogSpecSpread': {
        0: 'LogSpecSpread',
        1: '0.747558',
        2: '1.378373',
        3: '0.667634',
        4: '1.238404'
    },
    'MFCC1': {
        0: 'MFCC1',
        1: '3.502117',
        2: '6.697601',
        3: '4.011488',
        4: '0.823614'
    },
    'MFCC2': {
        0: 'MFCC2',
        1: '-9.208897',
        2: '-9.741549',
        3: '15.27665',
        4: '-15.22256'
    },
    'MFCC3': {
        0: 'MFCC3',
        1: '-2.334097',
        2: '-9.868089',
        3: '0.802509',
        4: '-4.978688'
    },
    'MFCC4': {
        0: 'MFCC4',
        1: '-9.013086',
        2: '0.609091',
        3: '2.50685',
        4: '-2.489553'
    },
    'MFCC5': {
        0: 'MFCC5',
        1: '4.847481',
        2: '1.733307',
        3: '0.10459',
        4: '1.066615'
    },
    'MFCC6': {
        0: 'MFCC6',
        1: '-4.770421',
        2: '-5.381835',
        3: '-0.260118',
        4: '-1.020861'
    },
    'MFCC7': {
        0: 'MFCC7',
        1: '-3.362488',
        2: '-1.261088',
        3: '0.593255',
        4: '-2.007349'
    },
    'MFCC8': {
        0: 'MFCC8',
        1: '-9.527529',
        2: '-3.809237',
        3: '-0.362287',
        4: '-8.938164'
    },
    'MFCC9': {
        0: 'MFCC9',
        1: '-9.629579',
        2: '1.486923',
        3: '-2.957592',
        4: '-2.324424'
    },
    'MFCC10': {
        0: 'MFCC10',
        1: '1.848685',
        2: '-3.938455',
        3: '-1.884439',
        4: '-2.535579'
    },
    'MFCC11': {
        0: 'MFCC11',
        1: '-2.311295',
        2: '-2.159865',
        3: '-0.827179',
        4: '0.638553'
    },
    'MFCC12': {
        0: 'MFCC12',
        1: '-7.696675',
        2: '-3.138412',
        3: '-0.605056',
        4: '-1.116259'
    },
    'MFCC13': {
        0: 'MFCC13',
        1: '10.35572',
        2: '9.095669',
        3: '6.426399',
        4: '15.04535'
    },
    'MFCCMin': {
        0: 'MFCCMin',
        1: '-9.629579',
        2: '-9.868089',
        3: '-2.957592',
        4: '-15.22256'
    },
    'MFCCMax': {
        0: 'MFCCMax',
        1: '10.35572',
        2: '9.095669',
        3: '15.27665',
        4: '15.04535'
    },
    'MFCCSum': {
        0: 'MFCCSum',
        1: '-37.300064',
        2: '-19.675939',
        3: '22.82507',
        4: '-23.059305'
    },
    'MFCCAvg': {
        0: 'MFCCAvg',
        1: '-2.869235692',
        2: '-1.513533769',
        3: '1.755774615',
        4: '-1.773792692'
    },
    'MFCCStd': {
        0: 'MFCCStd',
        1: '6.409842944',
        2: '5.558499123',
        3: '4.756836281',
        4: '6.76039911'
    },
    'Energy': {
        0: 'Energy',
        1: '-2.96148',
        2: '-3.522993',
        3: '-3.409359',
        4: '-2.235853'
    },
    'ZeroCrossings': {
        0: 'ZeroCrossings',
        1: '128',
        2: '188',
        3: '43',
        4: '288'
    },
    'SpecCentroid': {
        0: 'SpecCentroid',
        1: '284.0513',
        2: '414.8489',
        3: '102.2096',
        4: '405.1262'
    },
    'SpecSpread': {
        0: 'SpecSpread',
        1: '207.5526',
        2: '350.7937',
        3: '53.52178',
        4: '360.0353'
    },
    'Rolloff': {
        0: 'Rolloff',
        1: '263.7817',
        2: '783.2703',
        3: '129.1992',
        4: '912.4695'
    },
    'Flux': {
        0: 'Flux',
        1: '0',
        2: '0',
        3: '0',
        4: '0'
    },
    'bandsCoefMin': {
        0: 'bandsCoefMin',
        1: '-0.224957',
        2: '-0.247903',
        3: '-0.22283',
        4: '-0.232534'
    },
    'bandsCoefMax': {
        0: 'bandsCoefMax',
        1: '-0.074945',
        2: '-0.113654',
        3: '-0.062254',
        4: '-0.080883'
    },
    'bandsCoefSum1': {
        0: 'bandsCoefSum1',
        1: '-5.575428',
        2: '-5.524777',
        3: '-5.511125',
        4: '-5.532536'
    },
    'bandsCoefAvg': {
        0: 'bandsCoefAvg',
        1: '-0.168952364',
        2: '-0.167417485',
        3: '-0.167003788',
        4: '-0.167652606'
    },
    'bandsCoefStd': {
        0: 'bandsCoefStd',
        1: '0.042580181',
        2: '0.048429973',
        3: '0.049881374',
        4: '0.0475839'
    },
    'bandsCoefSum': {
        0: 'bandsCoefSum',
        1: '382.5963',
        2: '360.9232',
        3: '384.3541',
        4: '368.9903'
    },
    'prjmin': {
        0: 'prjmin',
        1: '-0.999362',
        2: '-0.999719',
        3: '-0.988315',
        4: '-0.999421'
    },
    'prjmax': {
        0: 'prjmax',
        1: '0.023797',
        2: '0.009596',
        3: '0.028112',
        4: '0.024612'
    },
    'prjSum': {
        0: 'prjSum',
        1: '-0.99911',
        2: '-1.006792',
        3: '-1.084054',
        4: '-1.002478'
    },
    'prjAvg': {
        0: 'prjAvg',
        1: '-0.030276061',
        2: '-0.030508848',
        3: '-0.032850121',
        4: '-0.030378121'
    },
    'prjStd': {
        0: 'prjStd',
        1: '0.174082468',
        2: '0.174040569',
        3: '0.173600498',
        4: '0.174064118'
    },
    'LogAttackTime': {
        0: 'LogAttackTime',
        1: '0.365883',
        2: '-0.35427',
        3: '-0.669283',
        4: '-0.026181'
    },
    'HamoPkMin': {
        0: 'HamoPkMin',
        1: '0',
        2: '0',
        3: '0',
        4: '0'
    },
    'HamoPkMax': {
        0: 'HamoPkMax',
        1: '1.025473',
        2: '1.05761',
        3: '0.986766',
        4: '0.957316'
    },
    'HamoPkSum': {
        0: 'HamoPkSum',
        1: '14.391206',
        2: '20.306125',
        3: '9.727358',
        4: '14.772449'
    },
    'HamoPkAvg': {
        0: 'HamoPkAvg',
        1: '0.513971643',
        2: '0.72521875',
        3: '0.347405643',
        4: '0.527587464'
    },
    'HamoPkStd': {
        0: 'HamoPkStd',
        1: '0.376622124',
        2: '0.325929503',
        3: '0.388971641',
        4: '0.381693476'
    },
    'class1': {
        0: 'class1',
        1: 'aerophone',
        2: 'aerophone',
        3: 'chordophone',
        4: 'aerophone'
    },
    'class2': {
        0: 'class2',
        1: 'aero_single-reed',
        2: 'aero_lip-vibrated',
        3: 'chrd_simple',
        4: 'aero_single-reed'
    },
    'mix1_instrument': {
        0: 'mix1_instrument',
        1: 'Saxophone',
        2: 'Trumpet',
        3: 'Piano',
        4: 'Clarinet'
    }
}
</code>```

Thanks

答:
Here is a small demo:

Source DF:

```<code>In [43]: df
Out[43]:
     Energy  HamoPkStd       class1             class2 mix1_instrument
0 -2.961480  14.391206    aerophone   aero_single-reed       Saxophone
1 -3.522993  20.306125  chordophone  aero_lip-vibrated         Trumpet
2 -3.409359   9.727358    aerophone        chrd_simple           Piano
</code>```

Labels encoding:

```<code>In [44]: %paste
from sklearn.preprocessing import LabelBinarizer, LabelEncoder

str_cols = df.columns[df.columns.str.contains('(?:class|instrument)')]
clfs = {c:LabelEncoder() for c in str_cols}

for col, clf in clfs.items():
    df[col] = clfs[col].fit_transform(df[col])
## -- End pasted text --
</code>```

Result - all text/string columns have been converted to numbers, so we can feed it to Neural Networks:

```<code>In [45]: df
Out[45]:
     Energy  HamoPkStd  class1  class2  mix1_instrument
0 -2.961480  14.391206       0       1                1
1 -3.522993  20.306125       1       0                2
2 -3.409359   9.727358       0       2                0
</code>```

Inverse transfomration:

```<code>In [48]: clfs['class1'].inverse_transform(df['class1'])
Out[48]: array(['aerophone', 'chordophone', 'aerophone'], dtype=object)

In [49]: clfs['mix1_instrument'].inverse_transform(df['mix1_instrument'])
Out[49]: array(['Saxophone', 'Trumpet', 'Piano'], dtype=object)
</code>```

Body:
I'm trying to run a kNN classifier across my dataset using 10-fold CV. I have some experience with models in WEKA but struggling to transfer this over to Sklearn.

Below is my code

filename = 'train4.csv'
names = ['attribute names are here']

df = pandas.read_csv(filename, names=names)

num_folds = 10
kfold = KFold(n_splits=10, random_state=7)
model = KNeighborsClassifier()
results = cross_val_score(model, df.drop('mix1_instrument', axis=1), df['mix1_instrument'], cv=kfold)
print(results.mean())

I am receiving this error

 ValueError: could not convert string to float: ''

How can I convert this attribute? And this contains useful information for classifying my instances would a conversion impact this?

There are two attributes that are 'object' that I believe need converting named 'class1' and class2'

Sample data below...

{
    'temporalCentroid': {
        0: 'temporalCentroid',
        1: '1.67324',
        2: '1.330722',
        3: '0.786984',
        4: '1.850129'
    },
    'LogSpecCentroid': {
        0: 'LogSpecCentroid',
        1: '-1.043802',
        2: '-0.82943',
        3: '-2.441297',
        4: '-0.837145'
    },
    'LogSpecSpread': {
        0: 'LogSpecSpread',
        1: '0.747558',
        2: '1.378373',
        3: '0.667634',
        4: '1.238404'
    },
    'MFCC1': {
        0: 'MFCC1',
        1: '3.502117',
        2: '6.697601',
        3: '4.011488',
        4: '0.823614'
    },
    'MFCC2': {
        0: 'MFCC2',
        1: '-9.208897',
        2: '-9.741549',
        3: '15.27665',
        4: '-15.22256'
    },
    'MFCC3': {
        0: 'MFCC3',
        1: '-2.334097',
        2: '-9.868089',
        3: '0.802509',
        4: '-4.978688'
    },
    'MFCC4': {
        0: 'MFCC4',
        1: '-9.013086',
        2: '0.609091',
        3: '2.50685',
        4: '-2.489553'
    },
    'MFCC5': {
        0: 'MFCC5',
        1: '4.847481',
        2: '1.733307',
        3: '0.10459',
        4: '1.066615'
    },
    'MFCC6': {
        0: 'MFCC6',
        1: '-4.770421',
        2: '-5.381835',
        3: '-0.260118',
        4: '-1.020861'
    },
    'MFCC7': {
        0: 'MFCC7',
        1: '-3.362488',
        2: '-1.261088',
        3: '0.593255',
        4: '-2.007349'
    },
    'MFCC8': {
        0: 'MFCC8',
        1: '-9.527529',
        2: '-3.809237',
        3: '-0.362287',
        4: '-8.938164'
    },
    'MFCC9': {
        0: 'MFCC9',
        1: '-9.629579',
        2: '1.486923',
        3: '-2.957592',
        4: '-2.324424'
    },
    'MFCC10': {
        0: 'MFCC10',
        1: '1.848685',
        2: '-3.938455',
        3: '-1.884439',
        4: '-2.535579'
    },
    'MFCC11': {
        0: 'MFCC11',
        1: '-2.311295',
        2: '-2.159865',
        3: '-0.827179',
        4: '0.638553'
    },
    'MFCC12': {
        0: 'MFCC12',
        1: '-7.696675',
        2: '-3.138412',
        3: '-0.605056',
        4: '-1.116259'
    },
    'MFCC13': {
        0: 'MFCC13',
        1: '10.35572',
        2: '9.095669',
        3: '6.426399',
        4: '15.04535'
    },
    'MFCCMin': {
        0: 'MFCCMin',
        1: '-9.629579',
        2: '-9.868089',
        3: '-2.957592',
        4: '-15.22256'
    },
    'MFCCMax': {
        0: 'MFCCMax',
        1: '10.35572',
        2: '9.095669',
        3: '15.27665',
        4: '15.04535'
    },
    'MFCCSum': {
        0: 'MFCCSum',
        1: '-37.300064',
        2: '-19.675939',
        3: '22.82507',
        4: '-23.059305'
    },
    'MFCCAvg': {
        0: 'MFCCAvg',
        1: '-2.869235692',
        2: '-1.513533769',
        3: '1.755774615',
        4: '-1.773792692'
    },
    'MFCCStd': {
        0: 'MFCCStd',
        1: '6.409842944',
        2: '5.558499123',
        3: '4.756836281',
        4: '6.76039911'
    },
    'Energy': {
        0: 'Energy',
        1: '-2.96148',
        2: '-3.522993',
        3: '-3.409359',
        4: '-2.235853'
    },
    'ZeroCrossings': {
        0: 'ZeroCrossings',
        1: '128',
        2: '188',
        3: '43',
        4: '288'
    },
    'SpecCentroid': {
        0: 'SpecCentroid',
        1: '284.0513',
        2: '414.8489',
        3: '102.2096',
        4: '405.1262'
    },
    'SpecSpread': {
        0: 'SpecSpread',
        1: '207.5526',
        2: '350.7937',
        3: '53.52178',
        4: '360.0353'
    },
    'Rolloff': {
        0: 'Rolloff',
        1: '263.7817',
        2: '783.2703',
        3: '129.1992',
        4: '912.4695'
    },
    'Flux': {
        0: 'Flux',
        1: '0',
        2: '0',
        3: '0',
        4: '0'
    },
    'bandsCoefMin': {
        0: 'bandsCoefMin',
        1: '-0.224957',
        2: '-0.247903',
        3: '-0.22283',
        4: '-0.232534'
    },
    'bandsCoefMax': {
        0: 'bandsCoefMax',
        1: '-0.074945',
        2: '-0.113654',
        3: '-0.062254',
        4: '-0.080883'
    },
    'bandsCoefSum1': {
        0: 'bandsCoefSum1',
        1: '-5.575428',
        2: '-5.524777',
        3: '-5.511125',
        4: '-5.532536'
    },
    'bandsCoefAvg': {
        0: 'bandsCoefAvg',
        1: '-0.168952364',
        2: '-0.167417485',
        3: '-0.167003788',
        4: '-0.167652606'
    },
    'bandsCoefStd': {
        0: 'bandsCoefStd',
        1: '0.042580181',
        2: '0.048429973',
        3: '0.049881374',
        4: '0.0475839'
    },
    'bandsCoefSum': {
        0: 'bandsCoefSum',
        1: '382.5963',
        2: '360.9232',
        3: '384.3541',
        4: '368.9903'
    },
    'prjmin': {
        0: 'prjmin',
        1: '-0.999362',
        2: '-0.999719',
        3: '-0.988315',
        4: '-0.999421'
    },
    'prjmax': {
        0: 'prjmax',
        1: '0.023797',
        2: '0.009596',
        3: '0.028112',
        4: '0.024612'
    },
    'prjSum': {
        0: 'prjSum',
        1: '-0.99911',
        2: '-1.006792',
        3: '-1.084054',
        4: '-1.002478'
    },
    'prjAvg': {
        0: 'prjAvg',
        1: '-0.030276061',
        2: '-0.030508848',
        3: '-0.032850121',
        4: '-0.030378121'
    },
    'prjStd': {
        0: 'prjStd',
        1: '0.174082468',
        2: '0.174040569',
        3: '0.173600498',
        4: '0.174064118'
    },
    'LogAttackTime': {
        0: 'LogAttackTime',
        1: '0.365883',
        2: '-0.35427',
        3: '-0.669283',
        4: '-0.026181'
    },
    'HamoPkMin': {
        0: 'HamoPkMin',
        1: '0',
        2: '0',
        3: '0',
        4: '0'
    },
    'HamoPkMax': {
        0: 'HamoPkMax',
        1: '1.025473',
        2: '1.05761',
        3: '0.986766',
        4: '0.957316'
    },
    'HamoPkSum': {
        0: 'HamoPkSum',
        1: '14.391206',
        2: '20.306125',
        3: '9.727358',
        4: '14.772449'
    },
    'HamoPkAvg': {
        0: 'HamoPkAvg',
        1: '0.513971643',
        2: '0.72521875',
        3: '0.347405643',
        4: '0.527587464'
    },
    'HamoPkStd': {
        0: 'HamoPkStd',
        1: '0.376622124',
        2: '0.325929503',
        3: '0.388971641',
        4: '0.381693476'
    },
    'class1': {
        0: 'class1',
        1: 'aerophone',
        2: 'aerophone',
        3: 'chordophone',
        4: 'aerophone'
    },
    'class2': {
        0: 'class2',
        1: 'aero_single-reed',
        2: 'aero_lip-vibrated',
        3: 'chrd_simple',
        4: 'aero_single-reed'
    },
    'mix1_instrument': {
        0: 'mix1_instrument',
        1: 'Saxophone',
        2: 'Trumpet',
        3: 'Piano',
        4: 'Clarinet'
    }
}

Thanks

Body:
Here is a small demo:

Source DF:

In [43]: df
Out[43]:
     Energy  HamoPkStd       class1             class2 mix1_instrument
0 -2.961480  14.391206    aerophone   aero_single-reed       Saxophone
1 -3.522993  20.306125  chordophone  aero_lip-vibrated         Trumpet
2 -3.409359   9.727358    aerophone        chrd_simple           Piano

Labels encoding:

In [44]: %paste
from sklearn.preprocessing import LabelBinarizer, LabelEncoder

str_cols = df.columns[df.columns.str.contains('(?:class|instrument)')]
clfs = {c:LabelEncoder() for c in str_cols}

for col, clf in clfs.items():
    df[col] = clfs[col].fit_transform(df[col])
## -- End pasted text --

Result - all text/string columns have been converted to numbers, so we can feed it to Neural Networks:

In [45]: df
Out[45]:
     Energy  HamoPkStd  class1  class2  mix1_instrument
0 -2.961480  14.391206       0       1                1
1 -3.522993  20.306125       1       0                2
2 -3.409359   9.727358       0       2                0

Inverse transfomration:

In [48]: clfs['class1'].inverse_transform(df['class1'])
Out[48]: array(['aerophone', 'chordophone', 'aerophone'], dtype=object)

In [49]: clfs['mix1_instrument'].inverse_transform(df['mix1_instrument'])
Out[49]: array(['Saxophone', 'Trumpet', 'Piano'], dtype=object)


问:
Replacing values in same column and same dataset in R
I have a dataset like this:

```<code>Name|Material |Project
John|LS       |222
Jack|Limestone|111
Job |LI       |121
</code>```

I want to replace LS and LI with Limestone in Materials column.

I have tried this for LS:

```<code>ds$Material[ds$material %in% grep("^LS^",ds$Material,ignore.case = TRUE)]<-"Limestone"
</code>```

But the column still has a bunch of LS in there. Any ideas?

答:
Using base R, you can use ifelse.

```<code># Reproducible example
data <- read.table(textConnection("Name|Material |Project
                                   John|LS       |222
                                   Jack|Limestone|111
                                   Job |LI       |121  "),
                   sep = "|", row.names = NULL, header = TRUE,
                   stringsAsFactors = FALSE, strip.white = TRUE)
data$Material <- ifelse(data$Material %in% c("LS", "LI"), "Limestone", data$Material)
</code>```

Body:
I have a dataset like this:

Name|Material |Project
John|LS       |222
Jack|Limestone|111
Job |LI       |121

I want to replace LS and LI with Limestone in Materials column.

I have tried this for LS:

ds$Material[ds$material %in% grep("^LS^",ds$Material,ignore.case = TRUE)]<-"Limestone"

But the column still has a bunch of LS in there. Any ideas?

Body:
Using base R, you can use ifelse.

# Reproducible example
data <- read.table(textConnection("Name|Material |Project
                                   John|LS       |222
                                   Jack|Limestone|111
                                   Job |LI       |121  "),
                   sep = "|", row.names = NULL, header = TRUE,
                   stringsAsFactors = FALSE, strip.white = TRUE)
data$Material <- ifelse(data$Material %in% c("LS", "LI"), "Limestone", data$Material)


问:
rails aborted! Don't know how to build task 'task_name'
I was creating a quick one-off task:

```<code>require 'yaml'

task generate_permissions_yaml: :environment do
  permissions = []

  Permission.order(:title).each do |permission|
    permissions << {
      title: permission.title,
      code: permission.code,
      description: permission.description
    }
  end

  puts permissions.to_yaml
end
</code>```

When I ran it with rails generate_permissions_yaml, I got this error:

```<code>rails aborted!
Don't know how to build task 'generate_permissions_yaml' (see --tasks)
/bundle/gems/railties-5.0.2/lib/rails/commands/rake_proxy.rb:14:in `block in run_rake_task'
/bundle/gems/railties-5.0.2/lib/rails/commands/rake_proxy.rb:11:in `run_rake_task'
/bundle/gems/railties-5.0.2/lib/rails/commands/commands_tasks.rb:51:in `run_command!'
/bundle/gems/railties-5.0.2/lib/rails/commands.rb:18:in `<top (required)>'
</code>```

答:
For newbies - this is a common error if you use a space instead of a colon in a rake command. For example if you enter:

```<code>rake db migrate
</code>```

instead of:

```<code>rake db:migrate
</code>```

The correct format has a colon, not a space

Body:
I was creating a quick one-off task:

require 'yaml'

task generate_permissions_yaml: :environment do
  permissions = []

  Permission.order(:title).each do |permission|
    permissions << {
      title: permission.title,
      code: permission.code,
      description: permission.description
    }
  end

  puts permissions.to_yaml
end

When I ran it with rails generate_permissions_yaml, I got this error:

rails aborted!
Don't know how to build task 'generate_permissions_yaml' (see --tasks)
/bundle/gems/railties-5.0.2/lib/rails/commands/rake_proxy.rb:14:in `block in run_rake_task'
/bundle/gems/railties-5.0.2/lib/rails/commands/rake_proxy.rb:11:in `run_rake_task'
/bundle/gems/railties-5.0.2/lib/rails/commands/commands_tasks.rb:51:in `run_command!'
/bundle/gems/railties-5.0.2/lib/rails/commands.rb:18:in `<top (required)>'

Body:
For newbies - this is a common error if you use a space instead of a colon in a rake command. For example if you enter:

rake db migrate

instead of:

rake db:migrate

The correct format has a colon, not a space


问:
How to change SAS sgplot refline label orientation
I am plotting in SAS using SGPLOT. I added a few reflines on the x-axis to mark certain dates however, the labels of these reflines become vertical as shown  here. With only three reflines, the labels were horizontal as I hoped. However, as I added more reflines, the labels turned vertical.

Is there a way to change the orientation of the label? Or is it just because there is not enough space...

Here is my code for the refline:

```<code>refline '01Jul2002'd / axis=x label = "[1]"
labelloc=outside labelpos=max labelattrs=(size=6.5pt family="arial")
</code>```

答:
I cannot replicate your issue. Here's code that doesn't replicate your issue. This means either you've set something else somewhere else that's causing this or you could be using a different version. I'm on SAS 9.4 TS1M3. In the future please include code so we can replicate your issue. </p>

```<code>proc sgplot data=sashelp.stocks(where=(stock='IBM'));
series x=date y=open;
refline '01Jul2002'd / axis=x label = "[1]"
labelloc=outside labelpos=max labelattrs=(size=6.5pt family="arial");
run;
</code>```

Body:
I am plotting in SAS using SGPLOT. I added a few reflines on the x-axis to mark certain dates however, the labels of these reflines become vertical as shown  here. With only three reflines, the labels were horizontal as I hoped. However, as I added more reflines, the labels turned vertical.

Is there a way to change the orientation of the label? Or is it just because there is not enough space...

Here is my code for the refline:

refline '01Jul2002'd / axis=x label = "[1]"
labelloc=outside labelpos=max labelattrs=(size=6.5pt family="arial")

Body:
I cannot replicate your issue. Here's code that doesn't replicate your issue. This means either you've set something else somewhere else that's causing this or you could be using a different version. I'm on SAS 9.4 TS1M3. In the future please include code so we can replicate your issue.

proc sgplot data=sashelp.stocks(where=(stock='IBM'));
series x=date y=open;
refline '01Jul2002'd / axis=x label = "[1]"
labelloc=outside labelpos=max labelattrs=(size=6.5pt family="arial");
run;