问:
Create a JDBC connection to HBase
I am trying to cretae a JDBC to connection to HBase in our cluster using CDATA (https://www.cdata.com/kb/tech/hbase-jdbc-dbvr.rst)

The HBase properties in our cluster is as follow:

```<code>hbase.zookeeper.quorum=auper01-01-20-01-0.prod.vroc.com.au,auper01-02-10-01-0.prod.vroc.com.au,auper01-02-10-02-0.prod.vroc.com.au
hbase.zookeeper.port=2181
hbase.zokeeper.znode.parent=/hbase-unsecure
</code>```

Based on the document, i have set the JDBC URL as follow:

```<code>jdbc:apachehbase:Server=auper01-01-20-01-0.prod.vroc.com.au,auper01-02-10-01-0.prod.vroc.com.au,auper01-02-10-02-0.prod.vroc.com.au;Port=2181;
</code>```

but it doesn't fetch data from HBase database..Does anyone know how to populate the JDBC string.

答:
It looks like you have the wrong value for the Server property. In your connection string, set the Server property in the connection to the IP address or hostname of the HBase master, not the hbase.zookeeper.quorum property value. For example:

```<code>jdbc:apachehbase:Server=###.###.###.###;Port=2181;
</code>```

Title: Create a JDBC connection to HBase

Body:
I am trying to cretae a JDBC to connection to HBase in our cluster using CDATA (https://www.cdata.com/kb/tech/hbase-jdbc-dbvr.rst)

The HBase properties in our cluster is as follow:

hbase.zookeeper.quorum=auper01-01-20-01-0.prod.vroc.com.au,auper01-02-10-01-0.prod.vroc.com.au,auper01-02-10-02-0.prod.vroc.com.au
hbase.zookeeper.port=2181
hbase.zokeeper.znode.parent=/hbase-unsecure

Based on the document, i have set the JDBC URL as follow:

jdbc:apachehbase:Server=auper01-01-20-01-0.prod.vroc.com.au,auper01-02-10-01-0.prod.vroc.com.au,auper01-02-10-02-0.prod.vroc.com.au;Port=2181;

but it doesn't fetch data from HBase database..Does anyone know how to populate the JDBC string.

Body:
It looks like you have the wrong value for the Server property. In your connection string, set the Server property in the connection to the IP address or hostname of the HBase master, not the hbase.zookeeper.quorum property value. For example:

jdbc:apachehbase:Server=###.###.###.###;Port=2181;


来源: stackexchange

问:
React-Router-dom :- Cannot read property 'string' of undefined at Object.../node_modules/react-router-dom/es/BrowserRouter.js
I have used create-react-app for creating a new working repository for react and i wanted to add some Routing paths using react-router-dom.

This is my index.js file.

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import PostsIndex from './components/posts_index';
import {BrowserRouter,Switch,Route} from 'react-router-dom';

ReactDom.render(
<BrowserRouter>
<div>
<Switch>
<Route path="/" component={PostsIndex} />
</Switch>
</div>
</BrowserRouter>,
document.getElementById('root')
);
</code>```

And this is my posts_index.js file

```<code>import React,{Component} from 'react';

class PostsIndex extends Component {
render(){
return(
<div>Posts Index </div>
)
}
export default PostsIndex;
</code>```

Can someone help me with this error?

答:
Seems to be working on my end.

Only things I had to adjust was the ReactDom to ReactDOM and a missing closing parenthesis in posts_index.js

Working solution: https://codesandbox.io/s/nkvjqrvpwj

ContentLicense: CC BY-SA 3.0

Body:
I have used create-react-app for creating a new working repository for react and i wanted to add some Routing paths using react-router-dom.

This is my index.js file.

import React from 'react';
import ReactDOM from 'react-dom';
import PostsIndex from './components/posts_index';
import {BrowserRouter,Switch,Route} from 'react-router-dom';

ReactDom.render(
<BrowserRouter>

<Switch>
<Route path="/" component={PostsIndex} />
</Switch>

</BrowserRouter>,
document.getElementById('root')
);

And this is my posts_index.js file

import React,{Component} from 'react';

class PostsIndex extends Component {
render(){
return(

Posts Index

)
}
export default PostsIndex;

Can someone help me with this error?


问:
Center contents of div horizontally/vertically and align text to image
I have a bootstrap div container split into 3 divs of equal sizes (widths are equal but not sure how to maintain height as well). I am not able to center the contents of it vertically and horizontally. Also, I am unable to figure out how to center a text that lies on the right of an image.

My HTML code:

```<code><div class="container-fluid">
  <div>
    <img src="https://image.ibb.co/cjLadR/icon_1.png" alt="icon_1">
    <div> Test comments </div>
  </div>
  <div>
    <img src="https://image.ibb.co/gDrgJR/icon_2.png" alt="icon_2">
    <div> Test comments </div>
  </div>
  <div>
    <img src="https://image.ibb.co/hm1Rk6/icon_3.png" alt="icon_3">
    <div> Test comments </div>
  </div>
</div>
</code>```

Here is JsFiddle

And my expected output:

答:
You could explore using flex-box to leverage its precise positioning and allow (let) the browser do all the calculations and other heavy lifting.

I've also accounted for your @media-query to make the necessary adjustment at that viewport as well.

Updated JSFiddle

Code Snippet Demonstration:

.container-fluid {
    padding: 0 !important;
    margin: 0 !important;
    display: flex;
    justify-content: center;
    align-items: center;
}

.container-fluid > div {
    background-color: #34caf7;
    flex: 1 1 33.33%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.container-fluid > div > img {
    float: left;
    width: 20%;
    margin-right: 30px;
}

.container-fluid > div > div {
    color: white;
    display: block;
}
@media (max-width: 480px) {
    .container-fluid > div {
        flex: 1 1 100%;
        padding: 10px;
    }

    .container-fluid {
        flex-direction: column;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container-fluid">
  <div>
    <img src="https://image.ibb.co/cjLadR/icon_1.png" alt="icon_1">
    <div> Test comments </div>
  </div>
  <div>
    <img src="https://image.ibb.co/gDrgJR/icon_2.png" alt="icon_2">
    <div> Test comments </div>
  </div>
  <div>
    <img src="https://image.ibb.co/hm1Rk6/icon_3.png" alt="icon_3">
    <div> Test comments </div>
  </div>
</div></code>```

A note on cross browser compatibility:

flex-box has limited or no support for legacy browsers, refer to compatibility overviews before considering using in production - If supporting IE11 (shudder) is still a concern for you.

https://caniuse.com/#search=flexbox

https://developer.mozilla.org/en-US/docs/Web/CSS/flex#Browser_compatibility

Body:
I have a bootstrap div container split into 3 divs of equal sizes (widths are equal but not sure how to maintain height as well). I am not able to center the contents of it vertically and horizontally. Also, I am unable to figure out how to center a text that lies on the right of an image.

My HTML code:

 Test comments

 Test comments

 Test comments

Here is JsFiddle

And my expected output:

Body:
You could explore using flex-box to leverage its precise positioning and allow (let) the browser do all the calculations and other heavy lifting.

I've also accounted for your @media-query to make the necessary adjustment at that viewport as well.

Updated JSFiddle

Code Snippet Demonstration:

.container-fluid {
    padding: 0 !important;
    margin: 0 !important;
    display: flex;
    justify-content: center;
    align-items: center;
}

.container-fluid > div {
    background-color: #34caf7;
    flex: 1 1 33.33%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.container-fluid > div > img {
    float: left;
    width: 20%;
    margin-right: 30px;
}

.container-fluid > div > div {
    color: white;
    display: block;
}
@media (max-width: 480px) {
    .container-fluid > div {
        flex: 1 1 100%;
        padding: 10px;
    }

    .container-fluid {
        flex-direction: column;
    }
}

<div class="container-fluid">
  <div>
    <img src="https://image.ibb.co/cjLadR/icon_1.png" alt="icon_1">
    <div> Test comments </div>
  </div>
  <div>
    <img src="https://image.ibb.co/gDrgJR/icon_2.png" alt="icon_2">
    <div> Test comments </div>
  </div>
  <div>
    <img src="https://image.ibb.co/hm1Rk6/icon_3.png" alt="icon_3">
    <div> Test comments </div>
  </div>
</div>

A note on cross browser compatibility:

flex-box has limited or no support for legacy browsers, refer to compatibility overviews before considering using in production - If supporting IE11 (shudder) is still a concern for you.

https://caniuse.com/#search=flexbox

https://developer.mozilla.org/en-US/docs/Web/CSS/flex#Browser_compatibility


问:
Immutable string and pointer address
In Go spec is written:

Strings are immutable: once created, it is impossible to change the
  contents of a string.

I have following code:

```<code>str := "hello"
fmt.Printf("%p\n",&str) // 0x1040c128
fmt.Printf("%v\n",str) // hello
ptr := &str
*ptr = "world"
fmt.Printf("%p\n",&str) // 0x1040c128
fmt.Printf("%v\n",str) // world
</code>```

I would have expected &str address was changed after *ptr = "world". As it would happen with Java, where we reassign String references.

What is 'immutability' here?

答:
string values are immutable.

str is not a string value. It's a variable (of string type). And values of variables may be changed, that's what you'd expect from any programming language.

"hello" is a string value, and this is what is immutable. "world" is another string value, and when you assign "world" to str, you just assign another, different value to the str variable. It doesn't matter if you're doing it directly to str, or via a pointer. You're just changing the value of the variable denoted by str.

Immutable means you cannot take the string value "world", and change its second character for example. If you have a function for example which receives a string argument, whatever it receives (e.g. "hello"), you can be sure it will always remain the same. No matter when / how you print this string value, it will always be "hello".

A string value is a struct value under the hood, represented by the reflect.StringHeader type:

```<code>type StringHeader struct {
    Data uintptr
    Len  int
}
</code>```

It basically stores a data pointer (to the byte array holding the UTF-8 encoded value of the text), and the byte-length of the string value. The data array and its length are not exposed to you, so you can't modify them. This is one element of making sure that string values are immutable. Another element is that although string values can be indexed (which indexes its bytes), you can not assign new values to the index expressions. E.g. it is valid to use the value "abc"[0], but it is invalid to assign a new value to it like "abc"[0] = 'x'. Similarly, you cannot take the address of an index expression indexing a string value (else you could modify the pointed value and thus indirectly the string value).

This is what the language spec guarantees. Note that there are certain ways to still change string values, e.g. using package unsafe, but this falls outside the guarantees of the spec:

Package unsafe contains operations that step around the type safety of Go programs.

Packages that import unsafe may be non-portable and are not protected by the Go 1 compatibility guidelines.

The "moment" you import package unsafe, you'll lose any guarantees and safety provided by the language spec, and from there on you can't complain for anything. But without using these "special" means, it cannot happen that a string value gets altered.

Read the blog post Strings, bytes, runes and characters in Go for how string is implemented and works in Go.

See related questions:

What is the difference between the string and []byte in Go?

What are the possible consequences of using unsafe conversion from []byte to string in go?

Title: Immutable string and pointer address

Body:
In Go spec is written:

Strings are immutable: once created, it is impossible to change the
  contents of a string.

I have following code:

str := "hello"
fmt.Printf("%p\n",&str) // 0x1040c128
fmt.Printf("%v\n",str) // hello
ptr := &str
*ptr = "world"
fmt.Printf("%p\n",&str) // 0x1040c128
fmt.Printf("%v\n",str) // world

I would have expected &str address was changed after *ptr = "world". As it would happen with Java, where we reassign String references.

What is 'immutability' here?

Body:
string values are immutable.

str is not a string value. It's a variable (of string type). And values of variables may be changed, that's what you'd expect from any programming language.

"hello" is a string value, and this is what is immutable. "world" is another string value, and when you assign "world" to str, you just assign another, different value to the str variable. It doesn't matter if you're doing it directly to str, or via a pointer. You're just changing the value of the variable denoted by str.

Immutable means you cannot take the string value "world", and change its second character for example. If you have a function for example which receives a string argument, whatever it receives (e.g. "hello"), you can be sure it will always remain the same. No matter when / how you print this string value, it will always be "hello".

A string value is a struct value under the hood, represented by the reflect.StringHeader type:

type StringHeader struct {
    Data uintptr
    Len  int
}

It basically stores a data pointer (to the byte array holding the UTF-8 encoded value of the text), and the byte-length of the string value. The data array and its length are not exposed to you, so you can't modify them. This is one element of making sure that string values are immutable. Another element is that although string values can be indexed (which indexes its bytes), you can not assign new values to the index expressions. E.g. it is valid to use the value "abc"[0], but it is invalid to assign a new value to it like "abc"[0] = 'x'. Similarly, you cannot take the address of an index expression indexing a string value (else you could modify the pointed value and thus indirectly the string value).

This is what the language spec guarantees. Note that there are certain ways to still change string values, e.g. using package unsafe, but this falls outside the guarantees of the spec:

Package unsafe contains operations that step around the type safety of Go programs.

Packages that import unsafe may be non-portable and are not protected by the Go 1 compatibility guidelines.

The "moment" you import package unsafe, you'll lose any guarantees and safety provided by the language spec, and from there on you can't complain for anything. But without using these "special" means, it cannot happen that a string value gets altered.

Read the blog post Strings, bytes, runes and characters in Go for how string is implemented and works in Go.

See related questions:

What is the difference between the string and []byte in Go?

What are the possible consequences of using unsafe conversion from []byte to string in go?


问:
Pattern and Matcher java problem

"SOMETHING, SOMETHING1,
  SOMETHING2,..."

How can I split that string to

SOMETHING SOMETHING1 SOMETHING2

This is what I have at the moment:

```<code>Pattern p = Pattern.compile("\\,+");
Matcher m = p.matcher(nVI);
while(m.find()){
System.out.println(m.group(1));
</code>```

However, it is not producing the desired result.

答:
```<code>String s = "SOMETHING, SOMETHING1, SOMETHING2";
String[] stringList = s.split(", ");

for(String str : stringList){
    System.out.println(str);
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Pattern and Matcher java problem

Body:
"SOMETHING, SOMETHING1,
  SOMETHING2,..."

How can I split that string to

SOMETHING SOMETHING1 SOMETHING2

This is what I have at the moment:

Pattern p = Pattern.compile("\\,+");
Matcher m = p.matcher(nVI);
while(m.find()){
System.out.println(m.group(1));

However, it is not producing the desired result.


问:
Connecting to postgres on command line works, but not with PDO
I have a working login on the command line to my Postgres server:

```<code>psql -h127.0.0.1 -Upostgres --password -dDATABASE
</code>```

but, when I try to use it through PDO, it doesn't work:

```<code>new PDO("pgsql:dbname=DATABASE;host=127.0.0.1;port=5432", "postgres", "PASSWORD");
</code>```

and I get this message:

SQLSTATE[08006] [7] could not connect to server: Permission denied\n\tIs the server running on host "127.0.0.1" and accepting\n\tTCP/IP connections on port 5432?

答:
The username and password parameters in the PDO constructor are a slightly odd design mostly used for MySQL. For Postgres, and most other drivers, you should include those parameters in the DSN, as shown in the examples in the manual:</p>

```<code>new PDO("pgsql:dbname=DATABASE;host=127.0.0.1;port=5432;user=postgres;password=PASSWORD");
</code>```

Body:
I have a working login on the command line to my Postgres server:

psql -h127.0.0.1 -Upostgres --password -dDATABASE

but, when I try to use it through PDO, it doesn't work:

new PDO("pgsql:dbname=DATABASE;host=127.0.0.1;port=5432", "postgres", "PASSWORD");

and I get this message:

SQLSTATE[08006] [7] could not connect to server: Permission denied\n\tIs the server running on host "127.0.0.1" and accepting\n\tTCP/IP connections on port 5432?

Body:
The username and password parameters in the PDO constructor are a slightly odd design mostly used for MySQL. For Postgres, and most other drivers, you should include those parameters in the DSN, as shown in the examples in the manual:

new PDO("pgsql:dbname=DATABASE;host=127.0.0.1;port=5432;user=postgres;password=PASSWORD");


问:
Convolutional Neural Network Training
I have a question regarding convolutional neural network (CNN) training.

I have managed to train a network using tensorflow that takes an input image (1600 pixels) and output one of three classes that matches it.

Testing the network with variations of the trained classes is giving good results. However; when I give it a different -fourth- image (does not contain any of the trained 3 image), it always returns a random match to one of the classes.

My question is, how can I train a network to classify that the image does not belong to either of the three trained images? A similar example, if i trained a network against the mnist database and then a gave it the character "A" or "B". Is there a way to discriminate that the input does not belong to either of the classes?

Thank you

答:
Your model will always make predictions like your labels, so for example if you train your model with MNIST data, when you will make predictions, prediction will always be 0-9 just like MNIST labels.

What you can do is train a different model first with 2 classes in which you will predict if an image belongs to data set A or B. E.x. for MNIST data you label all data as 1 and add data from other sources that are different (not 0-9) and label them as 0. Then train a model to find if image belongs to MNIST or not.

Title: Convolutional Neural Network Training


问:
Copy User Control from one project to another within same solution
Occasionally, a C# project will have a user control in it that belongs to another C# project and I will have to move it over.  Attempting to simply copy + paste that user control  over results in namespace errors. Let's say project 1 has a namespace of namespace General.Category1.Controls and project 2 has a namespace of namespace General.Category2.Controls.

The steps I initially took were:

1) Copy + paste control (which includes .cs, designer.cs and .resx files) from project 1 to project 2

2) Change namespace to project 2's namespace General.Category2.Controls

At this point upon building, I received additional errors from the forms on which this control is used before the copy + paste that states 'The type of namespace name 'UserControl1' does not exist in namespace 'General.Category1.Controls' (are you missing an assembly reference?).  It turns out that the designer.cs form files did not update to the correct namespace after the copy + paste.

So then I add to add an additional step:

3) Change declarations to match new namespace of General.Category2.controls aka private General.Category2.Controls UserControl userControl1;

I'm confused why the designer.cs files wouldn't have updated that since it's not usually advised to edit designer.cs files.  But then again, maybe it's ok to modify them as long as you don't touch the InitializeComponent() method as it states in the actual file itself.

In conclusion, why do all of the designer.cs not update automatically? Is the actual answer to know where this control is used and update the declarations myself as I have done?

[EDIT]: The first 2 steps are for the control itself (it's .cs and .designer.cs files). The 3rd step is for associated with any forms in which the control was placed on before copying it over because it is still using the old namespace, so all of the form .designer.cs files must be changed as well.

答:
Been there ! I do not use copy-paste for this.
In VS-2017 a UserControl1 can be copied to another project, as follows:

In Windows: copy UserControl1.cs, .designer.cs and .resx into your new project
directory

In VS: right click your project in Solution Explorer, set it as Startup
project

Right click new project in Solution Explorer, and choose Add Existing Item

Now, select only UserControl1.cs file in the file box

Wait, Solution Explorer will register the other files, change the symbol

In VS, open UserControl1.designer.cs .. change namespace to new project namespace

In VS, open UserControl1.cs, change namespace to new project namespace

After this step, rebuild your new project. Go to the form design and open Toolbox. Toolbox will show your UserControl.

Note if you move your control into a new Framework or Core class library, take into account, that WinForms is not referenced yet ! Make sure you add a reference to System.Windows.Forms before adding existing items using my tips above.

ContentLicense: CC BY-SA 4.0


问:
Data format and database choices Spark/hadoop
I am working on structured data (one value per field, the same fields for each row) that I have to put in a NoSql environment with Spark (as analysing tool) and Hadoop. Though, I am wondering what format to use. i was thinking about json or csv but I'm not sure. What do you think and why? I don't have enough experience in this field to properly decide.

2nd question : I have to analyse these data (stored in an HDFS). So, as far as I know I have two possibilities to query them (before the analysis):

direct reading and filtering. i mean that it can be done with Spark, for exemple:

```<code>data = sqlCtxt.read.json(path_data)
</code>```

Use Hbase/Hive to properly make a query and then process the data.

So, I don't know what is the standard way of doing all this and above all, what will be the fastest.
Thank you by advance!

答:
Use Parquet. I'm not sure about CSV but definitely don't use JSON. My personal experience using JSON with spark was extremely, extremely slow to read from storage, after switching to Parquet my read times were much faster (e.g. some small files took minutes to load in compressed JSON, now they take less than a second to load in compressed Parquet).

On top of improving read speeds, compressed parquet can be partitioned by spark when reading, whereas compressed JSON cannot. What this means is that Parquet can be loaded onto multiple cluster workers, whereas JSON will just be read onto a single node with 1 partition. This isn't a good idea if your files are large and you'll get Out Of Memory Exceptions. It also won't parallelise your computations, so you'll be executing on one node. This isn't the 'Sparky' way of doing things.

Final point: you can use SparkSQL to execute queries on stored parquet files, without having to read them into dataframes first. Very handy.

Hope this helps :)

Body:
I am working on structured data (one value per field, the same fields for each row) that I have to put in a NoSql environment with Spark (as analysing tool) and Hadoop. Though, I am wondering what format to use. i was thinking about json or csv but I'm not sure. What do you think and why? I don't have enough experience in this field to properly decide.

2nd question : I have to analyse these data (stored in an HDFS). So, as far as I know I have two possibilities to query them (before the analysis):

direct reading and filtering. i mean that it can be done with Spark, for exemple:

data = sqlCtxt.read.json(path_data)

Use Hbase/Hive to properly make a query and then process the data.

So, I don't know what is the standard way of doing all this and above all, what will be the fastest.
Thank you by advance!


问:
Make h1 decide the div width
I'm trying to set the div width to be decided by h1. So the header can be as wide as it wants to be, while the paragraph will only be as wide as the header.

```<code><div>
  <h1></h1>
  <p></p>
</div>
</code>```

I've heard that this is impossible in plain html/css. Is this true? If so, what would a solution look like?

答:
I typically have used a width:0; min-width:100%; combo on an internal wrapper to achieve this.  You also need to collapse the width of the div by either floating it or setting it to display:inline-block;.  It's important to keep the h1 outside of the wrapper so that it can force the width of the collapsed width div.

div {
  float: left;
  clear: left;
  margin-bottom: 1em;
}

p {
  width: 0;
  min-width: 100%;
}

h1, p {margin: 0;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <h1>This is a test</h1>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris</p>
</div>

<div>
  <h1>This is a test with a very long title</h1>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris</p>
</div>

<div>
  <h1>Short</h1>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris</p>
</div>

<div>
  <h1>This is a test with a title that is absurdly long with the hope that it will wrap in the final result.</h1>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris</p>
</div></code>```

Title: Make h1 decide the div width

Body:
I'm trying to set the div width to be decided by h1. So the header can be as wide as it wants to be, while the paragraph will only be as wide as the header.

I've heard that this is impossible in plain html/css. Is this true? If so, what would a solution look like?

Body:
I typically have used a width:0; min-width:100%; combo on an internal wrapper to achieve this.  You also need to collapse the width of the div by either floating it or setting it to display:inline-block;.  It's important to keep the h1 outside of the wrapper so that it can force the width of the collapsed width div.

div {
  float: left;
  clear: left;
  margin-bottom: 1em;
}

p {
  width: 0;
  min-width: 100%;
}

h1, p {margin: 0;}

<div>
  <h1>This is a test</h1>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris</p>
</div>

<div>
  <h1>This is a test with a very long title</h1>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris</p>
</div>

<div>
  <h1>Short</h1>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris</p>
</div>

<div>
  <h1>This is a test with a title that is absurdly long with the hope that it will wrap in the final result.</h1>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris</p>
</div>


问:
does @property update changed elements in an attribute or calculates it again?
I was wondering if using the @property  in python to update an attribute overwrites it or simply updates it? As the speed is very different in the 2 cases.
And in case it gets overwritten, what alternative can I use? Example:

```<code>class sudoku:
def __init__(self,puzzle):
    self.grid={(i,j):puzzle[i][j] for i in range(9) for j in range(9)}
    self.elements
    self.forbidden=set()

@property
def elements(self):
    self.rows=[[self.grid[(i,j)] for j in range(9)] for i in range(9)]
    self.columns=[[self.grid[(i,j)] for i in range(9)] for j in range(9)]
    self.squares={(i,j): [self.grid[(3*i+k,3*j+l)] for k in range(3) for l in range(3)] for i in range(3) for j in range(3)  }
    self.stack=[self.grid]
    self.empty={k for k in self.grid.keys() if self.grid[k]==0}
</code>```

Basically, I work with the grid method, and whenever I need to update the other attributes I call elements. I prefer to call it manually tho. The question, however, is that if I change self.grid[(i,j)], does python calculate each attribute from scratch because self.grid was changed or does it only change the i-th row, j-th column etc?

Thank you

edit: added example code

答:
As is, your question is totally unclear - but anyway, since you don't seem to understand what a property is and how it works...

```<code>class Obj(object):
    def __init__(self, x, y):
        self.x = x

    @property
    def x(self):
        return self._x / 2

    @x.setter
    def x(self, value):
        self._x = value * 2
</code>```

Here we have a class with a get/set ("binding") property x, backed by a protected attribute _x.

The "@property" syntax here is mainly syntactic sugar, you could actually write this code as

```<code>class Obj(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def get_x(self):
        return self._x / 2

    def set_x(self, value):
        self._x = value * 2

    x = property(fget=get_x, fset=set_x)
</code>```

The only difference with the previous version being that the get_x and set_x functions remain available as methods. Then if we have an obj instance:

```<code>obj = Obj(2, 4)
</code>```

Then

```<code>x = obj.x
</code>```

is just a shortcut for

```<code>x = obj.get_x()
</code>```

and

```<code>obj.x = 42
</code>```

is just a shortcut for

```<code>obj.set_x(42)
</code>```

How this "shortcut" works is fully documented here, with a whole chapter dedicated to the property type.

As you can see there's nothing magical here, and once you get (no pun intended) the descriptor protocol and how the property class uses it, you can answer the question by yourself.

Note that properties will ALWAYS add some overhead (vs plain attributes or direct method call) since you have more indirections levels and method calls invoked, so it's best to only use them when it really makes sense.

EDIT: now you posted your code, I confirm that you don't understand Python's "properties" - not only the technical side of it but even the basic concept of a "computed attribute".

The point of computed attributes in general (the builtin property type being just one generic implementation of) is to have the interface of a plain attribute (something you can get the value if with value = obj.attrname and eventually set the value of with obj.attrname = somevalue) but actually invoking a getter (and eventually a setter) behind the hood.

Your elements "property" while technically implemented as a read-only property, is really a method that initializes half a dozen attributes of your class, doesn't return anything (well it implicitely returns None) and which return value is actually never used (of course). This is definitly not what computed attributes are for. This should NOT be a property, it should be a plain function (with some explicit name such as "setup_elements" or whatever makes sense here).

```<code># nb1 : classes names should be CamelCased
# nb2 : in Python 2x, you want to inherit from 'object'

class Sudoku(object):
    def __init__(self,puzzle):
        self.grid={(i,j):puzzle[i][j] for i in range(9) for j in range(9)}
        self.setup_elements()
        self.forbidden=set()

    def setup_elements(self):
        self.rows=[[self.grid[(i,j)] for j in range(9)] for i in range(9)]
        self.columns=[[self.grid[(i,j)] for i in range(9)] for j in range(9)]
        self.squares={(i,j): [self.grid[(3*i+k,3*j+l)] for k in range(3) for l in range(3)] for i in range(3) for j in range(3)  }
        self.stack=[self.grid]
        self.empty={k for k, v in self.grid.items() if v==0}
</code>```

Now to answer your question:

if I change self.grid[(i,j)], does python calculate each attribute from scratch because self.grid was changed

self.grid is a plain attribute, so just rebinding self.grid[(i, j)] doesn't make "python" calculate anything else, of course. None of your object's other attributes will be impacted. Actually Python (the interpreter) has no mind-reading ability and will only do exactly what you asked for, nothing less, nothing more, period.

or does it only change the i-th row, j-th column

This :

```<code>obj = Sudoku(some_puzzle)
obj.grid[(1, 1)] = "WTF did you expect ?"
</code>```

will NOT (I repeat: "NOT") do anything else than assigning the literal string "WTF did you expect ?" to obj.grid[(1, 1)]. None of the other attributes will be updated in any way.

Now if your question was: "if I change something to self.grid and call self.setup_elements() after, will Python recompute all attributes or only update self.rows[xxx] and  self.columns[yyy]", then the answer is plain simple: Python will do exactly what you asked for: it will execute self.setup_elements(), line after line, statement after statement. Plain and simple. No magic here, and the only thing you'll get from making it a property instead of a plain method is that you won't have to type the () after to invoke the method.

So if what you expected from making this elements() method a property was to have some impossible magic happening behind the scene to detect that you actually only wanted to recompute impacted elements, then bad news, this is not going to happen, and you will have to explicitely tell the interpreter how to do so. Computed attributes might be part of the solution here, but not by any magic - you will have to write all the code needed to intercept assignments to any of those attributes and recompute what needs to be recomputed.

Beware, since all those attributes are mutable containers, just wrapping each of them into properties won't be enough - consider this:

```<code>class Foo(object):
    def __init__(self):
        self._bar = {"a":1, "b": 2}
    @property
    def bar(self):
        print("getting self._bar")
        return self._bar
    @bar.setter
    def bar(self, value):
        print("setting self._bar to {}".format(value))
        self._bar = value

>>> f = Foo()
>>> f.bar
getting self._bar
{'a': 1, 'b': 2}
>>> f.bar['z'] = "WTF ?"
getting self._bar
>>> f.bar
getting self._bar
{'a': 1, 'b': 2, 'z': 'WTF ?'}
>>> bar = f.bar
getting self._bar
>>> bar
{'a': 1, 'b': 2, 'z': 'WTF ?'}
>>> bar["a"] = 99
>>> f.bar
getting self._bar
{'a': 99, 'b': 2, 'z': 'WTF ?'}
</code>```

As you can see, we could mutate self._bar without the bar.setter function ever being invoked - because f.bar["x"] = "y" is actually NOT assigning to f.bar (which would need f.bar = "something else") but _getting_ thef._bardict thru theFoo.bargetter, then invokingsetitem()` on this dict.

So if you want to intercept something like f.bar["x"] = "y", you will also have to write some dict-like object that will intercept all mutators access on the dict itself ( __setitem__, but also __delitem__ etc) and notify f of those changes, and change your property so that it returns an instance of this dict-like objects instead.

Body:
I was wondering if using the @property  in python to update an attribute overwrites it or simply updates it? As the speed is very different in the 2 cases.
And in case it gets overwritten, what alternative can I use? Example:

class sudoku:
def __init__(self,puzzle):
    self.grid={(i,j):puzzle[i][j] for i in range(9) for j in range(9)}
    self.elements
    self.forbidden=set()

@property
def elements(self):
    self.rows=[[self.grid[(i,j)] for j in range(9)] for i in range(9)]
    self.columns=[[self.grid[(i,j)] for i in range(9)] for j in range(9)]
    self.squares={(i,j): [self.grid[(3*i+k,3*j+l)] for k in range(3) for l in range(3)] for i in range(3) for j in range(3)  }
    self.stack=[self.grid]
    self.empty={k for k in self.grid.keys() if self.grid[k]==0}

Basically, I work with the grid method, and whenever I need to update the other attributes I call elements. I prefer to call it manually tho. The question, however, is that if I change self.grid[(i,j)], does python calculate each attribute from scratch because self.grid was changed or does it only change the i-th row, j-th column etc?

Thank you

edit: added example code

Body:
As is, your question is totally unclear - but anyway, since you don't seem to understand what a property is and how it works...

class Obj(object):
    def __init__(self, x, y):
        self.x = x

    @property
    def x(self):
        return self._x / 2

    @x.setter
    def x(self, value):
        self._x = value * 2

Here we have a class with a get/set ("binding") property x, backed by a protected attribute _x.

The "@property" syntax here is mainly syntactic sugar, you could actually write this code as

class Obj(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def get_x(self):
        return self._x / 2

    def set_x(self, value):
        self._x = value * 2

    x = property(fget=get_x, fset=set_x)

The only difference with the previous version being that the get_x and set_x functions remain available as methods. Then if we have an obj instance:

obj = Obj(2, 4)

Then

x = obj.x

is just a shortcut for

x = obj.get_x()

and

obj.x = 42

is just a shortcut for

obj.set_x(42)

How this "shortcut" works is fully documented here, with a whole chapter dedicated to the property type.

As you can see there's nothing magical here, and once you get (no pun intended) the descriptor protocol and how the property class uses it, you can answer the question by yourself.

Note that properties will ALWAYS add some overhead (vs plain attributes or direct method call) since you have more indirections levels and method calls invoked, so it's best to only use them when it really makes sense.

EDIT: now you posted your code, I confirm that you don't understand Python's "properties" - not only the technical side of it but even the basic concept of a "computed attribute".

The point of computed attributes in general (the builtin property type being just one generic implementation of) is to have the interface of a plain attribute (something you can get the value if with value = obj.attrname and eventually set the value of with obj.attrname = somevalue) but actually invoking a getter (and eventually a setter) behind the hood.

Your elements "property" while technically implemented as a read-only property, is really a method that initializes half a dozen attributes of your class, doesn't return anything (well it implicitely returns None) and which return value is actually never used (of course). This is definitly not what computed attributes are for. This should NOT be a property, it should be a plain function (with some explicit name such as "setup_elements" or whatever makes sense here).

# nb1 : classes names should be CamelCased
# nb2 : in Python 2x, you want to inherit from 'object'

class Sudoku(object):
    def __init__(self,puzzle):
        self.grid={(i,j):puzzle[i][j] for i in range(9) for j in range(9)}
        self.setup_elements()
        self.forbidden=set()

    def setup_elements(self):
        self.rows=[[self.grid[(i,j)] for j in range(9)] for i in range(9)]
        self.columns=[[self.grid[(i,j)] for i in range(9)] for j in range(9)]
        self.squares={(i,j): [self.grid[(3*i+k,3*j+l)] for k in range(3) for l in range(3)] for i in range(3) for j in range(3)  }
        self.stack=[self.grid]
        self.empty={k for k, v in self.grid.items() if v==0}

Now to answer your question:

if I change self.grid[(i,j)], does python calculate each attribute from scratch because self.grid was changed

self.grid is a plain attribute, so just rebinding self.grid[(i, j)] doesn't make "python" calculate anything else, of course. None of your object's other attributes will be impacted. Actually Python (the interpreter) has no mind-reading ability and will only do exactly what you asked for, nothing less, nothing more, period.

or does it only change the i-th row, j-th column

This :

obj = Sudoku(some_puzzle)
obj.grid[(1, 1)] = "WTF did you expect ?"

will NOT (I repeat: "NOT") do anything else than assigning the literal string "WTF did you expect ?" to obj.grid[(1, 1)]. None of the other attributes will be updated in any way.

Now if your question was: "if I change something to self.grid and call self.setup_elements() after, will Python recompute all attributes or only update self.rows[xxx] and  self.columns[yyy]", then the answer is plain simple: Python will do exactly what you asked for: it will execute self.setup_elements(), line after line, statement after statement. Plain and simple. No magic here, and the only thing you'll get from making it a property instead of a plain method is that you won't have to type the () after to invoke the method.

So if what you expected from making this elements() method a property was to have some impossible magic happening behind the scene to detect that you actually only wanted to recompute impacted elements, then bad news, this is not going to happen, and you will have to explicitely tell the interpreter how to do so. Computed attributes might be part of the solution here, but not by any magic - you will have to write all the code needed to intercept assignments to any of those attributes and recompute what needs to be recomputed.

Beware, since all those attributes are mutable containers, just wrapping each of them into properties won't be enough - consider this:

class Foo(object):
    def __init__(self):
        self._bar = {"a":1, "b": 2}
    @property
    def bar(self):
        print("getting self._bar")
        return self._bar
    @bar.setter
    def bar(self, value):
        print("setting self._bar to {}".format(value))
        self._bar = value

>>> f = Foo()
>>> f.bar
getting self._bar
{'a': 1, 'b': 2}
>>> f.bar['z'] = "WTF ?"
getting self._bar
>>> f.bar
getting self._bar
{'a': 1, 'b': 2, 'z': 'WTF ?'}
>>> bar = f.bar
getting self._bar
>>> bar
{'a': 1, 'b': 2, 'z': 'WTF ?'}
>>> bar["a"] = 99
>>> f.bar
getting self._bar
{'a': 99, 'b': 2, 'z': 'WTF ?'}

As you can see, we could mutate self._bar without the bar.setter function ever being invoked - because f.bar["x"] = "y" is actually NOT assigning to f.bar (which would need f.bar = "something else") but _getting_ thef._bardict thru theFoo.bargetter, then invokingsetitem()` on this dict.

So if you want to intercept something like f.bar["x"] = "y", you will also have to write some dict-like object that will intercept all mutators access on the dict itself ( __setitem__, but also __delitem__ etc) and notify f of those changes, and change your property so that it returns an instance of this dict-like objects instead.


问:
Change boolean var onClick based on parameter
I am creating a page that sets a variable to true or false based on a button click. This is doable if I create a function per variable/button, but since there will be quite a few variables in the end, I would like to do this in a single function, if possible:

```<code><div>
  <button type="button" id="colorbutton" class="button red" onClick="manualSelect('Color')">Colors</button>
  <button type="button" id="animalbutton" class="button red" onClick="manualSelect('Animal')">Animals</button>
</div>
</code>```

$manualColor = false;
$manualAnimal = false;

function manualSelect(item) {
  if ($('manual' + item) == false) {
    $('manual' + item) = true;
  } else {
    $('manual' + item) = false;
  }
}
```

I know this is stupid, it's just to set the example.

Here's the full script:
https://jsfiddle.net/8ers54s9/5/

答:
You can access properties of an object by text, eg:

```<code>flags["animal"] = true;
</code>```

which you can also access as:

```<code>flags.animal = true;
</code>```

so put all the "variables" that you want to toggle onto another variable, eg:

var flags = {};

function toggleFlag(item) {
  flags[item] = !flags[item];

  console.log("color: " + flags.color)
  console.log("animal: " + flags.animal)
  console.log(flags)
}

toggleFlag("test")

$(".button").click(function() {
  toggleFlag($(this).data("flag"))
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <button type="button" class="button" data-flag='color'>Colors</button>
  <button type="button" class="button" data-flag='animal'>Animals</button>
</div></code>```

Body:
I am creating a page that sets a variable to true or false based on a button click. This is doable if I create a function per variable/button, but since there will be quite a few variables in the end, I would like to do this in a single function, if possible:

  <button type="button" id="colorbutton" class="button red" onClick="manualSelect('Color')">Colors</button>
  <button type="button" id="animalbutton" class="button red" onClick="manualSelect('Animal')">Animals</button>

$manualColor = false;
$manualAnimal = false;

function manualSelect(item) {
  if ($('manual' + item) == false) {
    $('manual' + item) = true;
  } else {
    $('manual' + item) = false;
  }
}

I know this is stupid, it's just to set the example.

Here's the full script:
https://jsfiddle.net/8ers54s9/5/

Body:
You can access properties of an object by text, eg:

flags["animal"] = true;

which you can also access as:

flags.animal = true;

so put all the "variables" that you want to toggle onto another variable, eg:

var flags = {};

function toggleFlag(item) {
  flags[item] = !flags[item];

  console.log("color: " + flags.color)
  console.log("animal: " + flags.animal)
  console.log(flags)
}

toggleFlag("test")

$(".button").click(function() {
  toggleFlag($(this).data("flag"))
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <button type="button" class="button" data-flag='color'>Colors</button>
  <button type="button" class="button" data-flag='animal'>Animals</button>
</div>


问:
Ansible bitbucket clone provisioning ssh error
In summary, When provisioning my vagrant box using Ansible, I get thrown a mysterious error when trying to clone my bitbucket private repo using ssh.
The error states that the "Host key verification failed".

Yet if I vagrant ssh and then run the 'git clone' command, the private repo is successfully cloned. This indicates that the ssh forward agent is indeed working and the vagrant box can access my private key associated with the bitbucket repo.

I have been struggling for two days on this issue and am loosing my mind!
Please, somebody help me!!!

Vagrantfile:

```<code>Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/xenial64"
  config.vm.network "private_network", ip: "192.168.33.10"
  config.ssh.forward_agent = true

  # Only contains ansible dependencies
  config.vm.provision "shell",
    inline: "sudo apt-get install python-minimal -y"

  # Use ansible for all provisioning:
  config.vm.provision "ansible" do |ansible|
    ansible.playbook = "provisioning/playbook.yml"
  end

end
</code>```

My playbook.yml is as follows:

```<code>---

- hosts: all
  become: true

  tasks:
    - name: create /var/www/ directory
      file: dest=/var/www/ state=directory owner=www-data group=www-data mode=0755

    - name: Add the user 'ubuntu' to group 'www-data'
      user:
        name: ubuntu
        shell: /bin/bash
        groups: www-data
        append: yes

    - name: Clone bitbucket repo
      git:
        repo: git@bitbucket.org:gustavmahler/example.com.git
        dest: /var/www/poo
        version: master
        accept_hostkey: yes
</code>```

Error Message:

vagrant provision

TASK [common : Clone bitbucket repo] *******************************************

fatal: [default]: FAILED! => {"changed": false, "cmd": "/usr/bin/git clone --origin origin '' /var/www/poo", "failed": true, "msg": "Cloning into '/var/www/poo'...\nWarning: Permanently added the RSA host key for IP address '104.192.143.3' to the list of known hosts.\r\nPermission denied (publickey).\r\nfatal: Could not read from remote repository.\n\nPlease make sure you have the correct access rights\nand the repository exists.", "rc": 128, "stderr": "Cloning into '/var/www/poo'...\nWarning: Permanently added the RSA host key for IP address '104.192.143.3' to the list of known hosts.\r\nPermission denied (publickey).\r\nfatal: Could not read from remote repository.\n\nPlease make sure you have the correct access rights\nand the repository exists.\n", "stderr_lines": ["Cloning into '/var/www/poo'...", "Warning: Permanently added the RSA host key for IP address '104.192.143.3' to the list of known hosts.", "Permission denied (publickey).", "fatal: Could not read from remote repository.", "", "Please make sure you have the correct access rights", "and the repository exists."], "stdout": "", "stdout_lines": []}

Additional Info:

ssh-add -l on my machine does contain the associated bitbucket repo key.

ssh-add -l inside the vagrant box does also contain the associated bitbucket repo key (through ssh-forwarding).

Yet cloning works if done manually inside the vagrant box ?:

```<code>vagrant ssh
git clone git@bitbucket.org:myusername/myprivaterepo.com.git
Then type "yes" to allow the RSA fingerprint to be added to ~/.ssh/known_hosts (as its first connection with bitbucket)
</code>```

Possible solution?

I have seen in the Ansible documentation that there is a key_file: option. How would I reference the private key which is located outside the vagrant box and is passed in using ssh forwarding?

I do have multiple ssh keys for different entities inside my ~/.ssh/ Perhaps the git clone command when run by Ansible provisioning isn't selecting the correct key?

Any help is greatly appreciated and thanks for reading my nightmare.

答:
Since you run the whole playbook with become: true, SSH key-forwarding (as well as troubleshooting) becomes irrelevant, because the user connecting to BitBucket from your play is root.

Run the task connecting to BitBucket as ubuntu user:

either specifying become: false in the Clone bitbucket repo task),

or removing become: true From the play and adding it only to tasks that require elevated permissions.

Body:
In summary, When provisioning my vagrant box using Ansible, I get thrown a mysterious error when trying to clone my bitbucket private repo using ssh.
The error states that the "Host key verification failed".

Yet if I vagrant ssh and then run the 'git clone' command, the private repo is successfully cloned. This indicates that the ssh forward agent is indeed working and the vagrant box can access my private key associated with the bitbucket repo.

I have been struggling for two days on this issue and am loosing my mind!
Please, somebody help me!!!

Vagrantfile:

Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/xenial64"
  config.vm.network "private_network", ip: "192.168.33.10"
  config.ssh.forward_agent = true

  # Only contains ansible dependencies
  config.vm.provision "shell",
    inline: "sudo apt-get install python-minimal -y"

  # Use ansible for all provisioning:
  config.vm.provision "ansible" do |ansible|
    ansible.playbook = "provisioning/playbook.yml"
  end

end

My playbook.yml is as follows:

---

- hosts: all
  become: true

  tasks:
    - name: create /var/www/ directory
      file: dest=/var/www/ state=directory owner=www-data group=www-data mode=0755

    - name: Add the user 'ubuntu' to group 'www-data'
      user:
        name: ubuntu
        shell: /bin/bash
        groups: www-data
        append: yes

    - name: Clone bitbucket repo
      git:
        repo: git@bitbucket.org:gustavmahler/example.com.git
        dest: /var/www/poo
        version: master
        accept_hostkey: yes

Error Message:

vagrant provision

TASK [common : Clone bitbucket repo] *******************************************

fatal: [default]: FAILED! => {"changed": false, "cmd": "/usr/bin/git clone --origin origin '' /var/www/poo", "failed": true, "msg": "Cloning into '/var/www/poo'...\nWarning: Permanently added the RSA host key for IP address '104.192.143.3' to the list of known hosts.\r\nPermission denied (publickey).\r\nfatal: Could not read from remote repository.\n\nPlease make sure you have the correct access rights\nand the repository exists.", "rc": 128, "stderr": "Cloning into '/var/www/poo'...\nWarning: Permanently added the RSA host key for IP address '104.192.143.3' to the list of known hosts.\r\nPermission denied (publickey).\r\nfatal: Could not read from remote repository.\n\nPlease make sure you have the correct access rights\nand the repository exists.\n", "stderr_lines": ["Cloning into '/var/www/poo'...", "Warning: Permanently added the RSA host key for IP address '104.192.143.3' to the list of known hosts.", "Permission denied (publickey).", "fatal: Could not read from remote repository.", "", "Please make sure you have the correct access rights", "and the repository exists."], "stdout": "", "stdout_lines": []}

Additional Info:

ssh-add -l on my machine does contain the associated bitbucket repo key.

ssh-add -l inside the vagrant box does also contain the associated bitbucket repo key (through ssh-forwarding).

Yet cloning works if done manually inside the vagrant box ?:

vagrant ssh
git clone git@bitbucket.org:myusername/myprivaterepo.com.git
Then type "yes" to allow the RSA fingerprint to be added to ~/.ssh/known_hosts (as its first connection with bitbucket)

Possible solution?

I have seen in the Ansible documentation that there is a key_file: option. How would I reference the private key which is located outside the vagrant box and is passed in using ssh forwarding?

I do have multiple ssh keys for different entities inside my ~/.ssh/ Perhaps the git clone command when run by Ansible provisioning isn't selecting the correct key?

Any help is greatly appreciated and thanks for reading my nightmare.


问:
Pig Latin Sentence Converter
I am trying a program that translates your sentence into pig latin. Here's the code I have so far:

```<code>public class PigLatin {
    public static void main(String[] args) {
        //Enter text in the quotes of System.ot.println(covertToLatin(" "));
        System.out.println(covertToLatin("Type your sentence here."));
    }

    private static String covertToLatin(String string) {
        String end = "";
        String delims = "\\s+";
        String[] words = string.split(delims);
        for (int i = 0; i < words.length; i++) {
            if(isVowel(words[i].toLowerCase().charAt(0))) {
                end += words[i] + "ay";
            } else {
                end += words[i].substring(1) + words[i].substring(0, 1) + "ay";
            }
        }
        return end;
    }

    private static boolean isVowel(char c) {
        if (c == 'a')
            return true;
        if (c == 'e')
            return true;
        if (c == 'i')
            return true;
        if (c == 'o')
            return true;
        if (c == 'u')
            return true;
        return false;
    }

}
</code>```

It translates "Type your sentence here." to "ypeTayouryayentencesayere.hay" I am stumped as to finding a way to translate my whole sentence. can you please help me translate a whole sentence into pig latin? Also, it would help if you could find a way to make the sentence convert in all caps too.

答: for upper case, use String.toUpperCase() function

Title: Pig Latin Sentence Converter

Body:
I am trying a program that translates your sentence into pig latin. Here's the code I have so far:

public class PigLatin {
    public static void main(String[] args) {
        //Enter text in the quotes of System.ot.println(covertToLatin(" "));
        System.out.println(covertToLatin("Type your sentence here."));
    }

    private static String covertToLatin(String string) {
        String end = "";
        String delims = "\\s+";
        String[] words = string.split(delims);
        for (int i = 0; i < words.length; i++) {
            if(isVowel(words[i].toLowerCase().charAt(0))) {
                end += words[i] + "ay";
            } else {
                end += words[i].substring(1) + words[i].substring(0, 1) + "ay";
            }
        }
        return end;
    }

    private static boolean isVowel(char c) {
        if (c == 'a')
            return true;
        if (c == 'e')
            return true;
        if (c == 'i')
            return true;
        if (c == 'o')
            return true;
        if (c == 'u')
            return true;
        return false;
    }

}

It translates "Type your sentence here." to "ypeTayouryayentencesayere.hay" I am stumped as to finding a way to translate my whole sentence. can you please help me translate a whole sentence into pig latin? Also, it would help if you could find a way to make the sentence convert in all caps too.


问:
http_client->receive - Internal Server Error in SAP ABAP
I have created one function module which executes the third party web page and get response.

Below is the code

```<code>    FUNCTION zmm_url_http_get_post.
*"*"Local Interface:
*"  IMPORTING
*"     VALUE(P_URL) TYPE  STRING OPTIONAL
*"  EXPORTING
*"     VALUE(P_RESPONSE) TYPE  STRING
*"  TABLES
*"      T_LOG STRUCTURE  VIFE OPTIONAL
*"  EXCEPTIONS
*"      ERROR_MESSAGE
*"----------------------------------------------------------------------
  DATA : lv_value TYPE string.
  DATA : http_client TYPE REF TO if_http_client
  DATA : lv_url TYPE string.
  DATA : return TYPE char2048
  DATA : lv_err_string TYPE string,
         lv_ret_code   TYPE sy-subrc.
* Build Url
  lv_url = p_url.
* Create Client
  CALL METHOD cl_http_client=>create_by_url
    EXPORTING
      url    = lv_url
    IMPORTING
      client = http_client.
* Send
  CALL METHOD http_client->send
    EXCEPTIONS
      http_communication_failure = 1
      http_invalid_state         = 2.
* Receive
  CALL METHOD http_client->receive
    EXCEPTIONS
      http_communication_failure = 1
      http_invalid_state         = 2
      http_processing_failed     = 3.
  IF sy-subrc NE 0.
    http_client->response->get_status(
      IMPORTING
        code   = lv_ret_code
        reason = lv_err_string
           ).
    MESSAGE lv_err_string TYPE 'I'.
    t_log-msgty = 'E'.
    t_log-msgtx = lv_err_string.
    APPEND t_log.
  ENDIF.
* Now we have the response , parse , display
* do what you like
  return = http_client->response->get_cdata( ).
  p_response = return.
  IF t_log-msgty NE 'E'.
    t_log-msgty = 'S'.
    t_log-msgtx = 'Success'.
    APPEND t_log.
  ENDIF.
ENDFUNCTION.
</code>```

i have created Background job to execute this code on daily basis. Background job is executing successfully , but the problem i am facing is some times job status is success some times job status is cancelled , the log which i am getting is Internal Server Error or Job cancelled after system exception ERROR_MESSAGE.

when i execute the same URL in web browser response is coming without any inter server error, do i need to do some configuration is SAP to increase Max execution time?

Anyone help me to solve this.

答:
I would not assume that target server is available/accessible all the time(poor network quality, overloaded server, etc.).

Maybe implement some kind of "retry strategy"(with time interval) to handle such failures(e.g. HTTP 503)?

Body:
I have created one function module which executes the third party web page and get response.

Below is the code

    FUNCTION zmm_url_http_get_post.
*"*"Local Interface:
*"  IMPORTING
*"     VALUE(P_URL) TYPE  STRING OPTIONAL
*"  EXPORTING
*"     VALUE(P_RESPONSE) TYPE  STRING
*"  TABLES
*"      T_LOG STRUCTURE  VIFE OPTIONAL
*"  EXCEPTIONS
*"      ERROR_MESSAGE
*"----------------------------------------------------------------------
  DATA : lv_value TYPE string.
  DATA : http_client TYPE REF TO if_http_client
  DATA : lv_url TYPE string.
  DATA : return TYPE char2048
  DATA : lv_err_string TYPE string,
         lv_ret_code   TYPE sy-subrc.
* Build Url
  lv_url = p_url.
* Create Client
  CALL METHOD cl_http_client=>create_by_url
    EXPORTING
      url    = lv_url
    IMPORTING
      client = http_client.
* Send
  CALL METHOD http_client->send
    EXCEPTIONS
      http_communication_failure = 1
      http_invalid_state         = 2.
* Receive
  CALL METHOD http_client->receive
    EXCEPTIONS
      http_communication_failure = 1
      http_invalid_state         = 2
      http_processing_failed     = 3.
  IF sy-subrc NE 0.
    http_client->response->get_status(
      IMPORTING
        code   = lv_ret_code
        reason = lv_err_string
           ).
    MESSAGE lv_err_string TYPE 'I'.
    t_log-msgty = 'E'.
    t_log-msgtx = lv_err_string.
    APPEND t_log.
  ENDIF.
* Now we have the response , parse , display
* do what you like
  return = http_client->response->get_cdata( ).
  p_response = return.
  IF t_log-msgty NE 'E'.
    t_log-msgty = 'S'.
    t_log-msgtx = 'Success'.
    APPEND t_log.
  ENDIF.
ENDFUNCTION.

i have created Background job to execute this code on daily basis. Background job is executing successfully , but the problem i am facing is some times job status is success some times job status is cancelled , the log which i am getting is Internal Server Error or Job cancelled after system exception ERROR_MESSAGE.

when i execute the same URL in web browser response is coming without any inter server error, do i need to do some configuration is SAP to increase Max execution time?

Anyone help me to solve this.


问:
how do you mock an imported enum with jasmine
I'm writing some jasmine tests for some existing code and can't find a way to mock an imported enum (to keep the test isolated). I'm trying to check the enum label looked up matches the one on the html page where expected.  I'm not interested in the actual looked up value, just that the label is on the page in the right page.

Existing Code

labels.service.ts

```<code>export enum LabelEnum {
  common_Greeting,
  Common_ButtonClose,
  Common_ButtonSave
}

export LabelsService {
    public Get(enumLabelId: string): string {
        return "This would come from external API for content management";
    }
}
</code>```

some.component.ts

```<code>import { Component, OnInit } from "@angular/core";
import { LabelEnum, LabelsService } from "./labels.service";

@Component({
  selector: 'my-app',
  templateUrl: './some.component.html',
  providers: [LabelsService]
})
export class SomeComponent implements OnInit {
  greetingLabel: string;

  constructor(
    public labelsService: LabelsService) { }

  ngOnInit(): void {
    this.greetingLabel = this.labelsService.Get(LabelEnum.Common_Greeting);
  }
}
</code>```

some.component.html

```<code><div id="somePage">
  <div>
    <h1>{{greetingLabel}}</h1>
  </div>
</div>
</code>```

Jasmine Test

some.component.spec.ts

```<code>import { async, ComponentFixture, TestBed } from "@angular/core/testing";
import { DebugElement, Injectable } from '@angular/core';
import { LabelEnum, LabelsService } from "./labels.service";
import { SomeComponent } from "./some.component";

enum LabelEnumMock {
    Common_Greeting
}

class LabelsServiceStub {
    Get(id: string): string {
        return id;
    }
}

describe('SomeComponent', () => {
    let component: SomeComponent;
    let fixture: ComponentFixture<SomeComponent>;
    let de: DebugElement;
    let el: HTMLElement;
    let labelsService;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [SomeComponent],
            providers: [
                { provide: LabelsService, useClass: LabelsServiceStub },
                { provide: LabelEnum, useValue: LabelEnumMock }
            ]
        })
            .compileComponents()
            .then(() => {
                this.fixture = TestBed.createComponent(SomeComponent);
                this.labelsService = this.fixture.debugElement.injector.get(LabelsService);
                this.el = this.fixture.nativeElement;
                this.de = this.fixture.debugElement;
            });
    }));

    afterEach(() => {
        this.fixture = null;
        this.stringsService = null;
        this.el = null;
        this.de = null;
    });

    describe('after initialised', () => {
        it('renders expected labels', () => {
            this.fixture.detectChanges();
            expect(this.el.querySelector('h1').innerText).toBe(LabelEnumMock.Common_Greeting);
        });
    });
});
</code>```

I started to get a plunker of this working unfortunately it doesn't run.

Demo.

答:
An enum doesn't work like this. We can compare an enum to an array with explicit name of key:

```<code>export enum LabelEnum {
  common_Greeting,
  Common_ButtonClose,
  Common_ButtonSave
}
console.log(LabelEnum.common_Greeting) //=> 0 (it's a number not a string)
console.log(LabelEnum.Common_ButtonClose) //=> 1
console.log(LabelEnum.Common_ButtonSave) //=> 2
</code>```

But you can assign value to your enum entries:

```<code>enum Direction {
    Up = "UP",
    Down = "DOWN",
    Left = "LEFT",
    Right = "RIGHT",
}
console.log(Direction.Up) //=> UP
console.log(Direction.Left) //=> LEFT
</code>```

I think your label service is bad typed too, I propose:

```<code>export LabelsService {
    public Get(enumLabelId: LabelEnum): string {
        return enumLabelId;
    }
}
</code>```

Personally, I don't take your way to test the service. I think I just test the return of get like:

```<code>it("Should return the converted value for common greeting label", () => {
   expect(labelsService.get(LabelEnum.common_Greeting)).toEqual(LabelEnum.common_Greeting)
})
</code>```

In this case, it's not useful to mock and stub your code, because it's your own logic and not depend of third-part especially for the enum.

And in the angular component I just display the return of the Get

Body:
I'm writing some jasmine tests for some existing code and can't find a way to mock an imported enum (to keep the test isolated). I'm trying to check the enum label looked up matches the one on the html page where expected.  I'm not interested in the actual looked up value, just that the label is on the page in the right page.

Existing Code

labels.service.ts

export enum LabelEnum {
  common_Greeting,
  Common_ButtonClose,
  Common_ButtonSave
}

export LabelsService {
    public Get(enumLabelId: string): string {
        return "This would come from external API for content management";
    }
}

some.component.ts

import { Component, OnInit } from "@angular/core";
import { LabelEnum, LabelsService } from "./labels.service";

@Component({
  selector: 'my-app',
  templateUrl: './some.component.html',
  providers: [LabelsService]
})
export class SomeComponent implements OnInit {
  greetingLabel: string;

  constructor(
    public labelsService: LabelsService) { }

  ngOnInit(): void {
    this.greetingLabel = this.labelsService.Get(LabelEnum.Common_Greeting);
  }
}

some.component.html

{{greetingLabel}}

Jasmine Test

some.component.spec.ts

import { async, ComponentFixture, TestBed } from "@angular/core/testing";
import { DebugElement, Injectable } from '@angular/core';
import { LabelEnum, LabelsService } from "./labels.service";
import { SomeComponent } from "./some.component";

enum LabelEnumMock {
    Common_Greeting
}

class LabelsServiceStub {
    Get(id: string): string {
        return id;
    }
}

describe('SomeComponent', () => {
    let component: SomeComponent;
    let fixture: ComponentFixture<SomeComponent>;
    let de: DebugElement;
    let el: HTMLElement;
    let labelsService;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [SomeComponent],
            providers: [
                { provide: LabelsService, useClass: LabelsServiceStub },
                { provide: LabelEnum, useValue: LabelEnumMock }
            ]
        })
            .compileComponents()
            .then(() => {
                this.fixture = TestBed.createComponent(SomeComponent);
                this.labelsService = this.fixture.debugElement.injector.get(LabelsService);
                this.el = this.fixture.nativeElement;
                this.de = this.fixture.debugElement;
            });
    }));

    afterEach(() => {
        this.fixture = null;
        this.stringsService = null;
        this.el = null;
        this.de = null;
    });

    describe('after initialised', () => {
        it('renders expected labels', () => {
            this.fixture.detectChanges();
            expect(this.el.querySelector('h1').innerText).toBe(LabelEnumMock.Common_Greeting);
        });
    });
});

