问:
What does YouTube mean when they say "key" in their documentation?
In the YouTube reference documentation found here:

https://developers.google.com/youtube/v3/docs/

It says:

"Every request must either specify an API key (with the key parameter)"

However, the language that is used in the Google Developer Console, they call credentials "Client ID" and "Client Secret"

Which one do they mean? Or are they talking about something completely different when they say "key?"

答:
The key that the document is referring to is the API key. As stated in the link that you have provided:

Every request must either specify an API key (with the key parameter) or provide an OAuth 2.0 token.

If you will be accessing user's private data or simply insert, update, and delete request OAuth 2.0 (clientID and client secret) must be use.

One example would be Videos: insert.

If you just list videos using search keyword, request for a method that do not need to identify a particular user, you can use an application API key.

```<code>https://www.googleapis.com/youtube/v3/videos?key={API-key}&fields=items(snippet(title,description,tags))&part=snippet&id={video_id}
</code>```

Hope this helps.

Body:
The key that the document is referring to is the API key. As stated in the link that you have provided:

Every request must either specify an API key (with the key parameter) or provide an OAuth 2.0 token.

If you will be accessing user's private data or simply insert, update, and delete request OAuth 2.0 (clientID and client secret) must be use.

One example would be Videos: insert.

If you just list videos using search keyword, request for a method that do not need to identify a particular user, you can use an application API key.

https://www.googleapis.com/youtube/v3/videos?key={API-key}&fields=items(snippet(title,description,tags))&part=snippet&id={video_id}

Hope this helps.


来源: stackexchange

问:
C# control browser
Please suggest how can write c# to control browser to go to url and auto fill in specific element</p>

答:
Use WatiN project to open browser, go to specific page and do the appropriate. Primarily this is a web testing automation tool, but you could (ab)use it for other things as well.

http://watin.sourceforge.net/

ContentLicense: CC BY-SA 2.5

Title: C# control browser


问:
before_save except on new record if field value changes
I need to execute a hook in a rails4 app if a field changes and only if its not a record record.

I know I can do...

```<code>  before_save :reset_confirmation, if: :email_changed?
  def reset_confirmation
    self.confirmed_at = nil
    self.confirmation_sent_at = nil
  end
</code>```

and I'm pretty sure this works...

```<code>  before_save :reset_confirmation, unless: new_record?
  def reset_confirmation
    self.confirmed_at = nil
    self.confirmation_sent_at = nil
  end
</code>```

but how do I combine the two, or is there an easier way to achieve what I want and I'm overthinking things. The field (email) will always contains a value after it's been created if that helps?

答:
I went with this in the end...

```<code>  before_update :reset_confirmation, if: :email_changed?
  def reset_confirmation
    self.confirmed_at = nil
    self.confirmation_sent_at = nil
  end
</code>```

with the logic being that before_update only runs on existing records, which takes care of the new record issue, and now it doesn't step into the method unless the condition has been met to reset the fields anyway.

ContentLicense: CC BY-SA 3.0

Body:
I need to execute a hook in a rails4 app if a field changes and only if its not a record record.

I know I can do...

  before_save :reset_confirmation, if: :email_changed?
  def reset_confirmation
    self.confirmed_at = nil
    self.confirmation_sent_at = nil
  end

and I'm pretty sure this works...

  before_save :reset_confirmation, unless: new_record?
  def reset_confirmation
    self.confirmed_at = nil
    self.confirmation_sent_at = nil
  end

but how do I combine the two, or is there an easier way to achieve what I want and I'm overthinking things. The field (email) will always contains a value after it's been created if that helps?

Body:
I went with this in the end...

  before_update :reset_confirmation, if: :email_changed?
  def reset_confirmation
    self.confirmed_at = nil
    self.confirmation_sent_at = nil
  end

with the logic being that before_update only runs on existing records, which takes care of the new record issue, and now it doesn't step into the method unless the condition has been met to reset the fields anyway.


问:
size of array of integer pointers
```<code>#include<stdio.h>
#include<conio.h>

void main()
{
  int a[5]={1,2,3,4,5};
  int (*p)[5];
  int *p1[5];
  clrscr();

  printf("%d\n",(int)sizeof(a)); // 10
  printf("%d\n",(int)sizeof(p));  //2
  printf("%d\n",(int)sizeof(p1)); //10
  getch();
}
</code>```

First output is 10 because each integer is of 2 bytes and hence 5 integers would take 10 bytes.

I am not able to understand the 3rd output which is 10. Here we have array of pointers each pointing to an integer. Size of pointer(or address) in my system is 32 bits (4 Bytes) . So the output should be 5*4=20 right as we have 5 pointers each of 4 bytes ?

答:
Size of pointer(or address) in my system is 32 bits

Turbo C++ is an MS-DOS program. It's unable to run on a modern OS directly. Your OS creates, in a way completely transparent to you, an emulated 16-bit MS-DOS machine to run your outdated stuff on. So no, the size of pointers on your (emulated) system is 16 bits. You are using a 16-bit system.

Turbo C++ is actually capable of using 32-bit pointers if you switch code generation to "large" or "huge" mode. The system is still a 16-bit one, it just has a weird addressing scheme with "long" pointers.

On a side note, using Turbo C++ in this current millennium is not recommended (warning: shameless plug).

Title: size of array of integer pointers

Body:
#include<stdio.h>
#include<conio.h>

void main()
{
  int a[5]={1,2,3,4,5};
  int (*p)[5];
  int *p1[5];
  clrscr();

  printf("%d\n",(int)sizeof(a)); // 10
  printf("%d\n",(int)sizeof(p));  //2
  printf("%d\n",(int)sizeof(p1)); //10
  getch();
}

First output is 10 because each integer is of 2 bytes and hence 5 integers would take 10 bytes.

I am not able to understand the 3rd output which is 10. Here we have array of pointers each pointing to an integer. Size of pointer(or address) in my system is 32 bits (4 Bytes) . So the output should be 5*4=20 right as we have 5 pointers each of 4 bytes ?


问:
Using PreparedStatement in Try with Resources shows 'unknown class' error
I am initialising a prepared statement globally (so it isn't pre-compiled everytime a function is run, only when the application is loaded), and attempting to use the preparedstatement in a try with resources, but it is showing an 'unknown class' error. This is the code:

```<code>private PreparedStatement ingredientDelete;

public void deleteIngredient(String name) {
    try(ingredientDelete = con.prepareStatement(DELETE_INGREDIENT_BY_NAME)){
        ingredientDelete.setString(1, name);
        ingredientDelete.execute();

    }catch(SQLException e){
        System.out.println("Delete failed - " + e.getMessage());

    }
}
</code>```

For clarity the connection is opened in another method and also declared globally.

答:
That isn't valid Java. The resourced declared in the try must be local variables, and thus have their type declared. See the JLS

```<code>Resource:
    VariableModifiersopt Type VariableDeclaratorId = Expression
</code>```

Making it a field doesn't make sense anyway, since a statement is bound to a connection, and since you're re-creating it every time the method is called anyway, thus potentially using the same statement in multiple threads.

You're pre-optimizing, which is the root of all evil. The database already has a cache of prepared statements. No need to do that by yourself. And you should definitely use a connection pool, too, instead of using a single connection for all your program.

Body:
I am initialising a prepared statement globally (so it isn't pre-compiled everytime a function is run, only when the application is loaded), and attempting to use the preparedstatement in a try with resources, but it is showing an 'unknown class' error. This is the code:

private PreparedStatement ingredientDelete;

public void deleteIngredient(String name) {
    try(ingredientDelete = con.prepareStatement(DELETE_INGREDIENT_BY_NAME)){
        ingredientDelete.setString(1, name);
        ingredientDelete.execute();

    }catch(SQLException e){
        System.out.println("Delete failed - " + e.getMessage());

    }
}

For clarity the connection is opened in another method and also declared globally.

Body:
That isn't valid Java. The resourced declared in the try must be local variables, and thus have their type declared. See the JLS

Resource:
    VariableModifiersopt Type VariableDeclaratorId = Expression

Making it a field doesn't make sense anyway, since a statement is bound to a connection, and since you're re-creating it every time the method is called anyway, thus potentially using the same statement in multiple threads.

You're pre-optimizing, which is the root of all evil. The database already has a cache of prepared statements. No need to do that by yourself. And you should definitely use a connection pool, too, instead of using a single connection for all your program.


问:
Why should I "Transform myVariable to final one element array"?
I'm trying to access the h variable in the inner class but an error keeps showing up "Cannot assign a value to final variable h". I tried quick-fix and it instructed me to "Transform h to final one element array".What does that mean?

```<code>int Update ()
{
    final int h;
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    preferences.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {

        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

            if(key.equalsIgnoreCase("PINCODE"))
            {
                h = sharedPreferences.getInt(key,0);

            }
        }
    });

    return h;
}
</code>```

}

答:
From the inner class you can't assign value to a local variable (itself) declared somewhere in the enclosing class, but you can change state (call methods, setters, ...) of the referenced object (if the variable points to some object and not to a primitive type). And array is object.

Check Java language specification - section about inner classes.

Body:
I'm trying to access the h variable in the inner class but an error keeps showing up "Cannot assign a value to final variable h". I tried quick-fix and it instructed me to "Transform h to final one element array".What does that mean?

int Update ()
{
    final int h;
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    preferences.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {

        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

            if(key.equalsIgnoreCase("PINCODE"))
            {
                h = sharedPreferences.getInt(key,0);

            }
        }
    });

    return h;
}

}


问:
A div is inheriting it's parent's width which is not what I want
Is there a way to make the div's width the same as the width of the image inside of it and ignore the width of the parent? My wrapper is 1200px, my image container's width is not set and the image inside the container is not hard coded so I can't hard code the width of the image container. I wanna make the image container wrap around the image and have the same width as it. Any way to do that?</p>

