问:
Adding ng-model to div using jQuery
I started with angular and I have a problem. I have this div. it contains div which displays {{stored}} value from angular javascript. When you type something inside a text box and clicks the button.

```<code><div>
  <div id="hidestore">{{stored}}</div> <input id="dobind" type="text" />
  <input type="button" id="showstore" value="show" />
</div>
</code>```

It calls this jquerycode which adds textbox a ng-model which corresponds to the {{stored}} above.
Basically I want div to display {{stored}} value from the time where the button is pressed (without using $scope).

```<code>$("#showstore").click(function() {
  $("#dobind").attr("ng-model", "stored")
});
</code>```

Sorry for my bad grammar. I need help!

答:
Its not good practice to use jquery with angularjs. You need to create one s for input box. and ng-click function for button. when you click on button assign input box text to stored ng-model.

angular.module('sample',[])
.controller('sampleCnt',function($scope){
$scope.show = function(){
  $scope.stored = $scope.text;
}
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="sample" ng-controller="sampleCnt">

        <div id="hidestore" >{{stored}}</div> <input id="dobind" type="text" ng-model="text"/>
        <input type="button" id="showstore" ng-click="show()" value="show"/>
    </div>

    </div></code>```

Title: Adding ng-model to div using jQuery

Body:
I started with angular and I have a problem. I have this div. it contains div which displays {{stored}} value from angular javascript. When you type something inside a text box and clicks the button.

{{stored}}
 <input id="dobind" type="text" />
  <input type="button" id="showstore" value="show" />

It calls this jquerycode which adds textbox a ng-model which corresponds to the {{stored}} above.
Basically I want div to display {{stored}} value from the time where the button is pressed (without using $scope).

$("#showstore").click(function() {
  $("#dobind").attr("ng-model", "stored")
});

Sorry for my bad grammar. I need help!

Body:
Its not good practice to use jquery with angularjs. You need to create one s for input box. and ng-click function for button. when you click on button assign input box text to stored ng-model.

angular.module('sample',[])
.controller('sampleCnt',function($scope){
$scope.show = function(){
  $scope.stored = $scope.text;
}
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="sample" ng-controller="sampleCnt">

        <div id="hidestore" >{{stored}}</div> <input id="dobind" type="text" ng-model="text"/>
        <input type="button" id="showstore" ng-click="show()" value="show"/>
    </div>

    </div>


来源: stackexchange

问:
Java: variable from parent class in child one isn't initialized and holds null
```<code>Parent class(*ch.qos.logback.core.FileAppender*):

     ...

   protected String fileName = null;

   public FileAppender() {
      }

          public void setFile(String file) {
            if (file == null) {
              fileName = file;
            } else {
              // Trim spaces from both ends. The users probably does not want
              // trailing spaces in file names.
              String val = file.trim();
              fileName = val;
            }
          }
    ...
</code>```

Child class:

```<code>    ...
   public class FileAppender<E> extends ch.qos.logback.core.FileAppender<E> {

     private FileResourceManager frm  = new FileResourceManager(fileName, tempDir, false, loggerFacade);

     public void writeOut(E event) throws IOException {
      Object txId = null;
      try {
       frm.start();
       txId = frm.generatedUniqueTxId();
       frm.startTransaction(txId);
       outputStream = frm.writeResource(txId, fileName, true);
       outputStream.write(event.toString().getBytes());
       frm.commitTransaction(txId);

      }

      catch (Exception e) {
    ...
      }
     }
</code>```

The problem is that fileName is passed as null to frm in this line:

```<code>private FileResourceManager frm  = new FileResourceManager(fileName, tempDir, false, loggerFacade);
</code>```

How can i create frm instance,with not-null fileName,e.g. already initialized in parent?

答: You have to call the setFile() method in the parent class.</p>

ContentLicense: CC BY-SA 2.5

Body:
Parent class(*ch.qos.logback.core.FileAppender*):

     ...

   protected String fileName = null;

   public FileAppender() {
      }

          public void setFile(String file) {
            if (file == null) {
              fileName = file;
            } else {
              // Trim spaces from both ends. The users probably does not want
              // trailing spaces in file names.
              String val = file.trim();
              fileName = val;
            }
          }
    ...

Child class:

    ...
   public class FileAppender<E> extends ch.qos.logback.core.FileAppender<E> {

     private FileResourceManager frm  = new FileResourceManager(fileName, tempDir, false, loggerFacade);

     public void writeOut(E event) throws IOException {
      Object txId = null;
      try {
       frm.start();
       txId = frm.generatedUniqueTxId();
       frm.startTransaction(txId);
       outputStream = frm.writeResource(txId, fileName, true);
       outputStream.write(event.toString().getBytes());
       frm.commitTransaction(txId);

      }

      catch (Exception e) {
    ...
      }
     }

The problem is that fileName is passed as null to frm in this line:

private FileResourceManager frm  = new FileResourceManager(fileName, tempDir, false, loggerFacade);

How can i create frm instance,with not-null fileName,e.g. already initialized in parent?


问:
How to setUp UiTableViewController below the battery bar
newBie here. I have added an UItableViewController into storyBoard. I use this as a setting page.

HomeVC ---->  Setting VC

In code : I use the below code to bring the tableView below the battery Bar:

```<code> self.tableView.contentInset = UIEdgeInsets(top: 20,left: 0,bottom: 0,right: 0)
</code>```

Problem:

How to move the TableView down below the battery bar so that I can add a button above the table in StoryBoard

Please help.

答:
After doing some search on UiTableViewController, to use it as setting page I have to set static cell to it. This UiTableViewController will occupy the entire view.
To set the tableView below the battery icon,
use:self.tableView.contentInset = UIEdgeInsets(top: 20,left: 0,bottom: 0,right: 0)

However, No need to do so. In the first TableViewSection, you can create a few tableView cell, just leave the first cell blank which acts as a margin below the battery bar.

ContentLicense: CC BY-SA 3.0

Body:
newBie here. I have added an UItableViewController into storyBoard. I use this as a setting page.

HomeVC ---->  Setting VC

In code : I use the below code to bring the tableView below the battery Bar:

 self.tableView.contentInset = UIEdgeInsets(top: 20,left: 0,bottom: 0,right: 0)

Problem:

How to move the TableView down below the battery bar so that I can add a button above the table in StoryBoard

Please help.


问:
MySql, can anyone suggest how to improve my query / index?
Can anyone suggest how I can improve my query, its used for a site map and theres 80000 pages, hence the limit.

Heres my query

```<code>SELECT PageName
FROM pads
WHERE RemoveMeDate = '2001-01-01 00:00:00'
ORDER BY PadID DESC
LIMIT 20000 , 30000
</code>```

Heres my EXPLAIN

Heres the indexes I have already

答:
Try not using any indexes.
How many rows are there in the table overall?

I notice that you are looking for 10k rows out of about 48k rows matching on just RemoveMeDate - the table must be large or you must be selecting a large proportion of the table.

```<code>SELECT PageName
FROM pads USE INDEX()
WHERE RemoveMeDate = '2001-01-01 00:00:00'
ORDER BY PadID DESC
LIMIT 20000 , 30000
</code>```

Not using any indexes forces it to just scan the table.
Now if that doesn't help and is slower, try to make a specific index that orders DESC, e.g. try one of the two below

```<code>CREATE INDEX IX_pads_rmd_iddesc ON pads (RemoveMeDate, PadID DESC, PageName)
CREATE INDEX IX_pads_rmd_iddesc ON pads (RemoveMeDate, PadID DESC)
</code>```

In conjunction with FORCE INDEX in case it doesn't get selected automatically

```<code>SELECT PageName
FROM pads USE INDEX(IX_pads_rmd_iddesc)
WHERE RemoveMeDate = '2001-01-01 00:00:00'
ORDER BY PadID DESC
LIMIT 20000 , 30000
</code>```

Note that even though the indexes re created "PadID DESC", it is ignored by MySQL. One can hope that one day when it gets implemented it will fall into place.

An index_col_name specification can
  end with ASC or DESC. These keywords
  are permitted for future extensions
  for specifying ascending or descending
  index value storage. Currently, they
  are parsed but ignored; index values
  are always stored in ascending order.

Body:
Can anyone suggest how I can improve my query, its used for a site map and theres 80000 pages, hence the limit.

Heres my query

SELECT PageName
FROM pads
WHERE RemoveMeDate = '2001-01-01 00:00:00'
ORDER BY PadID DESC
LIMIT 20000 , 30000

Heres my EXPLAIN

Heres the indexes I have already

Body:
Try not using any indexes.
How many rows are there in the table overall?

I notice that you are looking for 10k rows out of about 48k rows matching on just RemoveMeDate - the table must be large or you must be selecting a large proportion of the table.

SELECT PageName
FROM pads USE INDEX()
WHERE RemoveMeDate = '2001-01-01 00:00:00'
ORDER BY PadID DESC
LIMIT 20000 , 30000

Not using any indexes forces it to just scan the table.
Now if that doesn't help and is slower, try to make a specific index that orders DESC, e.g. try one of the two below

CREATE INDEX IX_pads_rmd_iddesc ON pads (RemoveMeDate, PadID DESC, PageName)
CREATE INDEX IX_pads_rmd_iddesc ON pads (RemoveMeDate, PadID DESC)

In conjunction with FORCE INDEX in case it doesn't get selected automatically

SELECT PageName
FROM pads USE INDEX(IX_pads_rmd_iddesc)
WHERE RemoveMeDate = '2001-01-01 00:00:00'
ORDER BY PadID DESC
LIMIT 20000 , 30000

Note that even though the indexes re created "PadID DESC", it is ignored by MySQL. One can hope that one day when it gets implemented it will fall into place.

An index_col_name specification can
  end with ASC or DESC. These keywords
  are permitted for future extensions
  for specifying ascending or descending
  index value storage. Currently, they
  are parsed but ignored; index values
  are always stored in ascending order.


问:
urllib.unquote_plus gives a different output on the same string
I'm a bit of a python noob and having problems understanding what's happening here. I'm decoding a URL encoded string. I have a file dump®.txt (the leading space is there on purpose). When I change my object type, I get two different results:

```<code>>>> string1 = u'+dump%C2%AE.txt'
>>> print urllib.unquote_plus(string1)
 dumpÂ®.txt

>>> string2 = '+dump%C2%AE.txt'
>>> print urllib.unquote_plus(string2)
 dump®.txt
</code>```

I was expecting was to see only the ® character for string1 and string2 (or maybe even the reverse behavior). Can anyone help me understand why is it that string1 needs to be a string type before I get my desired dump®.txt?

答:
Can anyone help me understand why is it that string1 needs to be a string type before I get my desired dump®.txt?

urllib does not support unicode, because urls can contain ASCII characters, by definition.  There is some crappy code in Python 2 that tries to do the right thing if you pass a unicode object, and it's buggy.

Passing a unicode object to urllib.unquote is user error - don't do that.  This is correct:

```<code>print urllib.unquote_plus(string1.encode())
</code>```

Body:
I'm a bit of a python noob and having problems understanding what's happening here. I'm decoding a URL encoded string. I have a file dump®.txt (the leading space is there on purpose). When I change my object type, I get two different results:

>>> string1 = u'+dump%C2%AE.txt'
>>> print urllib.unquote_plus(string1)
 dumpÂ®.txt

>>> string2 = '+dump%C2%AE.txt'
>>> print urllib.unquote_plus(string2)
 dump®.txt

I was expecting was to see only the ® character for string1 and string2 (or maybe even the reverse behavior). Can anyone help me understand why is it that string1 needs to be a string type before I get my desired dump®.txt?

Body:
Can anyone help me understand why is it that string1 needs to be a string type before I get my desired dump®.txt?

urllib does not support unicode, because urls can contain ASCII characters, by definition.  There is some crappy code in Python 2 that tries to do the right thing if you pass a unicode object, and it's buggy.

Passing a unicode object to urllib.unquote is user error - don't do that.  This is correct:

print urllib.unquote_plus(string1.encode())


问:
Slot Machine Java Game
I am making this java slot machine for school and have coded it. I am using JFrames but I cannot get the images to display on the screen.There seems to be a problem with the slot[] jLabel. a slot is an array that holds the three different reels. I dont know if the problem has to do with the gridlayout. Im confused </p>

```<code>package slots;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;

public class SlotMachineProgram extends JFrame {
  private int total = 2000; //this is the max bet you can have
  private int bet = 100; //default bet amount
  private int maxWin; //this variable stores the max wins

  private String[] symbols = {
    "Cherry",
    "Bear",
    "Diamond",
    "Penguin",
    "Star",
    "Shoe",
    "Banana",
    "Orange",
    "Apple"
  }; //symbols that are available for the slot machine

  //amount winning
  int[] gotTwo = {
    30,
    16,
    15,
    12,
    11,
    10,
    9,
    7,
    5
  }; //Prize moneys for two matches
  int[] gotThree = {
    60,
    32,
    30,
    24,
    22,
    20,
    18,
    14,
    10
  }; //prize money for three matches

  public JPanel slotPanel = new JPanel(new GridLayout(1, 3)); //creates a grid that holds the three slot options
  public JLabel[] slot = new JLabel[3]; //create the three slots

  //LABELS
  private JLabel amount = new JLabel("Total: $" + total); //this is the label for the total amount
  private JLabel betLabel = new JLabel("Bet: $" + bet); //this is the label for the bet amount

  //BUTTONS
  private JButton add50Button = new JButton("+50"); //creates a button called add50Button that adds 50 dollars to the bet
  private JButton spin = new JButton("Spin"); //creates a button that spins the slot machine
  private JButton maxBetButton = new JButton("Max"); //creates a button that makes the max amount the bet
  private JButton subtract50Button = new JButton("-50"); //creates a button that subtracts 50 from bet
  private JButton getBet = new JButton("Enter Bet"); //a button that pops up a new window that allows the user to type in a bet

  public SlotMachineProgram() { //constructor
    maxWin = total; //set win to total

    //Coloring Buttons
    spin.setBackground(Color.GREEN); //sets color of button to be green
    spin.setOpaque(true); //Sets Button Opaque so it can be seen
    maxBetButton.setBackground(Color.CYAN); //sets color of button to be green
    maxBetButton.setOpaque(true); //Sets Button Opaque so it can be seen
    add50Button.setBackground(Color.YELLOW); //sets color of button to be green
    add50Button.setOpaque(true); //Sets Button Opaque so it can be seen
    subtract50Button.setBackground(Color.MAGENTA); //sets color of button to be green
    subtract50Button.setOpaque(true); //Sets Button Opaque so it can be seen
    getBet.setBackground(Color.ORANGE); //sets color of button to be green
    getBet.setOpaque(true); //Sets Button Opaque so it can be seen

    //money panel
    JPanel moneyPanel = new JPanel(new GridLayout(2, 1)); //creates a grid called money panel that is 2x1 that stores total and bet
    moneyPanel.setBorder(new TitledBorder("Money")); //creates the title of the panel
    moneyPanel.add(amount); //adds the amount to the panel
    moneyPanel.add(betLabel); //adds the BetLabel to the panel

    //button panel
    JPanel buttonsPanel = new JPanel(new GridLayout(2, 1)); //creates a new panel called buttonsPanel that has all of the buttons
    JPanel buttonTopPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 2)); //this orients the buttons to the middle in a row
    buttonsPanel.setBorder(new TitledBorder("             Buttons")); //sets the title of the buttons panel to buttons

    buttonTopPanel.add(add50Button); //add the add50button to the button panel
    buttonTopPanel.add(spin); //adds a spin button
    buttonTopPanel.add(maxBetButton); //adds a max bet button

    JPanel BottomPanel = new JPanel(); //creates a panel for the bottom of the screen
    BottomPanel.add(subtract50Button); //adds the subtract 50 button
    BottomPanel.add(getBet); //adds the get bet button

    buttonsPanel.add(buttonTopPanel, BorderLayout.NORTH); //adds a border on the north edge
    buttonsPanel.add(BottomPanel, BorderLayout.SOUTH); //adds a border on the south edge

    // TODO
    //set slots to their default image
    slot[0] = new JLabel(new ImageIcon("/images/left.png"));
    slot[1] = new JLabel(new ImageIcon("/images/middle.png"));
    slot[2] = new JLabel(new ImageIcon("/images/right.png"));

    //add Action listeners to bet buttons
    add50Button.addActionListener(new ActionListener() { //action listener for the add 50 button
      @Override public void actionPerformed(ActionEvent e) { //makes an action performed method
        bet += 50; //increase bet by 50 if the button add50 is clicked
        if (bet > total) bet = total; //else skip
        betLabel.setText("Bet: $" + bet); //show the bet next to the bet label
      }
    });

    maxBetButton.addActionListener(new ActionListener() { //creates an action listener for the maxbetbutton
      @Override public void actionPerformed(ActionEvent e) { //creates a method for the maxbetbutton's action listener
        bet = total; //make bet the maxBet
        betLabel.setText("Bet: $" + bet); //show bet next to the bet label
      }
    });

    subtract50Button.addActionListener(new ActionListener() { //creates an actionlistener for the subtract 50 button
      @Override public void actionPerformed(ActionEvent e) { //creates an actionperformed method
        bet -= 50; //subtracts the value of the bet by 50
        if (bet < 0) bet = 0; //is the user tries to have a negative bet, set bet to 0
        betLabel.setText("Bet: $" + bet); //display the value of the bet next to a bet label
      }
    });

    getBet.addActionListener(new ActionListener() { //create an actionlistener for the getbet button that allows the user to type in a custom amount
      @Override public void actionPerformed(ActionEvent e) { // create an actionperformed method
        String input; //creates a variables called input of type string. This is what is displayed on the screen
        int betInput; //creates a variables called betInput of type int
        //"How much do you want to bet" is the text that appears in the bet amount window.
        //"Enter your bet amount" is the header on the bet window
        input = JOptionPane.showInputDialog(null,
          "How Much Do You Want To Bet? ", "Enter Your Bet Amount",
          JOptionPane.QUESTION_MESSAGE);
        betInput = Integer.parseInt(input); //set the user input to the betInput
        if (betInput > total) { //if the inputed value is more than the total amount of money they user has left
          bet = total; //set the bet to equal the amount of money the user has
        } else { //if the inputed bet amount is less than the total
          bet = betInput; //set the bet input the value of the bet
        }
        betLabel.setText("Bet: $" + bet); //updates the bet label to show the bet value next to its label
      }
    });

    spin.addActionListener(new ActionListener() { //creates an actionlistener for the spin button
      @Override
      public void actionPerformed(ActionEvent e) { //creates a method called actionperformed
        String[] rand = new String[3]; //creates an array of 3 strings
        int addTotal; //creates a variable called addTotal
        //generate 3 new slots
        for (int i = 0; i < 3; i++) { //loops through the three panes
          int choice; //creates a varaibe called choice
          double random = Math.random(); //creates a random variable and assigns it a random value
          random *= 8; //times the value by 8
          choice = (int) random; //assigns the value of choice to be random with a cast of int
          rand[i] = symbols[choice]; //assigns  the value rand at index i to be symbols at index choice
          slot[i].setIcon(new ImageIcon("/images/" + symbols[choice] + ".png")); //shows the image for the slot in the panel
          // TODO
        }

        //check for matches
        //three matches
        if (rand[0] == rand[1] && rand[1] == rand[2]) { //if there were three matches
          int index = 0; //creates a variable index of type int and assigns it to the value 0 and
          for (int i = 0; i < symbols.length; i++) //a loop that runs the length of symbols
            if (rand[0] == symbols[i]) { //if rand[0] is equal to symbols[i]
              index = i; //assign index to equal i
            }
          addTotal = bet * gotThree[index]; //increase addTotal by bet times gotThree[index], which stores the bonuses for triple pairs
          total += addTotal; //increment total by addTotal
          //pop-up menu saying the bet amount, the amount won and the updated total
          JOptionPane.showMessageDialog(null, "Your Bet: $" + bet + "\nYou Win: $" + addTotal + "\nMoney Left: $" + total,
            "Three Matches", JOptionPane.INFORMATION_MESSAGE);

          amount.setText("Total: $" + total); //set the label Total: to equal total
          if (total > maxWin) { //if the new total is greater than maxWin
            maxWin = total; //maxWin is now assigned to total
          }
        } else if (rand[0] == rand[1] || rand[1] == rand[2] || rand[2] == rand[0]) { //checks if there is a match between 2 tiles
          int match, index = 0; //creates integer variables match and index, assigning it to 0
          if (rand[0] == rand[1] || rand[0] == rand[2]) { //if the first box has a match
            match = 0; //match is assigned the value of 0
          } else { //if the second of third box has the match
            match = 1; //assign match to the value of 1
          }

          //find the index
          for (int i = 0; i < symbols.length; i++) { //A loop that iterates the amount of times of the length of symbols
            if (rand[0] == symbols[i]) { //if rand at index 0 is equal to symbols at index i
              index = i; //set index to equal i
            }
          }
          addTotal = bet * gotTwo[index]; //increment addTotal by bet*gotTwo[index]
          //Creates a pop-up window that displays the bet amount and the winnings
          JOptionPane.showMessageDialog(null, "Your Bet: $" + bet + "\nYou Win: $" + addTotal,
            "Two Matches", JOptionPane.INFORMATION_MESSAGE);
          total += addTotal; //increments total by addTotal
          amount.setText("Total: $" + total); //updates the text next to total
          if (total > maxWin) { //if the total is greater than maxWin
            maxWin = total; //set maxWin to total
          }

        } else { //run this is there are no matches
          total -= bet; //decrement  total by bet
          //Creates a pop-up window that shows the lost amount (bet) and the money left
          JOptionPane.showMessageDialog(null, "You Lost: $" + bet + "\nMoney Left: $" + total, "No Matches", JOptionPane.INFORMATION_MESSAGE);
          amount.setText("Total: $" + total); //updates the total amount that will be seen on the screen
          if (total > maxWin) { //if the total is greater than maxWin
            maxWin = total; //sets maxWin to equal total
          }
          if (bet > total) { //if bet is greater than the amount of money left (total) than
            bet = total; //set the bet to total
            betLabel.setText("Bet: $" + bet); //create the betLabel and update the value of it
          }
          if (total == 0) { //if the total is the
            bet = 0; //sets the bet value to equal 0
            betLabel.setText("Bet: $" + bet); //updates the betLabel to the new bet value
            //Creates a pop-up message saying "You Lost :( and it also displays the maximum amount that the user won
            JOptionPane.showMessageDialog(null, "You Lost :( \nThe Maximum That You Won Was $" + maxWin,
              "\nGame Over", JOptionPane.INFORMATION_MESSAGE);
            System.exit(0); //exit the program
          }
        }
      }
    });

    JPanel panelOnBottom = new JPanel(new BorderLayout()); //creates a panel on the bottom
    panelOnBottom.add(moneyPanel, BorderLayout.WEST); //adds the money panel to the west/left border of the window
    panelOnBottom.add(buttonsPanel, BorderLayout.EAST); //adds the buttons panel to the east/right border of the window

    // TODO
    JPanel all = new JPanel(new GridLayout(2, 1)); //creates a panel called all with a grid layout of 2x1
    slotPanel.setVisible(true);
    slotPanel.setOpaque(true);
    all.add(slotPanel); //adds slotPanel to the 'all' panel
    all.add(panelOnBottom); //adds the panelOnBottom to the 'all' panel
    add(all); //add all to the window

  }

  public static void main(String[] args) { //the main class
    JFrame frame = new SlotMachineProgram(); //creates a new frame of type SlotMachineProgram
    frame.setTitle("Gambling Time!"); //creates the title of the frame to be Gambling Time!
    frame.setLocationRelativeTo(null); //sets the location of the window to null, meaning it opens in the middle
    frame.setSize(400, 300); //sets the size of the window to be 400 by 300
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //sets the default close method to exit
    frame.setResizable(false); //makes the window not resizable
    frame.setVisible(true); //makes the window visible

  }
}
</code>```

答:
You have to add the jlables with images to the slotPanel first.

```<code>//set slots to their default image
slot[0] = new JLabel(new ImageIcon("/images/left.png"));
slot[1] = new JLabel(new ImageIcon("/images/middle.png"));
slot[2] = new JLabel(new ImageIcon("/images/right.png"));

slotPanel.add(slot[0]);
slotPanel.add(slot[1]);
slotPanel.add(slot[2]);
</code>```

Then, you are sure that all images exist in a /images directory as you declared at the first place in the code.

```<code>private String[] symbols = {
        "Cherry", "Bear",
        "Diamond", "Penguin",
        "Star", "Shoe",
        "Banana", "Orange",
        "Apple" }; // symbols that are available for the slot machine
</code>```

Title: Slot Machine Java Game

Body:
I am making this java slot machine for school and have coded it. I am using JFrames but I cannot get the images to display on the screen.There seems to be a problem with the slot[] jLabel. a slot is an array that holds the three different reels. I dont know if the problem has to do with the gridlayout. Im confused

package slots;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;

public class SlotMachineProgram extends JFrame {
  private int total = 2000; //this is the max bet you can have
  private int bet = 100; //default bet amount
  private int maxWin; //this variable stores the max wins

  private String[] symbols = {
    "Cherry",
    "Bear",
    "Diamond",
    "Penguin",
    "Star",
    "Shoe",
    "Banana",
    "Orange",
    "Apple"
  }; //symbols that are available for the slot machine

  //amount winning
  int[] gotTwo = {
    30,
    16,
    15,
    12,
    11,
    10,
    9,
    7,
    5
  }; //Prize moneys for two matches
  int[] gotThree = {
    60,
    32,
    30,
    24,
    22,
    20,
    18,
    14,
    10
  }; //prize money for three matches

  public JPanel slotPanel = new JPanel(new GridLayout(1, 3)); //creates a grid that holds the three slot options
  public JLabel[] slot = new JLabel[3]; //create the three slots

  //LABELS
  private JLabel amount = new JLabel("Total: $" + total); //this is the label for the total amount
  private JLabel betLabel = new JLabel("Bet: $" + bet); //this is the label for the bet amount

  //BUTTONS
  private JButton add50Button = new JButton("+50"); //creates a button called add50Button that adds 50 dollars to the bet
  private JButton spin = new JButton("Spin"); //creates a button that spins the slot machine
  private JButton maxBetButton = new JButton("Max"); //creates a button that makes the max amount the bet
  private JButton subtract50Button = new JButton("-50"); //creates a button that subtracts 50 from bet
  private JButton getBet = new JButton("Enter Bet"); //a button that pops up a new window that allows the user to type in a bet

  public SlotMachineProgram() { //constructor
    maxWin = total; //set win to total

    //Coloring Buttons
    spin.setBackground(Color.GREEN); //sets color of button to be green
    spin.setOpaque(true); //Sets Button Opaque so it can be seen
    maxBetButton.setBackground(Color.CYAN); //sets color of button to be green
    maxBetButton.setOpaque(true); //Sets Button Opaque so it can be seen
    add50Button.setBackground(Color.YELLOW); //sets color of button to be green
    add50Button.setOpaque(true); //Sets Button Opaque so it can be seen
    subtract50Button.setBackground(Color.MAGENTA); //sets color of button to be green
    subtract50Button.setOpaque(true); //Sets Button Opaque so it can be seen
    getBet.setBackground(Color.ORANGE); //sets color of button to be green
    getBet.setOpaque(true); //Sets Button Opaque so it can be seen

    //money panel
    JPanel moneyPanel = new JPanel(new GridLayout(2, 1)); //creates a grid called money panel that is 2x1 that stores total and bet
    moneyPanel.setBorder(new TitledBorder("Money")); //creates the title of the panel
    moneyPanel.add(amount); //adds the amount to the panel
    moneyPanel.add(betLabel); //adds the BetLabel to the panel

    //button panel
    JPanel buttonsPanel = new JPanel(new GridLayout(2, 1)); //creates a new panel called buttonsPanel that has all of the buttons
    JPanel buttonTopPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 2)); //this orients the buttons to the middle in a row
    buttonsPanel.setBorder(new TitledBorder("             Buttons")); //sets the title of the buttons panel to buttons

    buttonTopPanel.add(add50Button); //add the add50button to the button panel
    buttonTopPanel.add(spin); //adds a spin button
    buttonTopPanel.add(maxBetButton); //adds a max bet button

    JPanel BottomPanel = new JPanel(); //creates a panel for the bottom of the screen
    BottomPanel.add(subtract50Button); //adds the subtract 50 button
    BottomPanel.add(getBet); //adds the get bet button

    buttonsPanel.add(buttonTopPanel, BorderLayout.NORTH); //adds a border on the north edge
    buttonsPanel.add(BottomPanel, BorderLayout.SOUTH); //adds a border on the south edge

    // TODO
    //set slots to their default image
    slot[0] = new JLabel(new ImageIcon("/images/left.png"));
    slot[1] = new JLabel(new ImageIcon("/images/middle.png"));
    slot[2] = new JLabel(new ImageIcon("/images/right.png"));

    //add Action listeners to bet buttons
    add50Button.addActionListener(new ActionListener() { //action listener for the add 50 button
      @Override public void actionPerformed(ActionEvent e) { //makes an action performed method
        bet += 50; //increase bet by 50 if the button add50 is clicked
        if (bet > total) bet = total; //else skip
        betLabel.setText("Bet: $" + bet); //show the bet next to the bet label
      }
    });

    maxBetButton.addActionListener(new ActionListener() { //creates an action listener for the maxbetbutton
      @Override public void actionPerformed(ActionEvent e) { //creates a method for the maxbetbutton's action listener
        bet = total; //make bet the maxBet
        betLabel.setText("Bet: $" + bet); //show bet next to the bet label
      }
    });

    subtract50Button.addActionListener(new ActionListener() { //creates an actionlistener for the subtract 50 button
      @Override public void actionPerformed(ActionEvent e) { //creates an actionperformed method
        bet -= 50; //subtracts the value of the bet by 50
        if (bet < 0) bet = 0; //is the user tries to have a negative bet, set bet to 0
        betLabel.setText("Bet: $" + bet); //display the value of the bet next to a bet label
      }
    });

    getBet.addActionListener(new ActionListener() { //create an actionlistener for the getbet button that allows the user to type in a custom amount
      @Override public void actionPerformed(ActionEvent e) { // create an actionperformed method
        String input; //creates a variables called input of type string. This is what is displayed on the screen
        int betInput; //creates a variables called betInput of type int
        //"How much do you want to bet" is the text that appears in the bet amount window.
        //"Enter your bet amount" is the header on the bet window
        input = JOptionPane.showInputDialog(null,
          "How Much Do You Want To Bet? ", "Enter Your Bet Amount",
          JOptionPane.QUESTION_MESSAGE);
        betInput = Integer.parseInt(input); //set the user input to the betInput
        if (betInput > total) { //if the inputed value is more than the total amount of money they user has left
          bet = total; //set the bet to equal the amount of money the user has
        } else { //if the inputed bet amount is less than the total
          bet = betInput; //set the bet input the value of the bet
        }
        betLabel.setText("Bet: $" + bet); //updates the bet label to show the bet value next to its label
      }
    });

    spin.addActionListener(new ActionListener() { //creates an actionlistener for the spin button
      @Override
      public void actionPerformed(ActionEvent e) { //creates a method called actionperformed
        String[] rand = new String[3]; //creates an array of 3 strings
        int addTotal; //creates a variable called addTotal
        //generate 3 new slots
        for (int i = 0; i < 3; i++) { //loops through the three panes
          int choice; //creates a varaibe called choice
          double random = Math.random(); //creates a random variable and assigns it a random value
          random *= 8; //times the value by 8
          choice = (int) random; //assigns the value of choice to be random with a cast of int
          rand[i] = symbols[choice]; //assigns  the value rand at index i to be symbols at index choice
          slot[i].setIcon(new ImageIcon("/images/" + symbols[choice] + ".png")); //shows the image for the slot in the panel
          // TODO
        }

        //check for matches
        //three matches
        if (rand[0] == rand[1] && rand[1] == rand[2]) { //if there were three matches
          int index = 0; //creates a variable index of type int and assigns it to the value 0 and
          for (int i = 0; i < symbols.length; i++) //a loop that runs the length of symbols
            if (rand[0] == symbols[i]) { //if rand[0] is equal to symbols[i]
              index = i; //assign index to equal i
            }
          addTotal = bet * gotThree[index]; //increase addTotal by bet times gotThree[index], which stores the bonuses for triple pairs
          total += addTotal; //increment total by addTotal
          //pop-up menu saying the bet amount, the amount won and the updated total
          JOptionPane.showMessageDialog(null, "Your Bet: $" + bet + "\nYou Win: $" + addTotal + "\nMoney Left: $" + total,
            "Three Matches", JOptionPane.INFORMATION_MESSAGE);

          amount.setText("Total: $" + total); //set the label Total: to equal total
          if (total > maxWin) { //if the new total is greater than maxWin
            maxWin = total; //maxWin is now assigned to total
          }
        } else if (rand[0] == rand[1] || rand[1] == rand[2] || rand[2] == rand[0]) { //checks if there is a match between 2 tiles
          int match, index = 0; //creates integer variables match and index, assigning it to 0
          if (rand[0] == rand[1] || rand[0] == rand[2]) { //if the first box has a match
            match = 0; //match is assigned the value of 0
          } else { //if the second of third box has the match
            match = 1; //assign match to the value of 1
          }

          //find the index
          for (int i = 0; i < symbols.length; i++) { //A loop that iterates the amount of times of the length of symbols
            if (rand[0] == symbols[i]) { //if rand at index 0 is equal to symbols at index i
              index = i; //set index to equal i
            }
          }
          addTotal = bet * gotTwo[index]; //increment addTotal by bet*gotTwo[index]
          //Creates a pop-up window that displays the bet amount and the winnings
          JOptionPane.showMessageDialog(null, "Your Bet: $" + bet + "\nYou Win: $" + addTotal,
            "Two Matches", JOptionPane.INFORMATION_MESSAGE);
          total += addTotal; //increments total by addTotal
          amount.setText("Total: $" + total); //updates the text next to total
          if (total > maxWin) { //if the total is greater than maxWin
            maxWin = total; //set maxWin to total
          }

        } else { //run this is there are no matches
          total -= bet; //decrement  total by bet
          //Creates a pop-up window that shows the lost amount (bet) and the money left
          JOptionPane.showMessageDialog(null, "You Lost: $" + bet + "\nMoney Left: $" + total, "No Matches", JOptionPane.INFORMATION_MESSAGE);
          amount.setText("Total: $" + total); //updates the total amount that will be seen on the screen
          if (total > maxWin) { //if the total is greater than maxWin
            maxWin = total; //sets maxWin to equal total
          }
          if (bet > total) { //if bet is greater than the amount of money left (total) than
            bet = total; //set the bet to total
            betLabel.setText("Bet: $" + bet); //create the betLabel and update the value of it
          }
          if (total == 0) { //if the total is the
            bet = 0; //sets the bet value to equal 0
            betLabel.setText("Bet: $" + bet); //updates the betLabel to the new bet value
            //Creates a pop-up message saying "You Lost :( and it also displays the maximum amount that the user won
            JOptionPane.showMessageDialog(null, "You Lost :( \nThe Maximum That You Won Was $" + maxWin,
              "\nGame Over", JOptionPane.INFORMATION_MESSAGE);
            System.exit(0); //exit the program
          }
        }
      }
    });

    JPanel panelOnBottom = new JPanel(new BorderLayout()); //creates a panel on the bottom
    panelOnBottom.add(moneyPanel, BorderLayout.WEST); //adds the money panel to the west/left border of the window
    panelOnBottom.add(buttonsPanel, BorderLayout.EAST); //adds the buttons panel to the east/right border of the window

    // TODO
    JPanel all = new JPanel(new GridLayout(2, 1)); //creates a panel called all with a grid layout of 2x1
    slotPanel.setVisible(true);
    slotPanel.setOpaque(true);
    all.add(slotPanel); //adds slotPanel to the 'all' panel
    all.add(panelOnBottom); //adds the panelOnBottom to the 'all' panel
    add(all); //add all to the window

  }

  public static void main(String[] args) { //the main class
    JFrame frame = new SlotMachineProgram(); //creates a new frame of type SlotMachineProgram
    frame.setTitle("Gambling Time!"); //creates the title of the frame to be Gambling Time!
    frame.setLocationRelativeTo(null); //sets the location of the window to null, meaning it opens in the middle
    frame.setSize(400, 300); //sets the size of the window to be 400 by 300
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //sets the default close method to exit
    frame.setResizable(false); //makes the window not resizable
    frame.setVisible(true); //makes the window visible

  }
}

Body:
You have to add the jlables with images to the slotPanel first.

//set slots to their default image
slot[0] = new JLabel(new ImageIcon("/images/left.png"));
slot[1] = new JLabel(new ImageIcon("/images/middle.png"));
slot[2] = new JLabel(new ImageIcon("/images/right.png"));

slotPanel.add(slot[0]);
slotPanel.add(slot[1]);
slotPanel.add(slot[2]);

Then, you are sure that all images exist in a /images directory as you declared at the first place in the code.

private String[] symbols = {
        "Cherry", "Bear",
        "Diamond", "Penguin",
        "Star", "Shoe",
        "Banana", "Orange",
        "Apple" }; // symbols that are available for the slot machine


问:
Make a phone call from Cisco Jabber using .Net console app
I am trying to make a phone call from .Net console Application using Jabber client installed on my laptop.

I want to achieve something similar that you would achieve by the following anchor command in HTML:

```<code><a href="CISCOTELCONF:msmith@domain;amckenzi@domain">Weekly conference call</a>
</code>```

I want to run the same command through my console application so that it launches Jabber and make a call.

答:
I am not familiar with Jabber, but most likely the client has registered the CISCOTELCONF protocol (similar to how HTTP is registered to your default browser and MAILTO might open Outlook). Therefore you should be able to use Process.Start to pass the same URL to the shell, where it can decide what to do - hopefully invoking the Jabber client as it would if you clicked on the link. You can test this by copy-and-pasting the URL into Start-Run. If it works, then this should also.

```<code>var startInfo = new ProcessStartInfo("CISCOTELCONF:msmith@domain;amckenzi@domain")
{
    UseShellExecute = true
};

Process.Start(startInfo);
</code>```

Note the default for UseShellExecute is true, so you do not actually need this line. I've included it anyway because this is what causes Process.Start to, well, invoke the OS shell.

Body:
I am trying to make a phone call from .Net console Application using Jabber client installed on my laptop.

I want to achieve something similar that you would achieve by the following anchor command in HTML:

Weekly conference call

I want to run the same command through my console application so that it launches Jabber and make a call.

Body:
I am not familiar with Jabber, but most likely the client has registered the CISCOTELCONF protocol (similar to how HTTP is registered to your default browser and MAILTO might open Outlook). Therefore you should be able to use Process.Start to pass the same URL to the shell, where it can decide what to do - hopefully invoking the Jabber client as it would if you clicked on the link. You can test this by copy-and-pasting the URL into Start-Run. If it works, then this should also.

var startInfo = new ProcessStartInfo("CISCOTELCONF:msmith@domain;amckenzi@domain")
{
    UseShellExecute = true
};

Process.Start(startInfo);

Note the default for UseShellExecute is true, so you do not actually need this line. I've included it anyway because this is what causes Process.Start to, well, invoke the OS shell.


问:
How can I replace a the pattern ",," with <RETURN> in awk?
I am doing a ldapsearch query which returns the results as follow

```<code>John Joe jjoe@company.com +1 916 662-4727  Ann Tylor Atylor@company.com (987) 654-3210  Steve Harvey sharvey@company.com 4567893210  (321) 956-3344  ...
</code>```

As you can see between each personal record output there is a blank space and the phone numbers might start with +1 or not and might have blank between the numbers or parenthesis and finally between personal records there are two blank spaces. For example:

I would like to transform these entries to the following format:

```<code>John,Joe,jjoe@company.com,(916) 662-4727
Ann,Tylor,Atylor@company.com,(987) 654-3210
Steve,Harvey,sharvey@company.com,(456) 789-3210,(321) 956-3344
...
</code>```

So basically replace the one blanks with one comma "," and two blanks with , so that at the end I have one personal record (comma separated) per line. Example:

I am trying awk and have managed to replace  with "," which makes

```<code><blank><blank> to double comma ",,".
But can't figure out how to turn ",," to <RETURN>
</code>```

11/22/2017      ----******  UPDATE   ******---------           11/22/2017

I made this track too crowded. I will post a fresh questions with more details.

答:
For your request, a lot of replaces needed to be done by using sed.

```<code>$ cat sed-script
s/\ \ ([A-Za-z])/\n\1/g;        # replace alphabets which appended double spaced to '\n'
s/\ \ /,/g;                     # replace remaining double spaces to ','
s/([A-Za-z]) /\1,/g;            # releace the space appended alphabets to ','
s/\+1//;                        # eliminate +1
s/[ ()-]//g;                    # eliminate space, parenthesis, or dash
s/([^0-9])([0-9]{3})/\1(\2) /g; # modify first 3 numeric embraced by parenthesis
s/([0-9]{4}[^0-9])/-\1/g;       # prepend a '-' to last 4 numerics

$ sed -r -f sed-script file
John,Joe,jjoe@company.com,(916) 662-4727
Ann,Tylor,Atylor@company.com,(987) 654-3210
Steve,Harvey,sharvey@company.com,(456) 789-3210,(321) 956-3344,...
</code>```

Body:
I am doing a ldapsearch query which returns the results as follow

John Joe jjoe@company.com +1 916 662-4727  Ann Tylor Atylor@company.com (987) 654-3210  Steve Harvey sharvey@company.com 4567893210  (321) 956-3344  ...

As you can see between each personal record output there is a blank space and the phone numbers might start with +1 or not and might have blank between the numbers or parenthesis and finally between personal records there are two blank spaces. For example:

I would like to transform these entries to the following format:

John,Joe,jjoe@company.com,(916) 662-4727
Ann,Tylor,Atylor@company.com,(987) 654-3210
Steve,Harvey,sharvey@company.com,(456) 789-3210,(321) 956-3344
...

So basically replace the one blanks with one comma "," and two blanks with , so that at the end I have one personal record (comma separated) per line. Example:

I am trying awk and have managed to replace  with "," which makes

<blank><blank> to double comma ",,".
But can't figure out how to turn ",," to <RETURN>

11/22/2017      ----******  UPDATE   ******---------           11/22/2017

I made this track too crowded. I will post a fresh questions with more details.

Body:
For your request, a lot of replaces needed to be done by using sed.

$ cat sed-script
s/\ \ ([A-Za-z])/\n\1/g;        # replace alphabets which appended double spaced to '\n'
s/\ \ /,/g;                     # replace remaining double spaces to ','
s/([A-Za-z]) /\1,/g;            # releace the space appended alphabets to ','
s/\+1//;                        # eliminate +1
s/[ ()-]//g;                    # eliminate space, parenthesis, or dash
s/([^0-9])([0-9]{3})/\1(\2) /g; # modify first 3 numeric embraced by parenthesis
s/([0-9]{4}[^0-9])/-\1/g;       # prepend a '-' to last 4 numerics

$ sed -r -f sed-script file
John,Joe,jjoe@company.com,(916) 662-4727
Ann,Tylor,Atylor@company.com,(987) 654-3210
Steve,Harvey,sharvey@company.com,(456) 789-3210,(321) 956-3344,...


问:
Select all except particular column in spark sql
I want to select all columns in a table except StudentAddress and hence I wrote following query:

```<code>select `(StudentAddress)?+.+` from student;
</code>```

It gives following error in Squirrel Sql client.
org.apache.spark.sql.AnalysisException: cannot resolve '(StudentAddress)?+.+' given input columns

答:
You can use drop() method in the DataFrame API to drop a particular column and then select all the columns.

For example:

```<code>val df = hiveContext.read.table("student")
val dfWithoutStudentAddress = df.drop("StudentAddress")
</code>```

Body:
I want to select all columns in a table except StudentAddress and hence I wrote following query:

select `(StudentAddress)?+.+` from student;

It gives following error in Squirrel Sql client.
org.apache.spark.sql.AnalysisException: cannot resolve '(StudentAddress)?+.+' given input columns

Body:
You can use drop() method in the DataFrame API to drop a particular column and then select all the columns.

For example:

val df = hiveContext.read.table("student")
val dfWithoutStudentAddress = df.drop("StudentAddress")

ContentLicense: CC BY-SA 4.0


问:
if-statement overwriting my counter everytime in java
I'm trying to write a program that calculates the cost of a train ticket. I'm currently doing the method that adds any discounts to the current cost, I'm using if statements for it but every time it overwrites my previous calculation. How do I stop this?

here is my method so far... current is the current cost and amount is the amount of tickets the user wants.

```<code>public static double calcDiscounts(double a, double[] b) {

    double counter = 0;
    double current = b[1];
    double amount = b[0];

        System.out.println("You may be valid for discounts. Please answer these questions :"
                + "\nDo you have any under 10's travelling with you?\nType 1 for Yes\nType 2 for no");
        if (input.nextInt() == 1) {
            System.out.println("How many under 10's will be travelling with you?");
            int under = input.nextInt();
            if (under > amount - 1) {
                System.out.println("Invalid input - there must be at least one adult travelling alongside.");
            }
            double temp = a * under;
            counter += current - temp;

            System.out.println("The cost of your ticket(s) is now " + counter);
        }
        else {
            counter  = current;
        }

        System.out.println("Is anybody travelling with you under 16?\nType 1 for Yes\nType 2 for no");
        if (input.nextInt() == 1) {
            System.out.println("How many under 16's will be travelling with you?");
            int sixteen = input.nextInt();
            if (sixteen > amount) {
                System.out.println("Invalid input - you don't have this many tickets.");
            } else {
                double temp = a * 0.50;
                double next = temp * sixteen;
                counter = current - next;
                System.out.println("The cost of your ticket(s) is now " + counter);
            }
        }
        else {
            counter  = current;
        }

        System.out.println("Is anybody travel a student?\nType 1 for Yes\nType 2 for no");
        if (input.nextInt() == 1) {
            System.out.println("How many students will be travelling?");
            int student = input.nextInt();
            if (student > amount) {
                System.out.println("Invalid input - you don't have this many tickets.");
            } else {
                double temp = a * 0.25;
                double next = temp * student;
                counter = current - next;

                System.out.println("The cost of your ticket(s) is now " + counter);
            }
        }
        else {
            counter  = current;
        }

        System.out.println("Is anybody travelling over 60?\nType 1 for Yes\nType 2 for no");
        if (input.nextInt() == 1) {
            System.out.println("How many over 60's will be travelling?");
            int sixty = input.nextInt();
            if (sixty > amount) {
                System.out.println("Invalid input - you don't have this many tickets.");
            } else {
                double temp = a * 0.60;
                double next = temp * sixty;
                counter = current - next;

                System.out.println("The cost of your ticket(s) is now " + counter);
            }
        }
        else {
            counter  = current;
        }
    return counter;
}
</code>```

答:
You are override the value of counter in each if-else clause, and also there is no need to use counter since current will be enough.

Consider this code:

```<code>public static double calcDiscounts(double a, double[] b) {

    double current = b[1];
    double amount = b[0];

    Scanner input = new Scanner(System.in);
    System.out.println("You may be valid for discounts. Please answer these questions :"
            + "\nDo you have any under 10's travelling with you?\nType 1 for Yes\nType 2 for no");
    if (input.nextInt() == 1) {
        System.out.println("How many under 10's will be travelling with you?");
        int under = input.nextInt();
        if (under > amount - 1) {
            System.out.println("Invalid input - there must be at least one adult travelling alongside.");
        }
        double temp = a * under;
        current -= temp;

        System.out.println("The cost of your ticket(s) is now " + current);
    }

    System.out.println("Is anybody travelling with you under 16?\nType 1 for Yes\nType 2 for no");
    if (input.nextInt() == 1) {
        System.out.println("How many under 16's will be travelling with you?");
        int sixteen = input.nextInt();
        if (sixteen > amount) {
            System.out.println("Invalid input - you don't have this many tickets.");
        } else {
            double temp = a * 0.50;
            double next = temp * sixteen;
            current -=  next;
            System.out.println("The cost of your ticket(s) is now " + current);
        }
    }

    System.out.println("Is anybody travel a student?\nType 1 for Yes\nType 2 for no");
    if (input.nextInt() == 1) {
        System.out.println("How many students will be travelling?");
        int student = input.nextInt();
        if (student > amount) {
            System.out.println("Invalid input - you don't have this many tickets.");
        } else {
            double temp = a * 0.25;
            double next = temp * student;
            current -= next;

            System.out.println("The cost of your ticket(s) is now " + current);
        }
    }

    System.out.println("Is anybody travelling over 60?\nType 1 for Yes\nType 2 for no");
    if (input.nextInt() == 1) {
        System.out.println("How many over 60's will be travelling?");
        int sixty = input.nextInt();
        if (sixty > amount) {
            System.out.println("Invalid input - you don't have this many tickets.");
        } else {
            double temp = a * 0.60;
            double next = temp * sixty;
            current -= next;

            System.out.println("The cost of your ticket(s) is now " + current);
        }
    }
    return current;
}
</code>```

Body:
I'm trying to write a program that calculates the cost of a train ticket. I'm currently doing the method that adds any discounts to the current cost, I'm using if statements for it but every time it overwrites my previous calculation. How do I stop this?

here is my method so far... current is the current cost and amount is the amount of tickets the user wants.

public static double calcDiscounts(double a, double[] b) {

    double counter = 0;
    double current = b[1];
    double amount = b[0];

        System.out.println("You may be valid for discounts. Please answer these questions :"
                + "\nDo you have any under 10's travelling with you?\nType 1 for Yes\nType 2 for no");
        if (input.nextInt() == 1) {
            System.out.println("How many under 10's will be travelling with you?");
            int under = input.nextInt();
            if (under > amount - 1) {
                System.out.println("Invalid input - there must be at least one adult travelling alongside.");
            }
            double temp = a * under;
            counter += current - temp;

            System.out.println("The cost of your ticket(s) is now " + counter);
        }
        else {
            counter  = current;
        }

        System.out.println("Is anybody travelling with you under 16?\nType 1 for Yes\nType 2 for no");
        if (input.nextInt() == 1) {
            System.out.println("How many under 16's will be travelling with you?");
            int sixteen = input.nextInt();
            if (sixteen > amount) {
                System.out.println("Invalid input - you don't have this many tickets.");
            } else {
                double temp = a * 0.50;
                double next = temp * sixteen;
                counter = current - next;
                System.out.println("The cost of your ticket(s) is now " + counter);
            }
        }
        else {
            counter  = current;
        }

        System.out.println("Is anybody travel a student?\nType 1 for Yes\nType 2 for no");
        if (input.nextInt() == 1) {
            System.out.println("How many students will be travelling?");
            int student = input.nextInt();
            if (student > amount) {
                System.out.println("Invalid input - you don't have this many tickets.");
            } else {
                double temp = a * 0.25;
                double next = temp * student;
                counter = current - next;

                System.out.println("The cost of your ticket(s) is now " + counter);
            }
        }
        else {
            counter  = current;
        }

        System.out.println("Is anybody travelling over 60?\nType 1 for Yes\nType 2 for no");
        if (input.nextInt() == 1) {
            System.out.println("How many over 60's will be travelling?");
            int sixty = input.nextInt();
            if (sixty > amount) {
                System.out.println("Invalid input - you don't have this many tickets.");
            } else {
                double temp = a * 0.60;
                double next = temp * sixty;
                counter = current - next;

                System.out.println("The cost of your ticket(s) is now " + counter);
            }
        }
        else {
            counter  = current;
        }
    return counter;
}

Body:
You are override the value of counter in each if-else clause, and also there is no need to use counter since current will be enough.

Consider this code:

public static double calcDiscounts(double a, double[] b) {

    double current = b[1];
    double amount = b[0];

    Scanner input = new Scanner(System.in);
    System.out.println("You may be valid for discounts. Please answer these questions :"
            + "\nDo you have any under 10's travelling with you?\nType 1 for Yes\nType 2 for no");
    if (input.nextInt() == 1) {
        System.out.println("How many under 10's will be travelling with you?");
        int under = input.nextInt();
        if (under > amount - 1) {
            System.out.println("Invalid input - there must be at least one adult travelling alongside.");
        }
        double temp = a * under;
        current -= temp;

        System.out.println("The cost of your ticket(s) is now " + current);
    }

    System.out.println("Is anybody travelling with you under 16?\nType 1 for Yes\nType 2 for no");
    if (input.nextInt() == 1) {
        System.out.println("How many under 16's will be travelling with you?");
        int sixteen = input.nextInt();
        if (sixteen > amount) {
            System.out.println("Invalid input - you don't have this many tickets.");
        } else {
            double temp = a * 0.50;
            double next = temp * sixteen;
            current -=  next;
            System.out.println("The cost of your ticket(s) is now " + current);
        }
    }

    System.out.println("Is anybody travel a student?\nType 1 for Yes\nType 2 for no");
    if (input.nextInt() == 1) {
        System.out.println("How many students will be travelling?");
        int student = input.nextInt();
        if (student > amount) {
            System.out.println("Invalid input - you don't have this many tickets.");
        } else {
            double temp = a * 0.25;
            double next = temp * student;
            current -= next;

            System.out.println("The cost of your ticket(s) is now " + current);
        }
    }

    System.out.println("Is anybody travelling over 60?\nType 1 for Yes\nType 2 for no");
    if (input.nextInt() == 1) {
        System.out.println("How many over 60's will be travelling?");
        int sixty = input.nextInt();
        if (sixty > amount) {
            System.out.println("Invalid input - you don't have this many tickets.");
        } else {
            double temp = a * 0.60;
            double next = temp * sixty;
            current -= next;

            System.out.println("The cost of your ticket(s) is now " + current);
        }
    }
    return current;
}


问:
How to test the connection to a db2 database
I need to test the connection to a db2 database.

With oracle databases I'd execute a 'select * from dual' in order to do this.

But dual is specific for oracle. Is there a similar canonical test sql statement for db2?

答:
I ended up using

```<code>SELECT CURRENT SQLID FROM SYSIBM.SYSDUMMY1
</code>```

which seems to work nice.

Body:
I ended up using

SELECT CURRENT SQLID FROM SYSIBM.SYSDUMMY1

which seems to work nice.


问:
.net registered dll does not show function in vb6
net dll (PasswordHashLibrary) to be used in vb6 application. after creating the project, i went to project properties -> build -> Register for COM interop.

Then registered this dll on my machine using regasm command.
Started a fresh vb6 project -> added reference to PasswordHashLibrary

Now the vb6 project allows me to write the following

```<code>Dim objHash As New PasswordHashLibrary.Hash
</code>```

PasswordHashLibrary = namespace

Hash = Class

But it doesn't let me call any functions inside (class and functions are public)

for instance i have a static function

PasswordHashLibrary.Hash.HashPassword("abc")

It gives compile time error

method or data member not found

When i try to debug and look in object browser there is no member present

My Full .Net Code

```<code>namespace PasswordHashLibrary
{
public class Hash
{
    private const int PBKDF2IterCount = 1000; // default for Rfc2898DeriveBytes
    private const int PBKDF2SubkeyLength = 256 / 8; // 256 bits
    private const int SaltSize = 128 / 8; // 128 bits

    public static string HashPassword(string password)
    {

        //my code goes here
    }

  }
}
</code>```

答:
I removed the static attribute and added an interface that did the trick!</p>

```<code>namespace PasswordHashLibrary
{
public interface ComClassInterface
{
}

public class Hash : ComClassInterface
{

    private const int PBKDF2IterCount = 1000; // default for Rfc2898DeriveBytes
    private const int PBKDF2SubkeyLength = 256 / 8; // 256 bits
    private const int SaltSize = 128 / 8; // 128 bits

    //[ComVisible(true)]
    public string HashPassword(string password)
    {
       //my code goes here
    }
  }
}
</code>```

Body:
net dll (PasswordHashLibrary) to be used in vb6 application. after creating the project, i went to project properties -> build -> Register for COM interop.

Then registered this dll on my machine using regasm command.
Started a fresh vb6 project -> added reference to PasswordHashLibrary

Now the vb6 project allows me to write the following

Dim objHash As New PasswordHashLibrary.Hash

PasswordHashLibrary = namespace

Hash = Class

But it doesn't let me call any functions inside (class and functions are public)

for instance i have a static function

PasswordHashLibrary.Hash.HashPassword("abc")

It gives compile time error

method or data member not found

When i try to debug and look in object browser there is no member present

My Full .Net Code

namespace PasswordHashLibrary
{
public class Hash
{
    private const int PBKDF2IterCount = 1000; // default for Rfc2898DeriveBytes
    private const int PBKDF2SubkeyLength = 256 / 8; // 256 bits
    private const int SaltSize = 128 / 8; // 128 bits

    public static string HashPassword(string password)
    {

        //my code goes here
    }

  }
}

Body:
I removed the static attribute and added an interface that did the trick!

namespace PasswordHashLibrary
{
public interface ComClassInterface
{
}

public class Hash : ComClassInterface
{

    private const int PBKDF2IterCount = 1000; // default for Rfc2898DeriveBytes
    private const int PBKDF2SubkeyLength = 256 / 8; // 256 bits
    private const int SaltSize = 128 / 8; // 128 bits

    //[ComVisible(true)]
    public string HashPassword(string password)
    {
       //my code goes here
    }
  }
}


问:
Adding a SQL connection to my ASP.NET Core application - how to define ConnectionStrings
I am trying to connect my ASP.NET Core application to my database.

To do this I'm supposed to edit the appsettings.json file and define my default connection.

I am not sure what to put under Server and Database.

I am trying to connect the database StudentDB.

Here is what string I tried to use to connect to my database:

```<code>{
  "ConnectionStrings": {
    "DefaultConnection": "Server=ACTKPTP115;Database=StudentsDB;Trusted_Connection=True;MultipleActiveRes ultSets=true;"
},
</code>```

As you can see I connected the database in Visual Studio.

Here is the database I'm trying to connect in Microsoft SQL management studio:

What do I type in the ConnectionStrings under Server and Database to properly connect my server?

答:
This piece of code worked for me:</p>

```<code>{
"ConnectionStrings": {
    "DefaultConnection": "Server=tcp:xxUAT.domain.com,64609;Initial Catalog=IdentityDB;MultipleActiveResultSets=true;User ID=xx;Password=xx"
} }
</code>```

Body:
I am trying to connect my ASP.NET Core application to my database.

To do this I'm supposed to edit the appsettings.json file and define my default connection.

I am not sure what to put under Server and Database.

I am trying to connect the database StudentDB.

Here is what string I tried to use to connect to my database:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=ACTKPTP115;Database=StudentsDB;Trusted_Connection=True;MultipleActiveRes ultSets=true;"
},

As you can see I connected the database in Visual Studio.

Here is the database I'm trying to connect in Microsoft SQL management studio:

What do I type in the ConnectionStrings under Server and Database to properly connect my server?

Body:
This piece of code worked for me:

{
"ConnectionStrings": {
    "DefaultConnection": "Server=tcp:xxUAT.domain.com,64609;Initial Catalog=IdentityDB;MultipleActiveResultSets=true;User ID=xx;Password=xx"
} }


问:
how to add some data to sqlite database or sharedPrefence when installing apk
how to add some data to sqlite database or sharedPrefence when installing apk, which means the application has not been run once.</p>

答:
On SplashScreen, you can use boolean value to detect whether its first install or not. If it is first install, set the default values there, otherwise skip that.</p>

```<code>SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String alreadyInstalled = prefs.getBoolean("alreadyInstalled",false);
if(!alreadyInstalled){
     prefs.edit().putBoolean("alreadyInstalled",true).apply();
     // Do your initialization of default values here.
}
</code>```

Body:
On SplashScreen, you can use boolean value to detect whether its first install or not. If it is first install, set the default values there, otherwise skip that.

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String alreadyInstalled = prefs.getBoolean("alreadyInstalled",false);
if(!alreadyInstalled){
     prefs.edit().putBoolean("alreadyInstalled",true).apply();
     // Do your initialization of default values here.
}


问:
jquery positing problem
I have the following code. „YellowLeft“ and „YellowRight“ are buttons that move tabs tot he left or right. On startup oft he page I want „YellowLeft“ to hide since I can’t move the tabs to the left in the beginning. Once I scroll back to the beginning I want that button to disappear again.

To do that I have a variable called newPos which checkes if offset holds the same value. If it does, the „YellowLeft“ button should disappear again. But in theory the offset value never changes although I move the tabs to the left. So newPos and offset always hold the same value and the button disappear on the first click.

Where is my mistake?

Thanks!

```<code>$(document).ready(function()
        {

            $("#YellowLeft").hide();
            var offset = $("#Tab1").offset();
            var newPos = offset;
            newPos.left = offset.left;

            $("img").click(function()
            {
                var tabs_list = $("div#TabsWrapper > ul");
                if($(this).is("#YellowRight"))
                {
                    tabs_list.animate({ left: "-=155" }, 500);
                    $("#YellowLeft").show();
                    alert(newPos.left);
                }
                else if($(this).is("#YellowLeft"))
                {
                    tabs_list.animate({ left: "+=155" }, 500);

                    if (newPos.left == offset.left) {
                        $("#YellowLeft").hide();
                    }
                }
            });
        })
</code>```

答:
It would be useful to see the relevant HTML code, but I think you need to change the line:

```<code>if (newPos.left == offset.left) {
</code>```

to:

```<code>if ($('#Tab1').offset().left == offset.left) {
</code>```

Title: jquery positing problem

Body:
I have the following code. „YellowLeft“ and „YellowRight“ are buttons that move tabs tot he left or right. On startup oft he page I want „YellowLeft“ to hide since I can’t move the tabs to the left in the beginning. Once I scroll back to the beginning I want that button to disappear again.

To do that I have a variable called newPos which checkes if offset holds the same value. If it does, the „YellowLeft“ button should disappear again. But in theory the offset value never changes although I move the tabs to the left. So newPos and offset always hold the same value and the button disappear on the first click.

Where is my mistake?

Thanks!

$(document).ready(function()
        {

            $("#YellowLeft").hide();
            var offset = $("#Tab1").offset();
            var newPos = offset;
            newPos.left = offset.left;

            $("img").click(function()
            {
                var tabs_list = $("div#TabsWrapper > ul");
                if($(this).is("#YellowRight"))
                {
                    tabs_list.animate({ left: "-=155" }, 500);
                    $("#YellowLeft").show();
                    alert(newPos.left);
                }
                else if($(this).is("#YellowLeft"))
                {
                    tabs_list.animate({ left: "+=155" }, 500);

                    if (newPos.left == offset.left) {
                        $("#YellowLeft").hide();
                    }
                }
            });
        })

Body:
It would be useful to see the relevant HTML code, but I think you need to change the line:

if (newPos.left == offset.left) {

to:

if ($('#Tab1').offset().left == offset.left) {


问:
ArrayList contains case sensitivity
I am currently using the contains method belonging to the ArrayList class for making a search. Is there a way to make this search case insensitive in java? I found that in C# it is possible to use OrdinalIgnoreCase. Is there a java equivalent, or another way to do this?
Thanks.</p>

答:
If you don't want to create a new function, you can try this method:</p>

```<code>List<String> myList = new ArrayList<String>(); //The list you're checking
String wordToFind = "Test"; //or scan.nextLine() or whatever you're checking

//If your list has mix of uppercase and lowercase letters letters create a copy...
List<String> copyList = new ArrayList<String>();
for(String copyWord : myList){
   copyList.add(copyWord.toLowerCase());
}

for(String myWord : copyList){
   if(copyList.contains(wordToFind.toLowerCase()){
      //do something
   }
}
</code>```

Title: ArrayList contains case sensitivity

Body:
If you don't want to create a new function, you can try this method:

List<String> myList = new ArrayList<String>(); //The list you're checking
String wordToFind = "Test"; //or scan.nextLine() or whatever you're checking

//If your list has mix of uppercase and lowercase letters letters create a copy...
List<String> copyList = new ArrayList<String>();
for(String copyWord : myList){
   copyList.add(copyWord.toLowerCase());
}

for(String myWord : copyList){
   if(copyList.contains(wordToFind.toLowerCase()){
      //do something
   }
}


问:
YouTube Live Streaming API 'scheduledStartTime' Displaying Wrong Timezone to Viewers
When creating a new live event with the YouTube API I am having this problem. Despite passing the correct ISO 8601 date format, the timezone that is displayed to all viewers in GMT -7, not their local timezone. Here are the details:

I am working in JavaScript and making the following call:

```<code>gapi.client.youtube.liveBroadcasts.insert(
    {
      'part': 'snippet,status',
      'snippet':
        {
          'title': $("#title").val(),
          'scheduledStartTime': moment($('#datetime').data("DateTimePicker").date().format()).format(), // using datepicker and moment.js - looks like: 2017-10-31T16:02:05Z
          'description': $("#description").val() // optional
        },
          'status': {'privacyStatus': ($('input[name=privacy]:checked').val() == 'private') ? 'unlisted' : 'public' }
        }

     ).then(function(response){
...
</code>```

Here is the documentation which states the kind of datestring that is required:

The date and time that the broadcast is scheduled to start. The value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format.

https://developers.google.com/youtube/v3/live/docs/liveBroadcasts#snippet.scheduledStartTime

This is an example of a datestring I am passing, note the -04:00 for a US/Eastern Time Zone:

```<code>"2017-10-31T16:02:05Z"
</code>```

Despite that, YouTube creates the event at the right time but displays the  event in GMT-7, not the local timezone (I am EST) (see screen shot):

Any ideas what I am doing wrong or is this a possible bug in the API?

答:
I had submitted this question to the YouTube Partners API support.  I never heard back but I have noticed that now events flash between displaying in PST and Local time.  On the YouTube dashboard, the event also is stated in PST but it's nice to see local time on the "watch" page.

I don't know if my question contributed to this fix, but the behavior solves the problem I was having.

Body:
When creating a new live event with the YouTube API I am having this problem. Despite passing the correct ISO 8601 date format, the timezone that is displayed to all viewers in GMT -7, not their local timezone. Here are the details:

I am working in JavaScript and making the following call:

gapi.client.youtube.liveBroadcasts.insert(
    {
      'part': 'snippet,status',
      'snippet':
        {
          'title': $("#title").val(),
          'scheduledStartTime': moment($('#datetime').data("DateTimePicker").date().format()).format(), // using datepicker and moment.js - looks like: 2017-10-31T16:02:05Z
          'description': $("#description").val() // optional
        },
          'status': {'privacyStatus': ($('input[name=privacy]:checked').val() == 'private') ? 'unlisted' : 'public' }
        }

     ).then(function(response){
...

Here is the documentation which states the kind of datestring that is required:

The date and time that the broadcast is scheduled to start. The value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format.

https://developers.google.com/youtube/v3/live/docs/liveBroadcasts#snippet.scheduledStartTime

This is an example of a datestring I am passing, note the -04:00 for a US/Eastern Time Zone:

"2017-10-31T16:02:05Z"

Despite that, YouTube creates the event at the right time but displays the  event in GMT-7, not the local timezone (I am EST) (see screen shot):

Any ideas what I am doing wrong or is this a possible bug in the API?


问:
Property 'result' does not exist on type 'EventTarget'?
I have a Javascript inside my .ts file and it keep showing me that property 'result' does not exist on type 'EventTarget' ???

```<code>imageUpload() {

window.onload = function(){
    //Check File API support zzzz
        (<any>$('#files')).live("change", function(event) {
            var files = event.target.files; //FileList object
            var output = document.getElementById("result");
            for(var i = 0; i< files.length; i++)
            {
                var file = files[i];
                //Only pics
                // if(!file.type.match('image'))
                if(file.type.match('image.*')){
                    if(this.files[0].size < 2097152){
                  // continue;
                    var picReader = new FileReader();
                    picReader.addEventListener("load",function(event){
                        var picFile = event.target;
                        var div = document.createElement("div");
                        div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" +
                                "title='preview image'>";
                        output.insertBefore(div,null);
                    });
                    //Read the image
                    $('#clear, #result').show();
                    picReader.readAsDataURL(file);
                    }else{
                        alert("Image Size is too big. Minimum size is 2MB.");
                        $(this).val("");
                    }
                }else{
                alert("You can only upload image file.");
                $(this).val("");
            }
            }

        });
}
}
</code>```

In my HTML I used this input tag

```<code>    <input id="files" type="file" accept="image/*" multiple/>
</code>```

And my output tag like this

Why there is error inside the javascript ?? Anyone know what is the problem ? THanks !!!

答:
Looks like the event.target is of type FileReader and therefore try casting the event.target to the particular type to tell TypeScript that it will, in fact, have a .result value:

```<code>var picFile = <FileReader>event.target;
</code>```

See (here) for reference.

Body:
I have a Javascript inside my .ts file and it keep showing me that property 'result' does not exist on type 'EventTarget' ???

imageUpload() {

window.onload = function(){
    //Check File API support zzzz
        (<any>$('#files')).live("change", function(event) {
            var files = event.target.files; //FileList object
            var output = document.getElementById("result");
            for(var i = 0; i< files.length; i++)
            {
                var file = files[i];
                //Only pics
                // if(!file.type.match('image'))
                if(file.type.match('image.*')){
                    if(this.files[0].size < 2097152){
                  // continue;
                    var picReader = new FileReader();
                    picReader.addEventListener("load",function(event){
                        var picFile = event.target;
                        var div = document.createElement("div");
                        div.innerHTML = "";
                        output.insertBefore(div,null);
                    });
                    //Read the image
                    $('#clear, #result').show();
                    picReader.readAsDataURL(file);
                    }else{
                        alert("Image Size is too big. Minimum size is 2MB.");
                        $(this).val("");
                    }
                }else{
                alert("You can only upload image file.");
                $(this).val("");
            }
            }

        });
}
}

In my HTML I used this input tag

    <input id="files" type="file" accept="image/*" multiple/>

And my output tag like this

Why there is error inside the javascript ?? Anyone know what is the problem ? THanks !!!

Body:
Looks like the event.target is of type FileReader and therefore try casting the event.target to the particular type to tell TypeScript that it will, in fact, have a .result value:

var picFile = <FileReader>event.target;

See (here) for reference.


问:
Angular2 - *ngFor / loop through json object with array
Want to loop through json object

```<code>//Defined on component side :
jsonObj = {
    '1' : [ {"title" : "title1" , "desc" : "desc1" }],
    '2' : [ {"title" : "title2" , "desc" : "desc2" }],
    '3' : [ {"title" : "title3" , "desc" : "desc3" }],
    '4' : [ {"title" : "title4" , "desc" : "desc4" }],
    '5' : [ {"title" : "title5" , "desc" : "desc5" }]
}
</code>```

With *ngFor only on template side ,
And without any coding (function) on component side.

Want to print just each title and desc

Is this possible ? If Yes ? How ?

答:
So great to find the best solution from Angular itself provides pipe to loop through JSON , and its keyvalue

```<code><div *ngFor='let item of jsonObj | keyvalue'>
   Key: {{item.key}}

    <div *ngFor='let obj of item.value'>
        {{ obj.title }}
        {{ obj.desc }}
    </div>

</div>
</code>```

WORKIGN DEMO

Previously :

Component side :

```<code>objectKeys = Object.keys;
</code>```

Template side :

```<code><div *ngFor='let key of objectKeys(jsonObj)'>
   Key: {{key}}

    <div *ngFor='let obj of jsonObj[key]'>
        {{ obj.title }}
        {{ obj.desc }}
    </div>

</div>
</code>```

WORKING DEMO

Body:
Want to loop through json object

//Defined on component side :
jsonObj = {
    '1' : [ {"title" : "title1" , "desc" : "desc1" }],
    '2' : [ {"title" : "title2" , "desc" : "desc2" }],
    '3' : [ {"title" : "title3" , "desc" : "desc3" }],
    '4' : [ {"title" : "title4" , "desc" : "desc4" }],
    '5' : [ {"title" : "title5" , "desc" : "desc5" }]
}

With *ngFor only on template side ,
And without any coding (function) on component side.

Want to print just each title and desc

Is this possible ? If Yes ? How ?

Body:
So great to find the best solution from Angular itself provides pipe to loop through JSON , and its keyvalue

<div *ngFor='let item of jsonObj | keyvalue'>
   Key: {{item.key}}

    <div *ngFor='let obj of item.value'>
        {{ obj.title }}
        {{ obj.desc }}
    </div>

</div>

WORKIGN DEMO

Previously :

Component side :

objectKeys = Object.keys;

Template side :

<div *ngFor='let key of objectKeys(jsonObj)'>
   Key: {{key}}

    <div *ngFor='let obj of jsonObj[key]'>
        {{ obj.title }}
        {{ obj.desc }}
    </div>

</div>

WORKING DEMO


问:
Write semi-colon seperated email addresses into a csv file
I have a file email.txt which has email addresses as follows:

James, Brian < brian.james@abc.com>; Attar, Daniel < Daniel.Attar@abc.com>; Alex, James < james.alex@abc.com>; Trendy, Elizabeth < elizabeth.trendy@abc.com>; jones, Gary < Gary.Jones@abc.com>; bones, byron < byron.bones@abc.com>;

I want to write the email addresses into a .csv file in one column like this:

```<code>brian.james@abc.com
daniel.attar@abc.com
...
byron.bones@abc.com
</code>```

I wrote a Python script as follows which does this:

```<code>    fn1 = "email.txt"
    f1 = open(fn1,"r")
    f1r1 = f1.readlines()
    f1r2 = [i.strip() for i in f1r1]
    f1r3 = [i.split(";") for i in f1r2]
    s1 = f1r3[0]
    a = open("ef.csv","w")
    for i in s1:
        j = i.split("<")
        a.write(j[1].strip(">")+"\n")
    a.close()
</code>```

Is there a better, more efficient or more elegant way to write this?

答:
You could consider reading the contents of the text file as a single string and then using re to extract the emails from that string.

In this case, it looks like your email format is fairly specific, so the regex below is also specific also.  Realize, though, that a regex capable of finding any RFC 5322-compliant email address (the "official standard" for email address formats) is several hundred characters long.  For more on that see How to Find or Validate an Email Address from Jan Goyvaerts.

Anyway...

```<code>import re

with open('emails.txt', 'r') as file:
    # Produces a single string, `emails`
    emails = file.read().replace('\n', '')

regex = re.compile('\S+\.\S+@abc\.com')

for email in regex.findall(emails):
    print(email)
# brian.james@abc.com
# Daniel.Attar@abc.com
# james.alex@abc.com
# elizabeth.trendy@abc.com
# Gary.Jones@abc.com
# byron.bones@abc.com
</code>```

Regex walkthrough: this regex assumes each email takes a pretty specific form: something<dot>somethingelse<at>abc.com.

\S+ is 1 or more non-whitespace characters

\. is a literal period (backslashing a metacharacter)

Body:
I have a file email.txt which has email addresses as follows:

James, Brian < brian.james@abc.com>; Attar, Daniel < Daniel.Attar@abc.com>; Alex, James < james.alex@abc.com>; Trendy, Elizabeth < elizabeth.trendy@abc.com>; jones, Gary < Gary.Jones@abc.com>; bones, byron < byron.bones@abc.com>;

I want to write the email addresses into a .csv file in one column like this:

brian.james@abc.com
daniel.attar@abc.com
...
byron.bones@abc.com

I wrote a Python script as follows which does this:

    fn1 = "email.txt"
    f1 = open(fn1,"r")
    f1r1 = f1.readlines()
    f1r2 = [i.strip() for i in f1r1]
    f1r3 = [i.split(";") for i in f1r2]
    s1 = f1r3[0]
    a = open("ef.csv","w")
    for i in s1:
        j = i.split("<")
        a.write(j[1].strip(">")+"\n")
    a.close()

Is there a better, more efficient or more elegant way to write this?

Body:
You could consider reading the contents of the text file as a single string and then using re to extract the emails from that string.

In this case, it looks like your email format is fairly specific, so the regex below is also specific also.  Realize, though, that a regex capable of finding any RFC 5322-compliant email address (the "official standard" for email address formats) is several hundred characters long.  For more on that see How to Find or Validate an Email Address from Jan Goyvaerts.

Anyway...

import re

with open('emails.txt', 'r') as file:
    # Produces a single string, `emails`
    emails = file.read().replace('\n', '')

regex = re.compile('\S+\.\S+@abc\.com')

for email in regex.findall(emails):
    print(email)
# brian.james@abc.com
# Daniel.Attar@abc.com
# james.alex@abc.com
# elizabeth.trendy@abc.com
# Gary.Jones@abc.com
# byron.bones@abc.com

Regex walkthrough: this regex assumes each email takes a pretty specific form: something<dot>somethingelse<at>abc.com.

\S+ is 1 or more non-whitespace characters

\. is a literal period (backslashing a metacharacter)


问:
CSS: aligning elements inside a div
I have a div that contains three elements, and I am having problems correctly positioning the last one. The div at the left has to be at the left, the one in the middle needs to be centered, and the third one needs to be to the right.

So, I have something like:

```<code>#left-element {
    margin-left: 9px;
    margin-top: 3px;
    float:left;
    width: 13px;
}

#middle-element {
    margin:0 auto;
    text-align: center;
    width: 300px;
}

#right-element {
    float:right;
    width: 100px;
}
</code>```

My html looks like this:

```<code>   <div id="container-div">
        <div id="left-element">
            <img src="images/left_element.png" alt="left"/>
        </div>
        <div id="middle-element">
            I am the text inside the middle element
        </div>
        <div id="right-element">
            I am the text in right element
        </div>
    </div>
</code>```

Any ideas?

Thanks!

答:
I had the exact same issue. I used this approach. I made the center element display inline-block. That way I didn't have to give the elements specific width or the main container a specific height. The blocks only took up as much space as the content inside. Hope this helps.

.main-nav {
  text-align: center;
  padding: 2em 3em;
  background: #f4f4f4;
}

#logo {
  margin: 0;
  width: 50px;
  float: left;
  margin-top: 18px;
}

#logo-link {
  float: left;
  display: inline-block;
}

.name {
  display: inline-block;
}

.nav {
  float: right;
  margin-top: 18px;
}
.nav li {
  float: left;
  margin-right: 15px;
  margin-top: 5px;
}

.nav li:last-child {
  margin-right: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header class="clearfix">
      <div class="main-nav">
        <img src="img/site-logo.svg" alt="Munchies" id="logo">

          <div class="name">
            <h1>The Munchies Family Site</h1>
            <h2>Designer</h2>
          </div>

        <nav class="nav clearfix">
          <ul>
            <li>Gallery</li>
            <li>About</li>
            <li>Contact</li>
          </ul>
        </nav>
      </div>
    </header></code>```

strong text

Title: CSS: aligning elements inside a div

Body:
I have a div that contains three elements, and I am having problems correctly positioning the last one. The div at the left has to be at the left, the one in the middle needs to be centered, and the third one needs to be to the right.

So, I have something like:

#left-element {
    margin-left: 9px;
    margin-top: 3px;
    float:left;
    width: 13px;
}

#middle-element {
    margin:0 auto;
    text-align: center;
    width: 300px;
}

#right-element {
    float:right;
    width: 100px;
}

My html looks like this:

            I am the text inside the middle element

            I am the text in right element

Any ideas?

Thanks!

Body:
I had the exact same issue. I used this approach. I made the center element display inline-block. That way I didn't have to give the elements specific width or the main container a specific height. The blocks only took up as much space as the content inside. Hope this helps.

.main-nav {
  text-align: center;
  padding: 2em 3em;
  background: #f4f4f4;
}

#logo {
  margin: 0;
  width: 50px;
  float: left;
  margin-top: 18px;
}