I started to get a plunker of this working unfortunately it doesn't run.

Demo.

Body:
An enum doesn't work like this. We can compare an enum to an array with explicit name of key:

export enum LabelEnum {
  common_Greeting,
  Common_ButtonClose,
  Common_ButtonSave
}
console.log(LabelEnum.common_Greeting) //=> 0 (it's a number not a string)
console.log(LabelEnum.Common_ButtonClose) //=> 1
console.log(LabelEnum.Common_ButtonSave) //=> 2

But you can assign value to your enum entries:

enum Direction {
    Up = "UP",
    Down = "DOWN",
    Left = "LEFT",
    Right = "RIGHT",
}
console.log(Direction.Up) //=> UP
console.log(Direction.Left) //=> LEFT

I think your label service is bad typed too, I propose:

export LabelsService {
    public Get(enumLabelId: LabelEnum): string {
        return enumLabelId;
    }
}

Personally, I don't take your way to test the service. I think I just test the return of get like:

it("Should return the converted value for common greeting label", () => {
   expect(labelsService.get(LabelEnum.common_Greeting)).toEqual(LabelEnum.common_Greeting)
})

In this case, it's not useful to mock and stub your code, because it's your own logic and not depend of third-part especially for the enum.

And in the angular component I just display the return of the Get