```<code>    <?php
        include 'header.php';
        include 'includes/comments.inc.php';
        include 'includes/images.inc.php';
    ?>
    <div class="wrapper">

    <?php

        $imagePath = $_SERVER['QUERY_STRING'];
        $realImagePath = substr($imagePath, 1);

        $sql = "SELECT * FROM image WHERE path='$realImagePath'";
        $result = mysqli_query($conn, $sql);
        $getResult = mysqli_fetch_assoc($result);

        echo "<div class='imageContainer'>"
                        ."<h1>".$getResult['name'].'</h1>'
                        .'<div class="relativeContainer"><img class="uploadedRealImg" src="uploads/'.$realImagePath .'" alt="Random image" /></div>'."<br><br>"
                        .$getResult['description']."<br><br>"
                        .$getResult['date']."<br><br>"
                        .$getResult['author']."<br><br></div>";

                            if (isset($_SESSION['id'])) {
                                $id = $_SESSION['id'];
                                $sql2 = "SELECT * FROM user WHERE id='$id'";
                                $result2 = mysqli_query($conn, $sql2);
                                $getResult2 = mysqli_fetch_assoc($result2);

                                    if ($getResult2['username'] == $getResult['author']) {
                                        echo "<form method='POST' action='".deleteImage($conn)."'>
                                                <input type='hidden' name='id' value='".$getResult['id']."'>
                                                <input type='hidden' name='path' value='".$getResult['path']."'>
                                                <input type='hidden' name='author' value='".$getResult['author']."'>
                                                <button id='delImage' type='submit' name='imageDelete'>Delete Image</button>
                                            </form>";
                                        }
                                }

        echo "<form method='POST' action='".setComments($conn)."'>
                <textarea class='commentSection' name='message'></textarea><br>
                <button type='submit' name='commentSubmit'>Comment</button>
            </form>";

    ?>

    <div id="comments">
        <?php
            getComments($conn);
        ?>
    </div>

    <?php
        echo "<button id='moreComments'>Show more comments</button>";
    ?>

</div>
<?php
    include 'footer.php';
?>

css

    .wrapper {
        width: 63.1%;
      margin: 0 auto;
      height: 100%;
    }
    .imageContainer {
      text-align: center;
      position: relative;
    }
    .uploadedImg {
      width: 500px;
      height: auto;
    }
    .uploadedRealImg {
      max-width: 1200px;
    }
    .commentSection {
      width: 100%;
      height: 150px;
    }
    #delImage {
      padding: 0;
      border: none;
      width: 100px;
      height: 100px;
      position: absolute;
      top: 0px;
      right: 0px;
    }
    .relativeContainer {
      position: relative;
    }
</code>```

答:
Try the !importent tag after the css you want to force apply.

i.e: css: mycssproperty!important;

Body:
Is there a way to make the div's width the same as the width of the image inside of it and ignore the width of the parent? My wrapper is 1200px, my image container's width is not set and the image inside the container is not hard coded so I can't hard code the width of the image container. I wanna make the image container wrap around the image and have the same width as it. Any way to do that?

    <?php
        include 'header.php';
        include 'includes/comments.inc.php';
        include 'includes/images.inc.php';
    ?>

    <?php

        $imagePath = $_SERVER['QUERY_STRING'];
        $realImagePath = substr($imagePath, 1);

        $sql = "SELECT * FROM image WHERE path='$realImagePath'";
        $result = mysqli_query($conn, $sql);
        $getResult = mysqli_fetch_assoc($result);

        echo "
"
                        ."
".$getResult['name'].'
'
                        .'

'."

"
                        .$getResult['description']."

"
                        .$getResult['date']."

"
                        .$getResult['author']."

";

                            if (isset($_SESSION['id'])) {
                                $id = $_SESSION['id'];
                                $sql2 = "SELECT * FROM user WHERE id='$id'";
                                $result2 = mysqli_query($conn, $sql2);
                                $getResult2 = mysqli_fetch_assoc($result2);

                                    if ($getResult2['username'] == $getResult['author']) {
                                        echo "<form method='POST' action='".deleteImage($conn)."'>
                                                <input type='hidden' name='id' value='".$getResult['id']."'>
                                                <input type='hidden' name='path' value='".$getResult['path']."'>
                                                <input type='hidden' name='author' value='".$getResult['author']."'>
                                                <button id='delImage' type='submit' name='imageDelete'>Delete Image</button>
                                            </form>";
                                        }
                                }

        echo "<form method='POST' action='".setComments($conn)."'>
                <textarea class='commentSection' name='message'></textarea>

                <button type='submit' name='commentSubmit'>Comment</button>
            </form>";

    ?>

        <?php
            getComments($conn);
        ?>

    <?php
        echo "<button id='moreComments'>Show more comments</button>";
    ?>

<?php
    include 'footer.php';
?>

css

    .wrapper {
        width: 63.1%;
      margin: 0 auto;
      height: 100%;
    }
    .imageContainer {
      text-align: center;
      position: relative;
    }
    .uploadedImg {
      width: 500px;
      height: auto;
    }
    .uploadedRealImg {
      max-width: 1200px;
    }
    .commentSection {
      width: 100%;
      height: 150px;
    }
    #delImage {
      padding: 0;
      border: none;
      width: 100px;
      height: 100px;
      position: absolute;
      top: 0px;
      right: 0px;
    }
    .relativeContainer {
      position: relative;
    }


问:
xml parsing from String
I am parsing a xml the data is coming from a String. i am using the following code for parsing:-

```<code>DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
    .newInstance();
    DocumentBuilder docBuilder = docBuilderFactory
    .newDocumentBuilder();
    docBuilder.isValidating();
    ByteArrayInputStream ba= new ByteArrayInputStream(connect.content.getBytes("UTF-8"));
    doc = docBuilder.parse(ba);
    doc.getDocumentElement().normalize();
    NodeList locationStatus = doc.getElementsByTagName("street");
    for (int i = 0; i < locationStatus.getLength(); i++) {
        Node locationValue = locationStatus.item(i).getChildNodes().item(0);
        _node.addElement(locationValue.getNodeValue());
    }
    String [] nodeString = new String[_node.size()];
    _node.copyInto(nodeString);
    add(new LabelField(nodeString.length+""));
</code>```

But this code is giving error , i dont no where the error is.

please Help me out

Thanks in advance

答:
did u tried this way?</p>

```<code>SAXParserImpl saxparser = new SAXParserImpl();
ResponseHandler handler = new ResponseHandler();
ByteArrayInputStream stream = new ByteArrayInputStream(xmlresp.getBytes());

public class ResponseHandler extends DefaultHandler
{
  public void startElement(String uri, String localName,
                           String qName,Attributes attributes) {}
public void characters(char[] ch, int start, int length)
        {
            tempVal = new String(ch, start, length);
        }
public void endElement(String uri, String localName,
                       String qName) throws SAXException    {}
}
</code>```

Title: xml parsing from String

Body:
I am parsing a xml the data is coming from a String. i am using the following code for parsing:-

DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
    .newInstance();
    DocumentBuilder docBuilder = docBuilderFactory
    .newDocumentBuilder();
    docBuilder.isValidating();
    ByteArrayInputStream ba= new ByteArrayInputStream(connect.content.getBytes("UTF-8"));
    doc = docBuilder.parse(ba);
    doc.getDocumentElement().normalize();
    NodeList locationStatus = doc.getElementsByTagName("street");
    for (int i = 0; i < locationStatus.getLength(); i++) {
        Node locationValue = locationStatus.item(i).getChildNodes().item(0);
        _node.addElement(locationValue.getNodeValue());
    }
    String [] nodeString = new String[_node.size()];
    _node.copyInto(nodeString);
    add(new LabelField(nodeString.length+""));

But this code is giving error , i dont no where the error is.

please Help me out

Thanks in advance

Body:
did u tried this way?

SAXParserImpl saxparser = new SAXParserImpl();
ResponseHandler handler = new ResponseHandler();
ByteArrayInputStream stream = new ByteArrayInputStream(xmlresp.getBytes());

public class ResponseHandler extends DefaultHandler
{
  public void startElement(String uri, String localName,
                           String qName,Attributes attributes) {}
public void characters(char[] ch, int start, int length)
        {
            tempVal = new String(ch, start, length);
        }
public void endElement(String uri, String localName,
                       String qName) throws SAXException    {}
}


问:
beepbeepboopbeep
```<code>import java.util.Scanner;
import java.util.Arrays;

public class Lab_07_03 {
    public static void main(String args[]) {
        final int BOOP = 10;
        int i = 0;
        int j = 0; //
        int countr = 0;
        Scanner scnr = new Scanner(System.in);
        int[] countArray = new int[BOOP];
        System.out.println("Enter integers between 1 and 100: ");
        for (i = 0; i < BOOP; i++) {
            countArray[i] = scnr.nextInt(); // array reads user inputs
            if (countArray[i] == 0) {
                break; // 0 signals end of user input
            }
        }
        for (j = 0; countArray[j] != 0; j++) {
            for (i = 0; countArray[i] != 0; i++) {
                if (countArray[j] == countArray[i]) {
                    countr++; // number of times a number appears in an array
                }
            }
            if (countr > 1) {
                System.out.println(countArray[j] + " occurs " + countr + " times.");
                countr = 0;
            } else {
                System.out.println(countArray[j] + " occurs " + countr + " time.");
                countr = 0;
            }
        }
    }
}
</code>```

Right now I am trying to sort the array so that it prints the numbers in ascending order, and does not print any duplicate numbers. However this is proving difficult and I suspect it is because my array is of length 100 when only 10 slots are used. My reasoning for this is that the array length is supposed to be determined by the user input. Is there a better way to do this?