#logo-link {
  float: left;
  display: inline-block;
}

.name {
  display: inline-block;
}

.nav {
  float: right;
  margin-top: 18px;
}
.nav li {
  float: left;
  margin-right: 15px;
  margin-top: 5px;
}

.nav li:last-child {
  margin-right: 0;
}

<header class="clearfix">
      <div class="main-nav">
        <a href="index.html" id="logo-link" class="clearfix"><img src="img/site-logo.svg" alt="Munchies" id="logo"></a>

          <div class="name">
            <h1>The Munchies Family Site</h1>
            <h2>Designer</h2>
          </div>

        <nav class="nav clearfix">
          <ul>
            <li><a href="index.html">Gallery</a></li>
            <li><a href="about.html">About</a></li>
            <li><a href="contact.html">Contact</a></li>
          </ul>
        </nav>
      </div>
    </header>

strong text


问:
Adding ng-model to div using jQuery
I started with angular and I have a problem. I have this div. it contains div which displays {{stored}} value from angular javascript. When you type something inside a text box and clicks the button.

```<code><div>
  <div id="hidestore">{{stored}}</div> <input id="dobind" type="text" />
  <input type="button" id="showstore" value="show" />
</div>
</code>```

It calls this jquerycode which adds textbox a ng-model which corresponds to the {{stored}} above.
Basically I want div to display {{stored}} value from the time where the button is pressed (without using $scope).

