问:
Program returns all permutations of n elements?infinite loop?
This code should output all permutations of n elements, So when i enter for example 3 Output it must :

ABC
 BAC
 CAB
 ACB
 BCA
 CBA

with this code :

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

void swap(char *x, char *y){
  char temp;
  temp = *x;
  *x = *y;
  *y = temp;
}
void permute(char *a, int l, int r){
  int i;
  if (l == r)
    printf("%s\n", a);
  else
  {
    for (i = l; i <= r; i++){
      swap((a+l), (a+i));
      permute(a, l+1, r);
      swap((a+l), (a+i));

    }
  }
}
int main(){
  int x , n ;
  int i = 0 ;
  char str[26];
  printf("prem ");
  scanf("%d",&x);
  while (x > 0){
    str[i] = 'A' + i ;
    i++;
    x--;
  }
  n = strlen(str);
  permute(str, 0, n-1);

}
</code>```

I should type what I want for a number eg 3 for ABC or 4 for ABCD and then the code should handle that but it didnt workea and it goes in an infinite loop

but for this Code  :

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

void swap(char *x, char *y){
  char temp;
  temp = *x;
  *x = *y;
  *y = temp;
}
void permute(char *a, int l, int r){
  int i;
  if (l == r)
    printf("%s\n", a);
  else
  {
    for (i = l; i <= r; i++){
      swap((a+l), (a+i));
      permute(a, l+1, r);
      swap((a+l), (a+i));

    }
  }
}
int main()
{
  char str[26];
  gets(str);
  int n = strlen(str);
  permute(str, 0, n-1);
  return 0;
}
</code>```

I can enter whatever i want and it handle with it without Problem

my question is what is the problem with the first code? i mean i want to enter a number so that the program: if i type 3 for example it should deal with ABC

答:
Your main should be like:

```<code>int main(){
  int x , n ;
  int i = 0 ;
  char str[26];
  printf("prem ");
  scanf("%d",&x);

  //user entered the string length in x, let' save it in n
  n = x;

  while (x > 0){
    str[i] = 'A' + i ;
    i++;
    x--;
  }

  //n = strlen(str); ===> this is wrong, the user did not entered a string

  permute(str, 0, n-1);
}
</code>```

In the working code (the second block of code you posted), the user enters a string which is stored in str variable:

```<code>gets(str);
</code>```

Then the string length is passed to permute function using strlen:

```<code>int n = strlen(str);
permute(str, 0, n-1);
</code>```

In the first (non working) block of code, you ask the user to enter a length, not a string, and store it in x. You then put x characters in str array, but this is not a proper c string, because a null terminator is missing. So strlen return value is pretty much unreliable.

If you don't like the solution I suggested, you can just provide a

```<code>str[i] = '\0';
</code>```

right after your while block and leave everything else untouched, and it will work anyway.

Body:
This code should output all permutations of n elements, So when i enter for example 3 Output it must :

ABC
 BAC
 CAB
 ACB
 BCA
 CBA

with this code :

#include <stdio.h>
#include <string.h>

void swap(char *x, char *y){
  char temp;
  temp = *x;
  *x = *y;
  *y = temp;
}
void permute(char *a, int l, int r){
  int i;
  if (l == r)
    printf("%s\n", a);
  else
  {
    for (i = l; i <= r; i++){
      swap((a+l), (a+i));
      permute(a, l+1, r);
      swap((a+l), (a+i));

    }
  }
}
int main(){
  int x , n ;
  int i = 0 ;
  char str[26];
  printf("prem ");
  scanf("%d",&x);
  while (x > 0){
    str[i] = 'A' + i ;
    i++;
    x--;
  }
  n = strlen(str);
  permute(str, 0, n-1);

}

I should type what I want for a number eg 3 for ABC or 4 for ABCD and then the code should handle that but it didnt workea and it goes in an infinite loop

but for this Code  :

#include <stdio.h>
#include <string.h>

void swap(char *x, char *y){
  char temp;
  temp = *x;
  *x = *y;
  *y = temp;
}
void permute(char *a, int l, int r){
  int i;
  if (l == r)
    printf("%s\n", a);
  else
  {
    for (i = l; i <= r; i++){
      swap((a+l), (a+i));
      permute(a, l+1, r);
      swap((a+l), (a+i));

    }
  }
}
int main()
{
  char str[26];
  gets(str);
  int n = strlen(str);
  permute(str, 0, n-1);
  return 0;
}

I can enter whatever i want and it handle with it without Problem

my question is what is the problem with the first code? i mean i want to enter a number so that the program: if i type 3 for example it should deal with ABC

Body:
Your main should be like:

int main(){
  int x , n ;
  int i = 0 ;
  char str[26];
  printf("prem ");
  scanf("%d",&x);

  //user entered the string length in x, let' save it in n
  n = x;

  while (x > 0){
    str[i] = 'A' + i ;
    i++;
    x--;
  }

  //n = strlen(str); ===> this is wrong, the user did not entered a string

  permute(str, 0, n-1);
}

In the working code (the second block of code you posted), the user enters a string which is stored in str variable:

gets(str);

Then the string length is passed to permute function using strlen:

int n = strlen(str);
permute(str, 0, n-1);

In the first (non working) block of code, you ask the user to enter a length, not a string, and store it in x. You then put x characters in str array, but this is not a proper c string, because a null terminator is missing. So strlen return value is pretty much unreliable.

If you don't like the solution I suggested, you can just provide a

str[i] = '\0';

right after your while block and leave everything else untouched, and it will work anyway.


来源: stackexchange

问:
(Background-color) switch isn't working
I'm using the following code to turn the color of a guitar string first to red on the first click, then lightblue on the second click, and so on back and fourth between the two colors. The string turns red on the first click, but remains red with following clicks and I don't understand why.

```<code>var string = document.getElementById("a-string");
if (string.backgroundColor !== "red") {
  string.style.backgroundColor = "red";
} else {
  string.style.backgroundColor = "lightblue";
}
</code>```

Cam anyone see why this shouldn't work as I expect?

答:
Remark

Shorten it with classList.toggle(). Set a default background color to an element. Toggle it with a class that contains the other background color.

var btn = document.querySelector("button"),
  div = document.querySelector("div");