with an input of 2 5 6 5 4 3 23 43 2 0 output looks like this:
Enter integers between 1 and 100:
2 occurs 2 times.
5 occurs 2 times.
6 occurs 1 time.
5 occurs 2 times.
4 occurs 1 time.
3 occurs 1 time.
23 occurs 1 time.
43 occurs 1 time.
2 occurs 2 times.

答:
Use Arrays.sort then find the duplicate numbers in the array using for loop

Arrays sort

Title: beepbeepboopbeep

Body:
import java.util.Scanner;
import java.util.Arrays;

public class Lab_07_03 {
    public static void main(String args[]) {
        final int BOOP = 10;
        int i = 0;
        int j = 0; //
        int countr = 0;
        Scanner scnr = new Scanner(System.in);
        int[] countArray = new int[BOOP];
        System.out.println("Enter integers between 1 and 100: ");
        for (i = 0; i < BOOP; i++) {
            countArray[i] = scnr.nextInt(); // array reads user inputs
            if (countArray[i] == 0) {
                break; // 0 signals end of user input
            }
        }
        for (j = 0; countArray[j] != 0; j++) {
            for (i = 0; countArray[i] != 0; i++) {
                if (countArray[j] == countArray[i]) {
                    countr++; // number of times a number appears in an array
                }
            }
            if (countr > 1) {
                System.out.println(countArray[j] + " occurs " + countr + " times.");
                countr = 0;
            } else {
                System.out.println(countArray[j] + " occurs " + countr + " time.");
                countr = 0;
            }
        }
    }
}

Right now I am trying to sort the array so that it prints the numbers in ascending order, and does not print any duplicate numbers. However this is proving difficult and I suspect it is because my array is of length 100 when only 10 slots are used. My reasoning for this is that the array length is supposed to be determined by the user input. Is there a better way to do this?

with an input of 2 5 6 5 4 3 23 43 2 0 output looks like this:
Enter integers between 1 and 100:
2 occurs 2 times.
5 occurs 2 times.
6 occurs 1 time.
5 occurs 2 times.
4 occurs 1 time.
3 occurs 1 time.
23 occurs 1 time.
43 occurs 1 time.
2 occurs 2 times.


问:
Unable to borrow a Vec inside of a closure
I have a vector of Units. I'm trying to construct a Vec<Vec<Unit>> variable, called world. In the process of creating tiles, I need to know what tiles are adjacent that it knows of.

I have a function that returns a vector of points ((usize, usize)) that are adjacent to another point, and I'm converting that to an iterator, mapping over it, and getting the actual unit associated with that position in world if it's there, or the current line which has not yet been committed to world.

I need to access that line inside the closure that map takes, but I also need to access it later.

```<code>fn adjacent((x, y): (usize, usize)) -> Vec<(usize, usize)> {
    vec![
        (x+1, y),
        (x-1, y),
        (x, y+1),
        (x, y-1),
    ]
}

struct Unit {
    pub tiles: Vec<Tile>,
}

#[derive(Copy, Clone)]
enum Tile {
    Floor, Wall, Empty
}

fn main() {
    let heightmap = vec![
        vec![3, 3, 3, 3, 3, 3],
        vec![3, 1, 1, 1, 1, 3],
        vec![3, 1, 1, 1, 1, 3],
        vec![3, 1, 1, 1, 1, 3],
        vec![3, 1, 1, 1, 1, 3],
        vec![3, 1, 1, 1, 1, 3],
        vec![3, 3, 3, 3, 3, 3],
    ];
    let (sx, sy) = (5, 5);
    let mut world: Vec<Vec<Unit>> = vec![];
    for y in 0..sy {
        let mut line: Vec<Unit> = vec![];
        for x in 0..sx {
            let mut tiles: Vec<Tile> = vec![];
            let height = heightmap[y][x];
            let adj = adjacent((x, y))
                .iter()
                .map(|&(x, y)| {
                    let list = if y > world.len() {
                        vec![]
                    } else if y == world.len() {
                        line
                    } else {
                        world[y]
                    };

                    if x >= list.len() {
                        Tile::Empty
                    } else {
                        if height as usize >= list[x].tiles.len() {
                            Tile::Empty
                        } else {
                            list[x].tiles[height as usize]
                        }
                    }
                })
                .collect::<Vec<_>>();

            for z in 0..(height as isize - 1) {
                tiles.push(Tile::Wall);
            }
            line.push(Unit {
                tiles: tiles,
            });
        }
        world.push(line);
    }
}
</code>```

Here is the Rust Playground.

I would have rather used unwrap_or in combination with get and so on but that leads to other errors with temporary values, and that would be more complicated anyway, so the above code, while probably not optimal, is as simple as I can get it while still duplicating the error. I've found out that a lot of the errors I get with Rust is because what I'm doing isn't the best way to go about it, so if there is a more idiomatic way, I would certainly like to know.

I've tried to make Unit cloneable (deriving Clone and Copy) but Rust won't let me for some reason, even though all it is made up of is vectors which are cloneable if their members are.

答:
Here's a smaller example of your problem:

```<code>fn main() {
    let mut line = vec![1];
    let something_to_iterate_over = vec![true, false, true];

    for _ in 0..2 {
        let _dummy: Vec<_> = something_to_iterate_over
            .iter()
            .map(|&value| {
                let maybe_moved_line = if value { vec![] } else { line };
                () // Don't care about the return value
            })
            .collect();

        line.push(2);
    }
}
</code>```

The first part of the error message is:

error[E0382]: capture of moved value: `line`
 --> src/main.rs:9:67
  |