```<code>$("#showstore").click(function() {
  $("#dobind").attr("ng-model", "stored")
});
</code>```

Sorry for my bad grammar. I need help!

答:
Using jquery in angularjs is a bad practise but it is not that you can't achieve what you are trying. Instead of binding the ng-model on show, you need to prebind it. Just hide the hidestore div at first and make it show after you click the show button, which has a really good way to ng-show in angularjs.

angular.module('myApp',[])
.controller('myAppCtrl',function($scope){
        $('#hidestore').css('display','none');
     $("#showstore").click(function(){
        $('#hidestore').css('display','block');
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
 <script data-require="jquery@*" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div ng-app="myApp" ng-controller="myAppCtrl">

      <div>
    <div id="hidestore">{{stored}}</div>
    <input id="dobind" type="text" ng-model="stored"/>
    <input type="button" id="showstore" value="show" />
  </div>
    </div></code>```

Title: Adding ng-model to div using jQuery

Body:
I started with angular and I have a problem. I have this div. it contains div which displays {{stored}} value from angular javascript. When you type something inside a text box and clicks the button.

{{stored}}
 <input id="dobind" type="text" />
  <input type="button" id="showstore" value="show" />

It calls this jquerycode which adds textbox a ng-model which corresponds to the {{stored}} above.
Basically I want div to display {{stored}} value from the time where the button is pressed (without using $scope).

$("#showstore").click(function() {
  $("#dobind").attr("ng-model", "stored")
});

Sorry for my bad grammar. I need help!

Body:
Using jquery in angularjs is a bad practise but it is not that you can't achieve what you are trying. Instead of binding the ng-model on show, you need to prebind it. Just hide the hidestore div at first and make it show after you click the show button, which has a really good way to ng-show in angularjs.

angular.module('myApp',[])
.controller('myAppCtrl',function($scope){
        $('#hidestore').css('display','none');
     $("#showstore").click(function(){
        $('#hidestore').css('display','block');
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
 <script data-require="jquery@*" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div ng-app="myApp" ng-controller="myAppCtrl">

      <div>
    <div id="hidestore">{{stored}}</div>
    <input id="dobind" type="text" ng-model="stored"/>
    <input type="button" id="showstore" value="show" />
  </div>
    </div>


问:
the library's API can't be used after I update gradle to 4.1
After I updated Android Studio to 3.0,at the same time,I update gradle to 4.1。But,the library's API can't be used. Such as app module dependent on app1 module,then,app1 module dependent on app2 module,I can't use app2 module's API in app module。But，before gradle 4.1,it works。</p>

答:
I met the same problem after solve my error

Error:Cannot choose between the following configurations of project :lp_messaging_sdk:
    - debugApiElements
    - debugRuntimeElements
    - releaseApiElements
    - releaseRuntimeElements

with the answer #33.So,I update gradle to 4.3 and delete the "configuration: 'default'",then,my project built success