问:
How do I compile more than one .asm file with fasm into one output?
I want to compile multiple assembly files in fasm.
I have some instructions in the one file and other instructions in the other file. How do I link these files to a binary output ?

And may I use extern in this case ? Or is this an illegal command ?

答:
I want to compile multiple assembly files in fasm.

So you have multiple .ASM source files.

Select one of your source files as the main source file.

Insert in it an include preprocessor directive for every additional source file that you want in your single binary output file.

Assemble. No linker required, FASM does it all.

Example with 3 source files

```<code>; Main source is 'source1.asm'
include 'source2.asm'
include 'source3.asm'
...
</code>```

Body:
I want to compile multiple assembly files in fasm.

So you have multiple .ASM source files.

Select one of your source files as the main source file.

Insert in it an include preprocessor directive for every additional source file that you want in your single binary output file.

Assemble. No linker required, FASM does it all.

Example with 3 source files

; Main source is 'source1.asm'
include 'source2.asm'
include 'source3.asm'
...


问:
margin text in TextBlock
Is it possible margin Text in TextBlock control ?

My style on textBlock control is here :

```<code><Style x:Key="InfosStyle" TargetType="{x:Type TextBlock}">
    <Setter Property="FontSize" Value="13"/>
    <Setter Property="FontWeight" Value="Normal"/>
    <Setter Property="Height" Value="35"/>
    <Setter Property="VerticalAlignment" Value="Center"/>
    <Setter Property="TextAlignment" Value="Justify"/>
    <!--<Setter Property="BorderThickness" Value="1"/>-->
    <!--<Setter Property="BorderBrush" Value="#BFE3FE"/>-->
    <Setter Property="Background" Value="#BFE3FE"/>
    <Setter Property="Margin" Value="2,4,0,1" />
</Style>
</code>```