8 |             .map(|&value| {
  |                  -------- value moved (into closure) here
9 |                 let maybe_moved_line = if value { vec![] } else { line };
  |                                                                   ^^^^ value captured here after move
  |
  = note: move occurs because `line` has type `std::vec::Vec<i32>`, which does not implement the `Copy` trait

error[E0382]: use of moved value: `line`
  --> src/main.rs:14:9
   |
8  |             .map(|&value| {
   |                  -------- value moved (into closure) here
...
14 |         line.push(2);
   |         ^^^^ value used here after move
   |
   = note: move occurs because `line` has type `std::vec::Vec<i32>`, which does not implement the `Copy` trait
```

As the error message is attempting to convey, the code no longer has ownership of the variable line after the map call because the ownership has been transferred to the closure.

The code is attempting to give a single Vec to someone else while keeping it for itself, and that's simply not how ownership works. I can't give you my car and then continue to drive it everyday — it's not mine to drive!

The smallest amount of change to get your code to compile is to stop trying to give away the one and only line, but instead to clone it as needed:

Add #[derive(Clone)] to Unit

Clone line and world[y] inside the closure: line.clone(), world[y].clone()

After doing this, the code never gives up ownership of line so it can be cloned whenever needed.

Body:
I have a vector of Units. I'm trying to construct a Vec<Vec<Unit>> variable, called world. In the process of creating tiles, I need to know what tiles are adjacent that it knows of.

I have a function that returns a vector of points ((usize, usize)) that are adjacent to another point, and I'm converting that to an iterator, mapping over it, and getting the actual unit associated with that position in world if it's there, or the current line which has not yet been committed to world.

I need to access that line inside the closure that map takes, but I also need to access it later.

fn adjacent((x, y): (usize, usize)) -> Vec<(usize, usize)> {
    vec![
        (x+1, y),
        (x-1, y),
        (x, y+1),
        (x, y-1),
    ]
}

struct Unit {
    pub tiles: Vec<Tile>,
}

#[derive(Copy, Clone)]
enum Tile {
    Floor, Wall, Empty
}

fn main() {
    let heightmap = vec![
        vec![3, 3, 3, 3, 3, 3],
        vec![3, 1, 1, 1, 1, 3],
        vec![3, 1, 1, 1, 1, 3],
        vec![3, 1, 1, 1, 1, 3],
        vec![3, 1, 1, 1, 1, 3],
        vec![3, 1, 1, 1, 1, 3],
        vec![3, 3, 3, 3, 3, 3],
    ];
    let (sx, sy) = (5, 5);
    let mut world: Vec<Vec<Unit>> = vec![];
    for y in 0..sy {
        let mut line: Vec<Unit> = vec![];
        for x in 0..sx {
            let mut tiles: Vec<Tile> = vec![];
            let height = heightmap[y][x];
            let adj = adjacent((x, y))
                .iter()
                .map(|&(x, y)| {
                    let list = if y > world.len() {
                        vec![]
                    } else if y == world.len() {
                        line
                    } else {
                        world[y]
                    };

                    if x >= list.len() {
                        Tile::Empty
                    } else {
                        if height as usize >= list[x].tiles.len() {
                            Tile::Empty
                        } else {
                            list[x].tiles[height as usize]
                        }
                    }
                })
                .collect::<Vec<_>>();

            for z in 0..(height as isize - 1) {
                tiles.push(Tile::Wall);
            }
            line.push(Unit {
                tiles: tiles,
            });
        }
        world.push(line);
    }
}

Here is the Rust Playground.

I would have rather used unwrap_or in combination with get and so on but that leads to other errors with temporary values, and that would be more complicated anyway, so the above code, while probably not optimal, is as simple as I can get it while still duplicating the error. I've found out that a lot of the errors I get with Rust is because what I'm doing isn't the best way to go about it, so if there is a more idiomatic way, I would certainly like to know.

I've tried to make Unit cloneable (deriving Clone and Copy) but Rust won't let me for some reason, even though all it is made up of is vectors which are cloneable if their members are.

Body:
Here's a smaller example of your problem:

fn main() {
    let mut line = vec![1];
    let something_to_iterate_over = vec![true, false, true];

    for _ in 0..2 {
        let _dummy: Vec<_> = something_to_iterate_over
            .iter()
            .map(|&value| {
                let maybe_moved_line = if value { vec![] } else { line };
                () // Don't care about the return value
            })
            .collect();

        line.push(2);
    }
}

The first part of the error message is:

error[E0382]: capture of moved value: `line`
 --> src/main.rs:9:67
  |
8 |             .map(|&value| {
  |                  -------- value moved (into closure) here
9 |                 let maybe_moved_line = if value { vec![] } else { line };
  |                                                                   ^^^^ value captured here after move
  |
  = note: move occurs because `line` has type `std::vec::Vec<i32>`, which does not implement the `Copy` trait

error[E0382]: use of moved value: `line`
  --> src/main.rs:14:9
   |
8  |             .map(|&value| {
   |                  -------- value moved (into closure) here
...
14 |         line.push(2);
   |         ^^^^ value used here after move
   |
   = note: move occurs because `line` has type `std::vec::Vec<i32>`, which does not implement the `Copy` trait

As the error message is attempting to convey, the code no longer has ownership of the variable line after the map call because the ownership has been transferred to the closure.

The code is attempting to give a single Vec to someone else while keeping it for itself, and that's simply not how ownership works. I can't give you my car and then continue to drive it everyday — it's not mine to drive!

The smallest amount of change to get your code to compile is to stop trying to give away the one and only line, but instead to clone it as needed:

Add #[derive(Clone)] to Unit

Clone line and world[y] inside the closure: line.clone(), world[y].clone()

After doing this, the code never gives up ownership of line so it can be cloned whenever needed.


问:
Tensorflow-gpu on windows: ImportError: No module named _pywrap_tensorflow
When I try to import tensorflow I get the following error:

```<code>>>import tensorflow
  File "C:\Users\...\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "C:\Users\...\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\__init__.py", line 72, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "C:\Users\...\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\__init__.py", line 66, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "C:\Users\...\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 21, in <module>
    _pywrap_tensorflow = swig_import_helper()
  File "C:\Users\...\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 20, in swig_import_helper
    return importlib.import_module('_pywrap_tensorflow')
  File "C:\Users\...\Anaconda3\envs\tensorflow\lib\importlib\__init__.py", line 37, in import_module
    __import__(name)
ImportError: No module named _pywrap_tensorflow

Failed to load the native TensorFlow runtime.

See https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/get_started/os_setup.md#import_error

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.
</code>```

I installed the msvcp140.dll Redistributable as recommended here, but it didn't help. Any ideas? I am running Anaconda3 environment.

答: It turned out that tensorflow on windows requires python 3.5 or higher while my python was 2.7.8. I found out that this was the problem by the help of this great script which helps trace the source error and gives clear error messages.

Body:
When I try to import tensorflow I get the following error:

>>import tensorflow
  File "C:\Users\...\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "C:\Users\...\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\__init__.py", line 72, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "C:\Users\...\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\__init__.py", line 66, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "C:\Users\...\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 21, in <module>
    _pywrap_tensorflow = swig_import_helper()
  File "C:\Users\...\Anaconda3\envs\tensorflow\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 20, in swig_import_helper
    return importlib.import_module('_pywrap_tensorflow')
  File "C:\Users\...\Anaconda3\envs\tensorflow\lib\importlib\__init__.py", line 37, in import_module
    __import__(name)
ImportError: No module named _pywrap_tensorflow

Failed to load the native TensorFlow runtime.

See https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/get_started/os_setup.md#import_error

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.

I installed the msvcp140.dll Redistributable as recommended here, but it didn't help. Any ideas? I am running Anaconda3 environment.


问:
How to write a test for a ggplot plot
I have a lot of functions that generate plots, typically with ggplot2. Right now, I'm generating the plot and testing the underlying data. But I'd like to know if there's a reasonable way to test that the plot contains the layers/options I expect it to or that graphical elements match expectations.

For example:

```<code>library(ggplot2)
library(scales) # for percent()
library(testthat)

df <- data.frame(
  Response = LETTERS[1:5],
  Proportion = c(0.1,0.2,0.1,0.2,0.4)
)

#' @export plot_fun
plot_fun <- function(df) {
  p1 <- ggplot(df, aes(Response, Proportion)) +
    geom_bar(stat='identity') +
    scale_y_continuous(labels = percent)
return(p1)
}

test_that("Plot returns ggplot object",{
  p <- plot_fun(df)
  expect_is(p,"ggplot")
})

test_that("Plot uses correct data", {
  p <- plot_fun(df)
  expect_that(df, equals(p$data))

})
</code>```

This is where I'm stuck

```<code>test_that("Plot layers match expectations",{
  p <- plot_fun(df)
  expect_that(...,...)
})

test_that("Scale is labelled percent",{
  p <- plot_fun(df)
  expect_that(...,...)
})
</code>```

Perhaps there's a more direct approach?

答: It's worth noting that the vdiffr package is designed for comparing plots. A nice feature is that it integrates with the testthat package -- it's actually used for testing in ggplot2 -- and it has an add-in for RStudio to help manage your testsuite.</p>

Title: How to write a test for a ggplot plot

Body:
I have a lot of functions that generate plots, typically with ggplot2. Right now, I'm generating the plot and testing the underlying data. But I'd like to know if there's a reasonable way to test that the plot contains the layers/options I expect it to or that graphical elements match expectations.

For example:

library(ggplot2)
library(scales) # for percent()
library(testthat)

df <- data.frame(
  Response = LETTERS[1:5],
  Proportion = c(0.1,0.2,0.1,0.2,0.4)
)

#' @export plot_fun
plot_fun <- function(df) {
  p1 <- ggplot(df, aes(Response, Proportion)) +
    geom_bar(stat='identity') +
    scale_y_continuous(labels = percent)
return(p1)
}

test_that("Plot returns ggplot object",{
  p <- plot_fun(df)
  expect_is(p,"ggplot")
})

test_that("Plot uses correct data", {
  p <- plot_fun(df)
  expect_that(df, equals(p$data))

})

This is where I'm stuck

test_that("Plot layers match expectations",{
  p <- plot_fun(df)
  expect_that(...,...)
})

test_that("Scale is labelled percent",{
  p <- plot_fun(df)
  expect_that(...,...)
})

Perhaps there's a more direct approach?


问:
Android emulator Internet connection
I am using win 7 64 bit OS, using Android 2.2 my emulator couldn't be connected to computer. I am using internet behind proxy server. I change the APN setting by filling proxy setting of my machine. But still I can't be connected to the internet Please any one who can help me? Thanks for your answers.</p>

答:
You can set the proxy in the emulator.
This link describes all the options https://developer.android.com/studio/run/emulator-networking.html.

One way is when you run the emulator from the command line add -http-proxy:

```<code>emulator.exe -avd YOUR_AVD_NAME_HERE -http-proxy http://<machineName>:<port>
</code>```

or

```<code>emulator.exe -avd YOUR_AVD_NAME_HERE -http-proxy http://<username>:<password>@<machineName>:<port>
</code>```

And consider if you computer has more than one network interface. Maybe your emulator is trying to use one that is not connect, its very common. The simplest solution is just to disable the ETHERNET interface if you are using WIFI interface. Other way is to change the priority of your interfaces in the operational system. In Windows 10 you can do this by:

Goto Control Panel > Network and Internet > Network Connections

Right click the desired connection (Higher Priority Connection)

Click Properties > Internet Protocol Version 4

Click Properties > Advanced

Uncheck 'Automatic Metric'

Enter 1 in 'Interface Metric'

Click OK
Repeat for the Lower Priority Connection, but this time put 20 into the 'Interface Metric'
You'll now use the higher priority connection as a default.

Title: Android emulator Internet connection

Body:
You can set the proxy in the emulator.
This link describes all the options https://developer.android.com/studio/run/emulator-networking.html.

One way is when you run the emulator from the command line add -http-proxy:

emulator.exe -avd YOUR_AVD_NAME_HERE -http-proxy http://<machineName>:<port>

or

emulator.exe -avd YOUR_AVD_NAME_HERE -http-proxy http://<username>:<password>@<machineName>:<port>

And consider if you computer has more than one network interface. Maybe your emulator is trying to use one that is not connect, its very common. The simplest solution is just to disable the ETHERNET interface if you are using WIFI interface. Other way is to change the priority of your interfaces in the operational system. In Windows 10 you can do this by:

Goto Control Panel > Network and Internet > Network Connections

Right click the desired connection (Higher Priority Connection)

Click Properties > Internet Protocol Version 4

Click Properties > Advanced

Uncheck 'Automatic Metric'

Enter 1 in 'Interface Metric'

Click OK
Repeat for the Lower Priority Connection, but this time put 20 into the 'Interface Metric'
You'll now use the higher priority connection as a default.


问:
Program failing to call void function
I am having trouble with writing this program. My issue seems to be with the processOrder and displayOrder functions, upon running this code the getOrder function runs just fine, but the program doesn't call the other functions at all and just terminates after the data has been entered. I'm sure I am missing something simple, but I can't see it, any help would be appreciated.</p>

```<code>#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

struct Order {
    string name;
    double unitPrice;
    int quantity;
    double totalPrice;
};

const int NumOrder = 3;
Order GetOrder();
void ProcessOrder(Order& myOrder);
void DisplayOrders(Order orderList[]);

int main()
{

    Order orderList[NumOrder];

    for (int i = 0; i < NumOrder; i++) {
        // create an order variable
        Order myOrder;

        cout << "Enter information for order #" << i + 1 << ": " << endl;
        // call GetOrder() function to enter order’s information
        myOrder = GetOrder();

        cin.ignore(1000, '\n');
        cout << endl;

        // call ProcessOrder() function to update total price of an order
        void ProcessOrder(Order & myOrder);

        // add the new order in the order array
        orderList[i] = myOrder;
    }
    // call DisplayOrders() function to display all of three orders’ information
    void DisplayOrders(Order orderList[]);

    return 0;
}

Order GetOrder()
{
    Order myOrder;

    cout << "Item Nane: ";
    getline(cin, myOrder.name);
    cout << "Unit Price: ";
    cin >> myOrder.unitPrice;
    cout << "Quantity: ";
    cin >> myOrder.quantity;

    myOrder.totalPrice = 0.00;

    return myOrder;
}

void ProcessOrder(Order& myOrder)
{
    myOrder.totalPrice = (myOrder.quantity * myOrder.unitPrice) + (myOrder.quantity * myOrder.unitPrice) * 0.007;
}

void DisplayOrders(Order orderList[NumOrder])
{
    // complete function definition here
    int j;

    for (j = 0; j < NumOrder; j++) {
        string iName = orderList[j].name;
        cout << "Item name: " << iName << endl;
        cout << "Unit price: $" << orderList[j].unitPrice << endl;
        cout << "Quantity: " << orderList[j].quantity << endl;
        cout << "Total price: $" << orderList[j].totalPrice << endl;
    }
}
</code>```

答:
to put it simply:

```<code>void ProcessOrder(Order & myOrder);
</code>```

and

```<code>void DisplayOrders(Order orderList[]);
</code>```

are functions declaration. ie: you're declaring functions with these lines, not calling already declared ones.

In this context, use these instead:

```<code>ProcessOrder(myOrder);
DisplayOrders(orderList);
</code>```

if you're new to c++, I advise you to visit this link, it's a good way to learn efficiently with applications.

Hope this was helpful.

Title: Program failing to call void function

Body:
I am having trouble with writing this program. My issue seems to be with the processOrder and displayOrder functions, upon running this code the getOrder function runs just fine, but the program doesn't call the other functions at all and just terminates after the data has been entered. I'm sure I am missing something simple, but I can't see it, any help would be appreciated.

#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

struct Order {
    string name;
    double unitPrice;
    int quantity;
    double totalPrice;
};

const int NumOrder = 3;
Order GetOrder();
void ProcessOrder(Order& myOrder);
void DisplayOrders(Order orderList[]);

int main()
{

    Order orderList[NumOrder];

    for (int i = 0; i < NumOrder; i++) {
        // create an order variable
        Order myOrder;

        cout << "Enter information for order #" << i + 1 << ": " << endl;
        // call GetOrder() function to enter order’s information
        myOrder = GetOrder();

        cin.ignore(1000, '\n');
        cout << endl;

        // call ProcessOrder() function to update total price of an order
        void ProcessOrder(Order & myOrder);

        // add the new order in the order array
        orderList[i] = myOrder;
    }
    // call DisplayOrders() function to display all of three orders’ information
    void DisplayOrders(Order orderList[]);

    return 0;
}

Order GetOrder()
{
    Order myOrder;

    cout << "Item Nane: ";
    getline(cin, myOrder.name);
    cout << "Unit Price: ";
    cin >> myOrder.unitPrice;
    cout << "Quantity: ";
    cin >> myOrder.quantity;

    myOrder.totalPrice = 0.00;

    return myOrder;
}

void ProcessOrder(Order& myOrder)
{
    myOrder.totalPrice = (myOrder.quantity * myOrder.unitPrice) + (myOrder.quantity * myOrder.unitPrice) * 0.007;
}

void DisplayOrders(Order orderList[NumOrder])
{
    // complete function definition here
    int j;

    for (j = 0; j < NumOrder; j++) {
        string iName = orderList[j].name;
        cout << "Item name: " << iName << endl;
        cout << "Unit price: $" << orderList[j].unitPrice << endl;
        cout << "Quantity: " << orderList[j].quantity << endl;
        cout << "Total price: $" << orderList[j].totalPrice << endl;
    }
}

Body:
to put it simply:

void ProcessOrder(Order & myOrder);

and

void DisplayOrders(Order orderList[]);

are functions declaration. ie: you're declaring functions with these lines, not calling already declared ones.

In this context, use these instead:

ProcessOrder(myOrder);
DisplayOrders(orderList);

if you're new to c++, I advise you to visit this link, it's a good way to learn efficiently with applications.

Hope this was helpful.


问:
How to make file_get_contents return an unique result
I am new to php and would like to ask you for some help returning an unique result from file_get_contents(). The reason is I want to give each photo an unique name, so that later it will be possible to delete just one of them and not all.

```<code>$file =addslashes(file_get_contents($_FILES['image']['tmp_name'][$key]));
</code>```

Unfortunately time() and microtime() doesn't help in this situation.

答:
Why not just generate the SHA-1 of the content and use that as the file name (sort of like how git stores objects in a repository's loose object database)? I typically don't like to insert blobs into the RDBMS; it's a little clunky and you have to make sure the blob field has enough space for the kind of file sizes you're expecting to work with. Plus, the filesystem is optimized to handle, well, files. So it makes sense to keep a special directory on the server to which the Web server has write access. Then you write the files there and store references to them in the database. Here's an example:

```<code>// Read the contents of the file and create a SHA-1 hash signature.
$tmpPath = $_FILES['image']['tmp_name'];
$blob = file_get_contents($tmpPath);
$name = sha1($blob) . '.img'; // e.g. b99c6e26c3775fca9918ad614b7be7fe4fd7bee3.img

// Save the file to your server somewhere.
$dstPath = "/path/to/imgdb/$name";
move_uploaded_file($tmpPath,$dstPath);

// TODO: insert reference (i.e. $name) into database somehow...
</code>```

And yes, researches have broken SHA-1, but you could easily write some safeguards against that if you're paranoid enough (e.g. check for an existing upload with the same hash; it the content differs, just mutate/append to the name a little to change it). You aren't identifying the image on the backend by its content: you just need a unique name. Once you have that, you just look it up from the DB to figure out the file path on disk corresponding to the actual image data.

If you expect the image files to be pretty large, you could limit how much you read into memory using the 4th parameter to file_get_contents().

Body:
I am new to php and would like to ask you for some help returning an unique result from file_get_contents(). The reason is I want to give each photo an unique name, so that later it will be possible to delete just one of them and not all.

$file =addslashes(file_get_contents($_FILES['image']['tmp_name'][$key]));

Unfortunately time() and microtime() doesn't help in this situation.

Body:
Why not just generate the SHA-1 of the content and use that as the file name (sort of like how git stores objects in a repository's loose object database)? I typically don't like to insert blobs into the RDBMS; it's a little clunky and you have to make sure the blob field has enough space for the kind of file sizes you're expecting to work with. Plus, the filesystem is optimized to handle, well, files. So it makes sense to keep a special directory on the server to which the Web server has write access. Then you write the files there and store references to them in the database. Here's an example:

// Read the contents of the file and create a SHA-1 hash signature.
$tmpPath = $_FILES['image']['tmp_name'];
$blob = file_get_contents($tmpPath);
$name = sha1($blob) . '.img'; // e.g. b99c6e26c3775fca9918ad614b7be7fe4fd7bee3.img

// Save the file to your server somewhere.
$dstPath = "/path/to/imgdb/$name";
move_uploaded_file($tmpPath,$dstPath);

// TODO: insert reference (i.e. $name) into database somehow...

And yes, researches have broken SHA-1, but you could easily write some safeguards against that if you're paranoid enough (e.g. check for an existing upload with the same hash; it the content differs, just mutate/append to the name a little to change it). You aren't identifying the image on the backend by its content: you just need a unique name. Once you have that, you just look it up from the DB to figure out the file path on disk corresponding to the actual image data.

If you expect the image files to be pretty large, you could limit how much you read into memory using the 4th parameter to file_get_contents().


问:
"User "system" cannot get securitycontextconstraints at the cluster scope" in Openshift3
If I try to add a security constraint to a local OpenShift all-in-one cluster running in Windows10 Pro and Hyper-V, openshift client receives the following message:

```<code>c:\openshift\oc.exe adm policy add-scc-to-user anyuid -z default
Error from server (Forbidden): User "system" cannot get securitycontextconstraints at the cluster scope"
</code>```

The Openshift instance was created by docker machine using the following steps:

```<code>1) docker-machine create -d "hyperv" --engine-insecure-registry 172.30.0.0/16 --hyperv-virtual-switch "openshift" openshift
2) oc cluster up --docker-machine=openshift
</code>```

Is there any configuration to allow system user to have access to securitycontextconstraints?

答:
Try running:

```<code>docker exec origin oc adm policy add-scc-to-user anyuid -z default -n projectname
</code>```

This will run oc inside of the OpenShift cluster where it should run as an admin.

I would suggest also running:

```<code>docker exec origin oc adm policy add-cluster-role-to-group sudoer system:authenticated yourusername
</code>```

That way you can in future run admin commands by running:

```<code>oc adm policy add-scc-to-user anyuid -z default -n projectname --as system:admin
</code>```

That is, by using --as system:admin to impersonate admin.

You may want to consider using Minishift instead of oc cluster up as it from memory gives the developer user sudoer role by default and so can use --as system:admin to execute admin commands.

Body:
If I try to add a security constraint to a local OpenShift all-in-one cluster running in Windows10 Pro and Hyper-V, openshift client receives the following message:

c:\openshift\oc.exe adm policy add-scc-to-user anyuid -z default
Error from server (Forbidden): User "system" cannot get securitycontextconstraints at the cluster scope"

The Openshift instance was created by docker machine using the following steps:

1) docker-machine create -d "hyperv" --engine-insecure-registry 172.30.0.0/16 --hyperv-virtual-switch "openshift" openshift
2) oc cluster up --docker-machine=openshift

Is there any configuration to allow system user to have access to securitycontextconstraints?

Body:
Try running:

docker exec origin oc adm policy add-scc-to-user anyuid -z default -n projectname

This will run oc inside of the OpenShift cluster where it should run as an admin.

I would suggest also running:

docker exec origin oc adm policy add-cluster-role-to-group sudoer system:authenticated yourusername

That way you can in future run admin commands by running:

oc adm policy add-scc-to-user anyuid -z default -n projectname --as system:admin

That is, by using --as system:admin to impersonate admin.

You may want to consider using Minishift instead of oc cluster up as it from memory gives the developer user sudoer role by default and so can use --as system:admin to execute admin commands.


问:
max. length of List in Java
What is the maximum length of List in java? I mean that how many maximum elements can store in list?</p>

答:
It's very likely that you will run out of heap space well before you get anywhere close to Integer.MAX_VALUE number of elements, but let's see what would happen if we had infinite memory and tried to add more than Integer.MAX_VALUE elements to a List:

1) ArrayList:

An ArrayList will try to increase its capacity:

```<code>int newCapacity = (oldCapacity * 3)/2 + 1;
</code>```

This calculation will overflow and newCapacity will actually be less than Integer.MAX_VALUE. The ArrayList will then try to copy the elements in the original array to a smaller array and will hence lose elements.

2) LinkedList:

A LinkedList works a bit better once you cross the Integer.MAX_VALUE limit. It will continue to hold elements, however the size attribute will suffer from integer overflow and will affect other operations that make use of it.

Title: max. length of List in Java

Body:
It's very likely that you will run out of heap space well before you get anywhere close to Integer.MAX_VALUE number of elements, but let's see what would happen if we had infinite memory and tried to add more than Integer.MAX_VALUE elements to a List:

1) ArrayList:

An ArrayList will try to increase its capacity:

int newCapacity = (oldCapacity * 3)/2 + 1;

This calculation will overflow and newCapacity will actually be less than Integer.MAX_VALUE. The ArrayList will then try to copy the elements in the original array to a smaller array and will hence lose elements.

2) LinkedList:

A LinkedList works a bit better once you cross the Integer.MAX_VALUE limit. It will continue to hold elements, however the size attribute will suffer from integer overflow and will affect other operations that make use of it.


问:
Removed file is still accessible by collaborators in Google Drive. How I can delete it completely?
When I am deleting a file from Google drive which someone else shared with me, it showed me a message like "one removed file is still accessible by collaborators".

It no longer appears in that folder, but will it be shown in "shared with me"? How can I delete it completely?

答:
You mentioned you'd deleted the file from Google drive which was shared by someone else with you. After deleting you saw a message that stated, "one removed file is still accessible by collaborators". Perhaps the one who is sharing the file is one of the mentioned collaborators, or depending on how this document was shared, other members of the group.

Hope this helps!

ContentLicense: CC BY-SA 4.0


问:
Python switch statement with aliases
How to write an efficient "switch" statement that can return same thing for different input?

Simple switch in Python can be implemented using dictionary  like this:

```<code>def switch(s):
    case = {'phone': '123 456 789', 'website': 'www.example.com'}
    return case[s]
</code>```

This one has constant access time, however I want to use aliases, i.e. switch('website') will return the same thing as switch('site') etc. without duplicating values, i.e. without using

case = {'website': 'www.example.com, 'site': 'www.example.com}

What can be used, is:

```<code>def switch(s):
    case = {('telephone', 'number', 'phone'): '123 456 789',
            ('website', 'site'): 'www.example.com'}
    for key, value in case.items():
        if s in key:
            return value
</code>```

But this approach has worse than linear access time.

It can be made constant, by using

```<code>def switch(s):
    case = ['123 456 789', 'www.example.com']
    aliases = {'telephone': 0, 'number': 0, 'phone': 0,
               'website': 1, 'site': 1}
    return case[aliases[s]]
</code>```

but then I'm sort-of duplicating values and in case I decide to remove any answer, I have to edit aliases' and/or case's return values (if I no longer want to return '123 456 789' I have to delete it from case and modify aliases so that aliases['website'] and aliases['site'] return 0 OR leave dummy value in case's 1st cell OR make case a dictionary)

Is there a better way to write such statements?

答:
In your question you say:

I want to use aliases, i.e. switch('website') will return the same thing as switch('site') etc. without duplicating values

I think your concern about duplicated values is misplaced and you shouldn't reject that approach. Adding an extra dictionary entry with the same string value should not be a problem, and it's the natural way to solve your issue. Don't complicate your code with an extra indirection layer if you don't need to.

I'm assuming your concern with that approach is that it could increase your memory usage, since identical values are stored several times in the dictionary. But most of the time, you won't have multiple separate identical strings, rather, you'll have multiple references to the same string object. Since strings are immutable, Python may substitute in references to preexisting objects when it would appear it should be creating another independent string with the same contents.

You can test this for yourself. Try creating a dictionary with several identical string literals as values, then test the id of each one:

```<code>d = {"a": "foo", "b": "foo", "c": "foo"}

for val in d.values():
    print(id(val))
</code>```

On my system this tells me the ids are all the same. I think that multiple identical string literals that are compiled at the same time will always be turned into multiple references to a single string object. In some situations, thanks to string "interning", all strings with certain contents (generally things that look like they could be identifiers) will be shared everywhere in the program. But you probably don't need to care too much about the details. The important thing to realize is that the duplicated strings probably won't use an excessive amount of memory most of the time.

I can't think of any other reason to object to adding all the aliases to a single dictionary. That's the natural solution, so I'd just do it. If memory usage turns out to be an issue later, you might revisit the dictionary to double check that it's being populated with repeated references, not duplicate objects, but I doubt it will matter on the scale of any serious program.

Having code that is easy to use and understand is much more important.

As you've commented that your main concern is not repeating yourself, you might want to set up the dictionary using code to transform another slightly less redundant data structure, rather than doing it directly as a literal.

For instance, the following code uses a dictionary comprehension to turn a list that pairs up sublists of aliases with their values into an easily searchable dictionary:

```<code>_data = [     # contains (alias_list, value) 2-tuples
    (['telephone', 'number', 'phone'], '123 456 789'),
    (['website', 'site'], 'www.example.com'),
]

case = {alias: value for aliases, value in _data for alias in aliases}
</code>```

You probably want to put this code somewhere where it will only run once (e.g. at the top level, or in a class or instance variable somewhere), rather than having the dictionary comprehension run every time your switch function is called. Because the dictionary is mutable, Python won't assume it can use the same dict object for each call (even though it always has the same value).

Title: Python switch statement with aliases

Body:
How to write an efficient "switch" statement that can return same thing for different input?

Simple switch in Python can be implemented using dictionary  like this:

def switch(s):
    case = {'phone': '123 456 789', 'website': 'www.example.com'}
    return case[s]

This one has constant access time, however I want to use aliases, i.e. switch('website') will return the same thing as switch('site') etc. without duplicating values, i.e. without using

case = {'website': 'www.example.com, 'site': 'www.example.com}

What can be used, is:

def switch(s):
    case = {('telephone', 'number', 'phone'): '123 456 789',
            ('website', 'site'): 'www.example.com'}
    for key, value in case.items():
        if s in key:
            return value

But this approach has worse than linear access time.

It can be made constant, by using

def switch(s):
    case = ['123 456 789', 'www.example.com']
    aliases = {'telephone': 0, 'number': 0, 'phone': 0,
               'website': 1, 'site': 1}
    return case[aliases[s]]

but then I'm sort-of duplicating values and in case I decide to remove any answer, I have to edit aliases' and/or case's return values (if I no longer want to return '123 456 789' I have to delete it from case and modify aliases so that aliases['website'] and aliases['site'] return 0 OR leave dummy value in case's 1st cell OR make case a dictionary)

Is there a better way to write such statements?

Body:
In your question you say:

I want to use aliases, i.e. switch('website') will return the same thing as switch('site') etc. without duplicating values

I think your concern about duplicated values is misplaced and you shouldn't reject that approach. Adding an extra dictionary entry with the same string value should not be a problem, and it's the natural way to solve your issue. Don't complicate your code with an extra indirection layer if you don't need to.

I'm assuming your concern with that approach is that it could increase your memory usage, since identical values are stored several times in the dictionary. But most of the time, you won't have multiple separate identical strings, rather, you'll have multiple references to the same string object. Since strings are immutable, Python may substitute in references to preexisting objects when it would appear it should be creating another independent string with the same contents.

You can test this for yourself. Try creating a dictionary with several identical string literals as values, then test the id of each one:

d = {"a": "foo", "b": "foo", "c": "foo"}

for val in d.values():
    print(id(val))

On my system this tells me the ids are all the same. I think that multiple identical string literals that are compiled at the same time will always be turned into multiple references to a single string object. In some situations, thanks to string "interning", all strings with certain contents (generally things that look like they could be identifiers) will be shared everywhere in the program. But you probably don't need to care too much about the details. The important thing to realize is that the duplicated strings probably won't use an excessive amount of memory most of the time.

I can't think of any other reason to object to adding all the aliases to a single dictionary. That's the natural solution, so I'd just do it. If memory usage turns out to be an issue later, you might revisit the dictionary to double check that it's being populated with repeated references, not duplicate objects, but I doubt it will matter on the scale of any serious program.

Having code that is easy to use and understand is much more important.

As you've commented that your main concern is not repeating yourself, you might want to set up the dictionary using code to transform another slightly less redundant data structure, rather than doing it directly as a literal.

For instance, the following code uses a dictionary comprehension to turn a list that pairs up sublists of aliases with their values into an easily searchable dictionary:

_data = [     # contains (alias_list, value) 2-tuples
    (['telephone', 'number', 'phone'], '123 456 789'),
    (['website', 'site'], 'www.example.com'),
]

case = {alias: value for aliases, value in _data for alias in aliases}

You probably want to put this code somewhere where it will only run once (e.g. at the top level, or in a class or instance variable somewhere), rather than having the dictionary comprehension run every time your switch function is called. Because the dictionary is mutable, Python won't assume it can use the same dict object for each call (even though it always has the same value).


问:
Unix check mkpasswd against that stored in /etc/shadow
I want to validate a password (of user mark).

sudo cat /etc/shadow | grep mark
mark:$6$bvY9mYW3$XdKkg0tluBghADi45V.RG1dTfctvnYdU.5J40nW8bh4UqpxtHp8uF8Zxx8U9mth9w0dvmgtVUrAtydQCvsivA1:16304:0:99999:7:::

From the result ($6) I understand that the password is generated using a sha-512 encryption algorithm with bvY9mYW3 as the salt.

When I generate the hashed password using

mkpasswd -m sha-256 -S bvY9mYW3 -s

I get $6$bvY9mYW3$XdKkg0tluBghADi45V.RG1dTfctvnYdU.5J40nW8bh4UqpxtHp8uF8Zxx8U9mth9w0dvmgtVUrAtydQCvsivA1

It is almost the same but I am missing the tailing :16304:0:99999:7::: part

What am I doing wrong?

答:
The mkpasswd utility creates a hash from a password, but /etc/shadow doesn't just contain hashed passwords; it also contains other information including login names and details about the age of a password. Each line should have a total of 9 fields separated by colons, but some of the fields can be left empty (and often are).

For example, 16304 is the number of days since Jan 1 1970 when the password was created (i.e., 22nd August 2014), 99999 means the password doesn't need to be changed for 99,999 days (about 274 years), and 7 means you'll be given a week's notice when it's time to change your password. (Although you'll probably be dead by then.)

If you're verifying a password, you could just examine the first two fields (name and password hash), but you should really check the other fields to make sure it hasn't expired.


问:
Clear input if it's not an email address using Javascript or jquery
My client uses wordpress, the template he's using generates a dynamic form, so I don't know where the html is stored. Therefore I can't use email attribute in html, nor I can validate emails using php since I don't have a clue how his theme validates the form.

The form builder generates a text input called cp_email_address I want to check if the user entered a valid email, otherwise I want to clear the field, I don't have any other option, since I can't wait for the user to submit and then validate, I don't know where the submit code is. All I know is the name, class and id of the email field.

```<code><script type="text/javascript">
    $('#cp_email_address').blur(function() {
    var testEmail = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
    if (testEmail.test(this.value)) {}; // if true pass
    else {
        this.value="";
    };
});
</script>
</code>```

I also tried target.value= "";

And tried $('#cp_email_address').value = "";

And I tried document.getElementById('cp_email_address').value = "";

Nothing is clearing the the input field.

答:
You should look into the jQuery Validation plugin because trying to write your own regular expressions for emails is like trying to reinvent the wheel. You'll constantly find emails that are valid that don't validate. You fix your regex and then some other email doesn't validate.

jQuery Validation has validators for a wide range of inputs with email being just one of them. The framework is also friendly to customization allowing you to add your own validation methods dynamically as needed.

Also, instead of clearing the input, just show a message and require them to fix it before allowing them to submit. Clearing a field without telling the user why is going to driver users insane.

Additionally, using change events like keyup or mouseout on the field and then trying to clear the field can lead to problems.

If you try to validate an email on keyup a user will never be able to enter an email address because after typing their first key the validator would fire and the email wouldn't validate cause the field to be cleared. No one would every be able to fill out the form.

Mouseout is also not a good solution. Many people, especially those with disabilities, never use the mouse to complete a form. Instead they use the keyboard only using the TAB key to go from field to field. For these users mouseout will never fire and your field will never be validated. In my experience the blur event isn't reliable either. While it is nice to have dynamic validation you always need to make sure all of your fields are valid upon form submission regardless any events being fired or not fired on individual fields.

jQuery Validation takes care of all of these issues for us.

<!doctype html>

<meta charset="utf-8">
<title>Makes "cp_email_address" required and an email address.</title>
<link rel="stylesheet" href="https://jqueryvalidation.org/files/demo/site-demos.css">

<form id="myform">
Required, email:
<input class="left" id="cp_email_address" name="cp_email_address">

<input type="submit" value="Validate!">
</form>

```

Body:
My client uses wordpress, the template he's using generates a dynamic form, so I don't know where the html is stored. Therefore I can't use email attribute in html, nor I can validate emails using php since I don't have a clue how his theme validates the form.

The form builder generates a text input called cp_email_address I want to check if the user entered a valid email, otherwise I want to clear the field, I don't have any other option, since I can't wait for the user to submit and then validate, I don't know where the submit code is. All I know is the name, class and id of the email field.

I also tried target.value= "";

And tried $('#cp_email_address').value = "";

And I tried document.getElementById('cp_email_address').value = "";

Nothing is clearing the the input field.

Body:
You should look into the jQuery Validation plugin because trying to write your own regular expressions for emails is like trying to reinvent the wheel. You'll constantly find emails that are valid that don't validate. You fix your regex and then some other email doesn't validate.

jQuery Validation has validators for a wide range of inputs with email being just one of them. The framework is also friendly to customization allowing you to add your own validation methods dynamically as needed.

Also, instead of clearing the input, just show a message and require them to fix it before allowing them to submit. Clearing a field without telling the user why is going to driver users insane.

Additionally, using change events like keyup or mouseout on the field and then trying to clear the field can lead to problems.

If you try to validate an email on keyup a user will never be able to enter an email address because after typing their first key the validator would fire and the email wouldn't validate cause the field to be cleared. No one would every be able to fill out the form.

Mouseout is also not a good solution. Many people, especially those with disabilities, never use the mouse to complete a form. Instead they use the keyboard only using the TAB key to go from field to field. For these users mouseout will never fire and your field will never be validated. In my experience the blur event isn't reliable either. While it is nice to have dynamic validation you always need to make sure all of your fields are valid upon form submission regardless any events being fired or not fired on individual fields.

jQuery Validation takes care of all of these issues for us.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Makes "cp_email_address" required and an email address.</title>
<link rel="stylesheet" href="https://jqueryvalidation.org/files/demo/site-demos.css">

</head>
<body>
<form id="myform">
<label for="field">Required, email: </label>
<input class="left" id="cp_email_address" name="cp_email_address">
<br/>
<input type="submit" value="Validate!">
</form>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script>
<script>
// just for the demos, avoids form submit
jQuery.validator.setDefaults({
  debug: true,
  success: "valid"
});
jQuery( "#myform" ).validate({
  rules: {
    cp_email_address: {
      required: true,
      email: true
    }
  }
});
</script>
</body>
</html>


问:
Printing without newline (print 'a',) prints a space, how to remove?
I have this code:

```<code>>>> for i in xrange(20):
...     print 'a',
...
a a a a a a a a a a a a a a a a a a a a
</code>```

I want to output 'a', without ' ' like this:

```<code>aaaaaaaaaaaaaaaaaaaa
</code>```

Is it possible?

答:
without what?
do you mean

```<code>>>> print 'a' * 20
aaaaaaaaaaaaaaaaaaaa
</code>```

?

Body:
I have this code:

>>> for i in xrange(20):
...     print 'a',
...
a a a a a a a a a a a a a a a a a a a a

I want to output 'a', without ' ' like this:

aaaaaaaaaaaaaaaaaaaa

Is it possible?

Body:
without what?
do you mean

>>> print 'a' * 20
aaaaaaaaaaaaaaaaaaaa

?


问:
python 3.6 put number is str
```<code>def binary(n):
    if n>0:
        return binary(n//2)*10 + (n%2)
    else:
        return 0
</code>```

The answer is 10000000 but it have to be "10000000". How can I put str on the answer?

答:
The problem with simply wrapping your return in a cast to str(), is that the subsequent calls to binary() will be affected, not just the top-level call. After the deepest recursive call to binary has finished, it will return its result - which is a string - to the next deepest recursive call to the expression:

```<code>binary(n // 2) * 10 + (n % 2)
</code>```

But since the return value is a string, it fails when used in the expression.

The obvious solution is to simply cast the return value of binary() to a string from wherever it's being called. However, if for some reason you cannot do this, you can make a second function nested under binary, call this function inside of binary(), and cast its result to a string:

```<code>>>> def binary(n):
    def _binary(n):
        if n > 0:
            return _binary(n // 2) * 10 + (n % 2)

        else:
            return 0
    return str(_binary(n))

>>> binary(128)
'10000000'
>>> binary(64)
'1000000'
>>> binary(32)
'100000'
>>> binary(16)
'10000'
>>> binary(8)
'1000'
>>> binary(4)
'100'
>>> binary(2)
'10'
>>>
</code>```

As @StefanPochmann pointed out, this method would also work:

```<code>def binary(n):
    return binary(n // 2) + str(n % 2) if n > 1 else str(n)
</code>```

Title: python 3.6 put number is str

Body:
def binary(n):
    if n>0:
        return binary(n//2)*10 + (n%2)
    else:
        return 0

The answer is 10000000 but it have to be "10000000". How can I put str on the answer?

Body:
The problem with simply wrapping your return in a cast to str(), is that the subsequent calls to binary() will be affected, not just the top-level call. After the deepest recursive call to binary has finished, it will return its result - which is a string - to the next deepest recursive call to the expression:

binary(n // 2) * 10 + (n % 2)

But since the return value is a string, it fails when used in the expression.

The obvious solution is to simply cast the return value of binary() to a string from wherever it's being called. However, if for some reason you cannot do this, you can make a second function nested under binary, call this function inside of binary(), and cast its result to a string:

>>> def binary(n):
    def _binary(n):
        if n > 0:
            return _binary(n // 2) * 10 + (n % 2)

        else:
            return 0
    return str(_binary(n))

>>> binary(128)
'10000000'
>>> binary(64)
'1000000'
>>> binary(32)
'100000'
>>> binary(16)
'10000'
>>> binary(8)
'1000'
>>> binary(4)
'100'
>>> binary(2)
'10'
>>>

As @StefanPochmann pointed out, this method would also work:

def binary(n):
    return binary(n // 2) + str(n % 2) if n > 1 else str(n)


问:
Check if an array is descending, ascending or not sorted?
I'm just beginning with programming using javascript and I need to practice some questions to get EXP with the logic of code build.
I got this question for homework but I can't make it work for some reason, even though it seems "logic" to me.
Check if an array is descending, ascending or not sorted using loops.

I'm just a noob so please try and help me figure this out as I only got to loops in my studies (:
 this is the code I wrote:

```<code>        var array = [1, 2, 3, 7 ];
        var d = 0;
        var c =0 ;
        var b = 1;
        var a = 0;
        for (var i = 1; i <= array.length; i++)
            {
                if (array[c]<array[b] && a!== -1  ){
                   d = -1;
                   c =c+1;
                   b = b+1;
                   if(c==array.length){
                    console.log("asc");
                     break;
                   }else{
                     continue;
                }

                } else if (array[c]>array[b] && d!==-1 ){
                           a = -1;
                           d= d+1;
                           b = b+1;
                    if(i=array.length){
                    console.log("dsc");
                    break;
               }else{continue;}

               } else{

                    console.log("unsorted array");
                    break;
                }

            }
</code>```

答:
"Check if an array is descending, ascending or not sorted using loops"

// define the array
var array = [1,2,3,7];

// keep track of things
var isDescending = true;
var isAscending = true;

// we're looking ahead; loop from the first element to one before the last element
for (var i=0, l=array.length-1; i<l; i++)
{

   ////////////////////////////////////////////////////////////

   // log to the console to show what's happening for each loop iteration

   // this is the ith iteration
   console.log("loop iteration %s", i);

   // breaking isDescending down:
   // is this value greater than the next value?
   console.log("A: (%s > %s) = %s", array[i], array[i+1], (array[i] > array[i+1]));

   // have all values been descending so far?
   console.log("B: isDescending: %s", isDescending);

   // if this value is greater than the next and all values have been descending so far, isDescending remains true. Otherwise, it's set to false.
  console.log("are A and B both true? %s", (isDescending && (array[i] > array[i+1])));

   // add a line break for clarity
   console.log("");

   ////////////////////////////////////////////////////////////

   // true if this is greater than the next and all other so far have been true
   isDescending = isDescending && (array[i] > array[i+1]);

   // true if this is less than the next and all others so far have been true
   isAscending = isAscending && (array[i] < array[i+1]);

}

if (isAscending)
{
  console.log('Ascending');
}
else if (isDescending)
{
  console.log('Descending');
}
else
{
  console.log('Not Sorted');
}```

Body:
I'm just beginning with programming using javascript and I need to practice some questions to get EXP with the logic of code build.
I got this question for homework but I can't make it work for some reason, even though it seems "logic" to me.
Check if an array is descending, ascending or not sorted using loops.

I'm just a noob so please try and help me figure this out as I only got to loops in my studies (:
 this is the code I wrote:

        var array = [1, 2, 3, 7 ];
        var d = 0;
        var c =0 ;
        var b = 1;
        var a = 0;
        for (var i = 1; i <= array.length; i++)
            {
                if (array[c]<array[b] && a!== -1  ){
                   d = -1;
                   c =c+1;
                   b = b+1;
                   if(c==array.length){
                    console.log("asc");
                     break;
                   }else{
                     continue;
                }

                } else if (array[c]>array[b] && d!==-1 ){
                           a = -1;
                           d= d+1;
                           b = b+1;
                    if(i=array.length){
                    console.log("dsc");
                    break;
               }else{continue;}

               } else{

                    console.log("unsorted array");
                    break;
                }

            }


问:
How do i access all the JSON objects I got from MySQL individually - Android
I want to make a quiz app that gets everything from MySQL.
I got the data and I can call it and it will show in a Toast

here's my code

```<code>DataQA QA = null;
JSONArray jArray = new JSONArray(result);

for(int i = 0; i < jArray.length(); i++) {
    JSONObject json_data = jArray.getJSONObject(i);
    QA = new DataQA();
    QA.Question_no= json_data.getString("Question_no");
    QA.Answers= json_data.getString("Answers");
    QA.Correct= json_data.getString("Correct");
    QA.CR= json_data.getString("CR");
    QA.IDD= json_data.getString("IDD");
    QA.Question= json_data.getString("Question");
    data.add(QA);
}

Toast.makeText(MainActivity.this, QA.Question_no, Toast.LENGTH_SHORT).show();
</code>```

答:
It sounds like you can keep track of your questions with a HashMap

```<code>HashMap<String, QA> data = new HashMap<>();

JSONArray jArray = new JSONArray(result);
for (int i=0; i < jArray.length(); i++) {
  JSONObject json_data = jArray.getJSONObject(i);
  DataQA QA = new DataQA();
  QA.Question_no = json_data.getString("Question_no");
  QA.Answers = json_data.getString("Answers");
  QA.Correct = json_data.getString("Correct");
  QA.CR = json_data.getString("CR");
  QA.IDD = json_data.getString("IDD");
  QA.Question = json_data.getString("Question");
  data.add(QA.IDD, QA);
}

//now you can access any question you want by:
DataQA individualQuestion = data.get(/*QA IDD HERE*/);
</code>```

Notice how I'm keeping track of questions by using their ID. If you want, you can keep track of them with the question Question_no as long as all question numbers are distinct.

Body:
I want to make a quiz app that gets everything from MySQL.
I got the data and I can call it and it will show in a Toast

here's my code

DataQA QA = null;
JSONArray jArray = new JSONArray(result);

for(int i = 0; i < jArray.length(); i++) {
    JSONObject json_data = jArray.getJSONObject(i);
    QA = new DataQA();
    QA.Question_no= json_data.getString("Question_no");
    QA.Answers= json_data.getString("Answers");
    QA.Correct= json_data.getString("Correct");
    QA.CR= json_data.getString("CR");
    QA.IDD= json_data.getString("IDD");
    QA.Question= json_data.getString("Question");
    data.add(QA);
}

Toast.makeText(MainActivity.this, QA.Question_no, Toast.LENGTH_SHORT).show();

Body:
It sounds like you can keep track of your questions with a HashMap

HashMap<String, QA> data = new HashMap<>();

JSONArray jArray = new JSONArray(result);
for (int i=0; i < jArray.length(); i++) {
  JSONObject json_data = jArray.getJSONObject(i);
  DataQA QA = new DataQA();
  QA.Question_no = json_data.getString("Question_no");
  QA.Answers = json_data.getString("Answers");
  QA.Correct = json_data.getString("Correct");
  QA.CR = json_data.getString("CR");
  QA.IDD = json_data.getString("IDD");
  QA.Question = json_data.getString("Question");
  data.add(QA.IDD, QA);
}

//now you can access any question you want by:
DataQA individualQuestion = data.get(/*QA IDD HERE*/);

Notice how I'm keeping track of questions by using their ID. If you want, you can keep track of them with the question Question_no as long as all question numbers are distinct.


问:
Finding Currently Focused Application
I've been using this code to try and get the current process that's running (other that my application).

All over the internet it's been telling me to use the code below but it seems to be giving me issues.

```<code>[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();

[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

private string GetActiveWindowTitle()
{
    const int nChars = 256;
    StringBuilder Buff = new StringBuilder(nChars);
    IntPtr handle = GetForegroundWindow();

    if (GetWindowText(handle, Buff, nChars) > 0)
    {
     return Buff.ToString();
    }
  return null;
}
</code>```

It's giving me two errors.

Expected class, delegate, enum, interface, or struct

The modifier 'extern' is not valid for this item

Could anybody help?

答:
As stated by Rahul, put your code inside the class:</p>

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{

    public partial class Form1 : Form
    {

        [DllImport("user32.dll")]
        static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll")]
        static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

        public Form1()
        {
            InitializeComponent();
        }

        private string GetActiveWindowTitle()
        {
            const int nChars = 256;
            StringBuilder Buff = new StringBuilder(nChars);
            IntPtr handle = GetForegroundWindow();

            if (GetWindowText(handle, Buff, nChars) > 0)
            {
                return Buff.ToString();
            }
            return null;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string title = GetActiveWindowTitle();
            label1.Text = title;
        }

    }

}
</code>```

Title: Finding Currently Focused Application

Body:
I've been using this code to try and get the current process that's running (other that my application).

All over the internet it's been telling me to use the code below but it seems to be giving me issues.

[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();

[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

private string GetActiveWindowTitle()
{
    const int nChars = 256;
    StringBuilder Buff = new StringBuilder(nChars);
    IntPtr handle = GetForegroundWindow();

    if (GetWindowText(handle, Buff, nChars) > 0)
    {
     return Buff.ToString();
    }
  return null;
}

It's giving me two errors.

Expected class, delegate, enum, interface, or struct

The modifier 'extern' is not valid for this item

Could anybody help?

Body:
As stated by Rahul, put your code inside the class:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{

    public partial class Form1 : Form
    {

        [DllImport("user32.dll")]
        static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll")]
        static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

        public Form1()
        {
            InitializeComponent();
        }

        private string GetActiveWindowTitle()
        {
            const int nChars = 256;
            StringBuilder Buff = new StringBuilder(nChars);
            IntPtr handle = GetForegroundWindow();

            if (GetWindowText(handle, Buff, nChars) > 0)
            {
                return Buff.ToString();
            }
            return null;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string title = GetActiveWindowTitle();
            label1.Text = title;
        }

    }

}


问:
Convert string to array in Java?
I have a string which has the values like this (format is the same):

```<code>name:xxx
occupation:yyy
phone:zzz
</code>```

I want to convert this into an array and get the occupation value using indexes.

Any suggestions?

答: Read about Split functnio. You can split your text by " " and then by ":"</p>

Title: Convert string to array in Java?

Body:
I have a string which has the values like this (format is the same):

name:xxx
occupation:yyy
phone:zzz

I want to convert this into an array and get the occupation value using indexes.

Any suggestions?