问:
Find out if USB device is connected. Ruby in Linux
I'm using Ruby 1.8 and linux (Ubuntu and SLAX), and i need to write a script in ruby which  finds out if some specific usb device is connected to the system and on which USB port (0,1,2, etc). It was done before with the help of HAL (hal-find-by-capability --capability serial), but now i can't use this approach. I was trying to read /var/log/messages file trying to find the number of the usb port, but it appears that this number may not be written in some systems. Other thing i tried is to check /dev folder and search for ttyUSB# file, but it doesn't appear on some system when new device connects to USB.
I would appreciate any ideas how to do this.</p>

答:
lsusb is a linux command for displaying your usb hubs and listing the devices that are connected to them.  In ruby I believe you'd be able to do something like this:

```<code>ls_results = `lsusb`
</code>```

You should be able to parse that for whatever device you're looking for.

Body:
lsusb is a linux command for displaying your usb hubs and listing the devices that are connected to them.  In ruby I believe you'd be able to do something like this:

ls_results = `lsusb`

You should be able to parse that for whatever device you're looking for.


来源: stackexchange

问:
Inverting tridiagonal matrix
I am having an equation

Ax=By

Where A and  B are tridiagonal matrices. I want to calculate a matrix

C=inv (A).B

there are different x,s which will give different y,s hence calculation of C is handy.

Can someone please tell me a faster method to compute the inverse. I am using Python 3.5 and prefer if we use any method from numpy. If not possible I can use scipy or cython as second and third choice.

I have seen other similar questions but they do not fully match with my problem.

Thank you

答:
scipy.linalg.solve_banded is a wrapper for LAPACK which should in turn call MKL. It seems to run O(N). For a trivial example to show syntax</p>

```<code>  a = np.array([[1,2,0,0], [-1,2,1,0], [0,1,3,1], [0,0,1,2]])
  x = np.array([1,2,3,4])
  b = np.dot(a,x)
  ab = np.empty((3,4))
  ab[0,1:] = np.diag(a,1)
  ab[1,:] = np.diag(a,0)
  ab[2,:-1] = np.diag(a,-1)
  y =  solve_banded((1,1),ab,b)
  print y
</code>```

ContentLicense: CC BY-SA 3.0

Title: Inverting tridiagonal matrix

Body:
scipy.linalg.solve_banded is a wrapper for LAPACK which should in turn call MKL. It seems to run O(N). For a trivial example to show syntax

  a = np.array([[1,2,0,0], [-1,2,1,0], [0,1,3,1], [0,0,1,2]])
  x = np.array([1,2,3,4])
  b = np.dot(a,x)
  ab = np.empty((3,4))
  ab[0,1:] = np.diag(a,1)
  ab[1,:] = np.diag(a,0)
  ab[2,:-1] = np.diag(a,-1)
  y =  solve_banded((1,1),ab,b)
  print y


问:
How to create a .txt file whose name is based on user input using c++
I wish to create several .txt files to store information about cars. Each .txt file will store the information for one car. I will ask the user to input the car information, such as CarId, Make, Model etc. I wish to name the .txt file using CarId given by the user. How can I realize this using c++ 11?

Thank you!

答:
You can try this:</p>

```<code>#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
string filename; // string to take input
ofstream out; // Object to create file
getline(cin, filename); // Taking input for file Name
out.open(filename + ".txt"); // To create .txt file
out.close();
return 0;
}
</code>```

Body:
You can try this:

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
string filename; // string to take input
ofstream out; // Object to create file
getline(cin, filename); // Taking input for file Name
out.open(filename + ".txt"); // To create .txt file
out.close();
return 0;
}


问:
how to prevent super-class from calling overriden sub-class methods?
I just ran into this issue, and it has taken me by surprise.

super-class:

```<code>public class Foo {

    @Override
    public String toString(){
        return String.format("Result = %s", calculate());
    }
    public double calculate(){
        return 1;
    }
}
</code>```

sub-class:

```<code>public class Bar extends Foo {
    @Override
    public String toString(){
        return String.format("%s", super.toString());
    }
    @Override
    public double calculate(){
        return 123.456;
    }
}
</code>```

driver:

```<code>public static void main(String[] args) {
    System.out.println(new Bar().toString());
}
</code>```

The output I desire in this scenario is 1
The output I get is 123.456

How do I prevent Foo's toString() from calling Bar's calculate() ?

答:
If you don't want to let subclasses override calculate at all, mark it final:

```<code>public final double calculate() {
    ...
}
</code>```

If you want to let them override calculate, but you don't want to use the overrides in this particular location, put the implementation of calculate in a private method and use the private version:

```<code>public double calculate() {
    return _calculate();
}
private double _calculate() {
    return 1.0;
}
@Override
public String toString(){
    return String.format("Result = %s", _calculate());
}
</code>```

Body:
I just ran into this issue, and it has taken me by surprise.

super-class:

public class Foo {

    @Override
    public String toString(){
        return String.format("Result = %s", calculate());
    }
    public double calculate(){
        return 1;
    }
}

sub-class:

public class Bar extends Foo {
    @Override
    public String toString(){
        return String.format("%s", super.toString());
    }
    @Override
    public double calculate(){
        return 123.456;
    }
}

driver:

public static void main(String[] args) {
    System.out.println(new Bar().toString());
}

The output I desire in this scenario is 1
The output I get is 123.456

How do I prevent Foo's toString() from calling Bar's calculate() ?

Body:
If you don't want to let subclasses override calculate at all, mark it final:

public final double calculate() {
    ...
}

If you want to let them override calculate, but you don't want to use the overrides in this particular location, put the implementation of calculate in a private method and use the private version:

public double calculate() {
    return _calculate();
}
private double _calculate() {
    return 1.0;
}
@Override
public String toString(){
    return String.format("Result = %s", _calculate());
}


问:
I can't get my drawed picture in browser
This is the HTML code:

```<code><body >
<canvas id ="my_canvas" width =500 height =500></canvas>
</body >
</code>```

This is my JavaScript code:

```<code>var canvas = document.getElememtById("my_canvas");
var c=canvas.getContext("2d");
c.beginPath();
c.moveTo(100,200);
c.lineTo(200,200);
c.fill();
c.stroke();
c.endPath();
</code>```

After all done,I can't see anything in browser.

答:
working
example
HTML

```<code><canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
    </canvas>
</code>```

javascript

```<code>var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
</code>```

Body:
This is the HTML code:

<canvas id ="my_canvas" width =500 height =500></canvas>

This is my JavaScript code:

var canvas = document.getElememtById("my_canvas");
var c=canvas.getContext("2d");
c.beginPath();
c.moveTo(100,200);
c.lineTo(200,200);
c.fill();
c.stroke();
c.endPath();

After all done,I can't see anything in browser.

Body:
working
example
HTML

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
    </canvas>

javascript

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();


答:
You cannot do it directly - you have overridden calculate() and since you have a Bar object it will always be Bar.calculate() that is called when calculate() is used1. It would very confusing and hard to make reasonable OoO designs if it were any other way!

If you really want the behavior as described, the usual solution is simply to have Foo.toString() call a non-overridable (e.g., private or final) helper method that implements the logic that you have in Foo.calculate(). Then you can be assured that toString() always behaves in the same way, even when Foo is overridden2. Then, you can implement Foo.calculate() by calling this helper method, pleasing the DRY gods.

Of course, you might ask yourself if there is something wrong with your class design. The change suggested above means you have the unusual situation where Foo.calculate() is being used for toString() calls even on Bar objects, but a direct call to calculate() will result in the Bar behavior. So your toString() output is going to be inconsistent with what anyone who calls calculate() will see. That's rarely what you want.

1With the exception that it is possible, within Bar, to explicitly call the superclass calculate() method using super.calculate(). That doesn't help you here, since what you want to do is, in the superclass, prevent the virtual call to calculate() from going anywhere else.

2Of course, if someone overrides toString() then all bets are off. You can always make it final if you want to avoid that.

Title: how to prevent super-class from calling overriden sub-class methods?


问:
The name 'InitializeComponent' does not exist in the current context
If I create a new project in Visual Studio 2010 SP1 and select "WPF Application" and tries to build the generated application, I get the error

The name 'InitializeComponent' does not exist in the current context.

I got a similar error this morning when I tried to build my current project. Yesterday, I had no problem compiling and running it.

I created a new project and got the error whenever I compiled the project. I have just sent the project to a colleague, and he has just compiled without any errors.

What is wrong?

答: I try all suggestions above. If you try too without success get the more easy way. Create a new page.xaml then copy your code for new class and delete class XAML with problems. Don't spend more time.


问:
calculate sum or product based on input
I am asking user to enter 2 numbers and s for sum, or "p" for product.
when I run the script I don't see any results
here is my script</p>

```<code>#!/bin/bash

read -p "please enter two integers, s or p to calculate sum or  product of this numbers: "  num1 num2 result
if [ result == "s" ]
then
echo "num1+num2" | bc

elif [ result == "p" ]
then
echo $((num1*num2))

fi
</code>```

答:
To complement chepner's helpful answer, which explains the problem with the code in the question well, with a solution inspired by DRY[1]
:

```<code># Prompt the user.
prompt='please enter two integers, s or p to calculate sum or product of this numbers: '
read -p "$prompt" num1 num2 opChar

# Map the operator char. onto an operator symbol.
# In Bash v4+, consider using an associative array for this mapping.
case $opChar in
  'p')
    opSymbol='*'
    ;;
  's')
    opSymbol='+'
    ;;
  *)
    echo "Unknown operator char: $opChar" >&2; exit 1
    ;;
esac

# Perform the calculation.
# Note how the variable containing the *operator* symbol
# *must* be $-prefixed - unlike the *operand* variables.
echo $(( num1 $opSymbol num2 ))
</code>```

[1] Except for read's -p option, the solution is POSIX-compliant; it does, however, also work in dash, which is mostly a POSIX-features-only shell.

Title: calculate sum or product based on input

Body:
I am asking user to enter 2 numbers and s for sum, or "p" for product.
when I run the script I don't see any results
here is my script

#!/bin/bash

read -p "please enter two integers, s or p to calculate sum or  product of this numbers: "  num1 num2 result
if [ result == "s" ]
then
echo "num1+num2" | bc

elif [ result == "p" ]
then
echo $((num1*num2))

fi

Body:
To complement chepner's helpful answer, which explains the problem with the code in the question well, with a solution inspired by DRY[1]
:

# Prompt the user.
prompt='please enter two integers, s or p to calculate sum or product of this numbers: '
read -p "$prompt" num1 num2 opChar