Result is here:

For examole I would like align or set margin on text in textBlock.

Now: |Chatuje  to |_Chatuje

I would like  have some free space on left side in TextBlock.

Free space TextOfTextBlock

No

TextOfTextBlock

答:
You need to set Padding in your style. Something like this  </p>

```<code><Setter Property="Padding" Value="10,0,0,0" />
</code>```

Title: margin text in TextBlock

Body:
Is it possible margin Text in TextBlock control ?

My style on textBlock control is here :

Result is here:

For examole I would like align or set margin on text in textBlock.

Now: |Chatuje  to |_Chatuje

I would like  have some free space on left side in TextBlock.

Free space TextOfTextBlock

No

TextOfTextBlock

Body:
You need to set Padding in your style. Something like this

<Setter Property="Padding" Value="10,0,0,0" />


问:
Socket io handle two different user types
I have two socket servers running on separate machine.

```<code>// Customers
io.on('connection', function (socket) {

    socket.on(REQUEST, function (callback) {
        result = 'OK';
        callback(result);
    });
});

// Suppliers
// another socket server running on another instance

io.on('connection',function (socket) {

    socket.on(PRODUCTS, function (callback) {
        result = 'OK';
        callback(result);
    });
});
</code>```

As i know I cannot emit from one server to another if I don't have mapping between two.