btn.addEventListener("click", function() {
  div.classList.toggle("bg-red");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  width: 50px;
  height: 50px;
  background: lightblue;
}

.bg-red {
  background: red;
}</code>```

<button id="btn">Toggle background color</button>```

ContentLicense: CC BY-SA 3.0

Title: (Background-color) switch isn't working

Body:
I'm using the following code to turn the color of a guitar string first to red on the first click, then lightblue on the second click, and so on back and fourth between the two colors. The string turns red on the first click, but remains red with following clicks and I don't understand why.

var string = document.getElementById("a-string");
if (string.backgroundColor !== "red") {
  string.style.backgroundColor = "red";
} else {
  string.style.backgroundColor = "lightblue";
}

Cam anyone see why this shouldn't work as I expect?

Body:
Remark

Shorten it with classList.toggle(). Set a default background color to an element. Toggle it with a class that contains the other background color.

var btn = document.querySelector("button"),
  div = document.querySelector("div");

btn.addEventListener("click", function() {
  div.classList.toggle("bg-red");
});

div {
  width: 50px;
  height: 50px;
  background: lightblue;
}

.bg-red {
  background: red;
}

<div></div>
<button id="btn">Toggle background color</button>


问:
Read a specific memory address via /dev/mem from the command line
For context, programming a driver to interact with an FPGA IP core on an embedded Linux (Yocto: krogoth) on a Xilinx board.

For debugging purposes I would like to read out specific memory addresses from physical memory. /dev/mem looks promising. I wanted to ask how I can read out the value of a specific physical memory address from the command line. I was hoping for something along the lines of cat /dev/mem 0x2000000 to read the byte at 0x2000000.

答:
Usually you should already have devmem tool installed in your Linux image:

```<code>$ devmem 0x2000000
</code>```

If you don't however, you can go to Busybox menu and tweak it to make sure it gets compiled and installed:

```<code>$ bitbake busybox -c menuconfig
</code>```

(search for devmem)

Body:
Usually you should already have devmem tool installed in your Linux image:

$ devmem 0x2000000

If you don't however, you can go to Busybox menu and tweak it to make sure it gets compiled and installed:

$ bitbake busybox -c menuconfig

(search for devmem)


问:
Getter with arrow function syntax
Is there a JavaScript syntax that lets me do the following more succinctly?

```<code>class MyClass {
    static get myProp() {
        return 1;
    }
}
</code>```

It is not a huge deal, but I'd like to know if there was something that was like an arrow function that lets me make it just a little more streamlined, something like:

```<code>class MyClass {
    static get myProp = () => 1;
}
</code>```

I know I could write it like this (though not a safe equivalent):

```<code>class MyClass {}
MyClass.myProp = 1;
</code>```

Or this more-difficult-to-read and longer alternative:

```<code>class MyClass {}
Object.define(MyClass, 'myProp', { get: () => 1; });
</code>```

But that feels like an abuse of the class syntax.

答:
There is a better way to do it. It can be done using Babel Preset for class-transform.
The preset to get this particular feature is 'preset-stage-2'.

The documentation page of babel for preset-stage-2:
https://babeljs.io/docs/plugins/preset-stage-2/

Use Case:
In your .bablerc file ad the present.

```<code>{
  "presets": ["stage-2"]
}
</code>```

Note: it is a separate npm module so install it beforehand.

ContentLicense: CC BY-SA 4.0

Title: Getter with arrow function syntax

Body:
Is there a JavaScript syntax that lets me do the following more succinctly?

class MyClass {
    static get myProp() {
        return 1;
    }
}

It is not a huge deal, but I'd like to know if there was something that was like an arrow function that lets me make it just a little more streamlined, something like:

class MyClass {
    static get myProp = () => 1;
}

I know I could write it like this (though not a safe equivalent):

class MyClass {}
MyClass.myProp = 1;

Or this more-difficult-to-read and longer alternative:

class MyClass {}
Object.define(MyClass, 'myProp', { get: () => 1; });

But that feels like an abuse of the class syntax.

Body:
There is a better way to do it. It can be done using Babel Preset for class-transform.
The preset to get this particular feature is 'preset-stage-2'.

The documentation page of babel for preset-stage-2:
https://babeljs.io/docs/plugins/preset-stage-2/

Use Case:
In your .bablerc file ad the present.

{
  "presets": ["stage-2"]
}

Note: it is a separate npm module so install it beforehand.


问:
Create database with migration beego
I already created migration file via bee generate migration create_users_table. Then i had one file in folder database/migrations/20171205_154034_create_users_table.go
This is my file :

```<code>package main

import (
    "github.com/astaxie/beego/migration"
)

// DO NOT MODIFY
type CreateUsersTable_20171205_154034 struct {
    migration.Migration
}

// DO NOT MODIFY
func init() {
    m := &CreateUsersTable_20171205_154034{}
    m.Created = "20171205_154034"

    migration.Register("CreateUsersTable_20171205_154034", m)
}

// Run the migrations
func (m *CreateUsersTable_20171205_154034) Up() {
    m.CreateTable("users","InnoDB","utf8")
    m.PriCol("id").SetAuto(true).SetNullable(false).SetDataType("INT(10)").SetUnsigned(true)
}

// Reverse the migrations
func (m *CreateUsersTable_20171205_154034) Down() {
    m.SQL("DROP TABLE users")
}
</code>```

Finally, i run bee migrate -conn="username:password@tcp(127.0.0.1:3306)/mydb".
I got Migration successful! no error. But i did not have users table in database. Whats wrong?
Thank you for reading. Hope anyone help me

答:
To address your problem, you're not executing your SQL in the end.

Add the following line to your Up():

```<code>m.SQL(m.GetSQL())
</code>```

Title: Create database with migration beego

Body:
I already created migration file via bee generate migration create_users_table. Then i had one file in folder database/migrations/20171205_154034_create_users_table.go
This is my file :

package main

import (
    "github.com/astaxie/beego/migration"
)

// DO NOT MODIFY
type CreateUsersTable_20171205_154034 struct {
    migration.Migration
}

// DO NOT MODIFY
func init() {
    m := &CreateUsersTable_20171205_154034{}
    m.Created = "20171205_154034"

    migration.Register("CreateUsersTable_20171205_154034", m)
}

// Run the migrations
func (m *CreateUsersTable_20171205_154034) Up() {
    m.CreateTable("users","InnoDB","utf8")
    m.PriCol("id").SetAuto(true).SetNullable(false).SetDataType("INT(10)").SetUnsigned(true)
}

// Reverse the migrations
func (m *CreateUsersTable_20171205_154034) Down() {
    m.SQL("DROP TABLE users")
}

Finally, i run bee migrate -conn="username:password@tcp(127.0.0.1:3306)/mydb".
I got Migration successful! no error. But i did not have users table in database. Whats wrong?
Thank you for reading. Hope anyone help me

Body:
To address your problem, you're not executing your SQL in the end.

Add the following line to your Up():

m.SQL(m.GetSQL())


问:
All prime numbers within a range
I am trying to write a program that will print all the primes within a given range. I have written it, the output is almost okay, it prints primes, but for some reason it prints 4, which is not a prime...
Any assistant will be most appreciated !</p>

```<code>def primes():
    start = int(input("Enter the starting number: "))
    end = int(input("Enter the ending number: "))
    num = 0
    i = 0
    ctr = 0
    for num in range(start,end+1,1):
        ctr = 0
        for i in range(2,num//2,1):
            if num % i == 0 :
                ctr = ctr + 1
                break
        if (ctr==0 and num != 1):
            print(num)
</code>```

答:
```<code>for i in range(2,num//2,1):
</code>```

Lets check this snippet of code when num = 4,it becomes

```<code>for i in range(2,2,1):
</code>```

Now we see the problem.
Solution..?

```<code>for i in range(2,(num//2)+1,1):
</code>```

Title: All prime numbers within a range

Body:
I am trying to write a program that will print all the primes within a given range. I have written it, the output is almost okay, it prints primes, but for some reason it prints 4, which is not a prime...
Any assistant will be most appreciated !

def primes():
    start = int(input("Enter the starting number: "))
    end = int(input("Enter the ending number: "))
    num = 0
    i = 0
    ctr = 0
    for num in range(start,end+1,1):
        ctr = 0
        for i in range(2,num//2,1):
            if num % i == 0 :
                ctr = ctr + 1
                break
        if (ctr==0 and num != 1):
            print(num)

Body:
for i in range(2,num//2,1):

Lets check this snippet of code when num = 4,it becomes

for i in range(2,2,1):

Now we see the problem.
Solution..?

for i in range(2,(num//2)+1,1):


问:
Is it possible to dynamically compile and execute C# code fragments?
I was wondering if it is possible to save C# code fragments to a text file (or any input stream), and then execute those dynamically? Assuming what is provided to me would compile fine within any Main() block, is it possible to compile and/or execute this code? I would prefer to compile it for performance reasons.

At the very least, I could define an interface that they would be required to implement, then they would provide a code 'section' that implemented that interface.

答:
Found this useful - ensures the compiled Assembly references everything you currently have referenced, since there's a good chance you wanted the C# you're compiling to use some classes etc in the code that's emitting this:

(string code is the dynamic C# being compiled)

```<code>        var refs = AppDomain.CurrentDomain.GetAssemblies();
        var refFiles = refs.Where(a => !a.IsDynamic).Select(a => a.Location).ToArray();
        var cSharp = (new Microsoft.CSharp.CSharpCodeProvider()).CreateCompiler();
        var compileParams = new System.CodeDom.Compiler.CompilerParameters(refFiles);
        compileParams.GenerateInMemory = true;
        compileParams.GenerateExecutable = false;

        var compilerResult = cSharp.CompileAssemblyFromSource(compileParams, code);
        var asm = compilerResult.CompiledAssembly;
</code>```

In my case I was emitting a class, whose name was stored in a string, className, which had a single public static method named Get(), that returned with type StoryDataIds. Here's what calling that method looks like:

```<code>        var tempType = asm.GetType(className);
        var ids = (StoryDataIds)tempType.GetMethod("Get").Invoke(null, null);
</code>```

Warning: Compilation can be surprisingly, extremely slow. A small, relatively simple 10-line chunk of code compiles at normal priority in 2-10 seconds on our relatively fast server. You should never tie calls to CompileAssemblyFromSource() to anything with normal performance expectations, like a web request. Instead, proactively compile code you need on a low-priority thread and have a way of dealing with code that requires that code to be ready, until it's had a chance to finish compiling. For example you could use it in a batch job process.

ContentLicense: CC BY-SA 2.5

Body:
Found this useful - ensures the compiled Assembly references everything you currently have referenced, since there's a good chance you wanted the C# you're compiling to use some classes etc in the code that's emitting this:

(string code is the dynamic C# being compiled)

        var refs = AppDomain.CurrentDomain.GetAssemblies();
        var refFiles = refs.Where(a => !a.IsDynamic).Select(a => a.Location).ToArray();
        var cSharp = (new Microsoft.CSharp.CSharpCodeProvider()).CreateCompiler();
        var compileParams = new System.CodeDom.Compiler.CompilerParameters(refFiles);
        compileParams.GenerateInMemory = true;
        compileParams.GenerateExecutable = false;

        var compilerResult = cSharp.CompileAssemblyFromSource(compileParams, code);
        var asm = compilerResult.CompiledAssembly;

In my case I was emitting a class, whose name was stored in a string, className, which had a single public static method named Get(), that returned with type StoryDataIds. Here's what calling that method looks like:

        var tempType = asm.GetType(className);
        var ids = (StoryDataIds)tempType.GetMethod("Get").Invoke(null, null);

Warning: Compilation can be surprisingly, extremely slow. A small, relatively simple 10-line chunk of code compiles at normal priority in 2-10 seconds on our relatively fast server. You should never tie calls to CompileAssemblyFromSource() to anything with normal performance expectations, like a web request. Instead, proactively compile code you need on a low-priority thread and have a way of dealing with code that requires that code to be ready, until it's had a chance to finish compiling. For example you could use it in a batch job process.


问:
Add new column, multiply value with strings with dplyr
Some how I can't wrap my head around a simple question. How do I count the number of string values in sentiment times (*) the integer in another column times_used. Probably with group_by() and summarise()? With the following dataframe:

```<code>        word times_used sentiment
       <chr>      <int>     <chr>
 1      fake         68  negative
 2       bad         36  negative
 3 president         35  positive
 4       tax         32  negative
 5   failing         21  negative
 6      vote         20  negative
 7      vote         20  positive
 8      deal         19  positive
 9       job         19  positive
10    united         19  positive
# ... with 475 more rows
</code>```

Eventually looking for something like this:

```<code>times_used sentiment
     <int>     <chr>
      4090  negative
      3198  positive
</code>```

答:
If I understand correctly you would want something like:

```<code>library(dplyr)
df %>%
 group_by(sentiment) %>%
 summarise(count = n(),
           words = sum(times_used)) %>%
 mutate(total = count * words)
#  A tibble: 2 x 4
#  sentiment count words total
#     <fctr> <int> <int> <int>
#1  negative     5   177   885
#2  positive     5   112   560
</code>```

And then you can chain select(sentiment, total) if you just want those two columns.

Body:
Some how I can't wrap my head around a simple question. How do I count the number of string values in sentiment times (*) the integer in another column times_used. Probably with group_by() and summarise()? With the following dataframe:

        word times_used sentiment
       <chr>      <int>     <chr>
 1      fake         68  negative
 2       bad         36  negative
 3 president         35  positive
 4       tax         32  negative
 5   failing         21  negative
 6      vote         20  negative
 7      vote         20  positive
 8      deal         19  positive
 9       job         19  positive
10    united         19  positive
# ... with 475 more rows

Eventually looking for something like this:

times_used sentiment
     <int>     <chr>
      4090  negative
      3198  positive

Body:
If I understand correctly you would want something like:

library(dplyr)
df %>%
 group_by(sentiment) %>%
 summarise(count = n(),
           words = sum(times_used)) %>%
 mutate(total = count * words)
#  A tibble: 2 x 4
#  sentiment count words total
#     <fctr> <int> <int> <int>
#1  negative     5   177   885
#2  positive     5   112   560

And then you can chain select(sentiment, total) if you just want those two columns.


问:
InterpolationMode HighQualityBicubic introducing artefacts on edge of resized images
Using some pretty stock standard C# code to resize an image, and place it on a coloured background

```<code>Image imgToResize = Image.FromFile(@"Dejeuner.jpg");
Size size = new Size(768, 1024);
Bitmap b = new Bitmap(size.Width, size.Height);

Graphics g = Graphics.FromImage((Image)b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.FillRectangle(Brushes.Green, 0, 0, size.Width, size.Height);

g.DrawImage(imgToResize, new Rectangle(0,150,768, 570));
b.Save("sized_HighQualityBicubic.jpg");
</code>```

The result has a funny artefact in the 0th and 1st columns of pixels.  The 0th column appears to be mixed with the background colour, and the 1st column has been made lighter.

See the top left corner zoomed for high quality bicubic and bicubic.

..and HighQualityBilinear

This forum post appears to be someone with the same problem: DrawImage with sharp edges

The sounds like a bug to me? I can understand why the colours would mix at the top of the resized image.  But mixing the colours on the left / right edges doesn't make sense.  Does anyone know of a fix to prevent these artefacts?

Update: very similar conversation going on in the comments here: GDI+ InterpolationMode

答: Set the PixelOffsetMode property to HighQuality to get a better blend with the background at the edges.</p>

Body:
Using some pretty stock standard C# code to resize an image, and place it on a coloured background

Image imgToResize = Image.FromFile(@"Dejeuner.jpg");
Size size = new Size(768, 1024);
Bitmap b = new Bitmap(size.Width, size.Height);

Graphics g = Graphics.FromImage((Image)b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.FillRectangle(Brushes.Green, 0, 0, size.Width, size.Height);

g.DrawImage(imgToResize, new Rectangle(0,150,768, 570));
b.Save("sized_HighQualityBicubic.jpg");

The result has a funny artefact in the 0th and 1st columns of pixels.  The 0th column appears to be mixed with the background colour, and the 1st column has been made lighter.

See the top left corner zoomed for high quality bicubic and bicubic.

..and HighQualityBilinear

This forum post appears to be someone with the same problem: DrawImage with sharp edges

The sounds like a bug to me? I can understand why the colours would mix at the top of the resized image.  But mixing the colours on the left / right edges doesn't make sense.  Does anyone know of a fix to prevent these artefacts?

Update: very similar conversation going on in the comments here: GDI+ InterpolationMode


答:
The following methods are all possible prime checkers you might use to check within your range:</p>

```<code>def isPrime(Number):  # slow
    return 2 in [Number, 2 ** Number % Number]

def isprime(n):  # out of memory errors with big numbers
    """check if integer n is a prime"""
    # make sure n is a positive integer
    n = abs(int(n))
    # 0 and 1 are not primes
    if n < 2:
        return False
    # 2 is the only even prime number
    if n == 2:
        return True
        # all other even numbers are not primes
    if not n & 1:
        return False
    # range starts with 3 and only needs to go up the squareroot of n
    # for all odd numbers
    for x in range(3, int(n ** 0.5) + 1, 2):
        if n % x == 0:
            return False
    return True

def is_prime(n):  # Best until now
    if n == 2 or n == 3:
        return True
    if n < 2 or n % 2 == 0:
        return False
    if n < 9:
        return True
    if n % 3 == 0:
        return False
    r = int(n ** 0.5)
    f = 5
    while f <= r:
        # print '\t', f
        if n % f == 0:
            return False
        if n % (f + 2) == 0:
            return False
        f += 6
    return True
</code>```

Title: All prime numbers within a range

Body:
The following methods are all possible prime checkers you might use to check within your range:

def isPrime(Number):  # slow
    return 2 in [Number, 2 ** Number % Number]

def isprime(n):  # out of memory errors with big numbers
    """check if integer n is a prime"""
    # make sure n is a positive integer
    n = abs(int(n))
    # 0 and 1 are not primes
    if n < 2:
        return False
    # 2 is the only even prime number
    if n == 2:
        return True
        # all other even numbers are not primes
    if not n & 1:
        return False
    # range starts with 3 and only needs to go up the squareroot of n
    # for all odd numbers
    for x in range(3, int(n ** 0.5) + 1, 2):
        if n % x == 0:
            return False
    return True

def is_prime(n):  # Best until now
    if n == 2 or n == 3:
        return True
    if n < 2 or n % 2 == 0:
        return False
    if n < 9:
        return True
    if n % 3 == 0:
        return False
    r = int(n ** 0.5)
    f = 5
    while f <= r:
        # print '\t', f
        if n % f == 0:
            return False
        if n % (f + 2) == 0:
            return False
        f += 6
    return True


问:
MySQLdb Connecting To Database Error
I'm trying to connect to my SQL database on pythonanywhere and to connect I'm running this.

```<code>import MySQLdb

conn = MySQLdb.connect("MYUSERNAME.mysql.pythonanywhere-services.com","MYUSERNAME","DBPASSWORD","DBTABLENAME")

c = conn.cursor()

c.execute("SELECT * from game_db")

rows = c.fetchall()

for eachrow in rows:
    print(eachrow)
</code>```

I'm doing this from my laptop and I get this error when trying to connect.

```<code>_mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on MYUSERNAME.mysql.pythonanywhere-services.com' (10060)")
</code>```

Is there some sort of authentication I need to do or is there some other problem.
Thank you!

答: the pythonanywhere mysql service isn't accessible from outside pythonanywhere (unless you have a paid account, in which case you can use an ssh tunnel: https://help.pythonanywhere.com/pages/AccessingMySQLFromOutsidePythonAnywhere/)</p>

Title: MySQLdb Connecting To Database Error

Body:
I'm trying to connect to my SQL database on pythonanywhere and to connect I'm running this.

import MySQLdb

conn = MySQLdb.connect("MYUSERNAME.mysql.pythonanywhere-services.com","MYUSERNAME","DBPASSWORD","DBTABLENAME")

c = conn.cursor()

c.execute("SELECT * from game_db")

rows = c.fetchall()

for eachrow in rows:
    print(eachrow)

I'm doing this from my laptop and I get this error when trying to connect.

_mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on MYUSERNAME.mysql.pythonanywhere-services.com' (10060)")

Is there some sort of authentication I need to do or is there some other problem.
Thank you!


问:
Calling ViewController class methods in swift
Quick question, Imagine me having two ViewControllers, in one of them, I have a written a method that loads data from an API an stores it inside a global array.

Is it a good idea to call that method from THE OTHER ViewController by doing this?:

```<code>MyDataLoadingVC().loadData()
</code>```

Here I create another instance of the MyDataLoadingViewController class, and call the method on that instance. I'm thinking, since the method does not have any effect on the instance on which it is being called (in the case of this method it doesn't, I'm sure), this is ok, right?.
I have never seen someone do it and it seems okay to me, what do you think?

Thx in advance!

答:
Thanks guys, fixed it.

I made a special data managing class with all the data-fetching methods in it. This works fine!

Body:
Quick question, Imagine me having two ViewControllers, in one of them, I have a written a method that loads data from an API an stores it inside a global array.

Is it a good idea to call that method from THE OTHER ViewController by doing this?:

MyDataLoadingVC().loadData()

Here I create another instance of the MyDataLoadingViewController class, and call the method on that instance. I'm thinking, since the method does not have any effect on the instance on which it is being called (in the case of this method it doesn't, I'm sure), this is ok, right?.
I have never seen someone do it and it seems okay to me, what do you think?

Thx in advance!


问:
jquery read php array
im trying to change one var to get and stuck

here is what I did:

```<code>var choices = [['Australia', 'au'], ['Austria', 'at'], ['Brasil', 'br']];
</code>```

so this is working, and I want to change it on

```<code>$.getJSON('/modules/profile/readCountry.php',function(data){
    arrays = data;
});
var choices = arrays;
</code>```

but is not working

the php file is:

```<code>foreach($countryies as $countr => $countrv) {
    $json[] = array($countrv,$countr);
}
header("Content-type:application/json");
$out = array_values($json);
echo json_encode($out);
</code>```

and output is:

```<code>[['Australia', 'au'], ['Austria', 'at'], ['Brasil', 'br']]
</code>```

how to fine out what is missing or is not working ?

答:
$.getJSON is async call </p>

```<code>    var choices = [];
    $.getJSON('/modules/profile/readCountry.php',function(data){
        choices = data;
        // do something with array
    });
</code>```

Title: jquery read php array

Body:
im trying to change one var to get and stuck

here is what I did:

var choices = [['Australia', 'au'], ['Austria', 'at'], ['Brasil', 'br']];

so this is working, and I want to change it on

$.getJSON('/modules/profile/readCountry.php',function(data){
    arrays = data;
});
var choices = arrays;

but is not working

the php file is:

foreach($countryies as $countr => $countrv) {
    $json[] = array($countrv,$countr);
}
header("Content-type:application/json");
$out = array_values($json);
echo json_encode($out);

and output is:

[['Australia', 'au'], ['Austria', 'at'], ['Brasil', 'br']]

how to fine out what is missing or is not working ?

Body:
$.getJSON is async call

    var choices = [];
    $.getJSON('/modules/profile/readCountry.php',function(data){
        choices = data;
        // do something with array
    });


问:
What should If I want to check whether my union is list or string in perl
I need to write an union function using Perl, and what I did is here, questions is followed by code.

```<code>sub union
{
    my @array1  = qw/a b c d/;
    my @array2  = qw/a f g h/;
    my %myunion = ();
    @myunion{ @array1, @array2 } = (1) x ( @array1 + @array2 );
    @myunion = keys %myunion;
    return @myunion;

    #if(){
    #    return @myunion;
    #}
    #else{
    #    return join ',', @myunion;
    #}
}
my @uString = union( [ 1, 2, 3 ], [ 2, 3, 4 ] );
my @uList   = union( [ 1, 2, 3 ], [ 2, 3, 4 ] );
print "$uString\n"
print "@uList\n";
</code>```

So without my command part, my out put is a b c d f g h in random order, but I want to make them as 1 2 3 4 in random order as what I write as input in my @uList. Also I need to check whether the caller requires a list, if it is it will return 1 2 3 4in random order, otherwise, it will return a comman-seperate string of the union which should be 1,2,3,4 in random order. So I want to know what should I do in the condition part of the if else statement.

答:
Use the @_ variable to retrieve subroutine parameters.

To create the hash keys, you can let the values undefined.

```<code>#! /usr/bin/perl
use warnings;
use strict;

sub union {
    my ($aref1, $aref2) = @_;
    my %union;
    @union{ @$aref1, @$aref2 } = ();
    return keys %union
}

my @union = union([1, 2, 3], [2, 3, 4]);
print "@union\n";
</code>```

or

```<code>my $union = join ',', union([1, 2, 3], [2, 3, 4]);
print "$union\n";
</code>```

Body:
I need to write an union function using Perl, and what I did is here, questions is followed by code.

sub union
{
    my @array1  = qw/a b c d/;
    my @array2  = qw/a f g h/;
    my %myunion = ();
    @myunion{ @array1, @array2 } = (1) x ( @array1 + @array2 );
    @myunion = keys %myunion;
    return @myunion;

    #if(){
    #    return @myunion;
    #}
    #else{
    #    return join ',', @myunion;
    #}
}
my @uString = union( [ 1, 2, 3 ], [ 2, 3, 4 ] );
my @uList   = union( [ 1, 2, 3 ], [ 2, 3, 4 ] );
print "$uString\n"
print "@uList\n";

So without my command part, my out put is a b c d f g h in random order, but I want to make them as 1 2 3 4 in random order as what I write as input in my @uList. Also I need to check whether the caller requires a list, if it is it will return 1 2 3 4in random order, otherwise, it will return a comman-seperate string of the union which should be 1,2,3,4 in random order. So I want to know what should I do in the condition part of the if else statement.

Body:
Use the @_ variable to retrieve subroutine parameters.

To create the hash keys, you can let the values undefined.

#! /usr/bin/perl
use warnings;
use strict;

sub union {
    my ($aref1, $aref2) = @_;
    my %union;
    @union{ @$aref1, @$aref2 } = ();
    return keys %union
}

my @union = union([1, 2, 3], [2, 3, 4]);
print "@union\n";

or

my $union = join ',', union([1, 2, 3], [2, 3, 4]);
print "$union\n";


问:
Query distinct property and return complete nodes
I got a lot of nodes, some with similar values in field X, I want to select by distinct X values and take all the popular nodes (order by some other field Y) with all their properties.

Example:

ID | X | Y | Name

1  | A | 100 | David

2  | A | 10  | Chris

3  | B | 5   | Brad

4  | B | 25  | Amber

Should return:

1 | A | 100 | David

4 | B | 25  | Amber

I managed to get the list by distinct X:

```<code>MATCH (u:NodeType)
RETURN DISTINCT u.X
</code>```

I need to find the most popular (highest value of Y) nodes to join with my distinct nodes (which are now only a single property) and return whole nodes (with all the properties).

答:
You are looking for an arg max-style query. I recently answered a similar problem using collect:

```<code>MATCH (u:NodeType)
WITH u
ORDER BY u.Y DESC
WITH u.X AS X, collect(u)[0] AS u
RETURN u
</code>```

The idea is the following:

Order by the value of Y (descending).

Implicitly group by the values of X and for the aggregating function, use collect to gather other values to a list. The elements of the list are the nodes (which are still stored according to a descending order of Y).

For each collected list, select the first element with [0].

Maybe the query is a bit easier to read if you perform the last step in a separate clause (and not in the WITH clause that performs the collect):

```<code>MATCH (u:NodeType)
WITH u
ORDER BY u.Y DESC
WITH u.X AS X, collect(u) AS us
RETURN us[0] AS u
</code>```

Body:
I got a lot of nodes, some with similar values in field X, I want to select by distinct X values and take all the popular nodes (order by some other field Y) with all their properties.

Example:

ID | X | Y | Name

1  | A | 100 | David

2  | A | 10  | Chris

3  | B | 5   | Brad

4  | B | 25  | Amber

Should return:

1 | A | 100 | David

4 | B | 25  | Amber

I managed to get the list by distinct X:

MATCH (u:NodeType)
RETURN DISTINCT u.X

I need to find the most popular (highest value of Y) nodes to join with my distinct nodes (which are now only a single property) and return whole nodes (with all the properties).

Body:
You are looking for an arg max-style query. I recently answered a similar problem using collect:

MATCH (u:NodeType)
WITH u
ORDER BY u.Y DESC
WITH u.X AS X, collect(u)[0] AS u
RETURN u

The idea is the following:

Order by the value of Y (descending).

Implicitly group by the values of X and for the aggregating function, use collect to gather other values to a list. The elements of the list are the nodes (which are still stored according to a descending order of Y).

For each collected list, select the first element with [0].

Maybe the query is a bit easier to read if you perform the last step in a separate clause (and not in the WITH clause that performs the collect):

MATCH (u:NodeType)
WITH u
ORDER BY u.Y DESC
WITH u.X AS X, collect(u) AS us
RETURN us[0] AS u


答:
```<code>for i in range(2,num//2,1):
</code>```

Above line is wrong. You are iterating from 2 to num / 2 - 1.

You should iterate from 2 to sqrt(num). (range(2, int(math.sqrt(n)) + 1))

Alternatively you can do a special check for 2 and modify your range to range(3, int(math.sqrt(n) + 1, 2)

Title: All prime numbers within a range

Body:
for i in range(2,num//2,1):

Above line is wrong. You are iterating from 2 to num / 2 - 1.

You should iterate from 2 to sqrt(num). (range(2, int(math.sqrt(n)) + 1))

Alternatively you can do a special check for 2 and modify your range to range(3, int(math.sqrt(n) + 1, 2)


问:
How to parse unpredictable JSON objects?
My app parse JSON from an API based on user's selection. Since each user's search might be different I can't predict what the user will search and have a established parsing structure waiting for them every time I finish a API call.

The problem is how can I have a JSON parsing structure in my app that will handle this undefined/unpredictable JSON object from the different API call?

Basically what I need is a way to handle unpredictable and unknown JSON object like they were known and I could parse their keys and the data inside them.

Thank you.

答:
You can use ObjectMapper to convert your JSON to some key-value structure object like Map or HashMap:

Map<String,Object> result = new ObjectMapper().readValue(jsonData, Map.class);

jsonData can be file, stream, byte, string,....

More detail here: https://fasterxml.github.io/jackson-databind/javadoc/2.2.0/com/fasterxml/jackson/databind/ObjectMapper.html#readValue(byte[],%20java.lang.Class)


问:
Clojure macro for searching in lists of maps using an SQL-like syntax

Example input

```<code>=> (def persons '({:id 1 :name "olle"} {:id 2 :name "anna"} {:id 3 :name
"isak"} {:id 4 :name "beatrice"}))

=> (select [:id :name] from persons where [:id > 2] orderby :name)
</code>```

Example Output

```<code>({:id 4 :name "beatrice"} {:id 3 :name "isak"})
</code>```

The query format should be:

```<code>(select [columns]
from #{table}
where [:column op value]
orderby :column)
</code>```

where 'op' is equal to one of '=' '<' '>' or '<>'

Attempted solution

```<code>(defmacro select
    [vara _ coll _ wherearg _ orderarg]
    '(map [~vara]
        (filter [~wherearg]
            (sort-by ~orderarg) ~coll)
        )
    )
</code>```

What more does my solution need?
I don't understand what the errors mean so I don't even know what I should look for to find a solution.

```<code>IllegalArgumentException Don't know how to create ISeq from: clojure.lang.Symbol  clojure.lang.RT.seqFrom (RT.java:542)
</code>```

答:
I would break up the problem, and stick to regular Clojure syntax instead of trying to re-invent SQL.  Something like this:

```<code>(def persons '( {:id 1 :name "olle"}
                {:id 2 :name "anna"}
                {:id 3 :name "isak"}
                {:id 4 :name "beatrice"} ))

(defn id-over-2?
  [person]
  (< 2 (:id person)))

(def persons-2 (filter id-over-2? persons) )

(def persons-3 (sort-by :name persons-2))
</code>```

with results

```<code>persons-2 => ({:id 3, :name "isak"} {:id 4, :name "beatrice"})

persons-3 => ({:id 4, :name "beatrice"} {:id 3, :name "isak"})
</code>```

Body:
Example input

=> (def persons '({:id 1 :name "olle"} {:id 2 :name "anna"} {:id 3 :name
"isak"} {:id 4 :name "beatrice"}))

=> (select [:id :name] from persons where [:id > 2] orderby :name)

Example Output

({:id 4 :name "beatrice"} {:id 3 :name "isak"})

The query format should be:

(select [columns]
from #{table}
where [:column op value]
orderby :column)

where 'op' is equal to one of '=' '<' '>' or '<>'

Attempted solution

(defmacro select
    [vara _ coll _ wherearg _ orderarg]
    '(map [~vara]
        (filter [~wherearg]
            (sort-by ~orderarg) ~coll)
        )
    )

What more does my solution need?
I don't understand what the errors mean so I don't even know what I should look for to find a solution.

IllegalArgumentException Don't know how to create ISeq from: clojure.lang.Symbol  clojure.lang.RT.seqFrom (RT.java:542)

Body:
I would break up the problem, and stick to regular Clojure syntax instead of trying to re-invent SQL.  Something like this:

(def persons '( {:id 1 :name "olle"}
                {:id 2 :name "anna"}
                {:id 3 :name "isak"}
                {:id 4 :name "beatrice"} ))

(defn id-over-2?
  [person]
  (< 2 (:id person)))

(def persons-2 (filter id-over-2? persons) )

(def persons-3 (sort-by :name persons-2))

with results

persons-2 => ({:id 3, :name "isak"} {:id 4, :name "beatrice"})

persons-3 => ({:id 4, :name "beatrice"} {:id 3, :name "isak"})


问:
How to enable Annotation Processor in Android Studio 2.3
This is the error notification I'm getting

And when I go to the described Location I cant find it

答:
Copy from @Tudor Pop amswer
This is the right answer android-studio-2-3.
You can find the option under File -> Other Settings -> Default Settings -> Build, Execution, Deployment -> Compiler -> Annotation Processors</p>


问:
Program returns all permutations of n elements?infinite loop?
This code should output all permutations of n elements, So when i enter for example 3 Output it must :

ABC
 BAC
 CAB
 ACB
 BCA
 CBA

with this code :

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

void swap(char *x, char *y){
  char temp;
  temp = *x;
  *x = *y;
  *y = temp;
}
void permute(char *a, int l, int r){
  int i;
  if (l == r)
    printf("%s\n", a);
  else
  {
    for (i = l; i <= r; i++){
      swap((a+l), (a+i));
      permute(a, l+1, r);
      swap((a+l), (a+i));

    }
  }
}
int main(){
  int x , n ;
  int i = 0 ;
  char str[26];
  printf("prem ");
  scanf("%d",&x);
  while (x > 0){
    str[i] = 'A' + i ;
    i++;
    x--;
  }
  n = strlen(str);
  permute(str, 0, n-1);

}
</code>```

I should type what I want for a number eg 3 for ABC or 4 for ABCD and then the code should handle that but it didnt workea and it goes in an infinite loop

but for this Code  :

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

void swap(char *x, char *y){
  char temp;
  temp = *x;
  *x = *y;
  *y = temp;
}
void permute(char *a, int l, int r){
  int i;
  if (l == r)
    printf("%s\n", a);
  else
  {
    for (i = l; i <= r; i++){
      swap((a+l), (a+i));
      permute(a, l+1, r);
      swap((a+l), (a+i));

    }
  }
}
int main()
{
  char str[26];
  gets(str);
  int n = strlen(str);
  permute(str, 0, n-1);
  return 0;
}
</code>```

I can enter whatever i want and it handle with it without Problem

my question is what is the problem with the first code? i mean i want to enter a number so that the program: if i type 3 for example it should deal with ABC

答:
The problem is that strlen is invoked on a string which is not terminated.

Either add '\0' at the end of the string to terminal it:

```<code>while (x > 0){
    str[i] = 'A' + i ;
    i++;
    x--;
}
str[i] = '\0';
</code>```

OR (better)

invoke permute with the original value of x (save it after the scanf).

Body:
This code should output all permutations of n elements, So when i enter for example 3 Output it must :

ABC
 BAC
 CAB
 ACB
 BCA
 CBA

with this code :

#include <stdio.h>
#include <string.h>

void swap(char *x, char *y){
  char temp;
  temp = *x;
  *x = *y;
  *y = temp;
}
void permute(char *a, int l, int r){
  int i;
  if (l == r)
    printf("%s\n", a);
  else
  {
    for (i = l; i <= r; i++){
      swap((a+l), (a+i));
      permute(a, l+1, r);
      swap((a+l), (a+i));

    }
  }
}
int main(){
  int x , n ;
  int i = 0 ;
  char str[26];
  printf("prem ");
  scanf("%d",&x);
  while (x > 0){
    str[i] = 'A' + i ;
    i++;
    x--;
  }
  n = strlen(str);
  permute(str, 0, n-1);

}

I should type what I want for a number eg 3 for ABC or 4 for ABCD and then the code should handle that but it didnt workea and it goes in an infinite loop

but for this Code  :

#include <stdio.h>
#include <string.h>

void swap(char *x, char *y){
  char temp;
  temp = *x;
  *x = *y;
  *y = temp;
}
void permute(char *a, int l, int r){
  int i;
  if (l == r)
    printf("%s\n", a);
  else
  {
    for (i = l; i <= r; i++){
      swap((a+l), (a+i));
      permute(a, l+1, r);
      swap((a+l), (a+i));

    }
  }
}
int main()
{
  char str[26];
  gets(str);
  int n = strlen(str);
  permute(str, 0, n-1);
  return 0;
}

I can enter whatever i want and it handle with it without Problem

my question is what is the problem with the first code? i mean i want to enter a number so that the program: if i type 3 for example it should deal with ABC

Body:
The problem is that strlen is invoked on a string which is not terminated.

Either add '\0' at the end of the string to terminal it:

while (x > 0){
    str[i] = 'A' + i ;
    i++;
    x--;
}
str[i] = '\0';

OR (better)

invoke permute with the original value of x (save it after the scanf).


问:
Convert hexadecimal into unicode character
In C++, I would like to save hexadecimal string into file as unicode character
Ex: 0x4E3B save to file ---> 主

Any suggestions or ideas are appreciated.

答:
What encoding? I assume UTF-8.

What platform?

If you under Linux then

```<code>std::locale loc("en_US.UTF-8"); // or "" for system default
std::wofstream file;
file.imbue(loc); // make the UTF-8 locale for the stream as default
file.open("file.txt");
wchar_t cp = 0x4E3B;
file << cp;
</code>```

However if you need Windows it is quite different story:

You need to convert code point to UTF-8. Many ways. If it is bigger then 0xFFFF then convert it to UTF-16 and then search how to use WideCharToMultiByte, and then save to file.

Body:
What encoding? I assume UTF-8.

What platform?

If you under Linux then

std::locale loc("en_US.UTF-8"); // or "" for system default
std::wofstream file;
file.imbue(loc); // make the UTF-8 locale for the stream as default
file.open("file.txt");
wchar_t cp = 0x4E3B;
file << cp;

However if you need Windows it is quite different story:

You need to convert code point to UTF-8. Many ways. If it is bigger then 0xFFFF then convert it to UTF-16 and then search how to use WideCharToMultiByte, and then save to file.


问:
Prometheus auto discovery K8s
Can someone guide the configuration for auto discover for K8s. The Prometheus server is outside of the cluster. I tried Service Discovery With Kubernetes and someone mentioned in this discussion

I'm not yet a K8s expert enough to explain all the details here, but
  fundamentally it's perfectly possible to run Prometheus outside of the
  cluster (and required for things like redundant cross-cluster
  meta-monitoring). Cf. the in_cluster config option in
  http://prometheus.io/docs/operating/configuration/#kubernetes-sd-configurations-kubernetes_sd_config
  . You need to jump through certificate hoops if you run it outside.

So, I made a simple configuration

```<code>  - job_name: 'kubernetes'

    kubernetes_sd_configs:
      -
        # The API server addresses. In a cluster this will normally be
        # `https://kubernetes.default.svc`. Supports multiple HA API servers.
        api_servers:
          - https://xxx.xx.xx.xx

        # Run in cluster. This will use the automounted CA certificate and bearer
        # token file at /var/run/secrets/kubernetes.io/serviceaccount/ in the pod.
        in_cluster: false

        # Optional HTTP basic authentication information.
        basic_auth:
        username: prometheus
        password: secret

        # Retry interval between watches if they disconnect.
        retry_interval: 5s
</code>```

Getting unknown fields in kubernetes_sd_config: api_servers, in_cluster, retry_interval" or some other indentation errors

In sample configuration, they mentioned ca_file:. How to get that certificate file from K8s or is there any way to specify K8s config file(~/.kube/config)

答:
By digging though the source code I figured out, that Prometheus always uses the in cluster config, if no api_server is provided in the config  (discovery/kubernetes/kubernetes.go#L90-L96).

Somehow the docs don't say anything about the Kubernetes configuration parameters, but the source code does (config/config.go#L1026-L1037). Therefore there is not list named api_servers, but a single parameter named api_server.

So your config should look like this (untested):

```<code>  - job_name: 'kubernetes'

    kubernetes_sd_configs:
      -
        # The API server addresses. In a cluster this will normally be
        # `https://kubernetes.default.svc`. Supports multiple HA API servers.
        api_server: https://xxx.xx.xx.xx

        # Optional HTTP basic authentication information.
        basic_auth:
          username: prometheus
          password: secret

        # specify the CA
        tls_config:
          ca_file: /path/to/ca.crt
          ## If the actual CA file isn't available you need to disable verification:
          # insecure_skip_verify: true
</code>```

I don't know where the retry_interval parameter comes from, but AFAIK this isn't a Kubernetes config parameter and it's also not part of the Prometheus config.

Title: Prometheus auto discovery K8s

Body:
Can someone guide the configuration for auto discover for K8s. The Prometheus server is outside of the cluster. I tried Service Discovery With Kubernetes and someone mentioned in this discussion

I'm not yet a K8s expert enough to explain all the details here, but
  fundamentally it's perfectly possible to run Prometheus outside of the
  cluster (and required for things like redundant cross-cluster
  meta-monitoring). Cf. the in_cluster config option in
  http://prometheus.io/docs/operating/configuration/#kubernetes-sd-configurations-kubernetes_sd_config
  . You need to jump through certificate hoops if you run it outside.

So, I made a simple configuration

  - job_name: 'kubernetes'

    kubernetes_sd_configs:
      -
        # The API server addresses. In a cluster this will normally be
        # `https://kubernetes.default.svc`. Supports multiple HA API servers.
        api_servers:
          - https://xxx.xx.xx.xx

        # Run in cluster. This will use the automounted CA certificate and bearer
        # token file at /var/run/secrets/kubernetes.io/serviceaccount/ in the pod.
        in_cluster: false

        # Optional HTTP basic authentication information.
        basic_auth:
        username: prometheus
        password: secret

        # Retry interval between watches if they disconnect.
        retry_interval: 5s

Getting unknown fields in kubernetes_sd_config: api_servers, in_cluster, retry_interval" or some other indentation errors

In sample configuration, they mentioned ca_file:. How to get that certificate file from K8s or is there any way to specify K8s config file(~/.kube/config)

Body:
By digging though the source code I figured out, that Prometheus always uses the in cluster config, if no api_server is provided in the config  (discovery/kubernetes/kubernetes.go#L90-L96).

Somehow the docs don't say anything about the Kubernetes configuration parameters, but the source code does (config/config.go#L1026-L1037). Therefore there is not list named api_servers, but a single parameter named api_server.

So your config should look like this (untested):

  - job_name: 'kubernetes'

    kubernetes_sd_configs:
      -
        # The API server addresses. In a cluster this will normally be
        # `https://kubernetes.default.svc`. Supports multiple HA API servers.
        api_server: https://xxx.xx.xx.xx

        # Optional HTTP basic authentication information.
        basic_auth:
          username: prometheus
          password: secret

        # specify the CA
        tls_config:
          ca_file: /path/to/ca.crt
          ## If the actual CA file isn't available you need to disable verification:
          # insecure_skip_verify: true

I don't know where the retry_interval parameter comes from, but AFAIK this isn't a Kubernetes config parameter and it's also not part of the Prometheus config.


问:
C++: Using pair of (cpp_int, int) integers as key in unordered_map (where cpp_int are boost multiprecision integers)
For my unordered map I would like to use as keys pairs of (cpp_int, int) where cpp_int are boost multiprecision integers:

```<code>#include <boost/multiprecision/cpp_int.hpp>
#include <unordered_map>

using boost::multiprecision::cpp_int;

std::unordered_map<std::pair<cpp_int, int>, double> myMap
</code>```

Searching on this site I have found many suggestions of using a custom hash function for std::pair<int,int> as keys, but I couldn't found how to deal with std::pair<cpp_int, int>.

Update: To clarify, I have tried a hash function I found on the web (for (int,int):

```<code>#include <boost/multiprecision/cpp_int.hpp>
#include <unordered_map>
using boost::multiprecision::cpp_int;
typedef std::pair<cpp_int, int> MyPair;

struct MyHash {
public:
        size_t operator()(MyPair x) const throw() {
             size_t h = x.first * 1 + x.second * 100000;
             return h;
        }
};

void function()
{
    std::unordered_map<MyPair, double, MyHash> M;
}
</code>```

This doesn't compile:

```<code>error: cannot convert ‘boost::enable_if_c<true, boost::multiprecision::detail::expression<boost::multiprecision::detail::multiply_add, boost::multiprecision::detail::expression<boost::multiprecision::detail::terminal, boost::multiprecision::number<boost::multiprecision::backends::cpp_int_backend<> >, void, void, void>, boost::multiprecision::detail::expression<boost::multiprecision::detail::terminal, int, void, void, void>, int, void> >::type {aka boost::multiprecision::detail::expression<boost::multiprecision::detail::multiply_add, boost::multiprecision::detail::expression<boost::multiprecision::detail::terminal, boost::multiprecision::number<boost::multiprecision::backends::cpp_int_backend<> >, void, void, void>, boost::multiprecision::detail::expression<boost::multiprecision::detail::terminal, int, void, void, void>, int, void>}’ to ‘size_t {aka long unsigned int}’ in initialization
              size_t h = x.first * 1 + x.second * 100000;
                                                  ^
</code>```

My question is: how to use pairs of (cpp_int,int) as keys in an unordered_map?

Thank you very much in advance!

Update 2:
Thanks to @sehe for pointing me to his answer (in which he provided a hash function for cpp_int). Combining with this answer (which shows how to combine two hash functions for a pair), I've come up with the following solution (it compiles fine, I'll need to test on my problem to see if it works):

```<code>#include <boost/archive/binary_oarchive.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/cpp_int/serialize.hpp>
#include <boost/iostreams/device/back_inserter.hpp>
#include <boost/iostreams/stream_buffer.hpp>
#include <boost/iostreams/stream.hpp>

#include <boost/functional/hash.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <unordered_map>

using boost::multiprecision::cpp_int;

typedef std::pair<cpp_int, int> MyPair;

namespace mp_hashing {
    namespace io = boost::iostreams;

    struct hash_sink {
        hash_sink(size_t& seed_ref) : _ptr(&seed_ref) {}

        typedef char         char_type;
        typedef io::sink_tag category;

        std::streamsize write(const char* s, std::streamsize n) {
            boost::hash_combine(*_ptr, boost::hash_range(s, s+n));
            return n;
        }
      private:
        size_t* _ptr;
    };

    template <typename T> struct hash_impl {
        size_t operator()(T const& v) const {
            using namespace boost;
            size_t seed = 0;
            {
                iostreams::stream<hash_sink> os(seed);
                archive::binary_oarchive oa(os, archive::no_header | archive::no_codecvt);
                oa << v;
            }
            return seed;
        }
    };
}

namespace std {
    template <typename backend>
    struct hash<boost::multiprecision::number<backend> >
        : mp_hashing::hash_impl<boost::multiprecision::number<backend> >
    {};
}

struct pair_hash {
    template <class T1, class T2>
    std::size_t operator () (const std::pair<T1,T2> &p) const {
        auto h1 = std::hash<T1>{}(p.first);
        auto h2 = std::hash<T2>{}(p.second);

        // Mainly for demonstration purposes, i.e. works but is overly simple
        // In the real world, use sth. like boost.hash_combine
        return h1 ^ h2;
    }
};

void function()
    {
        std::unordered_map<MyPair, double, pair_hash> M;
    }
</code>```

答:
Yes, you took the Multiprecision hash I contributed earlier and added the hash for std::pair. I'm not a fan of handrolling the hash combination (good general hash combination is not trivial).

So I'd do the same with boost::hash_combine:

```<code>template <typename K, typename V>
struct hash<std::pair<K, V> >
{
    size_t operator()(std::pair<K, V> const& pair) const {
        size_t seed = std::hash<K>{}(pair.first);
        boost::hash_combine(seed, pair.second);
        return seed;
    }
};
</code>```

Live On MSVC RexTester

```<code>#include <iostream>
#include <iomanip>

#include <boost/archive/binary_oarchive.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/cpp_int/serialize.hpp>
#include <boost/iostreams/device/back_inserter.hpp>
#include <boost/iostreams/stream_buffer.hpp>
#include <boost/iostreams/stream.hpp>

#include <boost/functional/hash.hpp>

namespace mp_hashing {
    namespace io = boost::iostreams;

    struct hash_sink {
        hash_sink(size_t& seed_ref) : _ptr(&seed_ref) {}

        typedef char         char_type;
        typedef io::sink_tag category;

        std::streamsize write(const char* s, std::streamsize n) {
            boost::hash_combine(*_ptr, boost::hash_range(s, s+n));
            return n;
        }
      private:
        size_t* _ptr;
    };

    template <typename T> struct hash_impl {
        size_t operator()(T const& v) const {
            using namespace boost;
            size_t seed = 0;
            {
                iostreams::stream<hash_sink> os(seed);
                archive::binary_oarchive oa(os, archive::no_header | archive::no_codecvt);
                oa << v;
            }
            return seed;
        }
    };
}

#include <unordered_map>
#include <boost/unordered_map.hpp>

namespace std {
    template <typename backend>
    struct hash<boost::multiprecision::number<backend> >
        : mp_hashing::hash_impl<boost::multiprecision::number<backend> >
    {};

    template <typename K, typename V>
    struct hash<std::pair<K, V> >
    {
        size_t operator()(std::pair<K, V> const& pair) const {
            size_t seed = std::hash<K>{}(pair.first);
            boost::hash_combine(seed, pair.second);
            return seed;
        }
    };
}

int main() {
    using boost::multiprecision::cpp_int;

    std::unordered_map<std::pair<cpp_int, int>, int>  m {
        { { cpp_int(1) << 111, -1 }, 1 },
        { { cpp_int(2) << 222, -2 }, 2 },
        { { cpp_int(3) << 333, -3 }, 3 },
    };

    for (auto& p : m)
        std::cout << p.first.first << " -> " << p.second << "\n";
}
</code>```

Body:
For my unordered map I would like to use as keys pairs of (cpp_int, int) where cpp_int are boost multiprecision integers:

#include <boost/multiprecision/cpp_int.hpp>
#include <unordered_map>

using boost::multiprecision::cpp_int;

std::unordered_map<std::pair<cpp_int, int>, double> myMap

Searching on this site I have found many suggestions of using a custom hash function for std::pair<int,int> as keys, but I couldn't found how to deal with std::pair<cpp_int, int>.

Update: To clarify, I have tried a hash function I found on the web (for (int,int):

#include <boost/multiprecision/cpp_int.hpp>
#include <unordered_map>
using boost::multiprecision::cpp_int;
typedef std::pair<cpp_int, int> MyPair;

struct MyHash {
public:
        size_t operator()(MyPair x) const throw() {
             size_t h = x.first * 1 + x.second * 100000;
             return h;
        }
};

void function()
{
    std::unordered_map<MyPair, double, MyHash> M;
}

This doesn't compile:

error: cannot convert ‘boost::enable_if_c<true, boost::multiprecision::detail::expression<boost::multiprecision::detail::multiply_add, boost::multiprecision::detail::expression<boost::multiprecision::detail::terminal, boost::multiprecision::number<boost::multiprecision::backends::cpp_int_backend<> >, void, void, void>, boost::multiprecision::detail::expression<boost::multiprecision::detail::terminal, int, void, void, void>, int, void> >::type {aka boost::multiprecision::detail::expression<boost::multiprecision::detail::multiply_add, boost::multiprecision::detail::expression<boost::multiprecision::detail::terminal, boost::multiprecision::number<boost::multiprecision::backends::cpp_int_backend<> >, void, void, void>, boost::multiprecision::detail::expression<boost::multiprecision::detail::terminal, int, void, void, void>, int, void>}’ to ‘size_t {aka long unsigned int}’ in initialization
              size_t h = x.first * 1 + x.second * 100000;
                                                  ^

My question is: how to use pairs of (cpp_int,int) as keys in an unordered_map?

Thank you very much in advance!

Update 2:
Thanks to @sehe for pointing me to his answer (in which he provided a hash function for cpp_int). Combining with this answer (which shows how to combine two hash functions for a pair), I've come up with the following solution (it compiles fine, I'll need to test on my problem to see if it works):

#include <boost/archive/binary_oarchive.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/cpp_int/serialize.hpp>
#include <boost/iostreams/device/back_inserter.hpp>
#include <boost/iostreams/stream_buffer.hpp>
#include <boost/iostreams/stream.hpp>

#include <boost/functional/hash.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <unordered_map>

using boost::multiprecision::cpp_int;

typedef std::pair<cpp_int, int> MyPair;

namespace mp_hashing {
    namespace io = boost::iostreams;

    struct hash_sink {
        hash_sink(size_t& seed_ref) : _ptr(&seed_ref) {}

        typedef char         char_type;
        typedef io::sink_tag category;

        std::streamsize write(const char* s, std::streamsize n) {
            boost::hash_combine(*_ptr, boost::hash_range(s, s+n));
            return n;
        }
      private:
        size_t* _ptr;
    };

    template <typename T> struct hash_impl {
        size_t operator()(T const& v) const {
            using namespace boost;
            size_t seed = 0;
            {
                iostreams::stream<hash_sink> os(seed);
                archive::binary_oarchive oa(os, archive::no_header | archive::no_codecvt);
                oa << v;
            }
            return seed;
        }
    };
}

namespace std {
    template <typename backend>
    struct hash<boost::multiprecision::number<backend> >
        : mp_hashing::hash_impl<boost::multiprecision::number<backend> >
    {};
}

struct pair_hash {
    template <class T1, class T2>
    std::size_t operator () (const std::pair<T1,T2> &p) const {
        auto h1 = std::hash<T1>{}(p.first);
        auto h2 = std::hash<T2>{}(p.second);

        // Mainly for demonstration purposes, i.e. works but is overly simple
        // In the real world, use sth. like boost.hash_combine
        return h1 ^ h2;
    }
};

void function()
    {
        std::unordered_map<MyPair, double, pair_hash> M;
    }

Body:
Yes, you took the Multiprecision hash I contributed earlier and added the hash for std::pair. I'm not a fan of handrolling the hash combination (good general hash combination is not trivial).

So I'd do the same with boost::hash_combine:

template <typename K, typename V>
struct hash<std::pair<K, V> >
{
    size_t operator()(std::pair<K, V> const& pair) const {
        size_t seed = std::hash<K>{}(pair.first);
        boost::hash_combine(seed, pair.second);
        return seed;
    }
};

Live On MSVC RexTester

#include <iostream>
#include <iomanip>

#include <boost/archive/binary_oarchive.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/cpp_int/serialize.hpp>
#include <boost/iostreams/device/back_inserter.hpp>
#include <boost/iostreams/stream_buffer.hpp>
#include <boost/iostreams/stream.hpp>

#include <boost/functional/hash.hpp>

namespace mp_hashing {
    namespace io = boost::iostreams;

    struct hash_sink {
        hash_sink(size_t& seed_ref) : _ptr(&seed_ref) {}

        typedef char         char_type;
        typedef io::sink_tag category;

        std::streamsize write(const char* s, std::streamsize n) {
            boost::hash_combine(*_ptr, boost::hash_range(s, s+n));
            return n;
        }
      private:
        size_t* _ptr;
    };

    template <typename T> struct hash_impl {
        size_t operator()(T const& v) const {
            using namespace boost;
            size_t seed = 0;
            {
                iostreams::stream<hash_sink> os(seed);
                archive::binary_oarchive oa(os, archive::no_header | archive::no_codecvt);
                oa << v;
            }
            return seed;
        }
    };
}

#include <unordered_map>
#include <boost/unordered_map.hpp>

namespace std {
    template <typename backend>
    struct hash<boost::multiprecision::number<backend> >
        : mp_hashing::hash_impl<boost::multiprecision::number<backend> >
    {};

    template <typename K, typename V>
    struct hash<std::pair<K, V> >
    {
        size_t operator()(std::pair<K, V> const& pair) const {
            size_t seed = std::hash<K>{}(pair.first);
            boost::hash_combine(seed, pair.second);
            return seed;
        }
    };
}

int main() {
    using boost::multiprecision::cpp_int;

    std::unordered_map<std::pair<cpp_int, int>, int>  m {
        { { cpp_int(1) << 111, -1 }, 1 },
        { { cpp_int(2) << 222, -2 }, 2 },
        { { cpp_int(3) << 333, -3 }, 3 },
    };

    for (auto& p : m)
        std::cout << p.first.first << " -> " << p.second << "\n";
}


问:
Will the game lag if data is processed and called from a different language?
I am creating a game with my friends and we are using XNA C# monogame to build it. My question is if the game will lag a lot if we use different languages to process data. My friends know python and javascript well and all I know is C#. We decided to use monogame for graphics and use the languages to process the data. An example would be health, if i got hit then data would be sent to the language and then sent back to change the information. Our method is to read from the different programs reading and writing the txt file.  </p>

答: Yes, the game will obviously be slower than if it was done completely within C#. However, writing the data to and from a text file is possibly the worst way to transfer data between languages in a program. Instead, run a sub-process in C#.</p>


问:
iPhone animation based on input values (touches) not time
For an animation effect perfectly suited to an animation group approach as shown in Brad Larson's answer here, I need the animation to proceed according to inputs. Specifically touch and position of detected touches. It is easy to handle touchesMoved: and to set the position of the elements for every touch but it just isn't smooth like the core animation approach.

Imagine a marble in a grooved track. I want to push the marble along to any position at any speed in one direction or the other. The animation has to do something like that, moving a visual element along a path in response to touches. CAKeyframeAnimation has the path bit exactly but seems to always want to base the transition from frame to frame on time elapsed, not on any other factor, and in one direction.

31 January update - Thanks all for the responses so far however none is really solving the problem. I have a circular menu that is dragged to select an option. All of it needs to move together and I have worked around it by using an view that has a rotational transform applied and the inverse rotational transform applied to its subviews so the icons all rotate with appropriate ferris wheel orientation. It really looks better when the icons are animated along a slightly ovoid path though... the marble description is an attempt to make clear what I'm trying to do. Better perhaps to imagine magnets oriented to repel all travelling in a groove - move one and its neighbours move too but not necessarily in the direction that the dragged magnet moves as the path curves.

Right now the problem is one of following a simple path created with one circle but I'd really like to know how to animate objects along an arbitrary path, position controlled purely by touch with no calculations involving velocity or direction.

答: velocity = distance/time. You can try by giving delay according to touches moved and time. You can calculate time between touchesBegan and touchesEnded methods.</p>


答:
The issue is that the str string is not properly terminated therefore result of n = strlen(str); is undefined. strlen counts characters till \0 is encountered.

```<code>int main(){
int x , n ;
int i = 0 ;
char str[26];
printf("prem ");
scanf("%d",&x);
while (x > 0){
    str[i] = 'A' + i ;
    i++;
    x--;
}

str[i] = 0; // terminate the string

n = strlen(str);
permute(str, 0, n-1);

}
</code>```

Title: Program returns all permutations of n elements?infinite loop?

Body:
The issue is that the str string is not properly terminated therefore result of n = strlen(str); is undefined. strlen counts characters till \0 is encountered.

int main(){
int x , n ;
int i = 0 ;
char str[26];
printf("prem ");
scanf("%d",&x);
while (x > 0){
    str[i] = 'A' + i ;
    i++;
    x--;
}

str[i] = 0; // terminate the string

n = strlen(str);
permute(str, 0, n-1);

}


问:
I have converted stringbuffer to strings but how to convert string to unicode int?
I can see emojis if I enter unicode directly and convert it to String with a method like:

```<code>int intUnicode = 0x1F601;

public String getEmojiByUnicode(int unicode) {
    return new String(Character.toChars(unicode));
}
</code>```

But I just can't wrap my head around how to convert when the unicode value is a String like:

```<code>String strUnicode = "0xf601";
</code>```

How to covert it to an Integer like I did it directly. When I try to use Integer.parseInt(strUnicode) compiler throws an error every time.

```<code>InputStream is = assetManager.open("emoji_unicode.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
if (is != null){
    try {
        while ((data = reader.readLine()) != null){
            sbuffer.append(data + "\n");
            String j = sbuffer.toString().trim();
            int k = Integer.parseInt(j,16);
            String l = getEmojiByUnicode(k);
            emoArray.add(l);
        }
        btn.setText(emoArray.get(5));
        is.close();
    }catch (IOException e){
        e.printStackTrace();
    }
}
</code>```

It's not very hard, I know I'm very close but still it won't get to me. Any help would be very appreciated.
Regard

答:
You're attempting to parse a hex string (unicode "encodings" are hexadecimal numbers), and Integer.parseInt() has some odd limits for doing so. Take a look at this answer:

Parsing a Hexadecimal String to an Integer throws a NumberFormatException?

Body:
I can see emojis if I enter unicode directly and convert it to String with a method like:

int intUnicode = 0x1F601;

public String getEmojiByUnicode(int unicode) {
    return new String(Character.toChars(unicode));
}

But I just can't wrap my head around how to convert when the unicode value is a String like:

String strUnicode = "0xf601";

How to covert it to an Integer like I did it directly. When I try to use Integer.parseInt(strUnicode) compiler throws an error every time.

InputStream is = assetManager.open("emoji_unicode.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
if (is != null){
    try {
        while ((data = reader.readLine()) != null){
            sbuffer.append(data + "\n");
            String j = sbuffer.toString().trim();
            int k = Integer.parseInt(j,16);
            String l = getEmojiByUnicode(k);
            emoArray.add(l);
        }
        btn.setText(emoArray.get(5));
        is.close();
    }catch (IOException e){
        e.printStackTrace();
    }
}

It's not very hard, I know I'm very close but still it won't get to me. Any help would be very appreciated.
Regard


问:
Node.js MongoDB Find with projection to exclude _id still returns it
Trying to follow the examples here to filter by using a projection to exclude _id. The _id still returns:

Code

```<code>var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/db1";

MongoClient.connect(url, function (err, db) {
    if (err) throw err;
    var dbase = db.db("db1"); //here

    dbase.collection("customers").find(
        {},
        {
            _id: 0

        }
        ).toArray(function(err, result) {
        if (err) throw err;
        console.log(result);
        db.close();
    });

});
</code>```

Result still return as follows:

[ { _id: 5a2bb2d6ee48575cb54c4365,
      name: 'John',
      address: 'Highway 71' },   { _id: 5a2bb2d6ee48575cb54c436d,
      name: 'Susan',
      address: 'One way 98' },  ....   { _id: 5a2bb2d6ee48575cb54c4371,
      name: 'Chuck',
      address: 'Main Road 989' },   { _id: 5a2bb2d6ee48575cb54c4372,
      name: 'Viola',
      address: 'Sideway 1633' } ]

Theoretically _id should not be part of what is returned. What is wrong here?

答:
To limit the fields you have to use fields option( dont know about new updates):

```<code>dbase.collection("customers").find({}, {
    fields: { _id: 0 }
}).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
    db.close();
});
</code>```

UPDATE:

For version > 3 you have to use projection option instead:

```<code>dbase.collection("customers").find({}, {
    projection:{ _id: 0 }
}).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
    db.close();
});
</code>```

Body:
Trying to follow the examples here to filter by using a projection to exclude _id. The _id still returns:

Code

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/db1";

MongoClient.connect(url, function (err, db) {
    if (err) throw err;
    var dbase = db.db("db1"); //here

    dbase.collection("customers").find(
        {},
        {
            _id: 0

        }
        ).toArray(function(err, result) {
        if (err) throw err;
        console.log(result);
        db.close();
    });

});

Result still return as follows:

[ { _id: 5a2bb2d6ee48575cb54c4365,
      name: 'John',
      address: 'Highway 71' },   { _id: 5a2bb2d6ee48575cb54c436d,
      name: 'Susan',
      address: 'One way 98' },  ....   { _id: 5a2bb2d6ee48575cb54c4371,
      name: 'Chuck',
      address: 'Main Road 989' },   { _id: 5a2bb2d6ee48575cb54c4372,
      name: 'Viola',
      address: 'Sideway 1633' } ]

Theoretically _id should not be part of what is returned. What is wrong here?

Body:
To limit the fields you have to use fields option( dont know about new updates):

dbase.collection("customers").find({}, {
    fields: { _id: 0 }
}).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
    db.close();
});

UPDATE:

For version > 3 you have to use projection option instead:

dbase.collection("customers").find({}, {
    projection:{ _id: 0 }
}).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
    db.close();
});


问:
Visual studio android emulator will not start fully
I create a blank cordova application in visual studio 2015 and start debugging with the visual studio android emulators (first with the lollipop and then kitkat). XDE starts and the screen displays OS is starting.... It stays like that for quite a while until it displays

The emulator is unable to connect to the device operating system;
The device did not response to the connect request.
Some functionalities might be disabled'

After closing the dialog, it stays there forever until I kill the emulator. Killing the emulator triggers an error from visual studio.

Could not start emulated device 'VS Emulator Lollipop Phone'.

When I open hyper-v, I see the vm in the list and shown as running. When I connect, I see the console screen as below

答:
One of the reason I was having this issue is that I did not install the Android SDK on the default location.  So I had to follow these instructions in order to be able to debug my application: https://msdn.microsoft.com/en-us/library/mt228282.aspx#ADB

I had to create the folder "Android SDK Tools" and add the Key "Path" with the value to my SDK, which in my case it was "E:\Android\Android_SDK"


问:
how to obtain the Wireless AP's SSIDs of the network through java?
iam new to java programming and my final year project is based on a Rogue Access point detection tool, and i need to how can i obtain SSID from a java code of the exisiting wifi networks?

for eg: say iam in my laptop i need the program to show how many SSIDs are there broadcasting the SSIDS and the names! (through the built in wifi adapter in the laptop).

Thank you.

答:
Java is a High-Level, Platform-Independent programming language. Network settings, and how you control them will depend on your Operating System, and to my knowledge there is no simple way or an API to expose this,but i tried write a code maybe is helpful for you.

Code :

```<code>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Electron-Eddine
 */
public class Network {

    ArrayList<String> localNetworks = new ArrayList<>();

    public static void main(String[] args) throws IOException {

        new network.Network().display(new Network().getNetwokrs());
        new Network().searchSystemNetwork(new Network().getNetwokrs());
    }

    public ArrayList<String> getNetwokrs() throws IOException {

        ProcessBuilder builder = new ProcessBuilder(
                "cmd.exe", "/c", "netsh wlan show networks mode=Bssid");
        builder.redirectErrorStream(true);
        Process p = builder.start();
        BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String lineCommand;
        String network ;
        while (true) {
            lineCommand = r.readLine();
            if (lineCommand == null) {
                break;
            } else if (lineCommand.contains("SSID")&&!lineCommand.contains("BSSID")) {
                String[] networks = lineCommand.split(":", 2);
                network = networks[1];
                if (!network.equals(" ")) {
                    String pureNetworkName = network.trim();
                    localNetworks.add(pureNetworkName);
                } else {
                    return null;
                }
            }

        }
        return localNetworks;
    }

    private void display(ArrayList<String> networks) {
        networks.forEach(network -> {
            System.out.println(network);
        });
    }

    private void searchSystemNetwork(ArrayList<String> networks) {
        String REQUIRED_NETWORK = "PEER2PEER";
        networks.forEach(network -> {
            if (network.equals(REQUIRED_NETWORK)) {
                System.out.println("Network is availabale");

            } else {

            }
        });
    }
    void create()
    {

     //  Netsh WLAN export profile key=clear folder="Folder_Path"
    }

}
</code>```

Output :

run:

PEER2PEER

condor PGN522

Ammar_A

Network is availabale

BUILD SUCCESSFUL (total time: 1 second)

Body:
Java is a High-Level, Platform-Independent programming language. Network settings, and how you control them will depend on your Operating System, and to my knowledge there is no simple way or an API to expose this,but i tried write a code maybe is helpful for you.

Code :

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Electron-Eddine
 */
public class Network {

    ArrayList<String> localNetworks = new ArrayList<>();

    public static void main(String[] args) throws IOException {

        new network.Network().display(new Network().getNetwokrs());
        new Network().searchSystemNetwork(new Network().getNetwokrs());
    }

    public ArrayList<String> getNetwokrs() throws IOException {

        ProcessBuilder builder = new ProcessBuilder(
                "cmd.exe", "/c", "netsh wlan show networks mode=Bssid");
        builder.redirectErrorStream(true);
        Process p = builder.start();
        BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String lineCommand;
        String network ;
        while (true) {
            lineCommand = r.readLine();
            if (lineCommand == null) {
                break;
            } else if (lineCommand.contains("SSID")&&!lineCommand.contains("BSSID")) {
                String[] networks = lineCommand.split(":", 2);
                network = networks[1];
                if (!network.equals(" ")) {
                    String pureNetworkName = network.trim();
                    localNetworks.add(pureNetworkName);
                } else {
                    return null;
                }
            }

        }
        return localNetworks;
    }

    private void display(ArrayList<String> networks) {
        networks.forEach(network -> {
            System.out.println(network);
        });
    }

    private void searchSystemNetwork(ArrayList<String> networks) {
        String REQUIRED_NETWORK = "PEER2PEER";
        networks.forEach(network -> {
            if (network.equals(REQUIRED_NETWORK)) {
                System.out.println("Network is availabale");

            } else {

            }
        });
    }
    void create()
    {

     //  Netsh WLAN export profile key=clear folder="Folder_Path"
    }

}

Output :

run:

PEER2PEER

condor PGN522

Ammar_A

Network is availabale

BUILD SUCCESSFUL (total time: 1 second)


问:
Unable to sort div Elements using javascript
This is the HTML elements which i am trying to sort

```<code>    <div id="notStarted-tasks">
  <div id="K1512844566066" class="row">
    <div class="span4 offset4 alert alert-warning" style="margin: auto; display: table;"><span style="font-size: 170%">Breakfast</span>
      <button href="#" type="button" class="btn btn-warning">Start</button>
    </div>
  </div>
  <div id="I1512844569230" class="row">
    <div class="span4 offset4 alert alert-warning" style="margin: auto; display: table;"><span style="font-size: 170%">dinner</span>
      <button href="#" type="button" class="btn btn-warning">Start</button>
    </div>
  </div>
</div>
</code>```

And this is my sort function in javascript, in the first "if" block i am just returning if the list is empty. In the second "if" i am doing a descending sort and in the "else" ascending sort.

```<code>const todoSort = () =>{
    if(notStartedElement.length==0)
            return;
    if(todoCurrent=="asc"){
        document.getElementById("todoSort").setAttribute("src","src/image/desc.png");
        todoCurrent="desc";
        const ele = document.getElementById("notStarted-tasks");
        const divEle = ele.getElementsByClassName("row");
        divEle.sort(function(a,b){
            let spana = a.getElementsByTagName("span")[0];
            let spanb = b.getElementsByTagName("span")[0];
            return spana.innerHTML == spanb.innerHTML? 0 : (spana.innerHTML > spanb.innerHTML ? -1 : 1);
        });
        ele.innerHTML="";
        for(let i = 0;i<divEle.length;i++)
            ele.appendChild(divEle[i]);
    }
    else{
        document.getElementById("todoSort").setAttribute("src","src/image/asc.png");
        todoCurrent="asc";
        const ele = document.getElementById("notStarted-tasks");
        const divEle = ele.getElementsByClassName("row");
        divEle.sort(function(a,b){
            let spana = a.getElementsByTagName("span")[0];
            let spanb = b.getElementsByTagName("span")[0];
            return spana.innerHTML == spanb.innerHTML? 0 : (spana.innerHTML > spanb.innerHTML ? 1 : -1);
        });
        ele.innerHTML="";
        for(let i = 0;i<divEle.length;i++)
            ele.appendChild(divEle[i]);
    }
}
</code>```

When i click on my sort button i get this message "Uncaught TypeError: divEle.sort is not a function". And i need this to be done only in javascript and i am not allowed to use jquery. So, can anybody point me out what am i doing wrong here ?
Thank you

答:
getElementsByClassName returns a HTMLCollection and you need a Array to use sort.

You can easily make it into an array like this:

```<code>var collection = document.getElementsByClassName("some-class");
var array = [];
for (var x = 0; x < collection.length; x++) {
    array.push(collection[x]);
}
array.sort(...);
</code>```

Body:
This is the HTML elements which i am trying to sort

Breakfast
      <button href="#" type="button" class="btn btn-warning">Start</button>

dinner
      <button href="#" type="button" class="btn btn-warning">Start</button>

And this is my sort function in javascript, in the first "if" block i am just returning if the list is empty. In the second "if" i am doing a descending sort and in the "else" ascending sort.

const todoSort = () =>{
    if(notStartedElement.length==0)
            return;
    if(todoCurrent=="asc"){
        document.getElementById("todoSort").setAttribute("src","src/image/desc.png");
        todoCurrent="desc";
        const ele = document.getElementById("notStarted-tasks");
        const divEle = ele.getElementsByClassName("row");
        divEle.sort(function(a,b){
            let spana = a.getElementsByTagName("span")[0];
            let spanb = b.getElementsByTagName("span")[0];
            return spana.innerHTML == spanb.innerHTML? 0 : (spana.innerHTML > spanb.innerHTML ? -1 : 1);
        });
        ele.innerHTML="";
        for(let i = 0;i<divEle.length;i++)
            ele.appendChild(divEle[i]);
    }
    else{
        document.getElementById("todoSort").setAttribute("src","src/image/asc.png");
        todoCurrent="asc";
        const ele = document.getElementById("notStarted-tasks");
        const divEle = ele.getElementsByClassName("row");
        divEle.sort(function(a,b){
            let spana = a.getElementsByTagName("span")[0];
            let spanb = b.getElementsByTagName("span")[0];
            return spana.innerHTML == spanb.innerHTML? 0 : (spana.innerHTML > spanb.innerHTML ? 1 : -1);
        });
        ele.innerHTML="";
        for(let i = 0;i<divEle.length;i++)
            ele.appendChild(divEle[i]);
    }
}

When i click on my sort button i get this message "Uncaught TypeError: divEle.sort is not a function". And i need this to be done only in javascript and i am not allowed to use jquery. So, can anybody point me out what am i doing wrong here ?
Thank you

Body:
getElementsByClassName returns a HTMLCollection and you need a Array to use sort.

You can easily make it into an array like this:

var collection = document.getElementsByClassName("some-class");
var array = [];
for (var x = 0; x < collection.length; x++) {
    array.push(collection[x]);
}
array.sort(...);