# Map the operator char. onto an operator symbol.
# In Bash v4+, consider using an associative array for this mapping.
case $opChar in
  'p')
    opSymbol='*'
    ;;
  's')
    opSymbol='+'
    ;;
  *)
    echo "Unknown operator char: $opChar" >&2; exit 1
    ;;
esac

# Perform the calculation.
# Note how the variable containing the *operator* symbol
# *must* be $-prefixed - unlike the *operand* variables.
echo $(( num1 $opSymbol num2 ))

[1] Except for read's -p option, the solution is POSIX-compliant; it does, however, also work in dash, which is mostly a POSIX-features-only shell.


问:
Android Activity back manager
In my android activity I have 3 activity A B C
But when i start A - >B - >C - >A  and when i click back all activity remain A-C-B-A

I want when I press back in current activity it returns to activity A

Help

答:
When you want an Activity to not be added to the back stack after leaving it just call:

```<code>finish();
</code>```

So for example, to start Activity B from Activity A and get rid of Activity A completely:

```<code>startActivity(new Intent(ActivityA.this, ActivityB.class));
finish();
</code>```

Now if you press the back button in Activity B, it will exit the app because there are no other Activities in the back stack.

For your specific situation, you can call finish on everything except Activity A, which will make Activity A the only Activity in your back stack. So the back button will always send you back to Activity A no matter what Activity you press it from.

Title: Android Activity back manager

Body:
When you want an Activity to not be added to the back stack after leaving it just call:

finish();

So for example, to start Activity B from Activity A and get rid of Activity A completely:

startActivity(new Intent(ActivityA.this, ActivityB.class));
finish();

Now if you press the back button in Activity B, it will exit the app because there are no other Activities in the back stack.

For your specific situation, you can call finish on everything except Activity A, which will make Activity A the only Activity in your back stack. So the back button will always send you back to Activity A no matter what Activity you press it from.


问:
want to hide image when image is not found at the src location?
```<code>jQuery('img').bind('error',function(){
            alert('hi');
        jQuery(this).hide();
        });
</code>
```

I have written this code but non available images are not hiding and still showing cross sign. Can anybody point out what can be wrong. I am writing this under document.ready and i have tried it under window.onload as well.

答:
You might want to try a different tactic and instead show the images when they load:

```<code>jQuery('img').each(function(i,img){
    jQuery('img').bind('load',function(){ this.show(); });
    if (img.complete)
        jQuery(img).show();
});
</code>```

First bind to the event, then check to see if the image has already loaded (.complete) and show it.  This will require you to hide all of the images before-hand with a script or within the inline style of the individual images.  Using a known container as a scope...

```<code>jQuery('#container img')
</code>```

...you can limit this behavior to a subset of the images.

ContentLicense: CC BY-SA 2.5

Body:
jQuery('img').bind('error',function(){
            alert('hi');
        jQuery(this).hide();
        });

I have written this code but non available images are not hiding and still showing cross sign. Can anybody point out what can be wrong. I am writing this under document.ready and i have tried it under window.onload as well.

Body:
You might want to try a different tactic and instead show the images when they load:

jQuery('img').each(function(i,img){
    jQuery('img').bind('load',function(){ this.show(); });
    if (img.complete)
        jQuery(img).show();
});

First bind to the event, then check to see if the image has already loaded (.complete) and show it.  This will require you to hide all of the images before-hand with a script or within the inline style of the individual images.  Using a known container as a scope...

jQuery('#container img')

...you can limit this behavior to a subset of the images.


问:
How to set radio button as hidden for the div
I am working on simple feedback form where I have 3 fields Name,rating(Poor, fair, good) and feedback comment.

In my form I want user to select a single rating at a time and submit the form with selected rating & feedback comments.

I have created the
 elements for each rating and make them as radio type.

I don't want to show the radio button on the form, but I want my Div to behave as radio button.

Also how to fix the border of Divs?

I am attaching the screenshots.

First one, how I want it to appear and second one is how my current code is appearing on UI.

Below is my form code & CSS

```<code><div id="modal_wrapper">
  <div id="modal_window">

    <div style="text-align: right;"><a id="modal_close" href="#">close   <b>X</b></a></div>

    <p><Strong>We'd love your feedback.</Strong><br></p>

    <p>Your feedback will help us improve your experience. To protect your privacy, please do not enter personal or account information.</p>

    <form id="modal_feedback" method="POST" action="#" accept-charset="UTF-8">
      Your Name :<br>
      <input type="text" name="name" value=""><span></span><br>
      <div class="feedbackCl" >
        <input id="overall_0" name="overall" type="radio" value="1" tabindex="0" aria-describedby="o1-l">
        <label for="overall_0" class="labelClass">— —</label>
        <span class="screen_reader" id="o1-l">Poor</span>
      </div>
      <div class="feedbackCl">
        <input id="overall_1" name="overall" type="radio" value="2" tabindex="0" aria-describedby="o2-l">
        <label for="overall_1" class="labelClass">—</label>
        <span class="screen_reader" id="o2-l">Fair</span>
      </div>
      <div class="feedbackCl">
        <input id="overall_2" name="overall" type="radio" value="3" tabindex="0" aria-describedby="o3-l">
        <label for="overall_2" class="labelClass">+ —</label>
        <span class="screen_reader" id="o3-l">Good</span>
      </div>
      <br>
      <span><br></span><br>
      <textarea style="overflow-x: hidden;" id="gBann" name="message" maxlength="1000" rows="4" cols="85" placeholder="How can we improve our site? Please share your suggestions." onKeyUp="toCount('gBann','uBann','{CHAR} characters left',1000);" >
      </textarea><br>
      <span id="uBann" class="minitext" style="text-align: right;">1000 characters left</span><br>
      <input type="submit" name="feedbackForm" value="Submit">
    </form>

  </div>
</div>
</code>```

CSS Code

```<code>.feedbackCl {
  float: left;
  box-sizing: border-box;
  padding-top: 5px;
  width: 9%;
  text-align: center;
  height: 40px;
}

input[type="radio" i] {
  -webkit-appearance: radio;
  box-sizing: border-box;
}

.labelClass{
  margin-right: 0 !important;
  height: 28px;
  background-color: #fff !important;
  color: #0511ac;
  box-sizing: border-box;
}
</code>```

答:
Rather than using radio buttons, you can add an onClick event to each div which will populate a hidden input.

```<code><input type="text" name="name" value=""><span></span><br>

<div class="feedbackCl" onclick="setRating(1)">
  <label for="overall_0" class="labelClass">- -</label>
  <span class="screen_reader" id="o1-l">Poor</span>
</div>

<div class="feedbackCl" onclick="setRating(2)">
  <label for="overall_1" class="labelClass">-</label>
  <span class="screen_reader" id="o2-l">Fair</span>
</div>
</code>```

Javascript

```<code><script>
  function setRating(v) {
    document.getElementById('overall').value = v;
  }
</script>
</code>```

Body:
I am working on simple feedback form where I have 3 fields Name,rating(Poor, fair, good) and feedback comment.

In my form I want user to select a single rating at a time and submit the form with selected rating & feedback comments.

I have created the
 elements for each rating and make them as radio type.

I don't want to show the radio button on the form, but I want my Div to behave as radio button.

Also how to fix the border of Divs?

I am attaching the screenshots.

First one, how I want it to appear and second one is how my current code is appearing on UI.

Below is my form code & CSS

close   X

We'd love your feedback.

Your feedback will help us improve your experience. To protect your privacy, please do not enter personal or account information.

    <form id="modal_feedback" method="POST" action="#" accept-charset="UTF-8">
      Your Name :

      <input type="text" name="name" value="">

        <input id="overall_0" name="overall" type="radio" value="1" tabindex="0" aria-describedby="o1-l">
        — —
        Poor

        <input id="overall_1" name="overall" type="radio" value="2" tabindex="0" aria-describedby="o2-l">
        —
        Fair

        <input id="overall_2" name="overall" type="radio" value="3" tabindex="0" aria-describedby="o3-l">
        + —
        Good

      <textarea style="overflow-x: hidden;" id="gBann" name="message" maxlength="1000" rows="4" cols="85" placeholder="How can we improve our site? Please share your suggestions." onKeyUp="toCount('gBann','uBann','{CHAR} characters left',1000);" >
      </textarea>

      1000 characters left

      <input type="submit" name="feedbackForm" value="Submit">
    </form>

CSS Code

.feedbackCl {
  float: left;
  box-sizing: border-box;
  padding-top: 5px;
  width: 9%;
  text-align: center;
  height: 40px;
}

input[type="radio" i] {
  -webkit-appearance: radio;
  box-sizing: border-box;
}

.labelClass{
  margin-right: 0 !important;
  height: 28px;
  background-color: #fff !important;
  color: #0511ac;
  box-sizing: border-box;
}

Body:
Rather than using radio buttons, you can add an onClick event to each div which will populate a hidden input.

<input type="text" name="name" value=""><span></span><br>

<div class="feedbackCl" onclick="setRating(1)">
  <label for="overall_0" class="labelClass">- -</label>
  <span class="screen_reader" id="o1-l">Poor</span>
</div>

<div class="feedbackCl" onclick="setRating(2)">
  <label for="overall_1" class="labelClass">-</label>
  <span class="screen_reader" id="o2-l">Fair</span>
</div>

Javascript

<script>
  function setRating(v) {
    document.getElementById('overall').value = v;
  }
</script>


问:
How to create custom wildcard domain in azure
I'm having an issue with setting a custom wildcard domain on an Azure Website.

The azure website is demo.azurewebsites.net

And my custom domain is tenant1.demo.azurewebsites.net

I have done following steps : --

Step A:- Login into the portal.azure.com

Step B:- Then created zone with the following steps.

In this I filled all required information and select resource group as use existing. Because I have existing resource group. And click on create button.

C) After click on create button of above image it will show following image.

D) After that I crated record set. Please refer following image. I filled all information that required.
Name = *

Type = CNAME

TTL = 1

TTL unit = Hours

Alias = my existing domain

E) after that I created custom domain.

When I am going to create custom domain it show following error.

答:
And my custom domain is tenant1.demo.azurewebsites.net

We can’t add subdomain to azurewebsites.net, because we are not the owner of azurewebsites.net.

Step B:- Then created zone with the following steps.

Until now, Azure doesn’t provide domain register service.  Azure DNS Zone is used to host the DNS records for a particular domain. Azure DNS Service will answers DNS queries for records in the zone. It works as a name server. The prerequisites to use Azure DNS Zone is that you must be the owner of the domain. Please check the following note from Azure DNS Zone official document.