How can I differentiate two types of users on single socket server. ? (then we have unique socket id and doesn't need mapping)

答:
I'm not 100% sure I understood your problem. If you need to differentiate different users connected to the same socket you can use the concept of Rooms. If you need to offer different endpoints you can use namespaces.

I'll sum up here an example from the documentation:

Rooms

You can call join to subscribe the socket to a given channel:

io.on('connection', function(socket){
  socket.join('some room'); // At user login maybe you can decide if
                            // the user should join the customer or suppliers
                            // room, or both if you need to
});
```

<p>And then simply use <strong>to</strong> or <strong>in</strong> (they are the same) when broadcasting or emitting:</p>

<pre class="lang-js prettyprint-override"><code>io.to('some room').emit('some event');
</code>```

To leave a channel you call leave in the same fashion as join.

Within each namespace, you can also define arbitrary channels that sockets can join and leave. Each connection join a default channel, useful to broadcasts, once you disconnect, your socketId will automatically leave any room he joined.

io.on('connection', function(socket){
  socket.on('say to someone', function(id, msg){
    // Useful to broadcast to every connected socket
    socket.broadcast.to(id).emit('my message', msg);
  });
});
```

<h2>Namespaces</h2>

<p>Basically we can define different endpoints, the default one is '/'. </p>

<h3>Server side</h3>

<p>When starting a server you can define many namepaces (endpoints) where your application can be reached. All of them may have different events and behaviours</p>

```var nsp = io.of('/my-namespace');
nsp.on('connection', function(socket){
  console.log('someone connected');
});
nsp.emit('hi', 'everyone!');
```

<h3>Client side</h3>

<p>At the client side you must connect to the namespace you declared before</p>

```var socket = io('/my-namespace');
```

https://socket.io/docs/rooms-and-namespaces/

Body:
I have two socket servers running on separate machine.

// Customers
io.on('connection', function (socket) {

    socket.on(REQUEST, function (callback) {
        result = 'OK';
        callback(result);
    });
});

// Suppliers
// another socket server running on another instance

io.on('connection',function (socket) {

    socket.on(PRODUCTS, function (callback) {
        result = 'OK';
        callback(result);
    });
});

As i know I cannot emit from one server to another if I don't have mapping between two.

How can I differentiate two types of users on single socket server. ? (then we have unique socket id and doesn't need mapping)

Body:
I'm not 100% sure I understood your problem. If you need to differentiate different users connected to the same socket you can use the concept of Rooms. If you need to offer different endpoints you can use namespaces.

I'll sum up here an example from the documentation:

Rooms

You can call join to subscribe the socket to a given channel:

io.on('connection', function(socket){
  socket.join('some room'); // At user login maybe you can decide if
                            // the user should join the customer or suppliers
                            // room, or both if you need to
});

And then simply use to or in (they are the same) when broadcasting or emitting:

io.to('some room').emit('some event');

To leave a channel you call leave in the same fashion as join.

Within each namespace, you can also define arbitrary channels that sockets can join and leave. Each connection join a default channel, useful to broadcasts, once you disconnect, your socketId will automatically leave any room he joined.

io.on('connection', function(socket){
  socket.on('say to someone', function(id, msg){
    // Useful to broadcast to every connected socket
    socket.broadcast.to(id).emit('my message', msg);
  });
});

Namespaces

Basically we can define different endpoints, the default one is '/'.

Server side

When starting a server you can define many namepaces (endpoints) where your application can be reached. All of them may have different events and behaviours

var nsp = io.of('/my-namespace');
nsp.on('connection', function(socket){
  console.log('someone connected');
});
nsp.emit('hi', 'everyone!');

Client side

At the client side you must connect to the namespace you declared before

var socket = io('/my-namespace');

https://socket.io/docs/rooms-and-namespaces/


问:
PHP shell_exec() sometimes doesn't work
I have a PHP script that performs an import of data from a vendor partner. One of the things that it needs to do is to call another script via shell_exec() that then processes an image file and uploads it to an Amazon S3 bucket. I'm watching the output from this script in a terminal right now, and after a while I see a series of messages along the lines of:

Warning: shell_exec(): Unable to execute 'php -f /path/to/second/script.php /path/to/image/to/process.jpg' in /path/to/this/script.php on line 453

The weird thing is that this same script is called multiple times in this script and works to begin with, and then stops. It's called from other scripts as well and works fine in those. When I copy the command that it couldn't run and paste it in myself it always works. Clearly PHP is capable of running it sometimes.

I've put a memory usage echo on each line as it runs, and I've seen it as high as 148MB while working correctly, and as low as 77MB when it's erroring. (this is in the main script, not the secondary script that cannot be run). The memory usage seems to get lower and lower as the errors start coming in. The first time I noticed it was around 88MB and then it dropped to 85MB, 81MB and then to 77MB.

I'm unclear on what might be causing the script to sometimes work and sometimes not. Last time I checked it wasn't possible for PHP to decide whether it can be bothered or not, and it doesn't get worn out, so why does it work fine for ages (I'm talking hundreds, if not thousands of successful downloads) and then suddenly it stops working. It's not that it's trying to process images that couldn't be downloaded, as there's a condition in the script that prevents that and I often see a load of image does not exist even while it's failing processing the rest. I've ended up having to write another script that runs back through and processes all missing images again afterwards.

ANY thoughts would be really gratefully received!

By the way, this is running on a large AWS EC2 instance with the Amazon Linux OS. We're running PHP5.3

答: I was dealing with the same issue and I found that /paht/to/php was /usr/bin/php5</p>

Title: PHP shell_exec() sometimes doesn't work


问:
Process with query "SSISDB.catalog.start_execution;1" getting suspended
we have one parent package which is executing some other packages in a sequence.
everytime when we run the job to execute parentpackage. one of the child package takes lot of time like 4 hours or 5 hours. and its random. its not for same package everytime.

when i check using sp_who2 there is one process which is suspended and the query of that process is:

SSISDB.catalog.start_execution;1

and then whatever is the next task in the execution, the process for query of that task is also suspended.

we have Retention window of SSISDB only 7 days and the size of DB is also 9000MB only. but still why this process is going in suspended mode. that out of my knowledge.

anyone encountered this kind of issue? is there any solution to it. or is there any setting i could check for this?

答:
I have this exact same issue on SQL 2016 SP1. Packages (built with VS2015 Upd 3 and targeted at SQL 2016) until last week ran fine and now taking hours, with some level of randomness to which one takes a long time. No other significant changes to the server, packages or databases since it used to run normally.

Update - Ended up being a lookup component issue. Looked through the "All messages" in standard reports on the catalog execution. A few duplicate lookup keys had crept into the data source... and that look up was failing over and over. with messages like this -

'The buffer manager failed a memory allocation call for 5570320 bytes, but was unable to swap out any buffers to relieve memory pressure. 88 buffers were considered and 72 were locked. Either not enough memory is available to the pipeline because not enough are installed, other processes were using it, or too many buffers are locked.'

and

'Buffer manager allocated [X] megabyte(s) in [Y] physical buffer(s)'

The execution report was 500 pages long, mostly with these messages repeated over and over in a loop with a gradual increase in the X and Y values. HTH


问:
Wordpress category/taxonomy query
I need to get all my posts in wordpress only from my category 6 and only this one, I dont want to query posts with 2 categorys like posts "X" has categories 6 and 9.

I'm stuck on this part of my query, and wanto to know if I should use NOT IN, and if that will make my query to much slower ?

```<code> SELECT p.*, t.term_id
        FROM wp_posts p
        LEFT JOIN wp_term_relationships rel ON rel.object_id = p.ID
        LEFT JOIN wp_term_taxonomy tax ON tax.term_taxonomy_id = rel.term_taxonomy_id
        LEFT JOIN wp_terms t ON t.term_id = tax.term_id
        WHERE t.term_id = 6
        ORDER BY p.post_date DESC Limit 10;
</code>```

答:
I think you need to get all the terms and remove all terms ids that not equal to terms_id that you wanted.

check this. I added some comments to explain the process

```<code>function get_posts_from_single_cat($cat_id) {
    // Get all the categories
    $cats = get_terms(array('taxonomy'=>'category'));
    $cats_ids = array();
    foreach($cats as $cat) {
        // Check if the category is NOT equal to the category that we want
        // Then we add it into array
        if($cat->term_id !== $cat_id) {
            $cats_ids[] = $cat->term_id;
        }
    }

    // then we create WP_Query with the category that we want and checking that its not in the other categories
    $args = array(
        'post_type' => 'post',
        'tax_query' => array(
            'relation' => 'AND',
            array(
                'taxonomy' => 'category',
                'field'    => 'term_id',
                'terms'    => array( $cat_id )
            ),
            array (
                'taxonomy' => 'category',
                'field'    => 'term_id',
                'terms'    => $cats_ids,
                'operator' => 'NOT IN'
            )
        ),
    );
    $query = new WP_Query( $args );
    // then do something with the posts...
}
</code>```

Title: Wordpress category/taxonomy query

Body:
I need to get all my posts in wordpress only from my category 6 and only this one, I dont want to query posts with 2 categorys like posts "X" has categories 6 and 9.

I'm stuck on this part of my query, and wanto to know if I should use NOT IN, and if that will make my query to much slower ?

 SELECT p.*, t.term_id
        FROM wp_posts p
        LEFT JOIN wp_term_relationships rel ON rel.object_id = p.ID
        LEFT JOIN wp_term_taxonomy tax ON tax.term_taxonomy_id = rel.term_taxonomy_id
        LEFT JOIN wp_terms t ON t.term_id = tax.term_id
        WHERE t.term_id = 6
        ORDER BY p.post_date DESC Limit 10;

Body:
I think you need to get all the terms and remove all terms ids that not equal to terms_id that you wanted.

check this. I added some comments to explain the process

function get_posts_from_single_cat($cat_id) {
    // Get all the categories
    $cats = get_terms(array('taxonomy'=>'category'));
    $cats_ids = array();
    foreach($cats as $cat) {
        // Check if the category is NOT equal to the category that we want
        // Then we add it into array
        if($cat->term_id !== $cat_id) {
            $cats_ids[] = $cat->term_id;
        }
    }

    // then we create WP_Query with the category that we want and checking that its not in the other categories
    $args = array(
        'post_type' => 'post',
        'tax_query' => array(
            'relation' => 'AND',
            array(
                'taxonomy' => 'category',
                'field'    => 'term_id',
                'terms'    => array( $cat_id )
            ),
            array (
                'taxonomy' => 'category',
                'field'    => 'term_id',
                'terms'    => $cats_ids,
                'operator' => 'NOT IN'
            )
        ),
    );
    $query = new WP_Query( $args );
    // then do something with the posts...
}


答:
As said by @Roland Ruul i've added some colours to visualise the fact that inline-block is what you need to do.

https://jsfiddle.net/L5eyd4bv/2/

```<code><div>
    <h1>Content goes here</h1>
    <p></p>
</div>

div {
    background-color: red;
    display: inline-block;
}

h1 {
    background-color: green;
}
</code>```

Title: Make h1 decide the div width

Body:
I'm trying to set the div width to be decided by h1. So the header can be as wide as it wants to be, while the paragraph will only be as wide as the header.

I've heard that this is impossible in plain html/css. Is this true? If so, what would a solution look like?

Body:
As said by @Roland Ruul i've added some colours to visualise the fact that inline-block is what you need to do.

https://jsfiddle.net/L5eyd4bv/2/

<div>
    <h1>Content goes here</h1>
    <p></p>
</div>

div {
    background-color: red;
    display: inline-block;
}

h1 {
    background-color: green;
}


问:
How do I select rows in a data frame before and after a condition is met?
I'm searching the web for a few a days now and I can't find a solution to my (probably easy to solve) problem.

I have huge data frames with 4 variables and over a million observations each. Now I want to select 100 rows before, all rows while and 1000 rows after a specific condition is met and fill the rest with NA's. I tried it with a for loop and if/ifelse but it doesn't work so far. I think it shouldn't be a big thing, but in the moment I just don't get the hang of it.

I create the data using:

```<code>foo<-data.frame(t = 1:15, a = sample(1:15), b = c(1,1,1,1,1,4,4,4,4,1,1,1,1,1,1), c = sample(1:15))
</code>```

My Data looks like this:

```<code>ID    t   a   b   c
1     1   4   1   7
2     2   7   1   10
3     3   10  1   6
4     4   2   1   4
5     5   13  1   9
6     6   15  4   3
7     7   8   4   15
8     8   3   4   1
9     9   9   4   2
10   10   14  1   8
11   11   5   1   11
12   12   11  1   13
13   13   12  1   5
14   14   6   1   14
15   15   1   1   12
</code>```

What I want is to pick the value of a (in this example) 2 rows before, all rows while and 3 rows after the value of b is >1 and fill the rest with NA's. [Because this is just an example I guess you can imagine that after these 15 rows there are more rows with the value for b changing from 1 to 4 several times (I did not post it, so I won't spam the question with unnecessary data).]
So I want to get something like:

```<code>ID    t   a   b   c   d
1     1   4   1   7  NA
2     2   7   1   10 NA
3     3   10  1   6  NA
4     4   2   1   4   2
5     5   13  1   9  13
6     6   15  4   3  15
7     7   8   4   15  8
8     8   3   4   1   3
9     9   9   4   2   9
10   10   14  1   8  14
11   11   5   1   11  5
12   12   11  1   13 11
13   13   12  1   5  NA
14   14   6   1   14 NA
15   15   1   1   12 NA
</code>```

I'm thankful for any help.

Thank you.

Best regards,
Chris

答:
Here is an attempt.

Get indexes that satisfy the condition b > 1

```<code>z <- which(foo$b > 1)
</code>```

get indexes for (z - 2) : (z + 3)

```<code>ind <- unique(unlist(lapply(z, function(x){
  g <- pmax(x - 2, 1) #if x - 2 is negative
  g : (x + 3)
})))
</code>```

create d column filled with NA

```<code>foo$d <- NA
</code>```

replace elements with appropriate indexes with foo$a

```<code>foo$d[ind] <- foo$a[ind]
</code>```

Body:
I'm searching the web for a few a days now and I can't find a solution to my (probably easy to solve) problem.

I have huge data frames with 4 variables and over a million observations each. Now I want to select 100 rows before, all rows while and 1000 rows after a specific condition is met and fill the rest with NA's. I tried it with a for loop and if/ifelse but it doesn't work so far. I think it shouldn't be a big thing, but in the moment I just don't get the hang of it.

I create the data using:

foo<-data.frame(t = 1:15, a = sample(1:15), b = c(1,1,1,1,1,4,4,4,4,1,1,1,1,1,1), c = sample(1:15))

My Data looks like this:

ID    t   a   b   c
1     1   4   1   7
2     2   7   1   10
3     3   10  1   6
4     4   2   1   4
5     5   13  1   9
6     6   15  4   3
7     7   8   4   15
8     8   3   4   1
9     9   9   4   2
10   10   14  1   8
11   11   5   1   11
12   12   11  1   13
13   13   12  1   5
14   14   6   1   14
15   15   1   1   12

What I want is to pick the value of a (in this example) 2 rows before, all rows while and 3 rows after the value of b is >1 and fill the rest with NA's. [Because this is just an example I guess you can imagine that after these 15 rows there are more rows with the value for b changing from 1 to 4 several times (I did not post it, so I won't spam the question with unnecessary data).]
So I want to get something like:

ID    t   a   b   c   d
1     1   4   1   7  NA
2     2   7   1   10 NA
3     3   10  1   6  NA
4     4   2   1   4   2
5     5   13  1   9  13
6     6   15  4   3  15
7     7   8   4   15  8
8     8   3   4   1   3
9     9   9   4   2   9
10   10   14  1   8  14
11   11   5   1   11  5
12   12   11  1   13 11
13   13   12  1   5  NA
14   14   6   1   14 NA
15   15   1   1   12 NA

I'm thankful for any help.

Thank you.

Best regards,
Chris

Body:
Here is an attempt.

Get indexes that satisfy the condition b > 1

z <- which(foo$b > 1)

get indexes for (z - 2) : (z + 3)

ind <- unique(unlist(lapply(z, function(x){
  g <- pmax(x - 2, 1) #if x - 2 is negative
  g : (x + 3)
})))

create d column filled with NA

foo$d <- NA

replace elements with appropriate indexes with foo$a

foo$d[ind] <- foo$a[ind]


问:
VB with Excel About Range Use
I'm trying to get the value from each cell from column A of the table compared to a value entered by the user, the problem is that in the line:
    If TamañoCmb.Value = Range("A" & Trim(fila)).Value Then
The range value doesn't return any value when it should get the cell a2 in the first loop and enter the if.  I debugged the code and isn't returning any value.

```<code>  Private Sub CalcularBtn_Click()

    If NombreTxt.Value = vbNullString Then
        MsgBox "Debe ingresar todos los datos"

    ElseIf TamañoCmb.Value = vbNullString Then
        MsgBox "Debe ingresar todos los datos"

    ElseIf CantidadTxt.Value = vbNullString Then
        MsgBox "Debe ingresar todos los datos"

    End If

    Worksheets("Información").Activate

    Dim fila As Single
    Dim Produccion_Principal As String
    Dim Precio_Principal As String

    For fila = 2 To 8

If TamañoCmb.Value = Range("A" & Trim(fila)).Value Then

            Produccion_Principal = Range("D" & Trim(fila)).Value
            Exit For

        End If

    Next

    ProduccionTxt.Value = Val(Produccion_Principal)

    For fila = 2 To 8

        If TamañoCmb.Value = Range("A" & Trim(fila)).Value Then

            Precio_Principal = Range("C" & Trim(fila)).Value
            Exit For

        End If

    Next

    PrecioUTxt.Text = Val(Precio_Principal) * CantidadTxt

    If Produccion_Principal < CantidadTxt.Value Then
        MsgBox "Producto primario mayor a producción, Cambie la cantidad"
    End If

    If Producto2Marco.Enabled Then

        Dim Produccion_Secundaria As String
        Dim Precio_Secundario As String

        For fila = 2 To 8

            If Producto2Cmb.Value = Range("A" & Trim(fila)).Value Then
                Produccion_Secundaria = Range("D" & Trim(fila)).Value
                Exit For
            End If

        Next

        If Producto2Cmb.Value = Range("A" & Trim(fila)).Value Then

            Precio_Secundario = Range("C" & Trim(fila)).Value

        End If

        PrecioSecTxt.Value = Val(Precio_Secundario)

        If Produccion_Secundaria < CantidadSecTxt.Value Then
            MsgBox "Producto secundario mayor a Producción, Cambie la cantidad"
        End If

    End If
</code>```

答:
I fixed the problem using a variable to store the value of the range like this:
Dim celda As String
celda = Range("A" & Trim(fila)).Value

Thanks to everyone for helpimg solve the issue!

Title: VB with Excel About Range Use

Body:
I'm trying to get the value from each cell from column A of the table compared to a value entered by the user, the problem is that in the line:
    If TamañoCmb.Value = Range("A" & Trim(fila)).Value Then
The range value doesn't return any value when it should get the cell a2 in the first loop and enter the if.  I debugged the code and isn't returning any value.

  Private Sub CalcularBtn_Click()

    If NombreTxt.Value = vbNullString Then
        MsgBox "Debe ingresar todos los datos"

    ElseIf TamañoCmb.Value = vbNullString Then
        MsgBox "Debe ingresar todos los datos"

    ElseIf CantidadTxt.Value = vbNullString Then
        MsgBox "Debe ingresar todos los datos"

    End If

    Worksheets("Información").Activate

    Dim fila As Single
    Dim Produccion_Principal As String
    Dim Precio_Principal As String

    For fila = 2 To 8

If TamañoCmb.Value = Range("A" & Trim(fila)).Value Then

            Produccion_Principal = Range("D" & Trim(fila)).Value
            Exit For

        End If

    Next

    ProduccionTxt.Value = Val(Produccion_Principal)

    For fila = 2 To 8

        If TamañoCmb.Value = Range("A" & Trim(fila)).Value Then

            Precio_Principal = Range("C" & Trim(fila)).Value
            Exit For

        End If

    Next

    PrecioUTxt.Text = Val(Precio_Principal) * CantidadTxt

    If Produccion_Principal < CantidadTxt.Value Then
        MsgBox "Producto primario mayor a producción, Cambie la cantidad"
    End If

    If Producto2Marco.Enabled Then

        Dim Produccion_Secundaria As String
        Dim Precio_Secundario As String

        For fila = 2 To 8

            If Producto2Cmb.Value = Range("A" & Trim(fila)).Value Then
                Produccion_Secundaria = Range("D" & Trim(fila)).Value
                Exit For
            End If

        Next

        If Producto2Cmb.Value = Range("A" & Trim(fila)).Value Then

            Precio_Secundario = Range("C" & Trim(fila)).Value

        End If

        PrecioSecTxt.Value = Val(Precio_Secundario)

        If Produccion_Secundaria < CantidadSecTxt.Value Then
            MsgBox "Producto secundario mayor a Producción, Cambie la cantidad"
        End If

    End If


问:
How to clone scope in angularjs?
I have data as follow:

```<code>$scope.form= response.data.shooter;
oldData= response.data.shooter;
</code>```

I have an issue in here:

Both have the same object array.

When I delete any value from oldData, it is also getting removed from $scope.form.

The code is as follows:

```<code>$.each(oldData, function(i, e) {
  console.log(oldData[e], $scope.form[e]);
  oldData[e] = '';
  console.log(oldData[e], $scope.form[e]);
});
</code>```

I have searched regarding this, but no luck.

Can anyone tell me, how to create a replica of scope to handle it separately regardless of sync between two array objects i.e. independent replica of scope so that if I make changes in that replica should not affect in scope?

答:
Use angular.copy()

```<code>$scope.form= response.data.shooter;
oldData= angular.copy(response.data.shooter);
</code>```

Title: How to clone scope in angularjs?

Body:
I have data as follow:

$scope.form= response.data.shooter;
oldData= response.data.shooter;

I have an issue in here:

Both have the same object array.

When I delete any value from oldData, it is also getting removed from $scope.form.

The code is as follows:

$.each(oldData, function(i, e) {
  console.log(oldData[e], $scope.form[e]);
  oldData[e] = '';
  console.log(oldData[e], $scope.form[e]);
});

I have searched regarding this, but no luck.

Can anyone tell me, how to create a replica of scope to handle it separately regardless of sync between two array objects i.e. independent replica of scope so that if I make changes in that replica should not affect in scope?

Body:
Use angular.copy()

$scope.form= response.data.shooter;
oldData= angular.copy(response.data.shooter);


问:
Project Not deploy on emulator in xamarin android native app
Console Output Message:

Additionally, check Build->Configuration Manager to ensure this
  project is set to Deploy for this configuration.

答: Try to go into emulator "Settings >Apps> All" and delete your application.