You do not have to own a domain name to create a DNS zone with that domain name in Azure DNS. However, you do need to own the domain to configure the Azure DNS name servers as the correct name servers for the domain name with the domain name registrar.

After you create a DNS Zone, to let the DNS record works, you also need to delegate your domain to Azure DNS by adding name server record in your domain register portal. Though you can add DNS record for demo.azurewebsites.net in your DNS zone as you mentioned in your post. But it won’t work until you have the right to configure the name server record in your domain register portal.


问:
asp net mvc validation and ViewModel
I have four layer solution a medium size project:

Model (EF POCO entities)

Data (EF ObjectContext)

Services

asp net MVC question

a)Should i have validation attributes- Dataanotation in Models or MVC project?

b)where should i set ViewModel-s if in MVC then where do i fill ViewModels with data, in Controller? else if on other project should create Repository for VewModel?

c) should ViewModel have validation>?

答:
I really prefer to create two folder inside the models:

One is for Database model class and another is for view models.

You can also add all type of validation into the database model class.

Title: asp net mvc validation and ViewModel


问:
Since Bootstrap 4 alpha 3 col push pull is not working but working on alpha 1 & 2
Push and Pull for columns is working on alpha 1 & 2
but I discover using alpha 3 to 6 it is not working.

I included jsfiddle.

```<code>   <div class="row">
     <div class="col-md-4 col-sm-4 col-md-push-4">2</div>
     <div class="col-md-4 col-sm-4 col-md-pull-4">1</div>
     <div class="col-md-4 col-sm-4></div>
   </div>
</code>```

答:
In Bootstrap 4 alpha 3, the push/pull class names changed..

from col-{tier}-push-{size} to push-{tier}-{size}

from col-{tier}-pull-{size} to pull-{tier}-{size}

```<code><div class="row">
  <div class="col-md-4 col-sm-4 push-md-4">2</div>
  <div class="col-md-4 col-sm-4 pull-md-4">1</div>
  <div class="col-md-4 col-sm-4">3</div>
</div>
</code>```

http://www.codeply.com/go/DvQNHOoFX8

Body:
Push and Pull for columns is working on alpha 1 & 2
but I discover using alpha 3 to 6 it is not working.

I included jsfiddle.

2

1

Body:
In Bootstrap 4 alpha 3, the push/pull class names changed..

from col-{tier}-push-{size} to push-{tier}-{size}

from col-{tier}-pull-{size} to pull-{tier}-{size}

<div class="row">
  <div class="col-md-4 col-sm-4 push-md-4">2</div>
  <div class="col-md-4 col-sm-4 pull-md-4">1</div>
  <div class="col-md-4 col-sm-4">3</div>
</div>

http://www.codeply.com/go/DvQNHOoFX8


问:
Why does React require Babel and Webpack to work?
I was looking at the wiki page of vue.js and saw this:

When compared to React development, Vue can be integrated to an
  existing web application much more easily. Normally, a web application
  can start using Vue immediately by simply including the Vue.js
  JavaScript library. Usage with Webpack or Browserify, are not strictly
  necessarily. This is in stark contrast to React development where
  Usage with Webpack and Babel is unavoidable, therefore making
  converting existing web application much more difficult.

Can someone explain why React needs webpack and babel? I thought you can just drop in the link to the CDN of React and it will work?

答:
No, Babel and Webpack is not necessary for React stack. You can still find other alternatives to build your favourite stack such as Browserify and Gulp.

However, if you want to make things easier, I do recommend you learn and use Babel and Webpack together with React because:

You can use modules.

You can use JSX with ES6.

It support a lot of browsers

You can use more advanced features (async/await) etc

With webpack

You can use different loaders for sass, less, postcss etc

You can use different plugins to optimise your build such as Uglify, HotModuleReplacement, Chunks etc

There are many more advantages to use webpack which you can find here


问:
Convert key value pairs with duplicate keys into a Counter
I've got this in Python 2.7

```<code>l = [('a', 1), ('a', 2), ('b', 3), ('b', 4)]
</code>```

How do I get a Counter c where:

```<code>c = Counter({'a': 3, 'b': 7 }]
</code>```

I would prefer to use comprehension if possible or the fastest possible way to do this.

答:
Sort and group by the key; sum the values for each key; add key:sum(values) to a dictionary.

```<code>>>> import operator
>>> a = [('a', 1), ('a', 2), ('b', 3), ('b', 4)]
>>> key = operator.itemgetter(0)
>>> value = operator.itemgetter(1)
>>> a.sort(key = key)
>>> d = {}
>>> for k, group in itertools.groupby(a, key = key):
    d[k] = sum(map(value, group))

>>> d
{'a': 3, 'b': 7}
>>>
</code>```

or

```<code>>>> g = {k:sum(map(value, group)) for k, group in itertools.groupby(a, key = key)}
>>> g
{'a': 3, 'b': 7}
>>>
</code>```

You don't really need a collections.Counter

Body:
I've got this in Python 2.7

l = [('a', 1), ('a', 2), ('b', 3), ('b', 4)]

How do I get a Counter c where:

c = Counter({'a': 3, 'b': 7 }]

I would prefer to use comprehension if possible or the fastest possible way to do this.

Body:
Sort and group by the key; sum the values for each key; add key:sum(values) to a dictionary.

>>> import operator
>>> a = [('a', 1), ('a', 2), ('b', 3), ('b', 4)]
>>> key = operator.itemgetter(0)
>>> value = operator.itemgetter(1)
>>> a.sort(key = key)
>>> d = {}
>>> for k, group in itertools.groupby(a, key = key):
    d[k] = sum(map(value, group))

>>> d
{'a': 3, 'b': 7}
>>>

or

>>> g = {k:sum(map(value, group)) for k, group in itertools.groupby(a, key = key)}
>>> g
{'a': 3, 'b': 7}
>>>

You don't really need a collections.Counter


问:
UIButton TapGestureRecognizer not firing
The purpose of this bit of code is to animate a UIView to a certain location on the screen. Unfortunately, it simply is not registering the tap. Am I suppose to set the delegate to something in my setup? Any help would be appreciated!</p>

```<code>public class NoteCardView:UIView {
internal var titleLabelTapGestureRecognizer: UITapGestureRecognizer?
@IBInspectable var delegate: NoteCardViewDelegate?

public func setup(positionX:CGFloat, positionY: CGFloat, view: UIView, cardValue: Int) {
    self.titleLabelTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(NoteCardView.handleTitleLabelTap(_:)))
    self.addGestureRecognizer(titleLabelTapGestureRecognizer!)
}

func handleTitleLabelTap(_ recognizer:UITapGestureRecognizer) {
    self.delegate?.noteCardViewTitleLabelDidRecieveTap(self)
}
}

public protocol NoteCardViewDelegate {
func noteCardViewTitleLabelDidRecieveTap(_ view: NoteCardView!) -> Bool
}

extension MainViewController: NoteCardViewDelegate {
func noteCardViewTitleLabelDidRecieveTap(_ view: NoteCardView!) -> Bool {
    let card:NoteCardView = (view)
    UIView.animate(withDuration: 0.5, delay: 0.0, options: UIViewAnimationOptions.curveEaseInOut, animations: {

        card.titleLabel.leftAnchor.constraint(equalTo: card.titleLabel.leftAnchor, constant: (self.elementPlacement / 4) + 20)

        card.titleLabel.bottomAnchor.constraint(equalTo: card.titleLabel.bottomAnchor, constant: 100)

    }, completion: { (finished: Bool) in

        self.elementPlacement = (self.elementPlacement + 1)
        card.titleLabelTapGestureRecognizer!.isEnabled = !(self.elementPlacement == 5)
    })
    return true
}
}
</code>```

答: Try to call setup method in viewDidAppear in the Viewcontroller.

Body:
The purpose of this bit of code is to animate a UIView to a certain location on the screen. Unfortunately, it simply is not registering the tap. Am I suppose to set the delegate to something in my setup? Any help would be appreciated!

public class NoteCardView:UIView {
internal var titleLabelTapGestureRecognizer: UITapGestureRecognizer?
@IBInspectable var delegate: NoteCardViewDelegate?

public func setup(positionX:CGFloat, positionY: CGFloat, view: UIView, cardValue: Int) {
    self.titleLabelTapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(NoteCardView.handleTitleLabelTap(_:)))
    self.addGestureRecognizer(titleLabelTapGestureRecognizer!)
}

func handleTitleLabelTap(_ recognizer:UITapGestureRecognizer) {
    self.delegate?.noteCardViewTitleLabelDidRecieveTap(self)
}
}

public protocol NoteCardViewDelegate {
func noteCardViewTitleLabelDidRecieveTap(_ view: NoteCardView!) -> Bool
}

extension MainViewController: NoteCardViewDelegate {
func noteCardViewTitleLabelDidRecieveTap(_ view: NoteCardView!) -> Bool {
    let card:NoteCardView = (view)
    UIView.animate(withDuration: 0.5, delay: 0.0, options: UIViewAnimationOptions.curveEaseInOut, animations: {

        card.titleLabel.leftAnchor.constraint(equalTo: card.titleLabel.leftAnchor, constant: (self.elementPlacement / 4) + 20)

        card.titleLabel.bottomAnchor.constraint(equalTo: card.titleLabel.bottomAnchor, constant: 100)

    }, completion: { (finished: Bool) in

        self.elementPlacement = (self.elementPlacement + 1)
        card.titleLabelTapGestureRecognizer!.isEnabled = !(self.elementPlacement == 5)
    })
    return true
}
}


问:
How do I set the text of a GtkTextView?
I can't understand how to load text into a GtkTexView, how is it done?</p>

答:
You have to access the Buffer property that represents the buffer holding all the content that is shown by GtkTextView.

To simply load a text, you must set the Text property, like that:

```<code>textview1.Buffer.Text = "Some sample text that will be displayed."
</code>```

Assuming the control you added has the name textview1.

If you want some more control on the apperance of the text, you have to use tags to mark the text. For example:

```<code>var tag = new TextTag (null);
this.textview1.Buffer.TagTable.Add (tag);
tag.Weight = Pango.Weight.Bold;
var iter = this.textview1.Buffer.GetIterAtLine (0);
this.textview1.Buffer.InsertWithTags (ref iter, "Bold text\n", tag);
</code>```

This will insert a bold text in first line. A lot more is possible using the TextBuffer, look on the methods available on textview1.Buffer.

Title: How do I set the text of a GtkTextView?

Body:
You have to access the Buffer property that represents the buffer holding all the content that is shown by GtkTextView.

To simply load a text, you must set the Text property, like that:

textview1.Buffer.Text = "Some sample text that will be displayed."

Assuming the control you added has the name textview1.

If you want some more control on the apperance of the text, you have to use tags to mark the text. For example:

var tag = new TextTag (null);
this.textview1.Buffer.TagTable.Add (tag);
tag.Weight = Pango.Weight.Bold;
var iter = this.textview1.Buffer.GetIterAtLine (0);
this.textview1.Buffer.InsertWithTags (ref iter, "Bold text\n", tag);

This will insert a bold text in first line. A lot more is possible using the TextBuffer, look on the methods available on textview1.Buffer.


问:
Yarn - executor for spark job
```<code>Process spark = new SparkLauncher()
.setAppResource("myApp.jar")
.setMainClass("com.aa.bb.app")
.setMaster("yarn")
.setDeployMode( "cluster")
.addAppArgs( data)
.launch();
</code>```

This is how I executed my spark jar to yarn cluster. Here are some question below.

Is this processing with a executor? ( 1 spark-submit per 1 yarn executor?)

How should I executed multi spark job concurrently? (Where should I set dynamic allocation(spark.dynamicAllocation.enabled)?)

Where should I set number of executor configuration? In java code? In yarn xml?

If I set number of executor as 2, and process single job, one of executor will do nothing?

答: Need to do nothing for this. It allocated automatically.

Title: Yarn - executor for spark job

Body:
Process spark = new SparkLauncher()
.setAppResource("myApp.jar")
.setMainClass("com.aa.bb.app")
.setMaster("yarn")
.setDeployMode( "cluster")
.addAppArgs( data)
.launch();

This is how I executed my spark jar to yarn cluster. Here are some question below.

Is this processing with a executor? ( 1 spark-submit per 1 yarn executor?)

How should I executed multi spark job concurrently? (Where should I set dynamic allocation(spark.dynamicAllocation.enabled)?)

Where should I set number of executor configuration? In java code? In yarn xml?

If I set number of executor as 2, and process single job, one of executor will do nothing?


问:
Is it possible to safely/securely check in API keys etc. into a repository?
I load sensitive details (eg, AWS Secret) into my node project with dotenv & an .env file, which I include in my .gitignore, as I've read that's best practice.

If I want to add others to the project, or even clone the repo on another system, what's the most efficient/safe way to transmit these sensitive details? I assume email/google drive are out, but I'm not sure what's 'in.'

My repo is private--does that mean the 'don't check-in API keys' advice is less concrete? As I see it, anyone with permission to see the repo will likely need relevant API keys, so it doesn't seem too unreasonable to simply check them in.

答:
Security is always a trade-off with convenience. There are no real absolutes. Are you cool with anyone who accesses the repository and the (potential) git host having access to the keys? Are all developers' computer secure and use disk encryption? What do the keys give access to? Everything on AWS? Do you trust people with access to the repo enough to stay secure and not accidentally share things further? The point is that you need to try to fully understand in which ways the secrets may be leaked.

Personally I rather keep them outside of git and distribute keys to developers via usb sticks or encrypted email. And only to the people who need them. Only a subset of our developers actually need access.

Just make sure that you replace all your secrets if you do decide it's too risky. Don't just delete them from the repository. Once they are in there, they are in there forever.


问:
Removing white space on the right side of a page
I am aware this is very basic but I have been trying so many ways of removing the white space on the right side of my page yet still it's been a little problem for me as a learner. The sign_in and paratext are inline as shown but when I used set the margins and paddings to 0 to remove the white space from the right side of my page, the sign in (which is the login form) moves below the paratext instead of staying inline.</p>

答:
I have refactored your code by removing irrelevant row classes and inline styles. You also specified sign_in{width:70%}, but haven't specified what is 100%, so I added body{width:100%}. In addition to that, I commented out certain paddings and margins you can see that in the example below.

body{width: 100%;}
.paratext, h1, a{color:#008B8B;}
h1{
  font-weight: 900;
  font-size: 40px;
}
.form-group button{
  font-weight: 900;
  background-color:#008B8B;
}
.sign_in {
  width: 70%;
  /*margin-right: -30%;*/
}
.paratext {
  display: inline-block;
  /*padding-top: 250px;*/
  font-size: 16px;
  word-wrap: break-word;
  /*width: 600px;*/
}```
<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>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<body>
  <div class="paratext">
      <h1>Get ready to sell Smarter, Better, Faster.</h1>
      <p>Dosty CRM is the latest e-customer relationship management system being used currently by tech companies. Easy and Secure.</p>
  </div>

  <div class="sign_in" id="sign_in">
      <form (ngSubmit)="submitForm(l)" #l="ngForm">
          <h1>Sign In</h1>

          <div class="row">
              <div class="col-sm-12">
                  <div class="form-group">
                      <label for="email">Email</label>
                      <input type="text" class="form-control" id="email" name="email" placeholder="First Name" [(ngModel)]="login.email" required>
                  </div>
              </div>
              <div class="col-sm-12">
                  <div class="form-group">
                      <label for="password">Password</label>
                      <input type="password" class="form-control" id="password"  name="password" placeholder="password" [(ngModel)]="login.password">
                  </div>
              </div>
              <div class="col-sm-12">
                  <div class="form-group">
                      <input type="checkbox" value="Remember Me" id="remember_me">
                      <label>Remember Me</label>
                  </div>
              </div>
              <div class="col-sm-12">
                  <div class="form-group">
                      <p class="text-right forgot-password">Forgot password?</p>
                  </div>
              </div>
              <div class="col-sm-12">
                  <div class="form-group">
                      <button class="button" type="submit">Login</button>
                  </div>
              </div>
              <div class="col-sm-12">
                  <div class="form-group">
                      <p class="text-right">Already a member?</p>
                  </div>
              </div>
          </div>
      </form>
  </div>
</body></code>```

Try this code example in your project and see if the problem remains. If you still have a problem then you need to update you question with the rest of the codebase you have.

ContentLicense: CC BY-SA 4.0

Body:
I have refactored your code by removing irrelevant row classes and inline styles. You also specified sign_in{width:70%}, but haven't specified what is 100%, so I added body{width:100%}. In addition to that, I commented out certain paddings and margins you can see that in the example below.

body{width: 100%;}
.paratext, h1, a{color:#008B8B;}
h1{
  font-weight: 900;
  font-size: 40px;
}
.form-group button{
  font-weight: 900;
  background-color:#008B8B;
}
.sign_in {
  width: 70%;
  /*margin-right: -30%;*/
}
.paratext {
  display: inline-block;
  /*padding-top: 250px;*/
  font-size: 16px;
  word-wrap: break-word;
  /*width: 600px;*/
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<body>
  <div class="paratext">
      <h1>Get ready to sell Smarter, Better, Faster.</h1>
      <p>Dosty CRM is the latest e-customer relationship management system being used currently by tech companies. Easy and Secure.</p>
  </div>

  <div class="sign_in" id="sign_in">
      <form (ngSubmit)="submitForm(l)" #l="ngForm">
          <h1>Sign In</h1>

          <div class="row">
              <div class="col-sm-12">
                  <div class="form-group">
                      <label for="email">Email</label>
                      <input type="text" class="form-control" id="email" name="email" placeholder="First Name" [(ngModel)]="login.email" required>
                  </div>
              </div>
              <div class="col-sm-12">
                  <div class="form-group">
                      <label for="password">Password</label>
                      <input type="password" class="form-control" id="password"  name="password" placeholder="password" [(ngModel)]="login.password">
                  </div>
              </div>
              <div class="col-sm-12">
                  <div class="form-group">
                      <input type="checkbox" value="Remember Me" id="remember_me">
                      <label>Remember Me</label>
                  </div>
              </div>
              <div class="col-sm-12">
                  <div class="form-group">
                      <p class="text-right forgot-password"><a href="#">Forgot password?</a></p>
                  </div>
              </div>
              <div class="col-sm-12">
                  <div class="form-group">
                      <button class="button" type="submit">Login</button>
                  </div>
              </div>
              <div class="col-sm-12">
                  <div class="form-group">
                      <p class="text-right"><a href="#">Already a member?</a></p>
                  </div>
              </div>
          </div>
      </form>
  </div>
</body>

Try this code example in your project and see if the problem remains. If you still have a problem then you need to update you question with the rest of the codebase you have.


问:
How do I keep Data from a navigational popup form in MS Access
I have a MS Access database(I'm using 2007 users are using 2016 runtime)

When the users open reports I have a modal form that gets the date(query gets entire week that user input is in) that the user wants information about, the modal form closes once the report has been generated since the user no longer needs it.

My problem occurs when the user prints or changes layout of the report,

Some text fields give me #Name? or #Error since they reference the modal form(now closed) in their control source.

How do I prevent this?

If I put an invisible textfield referencing the date on the form, wont that date also become #Name? when trying to print

答: store those values on your form as a global/public variable in a module. then instead of your report referencing the form, have it reference the variables on its open event. you do need a function that returns the variable , and that the report reads.</p>


问:
How to compile dynamic content in Angular UI tabs?
In this plunk I have an Angular UI tab that displays HTML content. Each content has a div containing an ng-click directive, that doesn't work. Most likely the directive needs to be compiled? how to achieve that?

HTML

```<code>  <uib-tabset>
    <uib-tab index="$index + 1" ng-repeat="tab in tabs" heading="{{tab.title}}">
      <div ng-bind-html="tab.content"></div>
    </uib-tab>
  </uib-tabset>
</code>```

Javascript

```<code>var app = angular.module('ui.bootstrap.demo', ['ui.bootstrap', 'ngSanitize']);

app.controller('ctl', function ($scope) {

     $scope.tabs = [
       { title:'title 1', content:'<div ng-click="click(1)" id="id1">111</div>' },
       { title:'title 2', content:'<div ng-click="click(2)" id="id2">222</div>' }
     ];

     $scope.click = function(i){
       alert(i);
     };

});
</code>```

答:
Instead change the implementation.

var app = angular.module('ui.bootstrap.demo', ['ui.bootstrap', 'ngSanitize']);

app.controller('ctl', function ($scope) {

     $scope.tabs = [
       { title:'title 1', content: {id:1, label: 111} },
       { title:'title 2', content: {id:2, label: 222} }
     ];

     $scope.click = function(i){
       alert(i);
     };

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
<uib-tabset>
    <uib-tab index="$index + 1" ng-repeat="tab in tabs" heading="{{tab.title}}">
      <div ng-click="click(tab.content.id)" id="id{{tab.content.id}}">{{tab.content.label}}</div>
    </uib-tab>
  </uib-tabset></code>```

Other best way is to use directives.

<uib-tabset>
    <uib-tab index="$index + 1" ng-repeat="tab in tabs" heading="{{tab.title}}">
      <my-directive my-click="click(tab.content.id)" my-content="tab.content"</directive-x>
    </uib-tab>
  </uib-tabset>
```

Body:
In this plunk I have an Angular UI tab that displays HTML content. Each content has a div containing an ng-click directive, that doesn't work. Most likely the directive needs to be compiled? how to achieve that?

HTML

  <uib-tabset>
    <uib-tab index="$index + 1" ng-repeat="tab in tabs" heading="{{tab.title}}">

    </uib-tab>
  </uib-tabset>

Javascript

var app = angular.module('ui.bootstrap.demo', ['ui.bootstrap', 'ngSanitize']);

app.controller('ctl', function ($scope) {

     $scope.tabs = [
       { title:'title 1', content:'
111
' },
       { title:'title 2', content:'
222
' }
     ];

     $scope.click = function(i){
       alert(i);
     };

});

Body:
Instead change the implementation.

var app = angular.module('ui.bootstrap.demo', ['ui.bootstrap', 'ngSanitize']);

app.controller('ctl', function ($scope) {

     $scope.tabs = [
       { title:'title 1', content: {id:1, label: 111} },
       { title:'title 2', content: {id:2, label: 222} }
     ];

     $scope.click = function(i){
       alert(i);
     };

});

<uib-tabset>
    <uib-tab index="$index + 1" ng-repeat="tab in tabs" heading="{{tab.title}}">
      <div ng-click="click(tab.content.id)" id="id{{tab.content.id}}">{{tab.content.label}}</div>
    </uib-tab>
  </uib-tabset>

Other best way is to use directives.

<uib-tabset>
    <uib-tab index="$index + 1" ng-repeat="tab in tabs" heading="{{tab.title}}">
      <my-directive my-click="click(tab.content.id)" my-content="tab.content"</directive-x>
    </uib-tab>
  </uib-tabset>


问:
Cell dropdown list option depends on delimiter string of a cell
I have "Choices" column which stores the choices of test question.

If the text in "Choices cell" is seperated by delimiter "|||" as follows:
Apple|||Orange|||Banana|||Guava|||

Here it means there are 4 Choices.

I have another column "correct answer" which is a drop down list that let user input the correct answer.

I like to make it depends on the the number of choices.

In this example, the cell of the same row will show 4 options, that are A, B, C and D.

Any formula that can acheive this? Can someone teach me on how to do this?

Thank you in advance!

答:
You can use the OFFSET function inside of data validation to achieve this.  In particular you need the below function.

```<code>=OFFSET($I$2, 0, 0, (LEN(A2) - LEN(SUBSTITUTE(A2, "|||", "")))/3)
</code>```

What I did was create a list of all the possible letters in column I.  The OFFSET function lets you dynamically create a range.  So the above function is saying: Start on cell I2, then go down the required number of space.  The required number of spaces is determine by replacing "|||" with "" then comparing the length of those two strings and dividing by 3.  That will tell you the number of choices.

Body:
You can use the OFFSET function inside of data validation to achieve this.  In particular you need the below function.

=OFFSET($I$2, 0, 0, (LEN(A2) - LEN(SUBSTITUTE(A2, "|||", "")))/3)

What I did was create a list of all the possible letters in column I.  The OFFSET function lets you dynamically create a range.  So the above function is saying: Start on cell I2, then go down the required number of space.  The required number of spaces is determine by replacing "|||" with "" then comparing the length of those two strings and dividing by 3.  That will tell you the number of choices.


问:
How to count how many elements satisfy a condition in an idiomatic way?
Having this data:

```<code>> data
 [1] 1290603356 1290603360 1290603350 1290603344 1290603340 1290603373
 [7] 1290603354 1290603359 1290603345 1290603363 1290603357 1290603354
[13] 1290603364 1290603349 1290603352 1290603365 1290603349 1290603343
[19] 1290603339 1290603343
> offsets <- c(0, 0.5,1,2,4,8,24,4*24,7*24) * 3600)
[1]   1800   3600   7200  14400  28800  86400 345600 604800
> myoffsets <- min(data)+offsets
</code>```

being, a list of UNIX epochs and a list of offsets (0.5 hours, 1h, 2h, 4h...)
I want to be able to graph how many of the epochs are <= than the min(data) + offset

In this example it would be

```<code>1 20 20 20 20 20 20 20
</code>```

I have found how to do this with a for loop:

```<code>for(i in c(1:length(myoffsets))) myres$x[i] <- length(data[data <= myoffsets[i]])
</code>```

But I'm sure there's a more idiomatic way if doing this that is not as convoluted?

答:
Suggestion 1: A slightly more idiomatic way would be to replace

length(data[data <= myoffsets[i]])

with

sum(data <= myoffsets[i])

This way you don't end up taking a subset of data for each value in myoffsets, only to compute its length and discard.

Suggestion 2: The c() in the for is redundant. The following would do exactly the same with fewer keystrokes: for(i in 1:length(myoffsets)).

Lastly, if you prefer to get rid of the explicit loop, something like this might be to your taste:

myres$x <- sapply(myoffsets, function(o)sum(data<=o))

Body:
Having this data:

> data
 [1] 1290603356 1290603360 1290603350 1290603344 1290603340 1290603373
 [7] 1290603354 1290603359 1290603345 1290603363 1290603357 1290603354
[13] 1290603364 1290603349 1290603352 1290603365 1290603349 1290603343
[19] 1290603339 1290603343
> offsets <- c(0, 0.5,1,2,4,8,24,4*24,7*24) * 3600)
[1]   1800   3600   7200  14400  28800  86400 345600 604800
> myoffsets <- min(data)+offsets

being, a list of UNIX epochs and a list of offsets (0.5 hours, 1h, 2h, 4h...)
I want to be able to graph how many of the epochs are <= than the min(data) + offset

In this example it would be

1 20 20 20 20 20 20 20

I have found how to do this with a for loop:

for(i in c(1:length(myoffsets))) myres$x[i] <- length(data[data <= myoffsets[i]])

But I'm sure there's a more idiomatic way if doing this that is not as convoluted?


问:
My android application suddenly stopped working
I've been bugged by this problem and I got to make a quick fix to this. Please help me. So currently im experiencing crashes everytime I paste some new codes that I find online. [P.S. Im a newb in android programming]

This is my AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="birada1.tulungatung.ph.myapplication2">

<application
    android:allowBackup="true"
    android:icon="@mipmap/chess_icon"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>
</code>```

I made some minor changes to MainActivity.java

```<code>import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity implements View.OnClickListener {

private Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Button one = (Button) findViewById(R.id.button2);
    Button two = (Button) findViewById(R.id.button3);
    Button three = (Button) findViewById(R.id.button4);

    one.setOnClickListener(this);
    two.setOnClickListener(this);
    three.setOnClickListener(this);
}

@Override
public void onClick(View view) {
    switch (view.getId()) {

        case R.id.button2:
            Intent intenthistory = new Intent(this, ChessHistoryActivity.class);
            startActivity(intenthistory);
            // do your code
            break;

        case R.id.button3:
            Intent intenthistory2 = new Intent(this, LearnChessActivity.class);
            startActivity(intenthistory2);
            break;
        case R.id.button4:
            Intent intenthistory3 = new Intent(this, GrandmastersActivity.class);
            startActivity(intenthistory3);
            break;

        default:
    }

}
}
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<ImageView
android:id="@+id/img_view3"
android:layout_width="wrap_content"
android:layout_height="95dp"
android:contentDescription="@string/hellow"
app:srcCompat="@drawable/boom" />

<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimaryDark"
android:onClick="btnClick1"
android:text="@string/c_history" />

<ImageView
android:id="@+id/img_view4"
android:layout_width="wrap_content"
android:layout_height="101dp"
android:contentDescription="@string/hellow"
app:srcCompat="@drawable/chess_moves_three" />

<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="btnClick2"
android:background="@color/colorPrimaryDark"
android:text="@string/c_moves" />

<ImageView
android:id="@+id/imageView5"
android:layout_width="wrap_content"
android:layout_height="113dp"
android:contentDescription="@string/hellow"
app:srcCompat="@drawable/grandmasters" />

<Button
android:id="@+id/button4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimaryDark"
android:onClick="btnClick3"
android:text="@string/c_grandmasters" />
</LinearLayout>
</code>```

答:
Have you declared ChessHistoryActivity / LearnChessActivity / GrandmastersActivity in AndroidManifest.xml ?
if not add </p>

```<code><activity android:name=".ChessHistoryActivity"
          android:launchMode="singleTask" />

<activity android:name=".LearnChessActivity"
          android:launchMode="singleTask" />

<activity android:name=".GrandmastersActivity"
          android:launchMode="singleTask" />
</code>```

Body:
I've been bugged by this problem and I got to make a quick fix to this. Please help me. So currently im experiencing crashes everytime I paste some new codes that I find online. [P.S. Im a newb in android programming]

This is my AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="birada1.tulungatung.ph.myapplication2">

<application
    android:allowBackup="true"
    android:icon="@mipmap/chess_icon"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

I made some minor changes to MainActivity.java

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity implements View.OnClickListener {

private Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Button one = (Button) findViewById(R.id.button2);
    Button two = (Button) findViewById(R.id.button3);
    Button three = (Button) findViewById(R.id.button4);

    one.setOnClickListener(this);
    two.setOnClickListener(this);
    three.setOnClickListener(this);
}

@Override
public void onClick(View view) {
    switch (view.getId()) {

        case R.id.button2:
            Intent intenthistory = new Intent(this, ChessHistoryActivity.class);
            startActivity(intenthistory);
            // do your code
            break;

        case R.id.button3:
            Intent intenthistory2 = new Intent(this, LearnChessActivity.class);
            startActivity(intenthistory2);
            break;
        case R.id.button4:
            Intent intenthistory3 = new Intent(this, GrandmastersActivity.class);
            startActivity(intenthistory3);
            break;

        default:
    }

}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<ImageView
android:id="@+id/img_view3"
android:layout_width="wrap_content"
android:layout_height="95dp"
android:contentDescription="@string/hellow"
app:srcCompat="@drawable/boom" />

<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimaryDark"
android:onClick="btnClick1"
android:text="@string/c_history" />

<ImageView
android:id="@+id/img_view4"
android:layout_width="wrap_content"
android:layout_height="101dp"
android:contentDescription="@string/hellow"
app:srcCompat="@drawable/chess_moves_three" />

<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="btnClick2"
android:background="@color/colorPrimaryDark"
android:text="@string/c_moves" />

<ImageView
android:id="@+id/imageView5"
android:layout_width="wrap_content"
android:layout_height="113dp"
android:contentDescription="@string/hellow"
app:srcCompat="@drawable/grandmasters" />

<Button
android:id="@+id/button4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimaryDark"
android:onClick="btnClick3"
android:text="@string/c_grandmasters" />
</LinearLayout>

Body:
Have you declared ChessHistoryActivity / LearnChessActivity / GrandmastersActivity in AndroidManifest.xml ?
if not add

<activity android:name=".ChessHistoryActivity"
          android:launchMode="singleTask" />

<activity android:name=".LearnChessActivity"
          android:launchMode="singleTask" />

<activity android:name=".GrandmastersActivity"
          android:launchMode="singleTask" />


问:
Unable to connect to TFS using Powershell command - get-tfsserver
I am trying to connect to TFS using Powershell commands:

```<code>$tfsCollectionPath = "https://xxx.visualstudio.com"

[string]$username = "xxxx@hotmail.com"
$password = ConvertTo-SecureString 'xxxxx' -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential ($username, $password)

$tfs = get-tfsserver $tfsCollectionPath -credential $credential
</code>```

However, I get following error

```<code>get-tfsserver : TF30063: You are not authorized to access https://xxxx.visualstudio.com
</code>```

答:
Refer to these steps:

Open Team explorer and connect to your VSTS

It will prompt the dialog to login

Type your username and password > login

After success login, you can use Get-TfsServer command in PowerShell (e.g. $tfs=Get-TfsServer -Name “vsts url”)

Body:
I am trying to connect to TFS using Powershell commands:

$tfsCollectionPath = "https://xxx.visualstudio.com"

[string]$username = "xxxx@hotmail.com"
$password = ConvertTo-SecureString 'xxxxx' -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential ($username, $password)

$tfs = get-tfsserver $tfsCollectionPath -credential $credential

However, I get following error

get-tfsserver : TF30063: You are not authorized to access https://xxxx.visualstudio.com


问:
Setting SKSpriteNode position by using invisible UIView in Storyboard
I just recently started on iOS Spritekit. Most tutorials and StackOverflow topics mentioned that I can't use Storyboard for arranging SKSpriteNode so I've been struggling on layout my views, especially I also have some other components like UILabels.

I hack this by placing invisible UIViews (and do autolayout on them with other components), and pass the values into the SKScene which will place SpriteNode based on the value--after converting the coordinate systems, etc.

Would there be potential issues on this approach? It works for simple cases but it is obviously a hack... :P

Or if there are better way of layout SpriteNode? I am going through RayWenderlich tutorials, but so far many of them seems to be hardcoded positions?

答:
Well, it's certainly more work than needs to be done so there could be performance issues.  As an alternative (and the correct way) to do this is use the scene editor in Xcode.

Create a new SpriteKit Scene File and add your nodes to it.  Create a new Swift file of class SKScene and set the custom class for the scene file.

Then all you have to do to get those nodes into your class (like IBOutlet) is the following...

```<code>override func didMove(to: view){
    let shipNode = self.childNode(withName: "shipNodeName") as! SKSpriteNode

}
</code>```

Body:
Well, it's certainly more work than needs to be done so there could be performance issues.  As an alternative (and the correct way) to do this is use the scene editor in Xcode.

Create a new SpriteKit Scene File and add your nodes to it.  Create a new Swift file of class SKScene and set the custom class for the scene file.

Then all you have to do to get those nodes into your class (like IBOutlet) is the following...

override func didMove(to: view){
    let shipNode = self.childNode(withName: "shipNodeName") as! SKSpriteNode

}


问:
Highlighted squares on a CustomControl chessboard don't persist beyond the initial MouseDown event
I've been coding a Windows app chess game in C# as an exercise in honing my skills, and also because it's fun. I have included functionality that allows a player to select the option to highlight the squares a piece can legally move to when it gets clicked. A CustomControl handles the rendering of the chessboard and it also highlights the squares.

It all works as planned until the player begins to drag the piece to a new square. The moment the mouse moves, the highlights go away. I suspect that a Paint event is raised and the board redraws itself. And since the highlights are not part of the initial board layout, they don't get drawn.

What I would like to happen is for the squares to remain highlighted until the piece is dropped on its destination square. Is it possible to accomplish this? Any suggestions will be appreciated.

Psuedo code:

```<code>    void piece_MouseDown(object sender, MouseEventArgs e)
    {
        Piece piece = (Piece)sender;

        legalSquares = CalculateLegalSquares(piece.CurrentSquare);

        if (legalSquares.Count > 0 && this.showLegalMoves)
        {
            chessBoard1.HighlightSquares(legalSquares);
        }

        // I believe a Paint event gets raised either here...
        piece.DoDragDrop(piece, DragDropEffects.Move);
    }

    void piece_DragEnter(object sender, DragEventArgs e)
    {
        // ...or here, that removes the highlights.
        if (e.Data.GetDataPresent("Chess.Piece"))
        {
            e.Effect = DragDropEffects.Move;
        }
        else
        {
            e.Effect = DragDropEffects.None;
        }
    }

    void piece_DragDrop(object sender, DragEventArgs e)
    {
        Piece piece = (Piece)e.Data.GetData("Chess.Piece");

        if (piece.CurrentSquare != dropSquare)
        {
            if (legalSquares.Contains(dropSquare))
            {
                // This is where I’d like the highlights to stop

                // DoStuff()
            }
        }
    }
</code>```

答:
It sounds like you are highlighting the valid squares by drawing directly, but this will get erased on any repaint.  You will probably lose the highlights if your window is repainted for other reasons also, such as minimizing and restoring it, or dragging another window on top of it.

If this is the case, you probably need to override the OnPaint method and do your highlighting there.  When you want to change what is highlighted, set some state in your class to control what is drawn as highlighted in the OnPaint method, and then Invalidate your window.

OwnerDisplayName: Bryan

Body:
I've been coding a Windows app chess game in C# as an exercise in honing my skills, and also because it's fun. I have included functionality that allows a player to select the option to highlight the squares a piece can legally move to when it gets clicked. A CustomControl handles the rendering of the chessboard and it also highlights the squares.

It all works as planned until the player begins to drag the piece to a new square. The moment the mouse moves, the highlights go away. I suspect that a Paint event is raised and the board redraws itself. And since the highlights are not part of the initial board layout, they don't get drawn.

What I would like to happen is for the squares to remain highlighted until the piece is dropped on its destination square. Is it possible to accomplish this? Any suggestions will be appreciated.

Psuedo code:

    void piece_MouseDown(object sender, MouseEventArgs e)
    {
        Piece piece = (Piece)sender;

        legalSquares = CalculateLegalSquares(piece.CurrentSquare);

        if (legalSquares.Count > 0 && this.showLegalMoves)
        {
            chessBoard1.HighlightSquares(legalSquares);
        }

        // I believe a Paint event gets raised either here...
        piece.DoDragDrop(piece, DragDropEffects.Move);
    }

    void piece_DragEnter(object sender, DragEventArgs e)
    {
        // ...or here, that removes the highlights.
        if (e.Data.GetDataPresent("Chess.Piece"))
        {
            e.Effect = DragDropEffects.Move;
        }
        else
        {
            e.Effect = DragDropEffects.None;
        }
    }

    void piece_DragDrop(object sender, DragEventArgs e)
    {
        Piece piece = (Piece)e.Data.GetData("Chess.Piece");

        if (piece.CurrentSquare != dropSquare)
        {
            if (legalSquares.Contains(dropSquare))
            {
                // This is where I’d like the highlights to stop

                // DoStuff()
            }
        }
    }

OwnerDisplayName: Daniel Plaisted


问:
java item listener
i need help regarding the save menu item i have in my menu bar. i have set the code to

```<code>private void smActionPerformed(java.awt.event.ActionEvent evt) {

}
</code>```

but i am unsure what needs to go inbetween the brackets? The gui is a form where poeple fill in there medical record e.g combo box "mr/mrs" textfield "medical problems" etc and when they click file save i would like the user to get a save box (like save as box in word) and the information to be saved in a txt file.

P.S. would it be possible to have the "file type" set to save as a txt file as default.

答:
Maybe looking at this could help you. I don't fully understand what you need.

http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JFileChooser.html
http://download.oracle.com/javase/tutorial/uiswing/components/filechooser.html

Title: java item listener

Body:
i need help regarding the save menu item i have in my menu bar. i have set the code to

private void smActionPerformed(java.awt.event.ActionEvent evt) {

}

but i am unsure what needs to go inbetween the brackets? The gui is a form where poeple fill in there medical record e.g combo box "mr/mrs" textfield "medical problems" etc and when they click file save i would like the user to get a save box (like save as box in word) and the information to be saved in a txt file.

P.S. would it be possible to have the "file type" set to save as a txt file as default.


问:
Restore purchases after uninstall
I could manage in my code to perform an in-app-billing. However, if I install the app, and redo the purchase, it does purchase again.

Where is the problem?

Here is the code:

```<code>        case R.id.action_disable_ads:
            try {
                mHelper.launchPurchaseFlow(this, ITEM_SKU, 10001,
                        mPurchaseFinishedListener);
            } catch (IabHelper.IabAsyncInProgressException e) {
                //e.printStackTrace();
            }
            return true;
    }

    return super.onOptionsItemSelected(item);
}

//functions special for in App Billing
@Override
protected void onActivityResult(int requestCode, int resultCode,
                                Intent data)
{
    if (!mHelper.handleActivityResult(requestCode,
            resultCode, data)) {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener
        = new IabHelper.OnIabPurchaseFinishedListener() {
    public void onIabPurchaseFinished(IabResult result,
                                      Purchase purchase)
    {
        if (result.isFailure()) {
            // Handle error
            return;
        }
        else if (purchase.getSku().equals(ITEM_SKU)) {
            consumeItem();
            //buyButton.setEnabled(false);
        }

    }
};
public void consumeItem() {
    try {
        mHelper.queryInventoryAsync(mReceivedInventoryListener);
    } catch (IabHelper.IabAsyncInProgressException e) {
        //e.printStackTrace();
    }
}

IabHelper.QueryInventoryFinishedListener mReceivedInventoryListener
        = new IabHelper.QueryInventoryFinishedListener() {
    public void onQueryInventoryFinished(IabResult result,
                                         Inventory inventory) {

        if (result.isFailure()) {
            // Handle failure
        } else {
            try {
                mHelper.consumeAsync(inventory.getPurchase(ITEM_SKU),
                        mConsumeFinishedListener);
            } catch (IabHelper.IabAsyncInProgressException e) {
                //e.printStackTrace();
            }
        }
    }
};

IabHelper.OnConsumeFinishedListener mConsumeFinishedListener =
        new IabHelper.OnConsumeFinishedListener() {
            public void onConsumeFinished(Purchase purchase,
                                          IabResult result) {

                if (result.isSuccess()) {
                    //first save purchase state
                    SharedPreferences settings = getPreferences(0);
                    SharedPreferences.Editor settingsEditor = settings.edit();
                    settingsEditor.putString("adfree", "purchased");
                    settingsEditor.apply();
                    //then, hide the disable ads button
                    MenuItem disableAds = mainMenu.findItem(R.id.action_disable_ads);
                    disableAds.setVisible(false);
                    //then display a message that the transaction is successful
                    Toast.makeText(getApplicationContext(), "AdFree bundle purchased successfully!", Toast.LENGTH_SHORT).show();
                    //then change the state of ad-free bundle for current session:
                    adFreeBundle = "purchased";
                    //then disable ads
                    interstitialAd = null;
                    mAdView.setVisibility(View.GONE);

                } else {
                    //display an error message that the transaction was not successful
                    AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());

                    builder.setTitle("TRANSACTION FAILED!");
                    builder.setMessage("Unfortunately, the transaction was unsuccessful!");

                    builder.setPositiveButton("CLOSE", new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int which) {
                            // Do nothing but close the dialog
                            dialog.dismiss();
                        }
                    });

                    final AlertDialog alert = builder.create();
                    alert.setOnShowListener(new     DialogInterface.OnShowListener() {
                        @Override
                        public void onShow(DialogInterface arg0) {
                                alert.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.parseColor("#000000"));
                        }
                    });
                    alert.show();
                }
            }
        };

@Override
public void onDestroy() {
    super.onDestroy();
    if (mHelper != null) try {
        mHelper.dispose();
    } catch (IabHelper.IabAsyncInProgressException e) {
        //e.printStackTrace();
    }
    mHelper = null;
}
</code>```

The process of in-app-billing functioned just fine. However, I would be happy to try to get the purchased item upon reinstalling the app.

答:
This is because you are consuming the purchase, and setting a flag in sharedPreferences.

Don't do this anyone can change the sharedPreferences using the right tools.

When you uninstall your app your sharedPreferences will reset and you will lose your 'purchase'.

Because you consume the item, in the 2nd try your inventory won't have the right SKU available, this is why you are prompt to buy again.

If you make the buy button always visible you will be asked to pay every click.

To fix this

Don't consume the item, and the most important thing don't set any flag in sharedPreferences. this also apply's to sql databases.

Consuming is not meant to be used in a non-consumable item, this is your case since you are charging the user to remove the ads, if you try to consume this your users won't be very happy

When your app starts check your inventory if your inventory has the right SKU then give the user the product.

```<code> mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
        @Override
        public void onIabSetupFinished(IabResult result) {
            if (!result.isSuccess()) {
                return;
            }

            // Have we been disposed of in the meantime? If so, quit.
            if (mHelper == null) return;

            // IAB is fully set up. Now, let's get an inventory of stuff we own.
            Log.d(TAG, "Setup successful. Querying inventory.");
            try {
                mHelper.queryInventoryAsync(new IabHelper.QueryInventoryFinishedListener() {
                    @Override
                    public void onQueryInventoryFinished(IabResult result, Inventory inv) {
                        handleInventory(result, inv);
                    }
                });
            } catch (IabHelper.IabAsyncInProgressException e) {
                complain("Error querying inventory. Another async operation in progress.");
                e.printStackTrace();
            }
        }
    });

 public void handleInventory(IabResult result, Inventory inventory) {
    if (mHelper == null) return;

    // Is it a failure?
    if (result.isFailure()) {
        return;
    }

    Log.d(TAG, "Query inventory was successful.");
    Purchase premiumPurchase = inventory.getPurchase(YOUR SKU);
    //verify Developer Payload here, it's recommended but not mandatory.
    //mIsPremium = (premiumPurchase != null && verifyDeveloperPayload(premiumPurchase));
    mIsPremium = premiumPurchase != null;

    if (mIsPremium) {
        //Enable feature
    }else{
        //Disable feature
    }
}
</code>```

Title: Restore purchases after uninstall

Body:
I could manage in my code to perform an in-app-billing. However, if I install the app, and redo the purchase, it does purchase again.

Where is the problem?

Here is the code:

        case R.id.action_disable_ads:
            try {
                mHelper.launchPurchaseFlow(this, ITEM_SKU, 10001,
                        mPurchaseFinishedListener);
            } catch (IabHelper.IabAsyncInProgressException e) {
                //e.printStackTrace();
            }
            return true;
    }

    return super.onOptionsItemSelected(item);
}

//functions special for in App Billing
@Override
protected void onActivityResult(int requestCode, int resultCode,
                                Intent data)
{
    if (!mHelper.handleActivityResult(requestCode,
            resultCode, data)) {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener
        = new IabHelper.OnIabPurchaseFinishedListener() {
    public void onIabPurchaseFinished(IabResult result,
                                      Purchase purchase)
    {
        if (result.isFailure()) {
            // Handle error
            return;
        }
        else if (purchase.getSku().equals(ITEM_SKU)) {
            consumeItem();
            //buyButton.setEnabled(false);
        }

    }
};
public void consumeItem() {
    try {
        mHelper.queryInventoryAsync(mReceivedInventoryListener);
    } catch (IabHelper.IabAsyncInProgressException e) {
        //e.printStackTrace();
    }
}

IabHelper.QueryInventoryFinishedListener mReceivedInventoryListener
        = new IabHelper.QueryInventoryFinishedListener() {
    public void onQueryInventoryFinished(IabResult result,
                                         Inventory inventory) {

        if (result.isFailure()) {
            // Handle failure
        } else {
            try {
                mHelper.consumeAsync(inventory.getPurchase(ITEM_SKU),
                        mConsumeFinishedListener);
            } catch (IabHelper.IabAsyncInProgressException e) {
                //e.printStackTrace();
            }
        }
    }
};

IabHelper.OnConsumeFinishedListener mConsumeFinishedListener =
        new IabHelper.OnConsumeFinishedListener() {
            public void onConsumeFinished(Purchase purchase,
                                          IabResult result) {

                if (result.isSuccess()) {
                    //first save purchase state
                    SharedPreferences settings = getPreferences(0);
                    SharedPreferences.Editor settingsEditor = settings.edit();
                    settingsEditor.putString("adfree", "purchased");
                    settingsEditor.apply();
                    //then, hide the disable ads button
                    MenuItem disableAds = mainMenu.findItem(R.id.action_disable_ads);
                    disableAds.setVisible(false);
                    //then display a message that the transaction is successful
                    Toast.makeText(getApplicationContext(), "AdFree bundle purchased successfully!", Toast.LENGTH_SHORT).show();
                    //then change the state of ad-free bundle for current session:
                    adFreeBundle = "purchased";
                    //then disable ads
                    interstitialAd = null;
                    mAdView.setVisibility(View.GONE);

                } else {
                    //display an error message that the transaction was not successful
                    AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());

                    builder.setTitle("TRANSACTION FAILED!");
                    builder.setMessage("Unfortunately, the transaction was unsuccessful!");

                    builder.setPositiveButton("CLOSE", new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int which) {
                            // Do nothing but close the dialog
                            dialog.dismiss();
                        }
                    });

                    final AlertDialog alert = builder.create();
                    alert.setOnShowListener(new     DialogInterface.OnShowListener() {
                        @Override
                        public void onShow(DialogInterface arg0) {
                                alert.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.parseColor("#000000"));
                        }
                    });
                    alert.show();
                }
            }
        };

@Override
public void onDestroy() {
    super.onDestroy();
    if (mHelper != null) try {
        mHelper.dispose();
    } catch (IabHelper.IabAsyncInProgressException e) {
        //e.printStackTrace();
    }
    mHelper = null;
}

The process of in-app-billing functioned just fine. However, I would be happy to try to get the purchased item upon reinstalling the app.

Body:
This is because you are consuming the purchase, and setting a flag in sharedPreferences.

Don't do this anyone can change the sharedPreferences using the right tools.

When you uninstall your app your sharedPreferences will reset and you will lose your 'purchase'.

Because you consume the item, in the 2nd try your inventory won't have the right SKU available, this is why you are prompt to buy again.

If you make the buy button always visible you will be asked to pay every click.

To fix this

Don't consume the item, and the most important thing don't set any flag in sharedPreferences. this also apply's to sql databases.

Consuming is not meant to be used in a non-consumable item, this is your case since you are charging the user to remove the ads, if you try to consume this your users won't be very happy

When your app starts check your inventory if your inventory has the right SKU then give the user the product.

 mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
        @Override
        public void onIabSetupFinished(IabResult result) {
            if (!result.isSuccess()) {
                return;
            }

            // Have we been disposed of in the meantime? If so, quit.
            if (mHelper == null) return;

            // IAB is fully set up. Now, let's get an inventory of stuff we own.
            Log.d(TAG, "Setup successful. Querying inventory.");
            try {
                mHelper.queryInventoryAsync(new IabHelper.QueryInventoryFinishedListener() {
                    @Override
                    public void onQueryInventoryFinished(IabResult result, Inventory inv) {
                        handleInventory(result, inv);
                    }
                });
            } catch (IabHelper.IabAsyncInProgressException e) {
                complain("Error querying inventory. Another async operation in progress.");
                e.printStackTrace();
            }
        }
    });

 public void handleInventory(IabResult result, Inventory inventory) {
    if (mHelper == null) return;

    // Is it a failure?
    if (result.isFailure()) {
        return;
    }

    Log.d(TAG, "Query inventory was successful.");
    Purchase premiumPurchase = inventory.getPurchase(YOUR SKU);
    //verify Developer Payload here, it's recommended but not mandatory.
    //mIsPremium = (premiumPurchase != null && verifyDeveloperPayload(premiumPurchase));
    mIsPremium = premiumPurchase != null;

    if (mIsPremium) {
        //Enable feature
    }else{
        //Disable feature
    }
}


问:
MySQL using two databases in same query. Do not want to combine tables
New to MySQL, searched for answers, but multiple database questions seem to be all about combining tables, that's not what I'm after.

In new database, I duplicated a table from old database, with most columns but not all.

I need to get customer number from old database where customer name has 'Co.' in their name. This should return 14 or so customers with about 80 rows

I then need to delete all orders in the second database that has those customer numbers.

Is this possible with a subquery? that's where I am stuck right now.

Thanks so much.

答:
You can work with multiple databases on one query:

Ex:

SELECT database1.col1, database2.col2
 FROM database1.options, database2.options
  WHERE database1.option_name="sort_order"


问:
How to use an object, save the value into an arrayList, and reuse the same object to keep getting user input
I am trying to create a SavingsAccount object and then use a method create account to take user inputs (account name, account number, and starting balance) and then store that information into an arrayList to access later.

I was thinking that I could just have one instance of the object (Savings account) save the data into the arrayList and then reuse the object so that I do not have multiple objects ( was thinking this would be more memory efficient).

I am new to Java, and this is homework, I have posted my code below that I have so far.  I also am not exactly sure how I should be using the toString method in order to later print out a list of all the accounts that have been created.

The main problem I am having is how to store the objects data into the arrayList I know to use the .add() however, it seems to be overwriting all the information stored into the array with the last value entered.  So I unsure how to do this, I have read many posts here that are on the same topic or something similar and still do not understand the correct way to do this.

I would welcome any guidance or advice, thank you for taking the time to read my post.

```<code>   package bankingSystem;

/**
 *
 * @author xxxx
 *
 */
public class SavingsAccount {
    private String accountNumber;
    private String accountName;
    private double accountBalance;

    /**
     * Constructor to create a new savings account object that takes in a new
       account number and a new account name
     * @param newAccountNumber
     * @param newAccountName
     */
    public SavingsAccount(String newAccountNumber, String newAccountName){
    this.accountNumber = newAccountNumber;
    this.accountName = newAccountName;
    this.accountBalance = 0;
    }

    /**
     * Creates a new savings account with passed in data of new account name,
       number, and starting balance.
     * @param newAccountNumber
     * @param newAccountName
     * @param startingAccountBalance
     * @return true always as the information is stored in an arrayList and
       will not fill up.
     */
    public SavingsAccount(String newAccountNumber, String newAccountName,
    double startingAccountBalance){
        this.accountNumber = newAccountNumber;
        this.accountName = newAccountName;
        this.accountBalance = startingAccountBalance;
    }

    /**
     * Gets the banking account number
     * @return the bank account number
     */
    public String getAccountNumber(){
        return accountNumber;
    }

    /**
     * Gets the requested account name
     * @return
     */
    public String getAccountName(){
        return accountName;
    }

    /**
     * Gets the requsted account balance
     * @return the account balace;
     */
    public double getAccountBalance(){
        return accountBalance;
    }

    /**
     * Changes a bank account name.
     * @param updateAccountName
     * @return the updated value for accountName
     */
    public String setAccountName(String updateAccountName){
        accountName = updateAccountName;
        return accountName;
    }

    /**
     * Deposit funds into account.
     * @param depositAmount
     * @return true, as this would always be true for a realistic amount.
     */
    public boolean deposit(double depositAmount){
        accountBalance += depositAmount;
        return true;
    }

    /**
     * withdraws the specified amount of funds from the account.
     * @param withdrawlAmount
     * @return true if successful, else return false if there is an ISF
     transaction.
     */
    public boolean withdrawl(double withdrawlAmount){
        if(accountBalance - withdrawlAmount < 0){
            return false;
        }else{
            accountBalance -= withdrawlAmount;
            return true;
        }
    }

    @Override
    public String toString(){
        StringBuilder results = new StringBuilder();
        results.append("The account number is " + accountNumber + " The
    account name is " + accountName + " The account balance is " +
    accountBalance + "\n");
        return results.toString();
    }
}

package bankingSystem;
import java.util.Scanner;
import java.util.ArrayList;

/**
 *
 * @author xxxx
 *
 */
public class BankingSystem {

public static void main(String[] args) {
    ArrayList<SavingsAccount> arrayOfSavingsAccounts = new   \
ArrayList<SavingsAccount>();
    int totalNumberOfAccounts = 0;
    Scanner input = new Scanner(System.in);
    int menuSelection = 0;
    do{
        System.out.println("\nPlease select from the following options: \n1.
Create a new account\t\t\t2.  Deposit funds\n3.  Withdrawl funds\t\t\t\t4.
Transfer funds between accounts\n5.  Display all accounts\t\t\t6.  Exit
Program\n");
        if (input.hasNextInt()){
            int temp = input.nextInt();  //used a temp variable to compare the
if statement below
            if (temp > 0 && temp < 7){
                menuSelection = temp;
            }else{
                System.err.println("INVALID ENTRY, Please try again");
            }
        }else{
            System.err.println("INVALID ENTRY, Please try again");
        }
        input.nextLine();  //used this to clear the value being held in
scanner
    }
    while (menuSelection < 1 || menuSelection > 6);
    switch (menuSelection){
        case 1:  System.out.println("\t\t\t\tCREATE NEW ACCOUNT:\nPlease enter
the account holders name: \n");
            String AccountName = input.nextLine();
            System.out.println("Please enter an account number: ");
            String AccountNumber = input.nextLine();
            if (totalNumberOfAccounts == 0){
                //search for duplicate account number
            }
            System.out.println("Please enter starting account balance e.g.
2500.50 :");
            double startingAccountBalance = input.nextDouble();
            SavingsAccount createSavingsAccount = new
SavingsAccount(AccountNumber, AccountName, startingAccountBalance);
            arrayOfSavingsAccounts.add(createSavingsAccount);
            SavingsAccount createSavingsAccount = new
    }
}
</code>```

}

答:
You don't need the last line:

SavingsAccount createSavingsAccount = new SavingsAccount(AccountNumber, AccountName, startingAccountBalance);

because you initialize a new instance just remove it and then any new operation will overwrite the object old values just it.

Body:
I am trying to create a SavingsAccount object and then use a method create account to take user inputs (account name, account number, and starting balance) and then store that information into an arrayList to access later.

I was thinking that I could just have one instance of the object (Savings account) save the data into the arrayList and then reuse the object so that I do not have multiple objects ( was thinking this would be more memory efficient).

I am new to Java, and this is homework, I have posted my code below that I have so far.  I also am not exactly sure how I should be using the toString method in order to later print out a list of all the accounts that have been created.

The main problem I am having is how to store the objects data into the arrayList I know to use the .add() however, it seems to be overwriting all the information stored into the array with the last value entered.  So I unsure how to do this, I have read many posts here that are on the same topic or something similar and still do not understand the correct way to do this.

I would welcome any guidance or advice, thank you for taking the time to read my post.

   package bankingSystem;

/**
 *
 * @author xxxx
 *
 */
public class SavingsAccount {
    private String accountNumber;
    private String accountName;
    private double accountBalance;

    /**
     * Constructor to create a new savings account object that takes in a new
       account number and a new account name
     * @param newAccountNumber
     * @param newAccountName
     */
    public SavingsAccount(String newAccountNumber, String newAccountName){
    this.accountNumber = newAccountNumber;
    this.accountName = newAccountName;
    this.accountBalance = 0;
    }

    /**
     * Creates a new savings account with passed in data of new account name,
       number, and starting balance.
     * @param newAccountNumber
     * @param newAccountName
     * @param startingAccountBalance
     * @return true always as the information is stored in an arrayList and
       will not fill up.
     */
    public SavingsAccount(String newAccountNumber, String newAccountName,
    double startingAccountBalance){
        this.accountNumber = newAccountNumber;
        this.accountName = newAccountName;
        this.accountBalance = startingAccountBalance;
    }

    /**
     * Gets the banking account number
     * @return the bank account number
     */
    public String getAccountNumber(){
        return accountNumber;
    }

    /**
     * Gets the requested account name
     * @return
     */
    public String getAccountName(){
        return accountName;
    }

    /**
     * Gets the requsted account balance
     * @return the account balace;
     */
    public double getAccountBalance(){
        return accountBalance;
    }

    /**
     * Changes a bank account name.
     * @param updateAccountName
     * @return the updated value for accountName
     */
    public String setAccountName(String updateAccountName){
        accountName = updateAccountName;
        return accountName;
    }

    /**
     * Deposit funds into account.
     * @param depositAmount
     * @return true, as this would always be true for a realistic amount.
     */
    public boolean deposit(double depositAmount){
        accountBalance += depositAmount;
        return true;
    }

    /**
     * withdraws the specified amount of funds from the account.
     * @param withdrawlAmount
     * @return true if successful, else return false if there is an ISF
     transaction.
     */
    public boolean withdrawl(double withdrawlAmount){
        if(accountBalance - withdrawlAmount < 0){
            return false;
        }else{
            accountBalance -= withdrawlAmount;
            return true;
        }
    }

    @Override
    public String toString(){
        StringBuilder results = new StringBuilder();
        results.append("The account number is " + accountNumber + " The
    account name is " + accountName + " The account balance is " +
    accountBalance + "\n");
        return results.toString();
    }
}

package bankingSystem;
import java.util.Scanner;
import java.util.ArrayList;

/**
 *
 * @author xxxx
 *
 */
public class BankingSystem {

public static void main(String[] args) {
    ArrayList<SavingsAccount> arrayOfSavingsAccounts = new   \
ArrayList<SavingsAccount>();
    int totalNumberOfAccounts = 0;
    Scanner input = new Scanner(System.in);
    int menuSelection = 0;
    do{
        System.out.println("\nPlease select from the following options: \n1.
Create a new account\t\t\t2.  Deposit funds\n3.  Withdrawl funds\t\t\t\t4.
Transfer funds between accounts\n5.  Display all accounts\t\t\t6.  Exit
Program\n");
        if (input.hasNextInt()){
            int temp = input.nextInt();  //used a temp variable to compare the
if statement below
            if (temp > 0 && temp < 7){
                menuSelection = temp;
            }else{
                System.err.println("INVALID ENTRY, Please try again");
            }
        }else{
            System.err.println("INVALID ENTRY, Please try again");
        }
        input.nextLine();  //used this to clear the value being held in
scanner
    }
    while (menuSelection < 1 || menuSelection > 6);
    switch (menuSelection){
        case 1:  System.out.println("\t\t\t\tCREATE NEW ACCOUNT:\nPlease enter
the account holders name: \n");
            String AccountName = input.nextLine();
            System.out.println("Please enter an account number: ");
            String AccountNumber = input.nextLine();
            if (totalNumberOfAccounts == 0){
                //search for duplicate account number
            }
            System.out.println("Please enter starting account balance e.g.
2500.50 :");
            double startingAccountBalance = input.nextDouble();
            SavingsAccount createSavingsAccount = new
SavingsAccount(AccountNumber, AccountName, startingAccountBalance);
            arrayOfSavingsAccounts.add(createSavingsAccount);
            SavingsAccount createSavingsAccount = new
    }
}

}