问:
Bootstrap Datepicker not recognizing datesDisabled option
I am using the bootstrap datepicker plugin and everything works great with it (including chosen format, disabled weekdays, etc) but no matter how I pass in a datesDisabled option, the resulting calendar just will not show that date as actually disabled.

Here is my initialization code:

```<code>$('#tour_date').datepicker({
format: 'yyyy-mm-dd',
autoclose: true,
datesDisabled: '2017-08-10',
daysOfWeekDisabled: [0,6],
startDate: '2017-08-01',
endDate: '2018-05-30',
todayHighlight: true,
weekStart: 1,
});
</code>```

The corresponding input:

```<code><input id="tour_date" name="tour_date" type="text" value="" class="form-
control input-md" required>
</code>```

I have tried rearranging the header CSS and JS files, changing the position of the initialization code to just before the  (which is how it is now) and loading all files from a CDN.

The calendar displays just fine with all other options working as expected. The datesDisabled is the one thing where it just won't actually disable the date.

I eventually want to pass in an array of dates to disable, but this can't even disable one date.  Any advice would be greatly appreciated, as I have been pulling my hair out for hours trying to get this to work. I am using this with the AdminLTE admin panel if that makes a difference.

I also came across some Fiddle implementations of the bootstrap datepicker and edited them to fit my code, and it works there! Why does that particular option not work on my setup?

Thank you.

答: For future reference, my included CSS and JS files were out of date. I simply referenced the most updated versions, and everything worked!</p>

Body:
I am using the bootstrap datepicker plugin and everything works great with it (including chosen format, disabled weekdays, etc) but no matter how I pass in a datesDisabled option, the resulting calendar just will not show that date as actually disabled.

Here is my initialization code:

$('#tour_date').datepicker({
format: 'yyyy-mm-dd',
autoclose: true,
datesDisabled: '2017-08-10',
daysOfWeekDisabled: [0,6],
startDate: '2017-08-01',
endDate: '2018-05-30',
todayHighlight: true,
weekStart: 1,
});

The corresponding input:

<input id="tour_date" name="tour_date" type="text" value="" class="form-
control input-md" required>

I have tried rearranging the header CSS and JS files, changing the position of the initialization code to just before the  (which is how it is now) and loading all files from a CDN.

The calendar displays just fine with all other options working as expected. The datesDisabled is the one thing where it just won't actually disable the date.

I eventually want to pass in an array of dates to disable, but this can't even disable one date.  Any advice would be greatly appreciated, as I have been pulling my hair out for hours trying to get this to work. I am using this with the AdminLTE admin panel if that makes a difference.

I also came across some Fiddle implementations of the bootstrap datepicker and edited them to fit my code, and it works there! Why does that particular option not work on my setup?

Thank you.


来源: stackexchange

问:
Displaying images from ImageField
I try to display the same image of a coin in 2 sections of my site (a list of articles and a gallery of coins). The only difference (I guess) is that from the articles page I call it by a foreign key while from the gallery I call it directly.

The image is displayed in the article list but not in the gallery.

Here is some code:

the models:

```<code># coinCollection/models.py:
class coin(models.Model):
    #...
    coin_thumbnail = models.ImageField(max_length=500, upload_to = join(MEDIA_IMAGES_DIR, MEDIA_COINS_DIR), verbose_name='Miniature')
    #...

# blog/models.py:
class article(models.Model):
    #...
    article_money = models.ForeignKey(coin,
        null = True,
        on_delete = models.SET_NULL,
        related_name="money"
    )
</code>```

the views:

```<code># coinCollection/views.py:
class coinGallery(ListView):
    model = coin
    template_name = 'coinsCollection/gallery.html'
    context_object_name = 'coins_list'

    def get_queryset(self):
        coin_list = coin.objects.values('id', 'coin_name', 'coin_millesime', 'coin_thumbnail').order_by('coin_name')

        paginator = Paginator(coin_list, 3) # Show n coins per page

        page = self.request.GET.get('page')
        try:
            coins = paginator.page(page)
        except PageNotAnInteger:
            coins = paginator.page(1)
        except EmptyPage:
            coins = paginator.page(paginator.num_pages)
        return coins

# blog/views.py
class IndexView(generic.ListView):
    template_name = 'blog/articles.html'
    context_object_name = 'article_list'

    def get_queryset(self):
        article_list = article.objects.order_by('-article_pub_date')
        paginator = Paginator(article_list, 3) # Show n articles per page

        page = self.request.GET.get('page')
        try:
            articles = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            articles = paginator.page(1)
        except EmptyPage:
            # If page is out of range, deliver last page of results.
            articles = paginator.page(paginator.num_pages)
        return articles
</code>```

and in the templates :

```<code># gallery.html (Not displayed, empty var)
<img class="img-responsive" src="{{ coin.coin_thumbnail.url }}" alt="{{ coin.coin_name }}">

# articles.html (Displayed correctly)
<img class="img-responsive" src="{{ article.article_money.coin_thumbnail.url }}">
</code>```

Thanks by advance for your help.

答: values returns only the related path. Just use {{MEDIA_URL}}{{coin.coin_thumbnail}} on the template. (Beware of the appending slashes defined in your settings.py)

ContentLicense: CC BY-SA 3.0

Title: Displaying images from ImageField

Body:
I try to display the same image of a coin in 2 sections of my site (a list of articles and a gallery of coins). The only difference (I guess) is that from the articles page I call it by a foreign key while from the gallery I call it directly.

The image is displayed in the article list but not in the gallery.

Here is some code:

the models:

# coinCollection/models.py:
class coin(models.Model):
    #...
    coin_thumbnail = models.ImageField(max_length=500, upload_to = join(MEDIA_IMAGES_DIR, MEDIA_COINS_DIR), verbose_name='Miniature')
    #...

# blog/models.py:
class article(models.Model):
    #...
    article_money = models.ForeignKey(coin,
        null = True,
        on_delete = models.SET_NULL,
        related_name="money"
    )

the views:

# coinCollection/views.py:
class coinGallery(ListView):
    model = coin
    template_name = 'coinsCollection/gallery.html'
    context_object_name = 'coins_list'

    def get_queryset(self):
        coin_list = coin.objects.values('id', 'coin_name', 'coin_millesime', 'coin_thumbnail').order_by('coin_name')

        paginator = Paginator(coin_list, 3) # Show n coins per page

        page = self.request.GET.get('page')
        try:
            coins = paginator.page(page)
        except PageNotAnInteger:
            coins = paginator.page(1)
        except EmptyPage:
            coins = paginator.page(paginator.num_pages)
        return coins

# blog/views.py
class IndexView(generic.ListView):
    template_name = 'blog/articles.html'
    context_object_name = 'article_list'

    def get_queryset(self):
        article_list = article.objects.order_by('-article_pub_date')
        paginator = Paginator(article_list, 3) # Show n articles per page

        page = self.request.GET.get('page')
        try:
            articles = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            articles = paginator.page(1)
        except EmptyPage:
            # If page is out of range, deliver last page of results.
            articles = paginator.page(paginator.num_pages)
        return articles

and in the templates :

# gallery.html (Not displayed, empty var)

# articles.html (Displayed correctly)

Thanks by advance for your help.


问:
Can I use bamboo plan variables in a deployment project?
I would like to use a bamboo plan variable in a deployment project.

I inject the version of the project into ${bamboo.inject.version} during the build plan, and I would like to use it in the deployment project. (The artifact I am deploying uses the version in its name).

I've tried referencing ${bamboo.planRepository.inject.version} and ${bamboo.inject.version} but neither of these work.

I am happy to hear suggestions of other ways of doing this too.

Edit: I did manage to achieve the results I wanted by adding the properties file as a build artifact, then exporting it into the deployment project. This seems rather roundabout but works. Any other ideas appreciated!

答: You could potentially add that version info into the release name itself, but if what you're doing works then stick with that. Check out what's offered in the free plugins.</p>


问:
Where can I download the source for cron utility?
I have searched for the source for cron, to adapt it to modify/exend it. I cant locate it (thought it would be in coreutils).

Anyone knows where I can get the sources for cron?

BTW, I am running on Linux (Ubuntu 10.0.4)

答:
Just for the record, I tried to run just that (apt-get source cron), and the tool complains that the archives are not found (404 Not Found). A quick

```<code>sudo apt-get update
</code>```

will fix the situation and then we could do a

```<code>apt-get source cron
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Just for the record, I tried to run just that (apt-get source cron), and the tool complains that the archives are not found (404 Not Found). A quick

sudo apt-get update

will fix the situation and then we could do a

apt-get source cron


问:
What is ECU(AWS)? What does that mean?
I did a test performance for my server(1 ECU), but My server only arrived 1000 users in testing, how many ECU I need for 15000 users?</p>

答:
The ECU (Elastic Compute Unit) was a unit of measure designed to provide a relative measure of performance between Amazon EC2 instance types. For example, an m1.small instance had 1 ECU, an m1.large had 2 ECUs, etc.

However, it is no longer possible to summarize the power of an instance in a single number. Some instances have more RAM, some have more CPUs or more powerful CPUs, GPUs, enhanced networking and even burst capabilities.

Therefore, the ECU has slowly disappeared from AWS services and documentation. It can still be viewed as an optional column in the Amazon EC2 Launch Instance console.

The ECU is definitely not a good measure of "the number of users" that a system can support. The number of users that a system can support are totally dependent upon the application architecture and its system requirements. When testing the number of users a system can support, closely monitor all system components (eg CPU load, RAM utilization, disk queues) to identify the bottleneck. You can then try to modify the application or improve the bottleneck to provide better application performance.

Title: What is ECU(AWS)? What does that mean?


问:
A simple lambda calculus parser with FParsec
I'm new to F# and have a pretty annoying problem. I want to parse the following grammar:

```<code>Application := Expression Expression
Expression  := "(" "lambda" Name "." Application ")"
             | Name
Name        := [a-z]+
</code>```

That would match things like (lambda x. (lambda y. x y)) z and (lambda x. x) y.

My problem is that two rules depend on each other:

```<code>let popen = pchar '('
let pclose = pchar ')'
let pname = many1 letter |>> Seq.toArray |>> System.String |>> NameNode
let plambda = pstring "lambda"
let pdot = pchar '.'
let phead = plambda >>. pname .>> pdot
let pexpression =
        popen >>. pname .>>. papplication .>> pclose |>> ExpressionNode
    <|> pname
let papplication = pexpression .>>. pexpression
</code>```

pexpression depends on papplication and vicebersa. How can I get rid of that dependency?

答:
Recursive parsers can be implemented via createParserForwardedToRef. This function returns a pair of parser "handle", so to speak, and a mutable cell that holds the parser implementation. The "handle", once called upon to actually parse something, will forward the call to the implementation.

After acquiring this pair, you can implement the other part of the recursion using the "handle", and then create the forwarded parser's implementation and assign it to the mutable cell.

```<code>let pexpression, pexpressionImpl = createParserForwardedToRef()
let papplication = pexpression .>>. pexpression
pexpressionImpl :=
       popen >>. pname .>>. papplication .>> pclose |>> ExpressionNode
   <|> pname
</code>```

Body:
I'm new to F# and have a pretty annoying problem. I want to parse the following grammar:

Application := Expression Expression
Expression  := "(" "lambda" Name "." Application ")"
             | Name
Name        := [a-z]+

That would match things like (lambda x. (lambda y. x y)) z and (lambda x. x) y.

My problem is that two rules depend on each other:

let popen = pchar '('
let pclose = pchar ')'
let pname = many1 letter |>> Seq.toArray |>> System.String |>> NameNode
let plambda = pstring "lambda"
let pdot = pchar '.'
let phead = plambda >>. pname .>> pdot
let pexpression =
        popen >>. pname .>>. papplication .>> pclose |>> ExpressionNode
    <|> pname
let papplication = pexpression .>>. pexpression

pexpression depends on papplication and vicebersa. How can I get rid of that dependency?

Body:
Recursive parsers can be implemented via createParserForwardedToRef. This function returns a pair of parser "handle", so to speak, and a mutable cell that holds the parser implementation. The "handle", once called upon to actually parse something, will forward the call to the implementation.

After acquiring this pair, you can implement the other part of the recursion using the "handle", and then create the forwarded parser's implementation and assign it to the mutable cell.

let pexpression, pexpressionImpl = createParserForwardedToRef()
let papplication = pexpression .>>. pexpression
pexpressionImpl :=
       popen >>. pname .>>. papplication .>> pclose |>> ExpressionNode
   <|> pname


问:
In Javascript, how do I generate a random element out of a list?
Suppose I have a list of strings. How do I generate a random one?</p>

答:
```<code>var randomString = myStrings[Math.floor(Math.random() * myStrings.length)]
</code>```


问:
Perimeter Calculator Java
I'm trying to write a program that would be able to calculate the perimeter of either a circle, triangle, or rectangle. However the program doesn't run correctly, it just show the menu but I can't input anything.

```<code>public class GeometryDriver
{

public static void main(String[] args)
{

  double radius;
  double side1 = 0;
  double side2 = 0;
  double side3 = 0;
  double length =0;
  double width =0;
  double perimeter = 0;
  String userChoice;

    Scanner keyboard = new Scanner(System.in);
    int option;

    System.out.println("Welcome to the Geometry Calculator!\n"
            + "In this program we will use a menu to decide what kind of shape we will create.\n"
            + "\n1.Create and Calculate Perimeter of a Circle"
            + "\n2. Create and Calculate Perimeter of a Rectangle"
            + "\n3. Create and Calculate Perimeter of a Triangle");

    String input;
    GeometricShape aShape = null;

    option = keyboard.nextInt();

    switch (option)
    {
        case 1:

            input = JOptionPane. showInputDialog(null, "Enter the radius: ");
            radius = Double.parseDouble(input);
            aShape = new GeometricShape(radius);
            perimeter = aShape.getPerimeter();

            aShape = new GeometricShape(radius);
            break;

        case 2:

            input = JOptionPane.showInputDialog(null, "Enter the length: ");

            length = Double.parseDouble(input);

            perimeter = aShape.getPerimeter();
            input = JOptionPane.showInputDialog(null, "Enter the width: ");
            width = Double.parseDouble(input);

            aShape = new GeometricShape (length, width);

            break;
        case 3:

            perimeter = aShape.getPerimeter();

            input = JOptionPane.showInputDialog(null, "Enter side 1: ");
            input = JOptionPane.showInputDialog(null, "Enter side 2: ");
            input = JOptionPane.showInputDialog(null, "Enter side 3: ");
            side1 = Double.parseDouble(input);
            side2 = Double.parseDouble(input);
            side3 = Double.parseDouble(input);

            aShape = new GeometricShape (side1, side2, side3);

            break;
        default:

                    }

      System.out.println(aShape + " has perimeter" + perimeter);
}

}
</code>```

and...

```<code>public class GeometricShape
{
    private double side1, side2, side3;
    private double radius;
    private double length, width;
    private boolean triangle = false;
    private boolean rectangle = false;
    private boolean circle = false;`

    public GeometricShape(double aSide1, double aSide2, double aSide3)
    {
        side1 = aSide1;
        side2 = aSide2;
        side3 = aSide3;
        triangle = true;
    }

    public GeometricShape(double aLength, double aWidth)
    {
        length = aLength;
        width = aWidth;
        rectangle = true;
    }

    public GeometricShape(double aRadius)
    {
        radius = aRadius;
        circle = true;
    }

    public double getRadius()
    {
        return radius;
    }

    public double getSide1()
    {
        return side1;
    }

    public double getSide2()
    {
        return side2;
    }

    public double getSide3()
    {
        return side3;
    }

    public double getLength()
    {
        return length;
    }

    public double getWidth()
    {
    return width;
    }

    public void setRadius(double aRadius)
    {
        radius = aRadius;
    }

    public void setSide1(double aSide1)
    {
        side1 = aSide1;
    }

    public void setSide2(double aSide2)
    {
        side2 = aSide2;
    }

    public void setSide3(double aSide3)
    {
        side3 = aSide3;
    }

    public void setLength(double aLength)
    {
        length = aLength;
    }

    public void setWidth(double aWidth)
    {
        width = aWidth;
    }

    public double getPerimeter()
    {

        double perimeter = 0;

        if (triangle == true)
        {
            perimeter = side1 + side2 + side3;
        }

        else if (rectangle == true)
        {
            perimeter = (2* length) + (2*width);
        }

        else if (circle == true)
        {
            perimeter = 2* Math.PI * radius;
        }

    }

    public String toString()
    {
        return "The perimeter is: " + this.getPerimeter();
    }
}
</code>```

答:
New Answer
So exciting news! It does work!

Consider this:

```<code>        Scanner keyboard = new Scanner(System.in);
        JOptionPane.showInputDialog(null, "Dialog Box 1: ");
        System.out.println("Write something");
        keyboard.nextInt();
</code>```

It works fine right? However when you type this instead

```<code>        Scanner keyboard = new Scanner(System.in);
        System.out.println("Write something");
        keyboard.nextInt();
        JOptionPane.showInputDialog(null, "Dialog Box 1: ");
</code>```

It seems to stop working. I challenge you to minimise the window of the console. Behind it, you will find your dialog box saying "DialogBox 1:". This is obviously not ideal as the user of your application will not be able to use it.

So one workaround you can use is to change the keyboard input to a dialog box as shown below:

```<code>String displayMessage = "Welcome to the Geometry Calculator!\n"
            + "In this program we will use a menu to decide what kind of shape we will create.\n"
            + "\n1.Create and Calculate Perimeter of a Circle"
            + "\n2. Create and Calculate Perimeter of a Rectangle"
            + "\n3. Create and Calculate Perimeter of a Triangle";

    String input;
    GeometricShape aShape = null;

    option = Integer.parseInt(JOptionPane.showInputDialog(displayMessage));
</code>```

Further Information
This question has been discussed a couple of times. JOptionPane.showMessageDialog is not showing and JOptionPane and Scanner input issue.
The second explains a way of using this:

```<code>SwingUtilities.invokeLater(new Runnable() {
</code>```

To solve the problem.

However, I recommend for simplicity sake you just stick using scanner OR dialog boxes

Title: Perimeter Calculator Java

Body:
I'm trying to write a program that would be able to calculate the perimeter of either a circle, triangle, or rectangle. However the program doesn't run correctly, it just show the menu but I can't input anything.

public class GeometryDriver
{

public static void main(String[] args)
{

  double radius;
  double side1 = 0;
  double side2 = 0;
  double side3 = 0;
  double length =0;
  double width =0;
  double perimeter = 0;
  String userChoice;

    Scanner keyboard = new Scanner(System.in);
    int option;

    System.out.println("Welcome to the Geometry Calculator!\n"
            + "In this program we will use a menu to decide what kind of shape we will create.\n"
            + "\n1.Create and Calculate Perimeter of a Circle"
            + "\n2. Create and Calculate Perimeter of a Rectangle"
            + "\n3. Create and Calculate Perimeter of a Triangle");

    String input;
    GeometricShape aShape = null;

    option = keyboard.nextInt();

    switch (option)
    {
        case 1:

            input = JOptionPane. showInputDialog(null, "Enter the radius: ");
            radius = Double.parseDouble(input);
            aShape = new GeometricShape(radius);
            perimeter = aShape.getPerimeter();

            aShape = new GeometricShape(radius);
            break;

        case 2:

            input = JOptionPane.showInputDialog(null, "Enter the length: ");

            length = Double.parseDouble(input);

            perimeter = aShape.getPerimeter();
            input = JOptionPane.showInputDialog(null, "Enter the width: ");
            width = Double.parseDouble(input);

            aShape = new GeometricShape (length, width);

            break;
        case 3:

            perimeter = aShape.getPerimeter();

            input = JOptionPane.showInputDialog(null, "Enter side 1: ");
            input = JOptionPane.showInputDialog(null, "Enter side 2: ");
            input = JOptionPane.showInputDialog(null, "Enter side 3: ");
            side1 = Double.parseDouble(input);
            side2 = Double.parseDouble(input);
            side3 = Double.parseDouble(input);

            aShape = new GeometricShape (side1, side2, side3);

            break;
        default:

                    }

      System.out.println(aShape + " has perimeter" + perimeter);
}

}

and...

public class GeometricShape
{
    private double side1, side2, side3;
    private double radius;
    private double length, width;
    private boolean triangle = false;
    private boolean rectangle = false;
    private boolean circle = false;`

    public GeometricShape(double aSide1, double aSide2, double aSide3)
    {
        side1 = aSide1;
        side2 = aSide2;
        side3 = aSide3;
        triangle = true;
    }

    public GeometricShape(double aLength, double aWidth)
    {
        length = aLength;
        width = aWidth;
        rectangle = true;
    }

    public GeometricShape(double aRadius)
    {
        radius = aRadius;
        circle = true;
    }

    public double getRadius()
    {
        return radius;
    }

    public double getSide1()
    {
        return side1;
    }

    public double getSide2()
    {
        return side2;
    }

    public double getSide3()
    {
        return side3;
    }

    public double getLength()
    {
        return length;
    }

    public double getWidth()
    {
    return width;
    }

    public void setRadius(double aRadius)
    {
        radius = aRadius;
    }

    public void setSide1(double aSide1)
    {
        side1 = aSide1;
    }

    public void setSide2(double aSide2)
    {
        side2 = aSide2;
    }

    public void setSide3(double aSide3)
    {
        side3 = aSide3;
    }

    public void setLength(double aLength)
    {
        length = aLength;
    }

    public void setWidth(double aWidth)
    {
        width = aWidth;
    }

    public double getPerimeter()
    {

        double perimeter = 0;

        if (triangle == true)
        {
            perimeter = side1 + side2 + side3;
        }

        else if (rectangle == true)
        {
            perimeter = (2* length) + (2*width);
        }

        else if (circle == true)
        {
            perimeter = 2* Math.PI * radius;
        }

    }

    public String toString()
    {
        return "The perimeter is: " + this.getPerimeter();
    }
}

Body:
New Answer
So exciting news! It does work!

Consider this:

        Scanner keyboard = new Scanner(System.in);
        JOptionPane.showInputDialog(null, "Dialog Box 1: ");
        System.out.println("Write something");
        keyboard.nextInt();

It works fine right? However when you type this instead

        Scanner keyboard = new Scanner(System.in);
        System.out.println("Write something");
        keyboard.nextInt();
        JOptionPane.showInputDialog(null, "Dialog Box 1: ");

It seems to stop working. I challenge you to minimise the window of the console. Behind it, you will find your dialog box saying "DialogBox 1:". This is obviously not ideal as the user of your application will not be able to use it.

So one workaround you can use is to change the keyboard input to a dialog box as shown below:

String displayMessage = "Welcome to the Geometry Calculator!\n"
            + "In this program we will use a menu to decide what kind of shape we will create.\n"
            + "\n1.Create and Calculate Perimeter of a Circle"
            + "\n2. Create and Calculate Perimeter of a Rectangle"
            + "\n3. Create and Calculate Perimeter of a Triangle";

    String input;
    GeometricShape aShape = null;

    option = Integer.parseInt(JOptionPane.showInputDialog(displayMessage));

Further Information
This question has been discussed a couple of times. JOptionPane.showMessageDialog is not showing and JOptionPane and Scanner input issue.
The second explains a way of using this:

SwingUtilities.invokeLater(new Runnable() {

To solve the problem.

However, I recommend for simplicity sake you just stick using scanner OR dialog boxes


问:
how to create and download a file using play framework?
In my scala app I have an api method I want to use to a click on a button this api method will be triggered and a file that im creating on the spot will be downloaded to the client computer from the browser.

This is my api method:

```<code>def downloadFile = Action {

    // creating a new empty file
    val file = new File("outputFile.csv")

    // creating a write that opens the file
    val writer = CSVWriter.open(file)

    // writing to the file
    writer.writeAll(**some csv content**)

    writer.close()

    Ok.sendFile(file, inline = false, _ => file.getName)
  }
</code>```

this works, but the problem is that it downloading the file to the project directory folder...instead of downloading the file from the browser to my computer as I want it to be.

答:
You can add some headers for the client interpret that its an attachment.

This question has already been asked, and you can check it here :

Scala Playframework send file

Body:
In my scala app I have an api method I want to use to a click on a button this api method will be triggered and a file that im creating on the spot will be downloaded to the client computer from the browser.

This is my api method:

def downloadFile = Action {

    // creating a new empty file
    val file = new File("outputFile.csv")

    // creating a write that opens the file
    val writer = CSVWriter.open(file)

    // writing to the file
    writer.writeAll(**some csv content**)

    writer.close()

    Ok.sendFile(file, inline = false, _ => file.getName)
  }

this works, but the problem is that it downloading the file to the project directory folder...instead of downloading the file from the browser to my computer as I want it to be.


问:
Different groups of checkbox not working in jquery
I prefer to get checked checkboxes from a specific checkbox group, depending on which button I have clicked, I used $('input[name="' + groupName + '"]:checked'). This will ensure that the checked checkboxes from only the coffee or animals checkbox group are selected. But it's not working as I expected.

```<code><body>
    <div>
        <input type="checkbox" value="Lion" name="animals" checked />Lion<br>
        <input type="checkbox" value="Tiger" name="animals" />Tiger<br>
        <input type="checkbox" value="Elephant" name="animals" />Elephant<br>
        <input type="checkbox" value="Girafee" name="animals" />Girafee<br>
        <input type="submit" id="__mainAnimals" />
        <br><br><br><br><br><br>
        <input type="checkbox" value="Coffe" name="drinks" checked />Coffe<br>
        <input type="checkbox" value="Tea" name="drinks" />Tea<br>
        <input type="checkbox" value="Milk" name="drinks" />Milk<br>
        <input type="checkbox" value="Mocha" name="drinks" />Mocha<br>
        <input type="submit" id="__mainDrinks" />
    </div>
    <div id="__DIVresult"></div>

    <script type="text/javascript">
        $(document).ready(function () {
        $('#__mainAnimals').click(function () {
            getSelectedCheckBoxes('animals');
        });

        $('#__mainDrinks').click(function () {
            getSelectedCheckBoxes('drinks');
        });

        var getSelectedCheckBoxes = function (groupName) {
            var result = $('input[name="' + groupName + '"]:checked');
            if (result.length > 0) {
                var resultString = result.length + " checkboxe(s) checked<br/>";
                result.each(function () {
                    resultString += $(this).val() + "<br/>";
                });
                $('__DIVresult').html(resultString);
            }
            else {
                $('__DIVresult').html("No checkbox checked");
            }
        };
    });

    </script>

</body>
</code>```

答:
1st id selector is # so $('__DIVresult') should be $('#__DIVresult')

2nd An ID should start with a letter for compatibility

Using characters except ASCII letters and digits, '_', '-' and '.' may cause compatibility problems, as they weren't allowed in HTML 4. Though this restriction has been lifted in HTML 5, an ID should start with a letter for compatibility.

REF: https://developer.mozilla.org/en/docs/Web/HTML/Global_attributes/id

3rd some small update, added two result div, one for animal one for drink:

```<code><hr>
animals Result:
<div id="DIVresultanimals"></div>
<hr>
drinks Result:
<div id="DIVresultdrinks"></div>
</code>```

Then target them dynamically with $('#DIVresult'+groupName).html(resultString);

  <input type="checkbox" value="Lion" name="animals" checked />Lion

  <input type="checkbox" value="Tiger" name="animals" />Tiger

  <input type="checkbox" value="Elephant" name="animals" />Elephant

  <input type="checkbox" value="Girafee" name="animals" />Girafee

  <input type="submit" id="mainAnimals" />

  <input type="checkbox" value="Coffe" name="drinks" checked />Coffe

  <input type="checkbox" value="Tea" name="drinks" />Tea

  <input type="checkbox" value="Milk" name="drinks" />Milk

  <input type="checkbox" value="Mocha" name="drinks" />Mocha

  <input type="submit" id="mainDrinks" />

animals Result:

drinks Result:

```

Body:
I prefer to get checked checkboxes from a specific checkbox group, depending on which button I have clicked, I used $('input[name="' + groupName + '"]:checked'). This will ensure that the checked checkboxes from only the coffee or animals checkbox group are selected. But it's not working as I expected.

        <input type="checkbox" value="Lion" name="animals" checked />Lion

        <input type="checkbox" value="Tiger" name="animals" />Tiger

        <input type="checkbox" value="Elephant" name="animals" />Elephant

        <input type="checkbox" value="Girafee" name="animals" />Girafee

        <input type="submit" id="__mainAnimals" />

        <input type="checkbox" value="Coffe" name="drinks" checked />Coffe

        <input type="checkbox" value="Tea" name="drinks" />Tea

        <input type="checkbox" value="Milk" name="drinks" />Milk

        <input type="checkbox" value="Mocha" name="drinks" />Mocha

        <input type="submit" id="__mainDrinks" />

Body:
1st id selector is # so $('__DIVresult') should be $('#__DIVresult')

2nd An ID should start with a letter for compatibility

Using characters except ASCII letters and digits, '_', '-' and '.' may cause compatibility problems, as they weren't allowed in HTML 4. Though this restriction has been lifted in HTML 5, an ID should start with a letter for compatibility.

REF: https://developer.mozilla.org/en/docs/Web/HTML/Global_attributes/id

3rd some small update, added two result div, one for animal one for drink:

<hr>
animals Result:
<div id="DIVresultanimals"></div>
<hr>
drinks Result:
<div id="DIVresultdrinks"></div>

Then target them dynamically with $('#DIVresult'+groupName).html(resultString);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type="checkbox" value="Lion" name="animals" checked />Lion
  <br>
  <input type="checkbox" value="Tiger" name="animals" />Tiger
  <br>
  <input type="checkbox" value="Elephant" name="animals" />Elephant
  <br>
  <input type="checkbox" value="Girafee" name="animals" />Girafee
  <br>
  <input type="submit" id="mainAnimals" />
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <input type="checkbox" value="Coffe" name="drinks" checked />Coffe
  <br>
  <input type="checkbox" value="Tea" name="drinks" />Tea
  <br>
  <input type="checkbox" value="Milk" name="drinks" />Milk
  <br>
  <input type="checkbox" value="Mocha" name="drinks" />Mocha
  <br>
  <input type="submit" id="mainDrinks" />
</div>
<hr>
animals Result:
<div id="DIVresultanimals"></div>
<hr>
drinks Result:
<div id="DIVresultdrinks"></div>

<script type="text/javascript">
  $(document).ready(function() {
    $('#mainAnimals').click(function() {
      getSelectedCheckBoxes('animals');
    });

    $('#mainDrinks').click(function() {
      getSelectedCheckBoxes('drinks');
    });

    var getSelectedCheckBoxes = function(groupName) {
      var result = $('input[name="' + groupName + '"]:checked');
      if (result.length > 0) {
        var resultString = result.length + " checkboxe(s) checked<br/>";
        result.each(function() {
          resultString += $(this).val() + "<br/>";
        });
        $('#DIVresult'+groupName).html(resultString);
      } else {
        $('#DIVresult'+groupName).html("No checkbox checked");
      }
    };
  });
</script>


问:
TransformProcess transform data while using DataSetIterator
I have a CSV dataset with both numerical and nominal attributes. I defined Schema for dataset that list all possible values for nominal attributes. After that I created TransformProcess to convert nominal values to numeric values using  CategoricalToOneHotTransform. How can I use this TransformProcess on RecordReaderDataSetIterator to prepare for my neural network ?

```<code>        Schema schema = new Schema.Builder()
        .addColumnInteger("age")
        .addColumnCategorical("workclass", "Private", "Self-emp-not-inc", "Self-emp-inc", "Federal-gov", "Local-gov", "State-gov", "Without-pay", "Never-worked")
        .addColumnInteger("fnlwgt")
        .addColumnCategorical("education", "Bachelors", "Some-college", "11th", "HS-grad", "Prof-school", "Assoc-acdm", "Assoc-voc", "9th", "7th-8th", "12th", "Masters", "1st-4th", "10th", "Doctorate", "5th-6th", "Preschool")
        .addColumnInteger("education-num")
        .addColumnCategorical("marital-status", "Married-civ-spouse", "Divorced", "Never-married", "Separated", "Widowed", "Married-spouse-absent", "Married-AF-spouse")
        .addColumnCategorical("occupation", "Tech-support", "Craft-repair", "Other-service", "Sales", "Exec-managerial", "Prof-specialty", "Handlers-cleaners", "Machine-op-inspct", "Adm-clerical", "Farming-fishing", "Transport-moving", "Priv-house-serv", "Protective-serv", "Armed-Forces")
        .addColumnCategorical("relationship", "Wife", "Own-child", "Husband", "Not-in-family", "Other-relative", "Unmarried")
        .addColumnCategorical("race", "White", "Asian-Pac-Islander", "Amer-Indian-Eskimo", "Other", "Black")
        .addColumnCategorical("sex", "Female", "Male")
        .addColumnInteger("capital-gain")
        .addColumnInteger("capital-loss")
        .addColumnInteger("hours-per-week")
        .addColumnCategorical("native-country", "United-States", "Cambodia", "England", "Puerto-Rico", "Canada", "Germany", "Outlying-US(Guam-USVI-etc)", "India", "Japan", "Greece", "South", "China", "Cuba", "Iran", "Honduras", "Philippines", "Italy", "Poland", "Jamaica", "Vietnam", "Mexico", "Portugal", "Ireland", "France", "Dominican-Republic", "Laos", "Ecuador", "Taiwan", "Haiti", "Columbia", "Hungary", "Guatemala", "Nicaragua", "Scotland", "Thailand", "Yugoslavia", "El-Salvador", "Trinadad&Tobago", "Peru", "Hong", "Holand-Netherlands")
        .addColumnCategorical("class", ">50K", "<=50K")
        .build();

    TransformProcess tp = new TransformProcess.Builder(schema)
        .transform(new CategoricalToOneHotTransform("workclass"))
        .transform(new CategoricalToOneHotTransform("education"))
        .transform(new CategoricalToOneHotTransform("marital-status"))
        .transform(new CategoricalToOneHotTransform("occupation"))
        .transform(new CategoricalToOneHotTransform("relationship"))
        .transform(new CategoricalToOneHotTransform("race"))
        .transform(new CategoricalToOneHotTransform("sex"))
        .transform(new CategoricalToOneHotTransform("native-country"))
        .transform(new CategoricalToIntegerTransform("class"))
        .build();

    Schema outputSchema = tp.getFinalSchema();

    int numLinesToSkip = 0;
    String delimiter = ",";
    CSVRecordReader recordReader = new CSVRecordReader(numLinesToSkip, delimiter);
    recordReader.initialize(new FileSplit(Paths.get("..\\adult.data").toFile()));

    int labelIndex = outputSchema.getColumnNames().size() - 1;
    int numClasses = 2;
    int batchSize = 2000;

    RecordReaderDataSetIterator iterator = new RecordReaderDataSetIterator(recordReader, batchSize, labelIndex, numClasses);

    DataSet allData = iterator.next();
    allData.shuffle();
    SplitTestAndTrain testAndTrain = allData.splitTestAndTrain(0.65);
</code>```

答:
Take a  look at the: https://github.com/deeplearning4j/DataVec/blob/master/datavec-api/src/main/java/org/datavec/api/records/reader/impl/transform/TransformProcessRecordReader.java

The RecordReaderDataSetItertor takes in a record reader and handles the vectorization process. This wraps a record reader and outputs a transformed record which will then get fed to the recordreaderdatasetiterator.

Body:
I have a CSV dataset with both numerical and nominal attributes. I defined Schema for dataset that list all possible values for nominal attributes. After that I created TransformProcess to convert nominal values to numeric values using  CategoricalToOneHotTransform. How can I use this TransformProcess on RecordReaderDataSetIterator to prepare for my neural network ?

        Schema schema = new Schema.Builder()
        .addColumnInteger("age")
        .addColumnCategorical("workclass", "Private", "Self-emp-not-inc", "Self-emp-inc", "Federal-gov", "Local-gov", "State-gov", "Without-pay", "Never-worked")
        .addColumnInteger("fnlwgt")
        .addColumnCategorical("education", "Bachelors", "Some-college", "11th", "HS-grad", "Prof-school", "Assoc-acdm", "Assoc-voc", "9th", "7th-8th", "12th", "Masters", "1st-4th", "10th", "Doctorate", "5th-6th", "Preschool")
        .addColumnInteger("education-num")
        .addColumnCategorical("marital-status", "Married-civ-spouse", "Divorced", "Never-married", "Separated", "Widowed", "Married-spouse-absent", "Married-AF-spouse")
        .addColumnCategorical("occupation", "Tech-support", "Craft-repair", "Other-service", "Sales", "Exec-managerial", "Prof-specialty", "Handlers-cleaners", "Machine-op-inspct", "Adm-clerical", "Farming-fishing", "Transport-moving", "Priv-house-serv", "Protective-serv", "Armed-Forces")
        .addColumnCategorical("relationship", "Wife", "Own-child", "Husband", "Not-in-family", "Other-relative", "Unmarried")
        .addColumnCategorical("race", "White", "Asian-Pac-Islander", "Amer-Indian-Eskimo", "Other", "Black")
        .addColumnCategorical("sex", "Female", "Male")
        .addColumnInteger("capital-gain")
        .addColumnInteger("capital-loss")
        .addColumnInteger("hours-per-week")
        .addColumnCategorical("native-country", "United-States", "Cambodia", "England", "Puerto-Rico", "Canada", "Germany", "Outlying-US(Guam-USVI-etc)", "India", "Japan", "Greece", "South", "China", "Cuba", "Iran", "Honduras", "Philippines", "Italy", "Poland", "Jamaica", "Vietnam", "Mexico", "Portugal", "Ireland", "France", "Dominican-Republic", "Laos", "Ecuador", "Taiwan", "Haiti", "Columbia", "Hungary", "Guatemala", "Nicaragua", "Scotland", "Thailand", "Yugoslavia", "El-Salvador", "Trinadad&Tobago", "Peru", "Hong", "Holand-Netherlands")
        .addColumnCategorical("class", ">50K", "<=50K")
        .build();

    TransformProcess tp = new TransformProcess.Builder(schema)
        .transform(new CategoricalToOneHotTransform("workclass"))
        .transform(new CategoricalToOneHotTransform("education"))
        .transform(new CategoricalToOneHotTransform("marital-status"))
        .transform(new CategoricalToOneHotTransform("occupation"))
        .transform(new CategoricalToOneHotTransform("relationship"))
        .transform(new CategoricalToOneHotTransform("race"))
        .transform(new CategoricalToOneHotTransform("sex"))
        .transform(new CategoricalToOneHotTransform("native-country"))
        .transform(new CategoricalToIntegerTransform("class"))
        .build();

    Schema outputSchema = tp.getFinalSchema();

    int numLinesToSkip = 0;
    String delimiter = ",";
    CSVRecordReader recordReader = new CSVRecordReader(numLinesToSkip, delimiter);
    recordReader.initialize(new FileSplit(Paths.get("..\\adult.data").toFile()));

    int labelIndex = outputSchema.getColumnNames().size() - 1;
    int numClasses = 2;
    int batchSize = 2000;

    RecordReaderDataSetIterator iterator = new RecordReaderDataSetIterator(recordReader, batchSize, labelIndex, numClasses);

    DataSet allData = iterator.next();
    allData.shuffle();
    SplitTestAndTrain testAndTrain = allData.splitTestAndTrain(0.65);


问:
beautifulsoup CSS Select - find a tag in which a particular attribute (style for ex) is not present
My first here on SO. Thanks for helping us noobs for so long. Coming straight to point:

Scenario:
  I am working on an existing program that is reading the CSS selector as a string from a configuration file to make the program dynamic and able to scrap any site by just changing the configuration value of CSS selector.

Problem:
I am trying to scrape a site which is rendering items as one of the 2 options below:

Option1:

```<code>.........
<div class="price">
  <span class="price" style="color:red;margin-right:0.1in">
    <del>$299</del>
  </span>
  <span class="price">
    $195
  </span>
</div>

soup = soup.select("span.price") - this doesn't work as I need second span tag or last span tag :(
</code>```

Option2:

```<code>.........
<div class="price">
  <span class="price">
    $199
  </span>
</div>

soup = soup.select("span.price") - this works great!
</code>```

Question:
In both the above options I want to be able to get the last span tag ($195 or $199) and don't care about the $299. Basically I just want to extract the final sale price and not the original price.

So the 2 ways I know as of now are:

1) Always get the last span tag
 2) Always get the span tag which doesn't have style attribute

Now, I know the not operator, last-of-type are not present in bs4 (only nth-of-type is available) so I am stuck here. Any suggestions are helpful.

Edit: - Since this is an existing program, I cant use soup.find_all() or any other method apart from soup.select(). Sorry :(

Thanks!

答:
The code inside the select function needs to change to:</p>

```<code>def select(soup, the_variable_you_pass):
    soup.find('div', attrs={'class': 'price'}).find_all(the_variable_you_pass)[-1]
</code>```

Body:
My first here on SO. Thanks for helping us noobs for so long. Coming straight to point:

Scenario:
  I am working on an existing program that is reading the CSS selector as a string from a configuration file to make the program dynamic and able to scrap any site by just changing the configuration value of CSS selector.

Problem:
I am trying to scrape a site which is rendering items as one of the 2 options below:

Option1:

.........

    $299

    $195

soup = soup.select("span.price") - this doesn't work as I need second span tag or last span tag :(

Option2:

.........

    $199

soup = soup.select("span.price") - this works great!

Question:
In both the above options I want to be able to get the last span tag ($195 or $199) and don't care about the $299. Basically I just want to extract the final sale price and not the original price.

So the 2 ways I know as of now are:

1) Always get the last span tag
 2) Always get the span tag which doesn't have style attribute

Now, I know the not operator, last-of-type are not present in bs4 (only nth-of-type is available) so I am stuck here. Any suggestions are helpful.

Edit: - Since this is an existing program, I cant use soup.find_all() or any other method apart from soup.select(). Sorry :(

Thanks!

Body:
The code inside the select function needs to change to:

def select(soup, the_variable_you_pass):
    soup.find('div', attrs={'class': 'price'}).find_all(the_variable_you_pass)[-1]


问:
Regex href match a number
Well, here I am back at regex and my poor understanding of it. Spent more time learning it and this is what I came up with:

```<code>/<a href=\"travis.php?theTaco=([0-9999999])\">(.*)</a>
</code>```

I basically want the number in this string:

```<code><a href="travis.php?theTaco=510973">510973</a>
</code>```

My regex is almost good? my original was:

```<code>"/<a href=\"travis.php?theTaco(.*)\">(.*)<\/a>/";
</code>```

But sometimes it returned me huge strings. So, I just want to get numbers only.
I searched through other posts but there is such a large amount of unrelated material, please give an example, resource, or a link directing to a very related question.

Thank you.

答:
Others have already mentioned some issues regarding your regex, so I won't bother repeating them.

There are also issues regarding how you specified what it is you want. You can simply match via

```<code>/theTaco=(\d+)/
</code>```

and take the first capturing group. You have not given us enough information to know whether this suits your needs.

Title: Regex href match a number

Body:
Well, here I am back at regex and my poor understanding of it. Spent more time learning it and this is what I came up with:

/(.*)

I basically want the number in this string:

510973

My regex is almost good? my original was:

"/(.*)<\/a>/";

But sometimes it returned me huge strings. So, I just want to get numbers only.
I searched through other posts but there is such a large amount of unrelated material, please give an example, resource, or a link directing to a very related question.

Thank you.

Body:
Others have already mentioned some issues regarding your regex, so I won't bother repeating them.

There are also issues regarding how you specified what it is you want. You can simply match via

/theTaco=(\d+)/

and take the first capturing group. You have not given us enough information to know whether this suits your needs.


问:
Hangfire recurring tasks under minute
Is there a way to set hangfire recurring jobs every few seconds?
I do not seek a solution where fire and forget task creates another fire and forget task, and if not, what are suggested alternatives?</p>

答:
I think anyone who is against allowing a recurring trigger of less than 1 min is short sighted. After all, is 55 secs any less efficient than 1 min ? It seems so arbitrary! As much as I love Hangfire, I've encountered situations where I've had to steer a client to Quartz.net simply because there was a business requirement for a job to run every 55 secs or alike.

Anyone who makes the counter argument that if it was configured to run every 1sec it would have a serious impact on performance is again taking a closed view on things. Of course a trigger with a 1 sec interval is probably not a good idea, but do we dissalow 55 sec or 45 sec for the unlikely situation where someone will choose 1 sec ?

In any case, performance is both subjective and dependent on the host platform and hardware. It really isn't up to the API to enforce opinion when it comes to performance. Just make the polling interval and trigger recurrence configurable. That way the user can determine the best result for themselves.

Although a background process which is orchestrating a job to run every 55 sec may be an option, it isn't very satisfactory. In this case, the process isn't visible via the Hangfire UI so it's hidden from the administrator. I feel this approach is circumventing one of the major benefits of Hangfire.

If Hangfire was a serious competitor to the likes of Quartz.net it would at least match their basic functionality. If Quartz can support triggers with an interval below 1 min than why can't Hangfire!

Title: Hangfire recurring tasks under minute


问:
503 Error ObjectifyService NoSuchFieldError: WHITESPACE

UPDATE

If I remove the @Cache annotation on profile pojo it works on dev environment.

ORIGINAL

My issue is that in GAE dev server with intellij I´m getting this error when I'm trying to create a key from de userId with objectify

On api explorer

```<code>503 Service Unavailable

{
 "error": {
  "message": "java.lang.NoSuchFieldError: WHITESPACE",
  "code": 503,
  "errors": [
   {
    "domain": "global",
    "reason": "backendError",
    "message": "java.lang.NoSuchFieldError: WHITESPACE"
   }
  ]
 }
}
</code>```

Java exception

```<code>java.lang.NoSuchFieldError: WHITESPACE
    at com.google.appengine.api.datastore.KeyFactory.stringToKey(KeyFactory.java:194)
    at com.googlecode.objectify.cache.KeyMemcacheService.keyify(KeyMemcacheService.java:46)
    at com.googlecode.objectify.cache.KeyMemcacheService.getIdentifiables(KeyMemcacheService.java:76)
    at com.googlecode.objectify.cache.EntityMemcache.getAll(EntityMemcache.java:245)
    at com.googlecode.objectify.cache.CachingAsyncDatastoreService.get(CachingAsyncDatastoreService.java:252)
    at com.googlecode.objectify.impl.LoadEngine.fetch(LoadEngine.java:168)
    at com.googlecode.objectify.impl.Round.fetchPending(Round.java:168)
    at com.googlecode.objectify.impl.Round.execute(Round.java:137)
    at com.googlecode.objectify.impl.LoadEngine.execute(LoadEngine.java:89)
    at com.googlecode.objectify.impl.Round$1.nowUncached(Round.java:70)
    at com.googlecode.objectify.util.ResultCache.now(ResultCache.java:30)
    at com.googlecode.objectify.LoadResult.now(LoadResult.java:25)
</code>```

Also, deployed on app engine I don have any problem, it just works fine. I have tried on chrome and firefox.

My code is like this

OfyService.java

```<code>static {
        try {
            factory().register(Profile.class);
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    public static Objectify ofy() {
        return ObjectifyService.ofy();
    }

    public static ObjectifyFactory factory() {
        return ObjectifyService.factory();
    }
}
</code>```

Profile.java

```<code>@Entity
@Cache
public class Profile {
    String userName;
    String displayName;
    String mainEmail;

    @Id String userId;

    public Profile(String userId, String userName, String displayName, String mainEmail) {
        this.userId = userId;
        this.userName = userName;
        this.displayName = displayName;
        this.mainEmail = mainEmail;
    }

    public String getUserName() {
        return userName;
    }

    public String getDisplayName() {
        return displayName;
    }

    public String getMainEmail() {
        return mainEmail;
    }

    public String getUserId() {
        return userId;
    }

    private Profile() {
    }

    public void update(String userName, String displayName, String mainEmail) {
        if (userName != null) {
            this.userName = userName;
        }
        if (displayName != null) {
            this.displayName = displayName;
        }
        if (mainEmail != null) {
            this.mainEmail = mainEmail;
        }
    }

    public void updateName(String displayName) {
        if (displayName != null) {
            this.displayName = displayName;
        }
    }
}
</code>```

MyApi.java

```<code>//region Profile
    @ApiMethod(name = "saveProfile", path = "profile", httpMethod = ApiMethod.HttpMethod.POST)
    public Profile saveProfile(final User user, ProfileForm profileForm)
            throws UnauthorizedException {
        if (user == null) {
            throw new UnauthorizedException("Authorization required");
        }
        String mainEmail = user.getEmail();
        String userId = user.getUserId();
        String displayName = profileForm.getDisplayName();

        Key<Profile> profileKey = Key.create(Profile.class, userId);
        Profile profile = ofy().load().key(profileKey).now();

        String userName = extractDefaultDisplayNameFromEmail(mainEmail);
        if (profile == null) {
        ...
</code>```

At this line

```<code>Profile profile = ofy().load().key(profileKey).now();
</code>```

I'm using this versions (and tried whit other version to):

appengine-api-1.0-sdk:1.9.53

appengine-endpoints:1.9.53

guava:22.0-android

objectify:5.1.16

And this others versions:

jdk: 1.8.0_121

intellij 2017.1.3

Google Cloud SDK 156.0.0

app-engine-java 1.9.53

app-engine-python 1.9.53

bq 2.0.24

cloud-datastore-emulator 1.2.1

core 2017.05.19

gcloud

gsutil 4.26

答:
This error  is thrown if an application tries to access or modify a specified field of an object, and that object no longer has that field or also changed (in general partially compiled or same class in other depending project).
Try to identify the class in occurence all classes where that field came from before the change and update all your project, and simple clean and build will do the trick even if usually modern IDE will do this for you.  </p>

Body:
UPDATE

If I remove the @Cache annotation on profile pojo it works on dev environment.

ORIGINAL

My issue is that in GAE dev server with intellij I´m getting this error when I'm trying to create a key from de userId with objectify

On api explorer

503 Service Unavailable

{
 "error": {
  "message": "java.lang.NoSuchFieldError: WHITESPACE",
  "code": 503,
  "errors": [
   {
    "domain": "global",
    "reason": "backendError",
    "message": "java.lang.NoSuchFieldError: WHITESPACE"
   }
  ]
 }
}

Java exception

java.lang.NoSuchFieldError: WHITESPACE
    at com.google.appengine.api.datastore.KeyFactory.stringToKey(KeyFactory.java:194)
    at com.googlecode.objectify.cache.KeyMemcacheService.keyify(KeyMemcacheService.java:46)
    at com.googlecode.objectify.cache.KeyMemcacheService.getIdentifiables(KeyMemcacheService.java:76)
    at com.googlecode.objectify.cache.EntityMemcache.getAll(EntityMemcache.java:245)
    at com.googlecode.objectify.cache.CachingAsyncDatastoreService.get(CachingAsyncDatastoreService.java:252)
    at com.googlecode.objectify.impl.LoadEngine.fetch(LoadEngine.java:168)
    at com.googlecode.objectify.impl.Round.fetchPending(Round.java:168)
    at com.googlecode.objectify.impl.Round.execute(Round.java:137)
    at com.googlecode.objectify.impl.LoadEngine.execute(LoadEngine.java:89)
    at com.googlecode.objectify.impl.Round$1.nowUncached(Round.java:70)
    at com.googlecode.objectify.util.ResultCache.now(ResultCache.java:30)
    at com.googlecode.objectify.LoadResult.now(LoadResult.java:25)

Also, deployed on app engine I don have any problem, it just works fine. I have tried on chrome and firefox.

My code is like this

OfyService.java

static {
        try {
            factory().register(Profile.class);
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    public static Objectify ofy() {
        return ObjectifyService.ofy();
    }

    public static ObjectifyFactory factory() {
        return ObjectifyService.factory();
    }
}

Profile.java

@Entity
@Cache
public class Profile {
    String userName;
    String displayName;
    String mainEmail;

    @Id String userId;

    public Profile(String userId, String userName, String displayName, String mainEmail) {
        this.userId = userId;
        this.userName = userName;
        this.displayName = displayName;
        this.mainEmail = mainEmail;
    }

    public String getUserName() {
        return userName;
    }

    public String getDisplayName() {
        return displayName;
    }

    public String getMainEmail() {
        return mainEmail;
    }

    public String getUserId() {
        return userId;
    }

    private Profile() {
    }

    public void update(String userName, String displayName, String mainEmail) {
        if (userName != null) {
            this.userName = userName;
        }
        if (displayName != null) {
            this.displayName = displayName;
        }
        if (mainEmail != null) {
            this.mainEmail = mainEmail;
        }
    }

    public void updateName(String displayName) {
        if (displayName != null) {
            this.displayName = displayName;
        }
    }
}

MyApi.java

//region Profile
    @ApiMethod(name = "saveProfile", path = "profile", httpMethod = ApiMethod.HttpMethod.POST)
    public Profile saveProfile(final User user, ProfileForm profileForm)
            throws UnauthorizedException {
        if (user == null) {
            throw new UnauthorizedException("Authorization required");
        }
        String mainEmail = user.getEmail();
        String userId = user.getUserId();
        String displayName = profileForm.getDisplayName();

        Key<Profile> profileKey = Key.create(Profile.class, userId);
        Profile profile = ofy().load().key(profileKey).now();

        String userName = extractDefaultDisplayNameFromEmail(mainEmail);
        if (profile == null) {
        ...

At this line

Profile profile = ofy().load().key(profileKey).now();

I'm using this versions (and tried whit other version to):

appengine-api-1.0-sdk:1.9.53

appengine-endpoints:1.9.53

guava:22.0-android

objectify:5.1.16

And this others versions:

jdk: 1.8.0_121

intellij 2017.1.3

Google Cloud SDK 156.0.0

app-engine-java 1.9.53

app-engine-python 1.9.53

bq 2.0.24

cloud-datastore-emulator 1.2.1

core 2017.05.19

gcloud

gsutil 4.26


问:
Storing word frequencies from a text file in a map object
I am making the following class which creates a WordDistribution object. This object is essentially a TreeMap which is formatted to contain every word in a text file (all words are all converted to lowercase) as well as the frequency of that word in the text. The keys are the words and the values are the frequencies. I have already tried to test the constructor but the object keeps returning empty when I print it. I was wondering whether the constructor functions correctly and creates the correct object given a proper file input. </p>

```<code>public class WordDistribution {

// fields
   private static TreeMap<String, Integer> wordDistribution;

// constructors
   public WordDistribution(File f) throws FileNotFoundException{

   Scanner file = new Scanner(f);
   wordDistribution = new TreeMap<String, Integer>();
   while (file.hasNext()) {
       String word = file.next().toLowerCase();
       if(!wordDistribution.containsKey(word)){
           wordDistribution.put(word, 1);
       }else{
           int count = wordDistribution.get(word);
           wordDistribution.put(word, count + 1);
       }
   }
}
</code>```

答:
Your File is probably not where you think it is, so log that. Next, your wordDistribution should not be static (else you reset it with every constructor call). You should also close your Scanner (or else you, potentially, leak file handles), here I used a try-with-resources. Finally, I would prefer a more generalized put call with count and prefer the interface Map (and diamond operator <>).

```<code>public class WordDistribution {
    // fields
    private Map<String, Integer> wordDistribution = new TreeMap<>();

    // constructors
    public WordDistribution(File f) throws IOException {
        System.out.printf("Reading: %s%n", f.getCanonicalPath());
        if (!f.canRead()) {
            throw new FileNotFoundException(String.format("File %s can not be read",
                    f.getCanonicalPath()));
        }

        try (Scanner file = new Scanner(f)) {
            while (file.hasNext()) {
                String word = file.next().toLowerCase();
                int count = 0;
                if (wordDistribution.containsKey(word)) {
                    count = wordDistribution.get(word);
                }
                wordDistribution.put(word, count + 1);
            }
        }
    }
}
</code>```

Body:
I am making the following class which creates a WordDistribution object. This object is essentially a TreeMap which is formatted to contain every word in a text file (all words are all converted to lowercase) as well as the frequency of that word in the text. The keys are the words and the values are the frequencies. I have already tried to test the constructor but the object keeps returning empty when I print it. I was wondering whether the constructor functions correctly and creates the correct object given a proper file input.

public class WordDistribution {

// fields
   private static TreeMap<String, Integer> wordDistribution;

// constructors
   public WordDistribution(File f) throws FileNotFoundException{

   Scanner file = new Scanner(f);
   wordDistribution = new TreeMap<String, Integer>();
   while (file.hasNext()) {
       String word = file.next().toLowerCase();
       if(!wordDistribution.containsKey(word)){
           wordDistribution.put(word, 1);
       }else{
           int count = wordDistribution.get(word);
           wordDistribution.put(word, count + 1);
       }
   }
}

Body:
Your File is probably not where you think it is, so log that. Next, your wordDistribution should not be static (else you reset it with every constructor call). You should also close your Scanner (or else you, potentially, leak file handles), here I used a try-with-resources. Finally, I would prefer a more generalized put call with count and prefer the interface Map (and diamond operator <>).

public class WordDistribution {
    // fields
    private Map<String, Integer> wordDistribution = new TreeMap<>();

    // constructors
    public WordDistribution(File f) throws IOException {
        System.out.printf("Reading: %s%n", f.getCanonicalPath());
        if (!f.canRead()) {
            throw new FileNotFoundException(String.format("File %s can not be read",
                    f.getCanonicalPath()));
        }

        try (Scanner file = new Scanner(f)) {
            while (file.hasNext()) {
                String word = file.next().toLowerCase();
                int count = 0;
                if (wordDistribution.containsKey(word)) {
                    count = wordDistribution.get(word);
                }
                wordDistribution.put(word, count + 1);
            }
        }
    }
}


问:
How to download the latest log of a Bamboo job?
I want to download the latest log of a Bamboo job programmatically to parse its content and display in a dashboard.

However, Bamboo does not provide a direct link (e.g. with "latest" in URL similar to artifacts download) or to make the Bamboo build log as an artifact.

Someone who has worked around this issue, please share the knowledge.

答:
Check out the REST API offered for bamboo builds: https://docs.atlassian.com/bamboo/REST/6.0.0/

Here's one example from Atlassian's community: https://community.atlassian.com/t5/Answers-Developer-Questions/How-do-you-get-the-build-log-using-REST-API/qaq-p/485212

See "expand": https://docs.atlassian.com/bamboo/REST/6.0.0/#d2e485

... expands build result details on request. Possible values are: changes, metadata, artifacts, comments, labels, jiraIssues, stages, logEntries. stages expand is available only for top level plans. It allows to drill down to job results using stages.stage.results.result. logEntries and testResults are available only for job results


问:
Sending command line arguments with ZMQ and Python
I am beginner in Python, ZMQ,networking or even coding in general, so please pardon my mistakes.

I am trying to send instructions to open notepad.exe from my desktop to my laptop like this:

MAIN SERVER

```<code>import zmq
import subprocess

try:
    raw_input

except NameError:
    raw_input = input #for python 3

#This will handle all the sockets we will open on the mainServer
context = zmq.Context()

#Socket 1 - Using for instructions
instructions = context.socket(zmq.PUSH)
instructions.bind("tcp://*:5555")

#Socket 2 - Using for end of finished instructions
#doneWork = context.socket(zmq.PULL)
#instructions.bind("tcp://*:5556")

#Now we will press enter when the workers are ready

print("Press Enter when you want to send the instructions. Make sure test devices are ready")
_=raw_input()

print ("Sending tasks to test device. . .")

instruction_One= "subprocess.call(['C:\notepad.exe'])"

instructions.send_string('%s' %instruction_One)
</code>```

and

CLIENT

```<code>import zmq
import sys

context = zmq.Context()

instructions = context.socket(zmq.PULL)
instructions.connect("tcp://192.168.0.12:5555")

while True:
  instruction_One=instructions.recv()
  string_of_instruction = instruction_One.decode("utf-8")
  sys.std.out.write(string_of_instruction)
  sys.std.out.flush()
</code>```

I am sending the instructions in terms of string which encoded into binary through the socket. But on the client side (laptop), whatever I am fetching cannot be executed through command line. What is the stupid mistake I am making?

答:
I found out the fix.

instead of sys, I have used subprocess.

```<code>subprocess(command, shell=True)
</code>```

Thanks

Body:
I am beginner in Python, ZMQ,networking or even coding in general, so please pardon my mistakes.

I am trying to send instructions to open notepad.exe from my desktop to my laptop like this:

MAIN SERVER

import zmq
import subprocess

try:
    raw_input

except NameError:
    raw_input = input #for python 3

#This will handle all the sockets we will open on the mainServer
context = zmq.Context()

#Socket 1 - Using for instructions
instructions = context.socket(zmq.PUSH)
instructions.bind("tcp://*:5555")

#Socket 2 - Using for end of finished instructions
#doneWork = context.socket(zmq.PULL)
#instructions.bind("tcp://*:5556")

#Now we will press enter when the workers are ready

print("Press Enter when you want to send the instructions. Make sure test devices are ready")
_=raw_input()

print ("Sending tasks to test device. . .")

instruction_One= "subprocess.call(['C:\notepad.exe'])"

instructions.send_string('%s' %instruction_One)

and

CLIENT

import zmq
import sys

context = zmq.Context()

instructions = context.socket(zmq.PULL)
instructions.connect("tcp://192.168.0.12:5555")

while True:
  instruction_One=instructions.recv()
  string_of_instruction = instruction_One.decode("utf-8")
  sys.std.out.write(string_of_instruction)
  sys.std.out.flush()

I am sending the instructions in terms of string which encoded into binary through the socket. But on the client side (laptop), whatever I am fetching cannot be executed through command line. What is the stupid mistake I am making?

Body:
I found out the fix.

instead of sys, I have used subprocess.

subprocess(command, shell=True)

Thanks


问:
Show the current time of the video, instead of the remaining time on videojs
I use VideoJS, a HTML5 video player

By default it displays the remaining time (countdown) instead of the normal current time (like youtube)

Any ideas how to "fix" it? You can see a live example at their official website

答:
For other people that search for a solution...

All timers exist on the player but by default the current-time, time-divider and the duration info are hidden with display: none;.

So the only thing we have to do is hide the remaining-time and show the time-control which includes the current-time, time-divider and the duration.

The solution in CSS code that should work with your player:

```<code>.video-js .vjs-time-control {
    display: block;
}
.video-js .vjs-remaining-time {
    display: none;
}
</code>```

The documentation does not explain this, or to be precise it fails to explain it when it explains how to customize your player with CSS.

Fast html code snippet:

```<code><style type="text/css">
    .video-js .vjs-time-control{display:block;}
    .video-js .vjs-remaining-time{display: none;}
</style>
</code>```

Body:
For other people that search for a solution...

All timers exist on the player but by default the current-time, time-divider and the duration info are hidden with display: none;.

So the only thing we have to do is hide the remaining-time and show the time-control which includes the current-time, time-divider and the duration.

The solution in CSS code that should work with your player:

.video-js .vjs-time-control {
    display: block;
}
.video-js .vjs-remaining-time {
    display: none;
}

The documentation does not explain this, or to be precise it fails to explain it when it explains how to customize your player with CSS.

Fast html code snippet:

<style type="text/css">
    .video-js .vjs-time-control{display:block;}
    .video-js .vjs-remaining-time{display: none;}
</style>

ContentLicense: CC BY-SA 4.0


问:
How can I create an empty n*m PNG file in Python?
I would like to combine 4 PNG images to one PNG file. I know who to combine them with Image.paste method, but I couldn't create an save output file! Actually, I want to have a n*m empty PNG file, and use to combine my images.
I need to specify the file size, if not I couldn't use paste method.

答:
You can use the method PIL.Image.new() to create the image. But the default color is in black. To make a totally white-background empty image, you can initialize it with the code:

```<code>from PIL import Image
img = Image.new("RGB", (800, 1280), (255, 255, 255))
img.save("image.png", "PNG")
</code>```

It creates an image with the size 800x1280 with white background.

Body:
You can use the method PIL.Image.new() to create the image. But the default color is in black. To make a totally white-background empty image, you can initialize it with the code:

from PIL import Image
img = Image.new("RGB", (800, 1280), (255, 255, 255))
img.save("image.png", "PNG")

It creates an image with the size 800x1280 with white background.


问:
How to read a pixel off of the screen?
I am trying to make a simple bot for a web game, so I would like to be able to read the color of a pixel on the screen. I've done this on Windows with GetPixel(), but I can't seem to figure it out on OS X. I been looking online and came across glReadPixel. When I made a simple command line tool in XCode, I put in the following code. However, I cannot seem to make it work. I keep getting a EXC_BAD_ACCESS error from this:

```<code>GLfloat r;
glReadPixels(0, 0, 1, 1, GL_RED, GL_FLOAT, &r);
</code>```

I thought the above code would store the red value of the pixel at (0,0) into r. Oh, I'd like to avoid take a screen shot approach because that is slow. Any help?

P.S. With the command line tool, my end goal is to make a bash script or an applescript, since I already have a command line tool that can click on the screen.

答:
glReadPixels is only concerned about reading a pixel from the frame buffer (the area into which your graphics card draws).

Reading pixels from the "screen" is not related to OpenGL at all. You need system-specific functions for that.

Title: How to read a pixel off of the screen?

Body:
I am trying to make a simple bot for a web game, so I would like to be able to read the color of a pixel on the screen. I've done this on Windows with GetPixel(), but I can't seem to figure it out on OS X. I been looking online and came across glReadPixel. When I made a simple command line tool in XCode, I put in the following code. However, I cannot seem to make it work. I keep getting a EXC_BAD_ACCESS error from this:

GLfloat r;
glReadPixels(0, 0, 1, 1, GL_RED, GL_FLOAT, &r);

I thought the above code would store the red value of the pixel at (0,0) into r. Oh, I'd like to avoid take a screen shot approach because that is slow. Any help?

P.S. With the command line tool, my end goal is to make a bash script or an applescript, since I already have a command line tool that can click on the screen.


问:
How to do Xamarin.uwp in visual studio 2017
I downloaded latest visual studio 2017 and I have chosen Xamarin while installing it and I already have visual studio 2015 with Xamarin and I was able to develop visual studio Xamarin.winphone along with Xamarin.ios and Xamarin.Droid.

I am aware winphone is deprecated in visual studio 2017 and I thought to develop Xamarin.uwp by migrating all my winphone code uwp.

But When I create a new Xamarin native project I am not able to find Xamarin.uwp but I can find Xamarin.iOS and Xamarin.Droid.

Here is the screenshot

What could have gone wrong ?

答:
Please check if you have installed Windows 10 SDK. The following is check steps.

Enter the “Visual Studio Installer” in the conrtana search box.

Click the modify button in the window of Visual Studio Installer.

Select the version you need to install.


问:
Why is my canvas and/or my photoimage not displaying?
I don't know why my canvas is not displaying. There is a reference to it, self._screen, and it is being packed, but it does not display at all. What am I missing?

```<code>class Map(Frame):

    def __init__(self, size):

        Frame.__init__(self)
        self.pack()

        #images
        self.spriteDimension = 20
        self.img1 = PhotoImage(file="Terrain1.gif")
        self.img2 = PhotoImage(file="Terrain2.gif")

        #grid
        self._mapSize = size
        # self._grid = self.randomize()

        #canvas
        canvas_dimension = self._mapSize * self.spriteDimension

        self._screen = Canvas(self, width=canvas_dimension, height=canvas_dimension)
        self._screen.pack()

        self.test()

    def test(self):
        print("in here")
        self._screen.create_image((50,50), anchor = NW, image = self.img1)
        print("out here")

def main():

    m =Map(20);
    m.mainloop(20);
</code>```

答:
You have a few problems from what I can see.
Unlike other programming languages you don't use ; at the end of a line of code. You don't need to place m = Map(20) or root.mainloop() in a function. You also need to define a tkinter window so add root = Tk() to the start of your program. Take a look at the code below and let me know if you don't understand something.

```<code>from tkinter import *

root = Tk()

class Map(Frame):

    def __init__(self, size):

        Frame.__init__(self)
        self.pack()

        self.spriteDimension = 20
        self.img1 = PhotoImage(file="Terrain1.gif")
        self.img2 = PhotoImage(file="Terrain2.gif")

        self._mapSize = size

        canvas_dimension = self._mapSize * self.spriteDimension

        self._screen = Canvas(self, width=canvas_dimension, height=canvas_dimension)
        self._screen.pack()

        self.test()

    def test(self):
        print("in here")
        self._screen.create_image((50,50), anchor = NW, image = self.img1)
        print("out here")

m = Map(20)
root.mainloop()
</code>```

Body:
I don't know why my canvas is not displaying. There is a reference to it, self._screen, and it is being packed, but it does not display at all. What am I missing?

class Map(Frame):

    def __init__(self, size):

        Frame.__init__(self)
        self.pack()

        #images
        self.spriteDimension = 20
        self.img1 = PhotoImage(file="Terrain1.gif")
        self.img2 = PhotoImage(file="Terrain2.gif")

        #grid
        self._mapSize = size
        # self._grid = self.randomize()

        #canvas
        canvas_dimension = self._mapSize * self.spriteDimension

        self._screen = Canvas(self, width=canvas_dimension, height=canvas_dimension)
        self._screen.pack()

        self.test()

    def test(self):
        print("in here")
        self._screen.create_image((50,50), anchor = NW, image = self.img1)
        print("out here")

def main():

    m =Map(20);
    m.mainloop(20);

Body:
You have a few problems from what I can see.
Unlike other programming languages you don't use ; at the end of a line of code. You don't need to place m = Map(20) or root.mainloop() in a function. You also need to define a tkinter window so add root = Tk() to the start of your program. Take a look at the code below and let me know if you don't understand something.

from tkinter import *

root = Tk()

class Map(Frame):

    def __init__(self, size):

        Frame.__init__(self)
        self.pack()

        self.spriteDimension = 20
        self.img1 = PhotoImage(file="Terrain1.gif")
        self.img2 = PhotoImage(file="Terrain2.gif")

        self._mapSize = size

        canvas_dimension = self._mapSize * self.spriteDimension

        self._screen = Canvas(self, width=canvas_dimension, height=canvas_dimension)
        self._screen.pack()

        self.test()

    def test(self):
        print("in here")
        self._screen.create_image((50,50), anchor = NW, image = self.img1)
        print("out here")

m = Map(20)
root.mainloop()


问:
open pdf file selected in listbox
I have all the dirctories (2014, 2012), the files of each selected folder (.pdf) in the listbox 2

I get the dirctories by this code

```<code>if (FBD.ShowDialog() == DialogResult.OK)
{
    listBox1.Items.Clear();
    DirectoryInfo[] diri_info = newDirectoryInfo(FBD.SelectedPath).GetDirectories();
    foreach (DirectoryInfo diri in diri_info)
    {
        listBox1.Items.Add(diri);
    }
</code>```

and i get the files by this code

```<code>private void button1_Click(object sender, EventArgs e)
{
    if (listBox1.SelectedIndex >= 0)
    {
        DirectoryInfo dirictory_choisis = (DirectoryInfo)listBox1.SelectedItem;
        FileInfo[] files = dirictory_choisis.GetFiles();
        listBox2.Items.Clear();
        foreach (FileInfo file in files)
        {
            listBox2.Items.Add(file);
        }
    }
    else
    {
        MessageBox.Show("selectioner un dossier");
    }

}
</code>```

Now how I can open the selected file (.pdf)  ?

i use this code but dosn't work ( throw an exception file dosn't found)

```<code>private void listBox2_Click(object sender, EventArgs e)
{
    FileInfo file = (FileInfo) listBox2.SelectedItem;
    Process.Start(file.Name);
}
</code>```

答:
There is a syntax error in your code: "newDirectoryInfo"

By the way, file.Name only returns the name (not including path). You should replace that line with:

```<code>Process.Start(file.FullName);
</code>```

So the listBox2_Click should be like this:

```<code>private void listBox2_Click(object sender, EventArgs e)
    {
        FileInfo file = (FileInfo)listBox2.SelectedItem;
        Process.Start(file.FullName);
    }
</code>```

Title: open pdf file selected in listbox

Body:
I have all the dirctories (2014, 2012), the files of each selected folder (.pdf) in the listbox 2

I get the dirctories by this code

if (FBD.ShowDialog() == DialogResult.OK)
{
    listBox1.Items.Clear();
    DirectoryInfo[] diri_info = newDirectoryInfo(FBD.SelectedPath).GetDirectories();
    foreach (DirectoryInfo diri in diri_info)
    {
        listBox1.Items.Add(diri);
    }

and i get the files by this code

private void button1_Click(object sender, EventArgs e)
{
    if (listBox1.SelectedIndex >= 0)
    {
        DirectoryInfo dirictory_choisis = (DirectoryInfo)listBox1.SelectedItem;
        FileInfo[] files = dirictory_choisis.GetFiles();
        listBox2.Items.Clear();
        foreach (FileInfo file in files)
        {
            listBox2.Items.Add(file);
        }
    }
    else
    {
        MessageBox.Show("selectioner un dossier");
    }

}

Now how I can open the selected file (.pdf)  ?

i use this code but dosn't work ( throw an exception file dosn't found)

private void listBox2_Click(object sender, EventArgs e)
{
    FileInfo file = (FileInfo) listBox2.SelectedItem;
    Process.Start(file.Name);
}

Body:
There is a syntax error in your code: "newDirectoryInfo"

By the way, file.Name only returns the name (not including path). You should replace that line with:

Process.Start(file.FullName);

So the listBox2_Click should be like this:

private void listBox2_Click(object sender, EventArgs e)
    {
        FileInfo file = (FileInfo)listBox2.SelectedItem;
        Process.Start(file.FullName);
    }


问:
How much time does it take to get from the end of a for loop back to the beginning on an msp430?
I am asking this because the code below is what I'm using to make the 2 two leds perfectly alternate their flashing.  But it doesn't really make sense as to why this works. This loop with 2 xor's has 2 states one with pin1(red lit only) active and another with both pin 6 and pin 1 active(both red and green lit). But the lights flash like they are alternating on and off perfectly between each other.

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

// counter as a global variable
unsigned int i = 0;

void main(void)
{
    // stop the watchdog timer
    WDTCTL = WDTPW + WDTHOLD;

    // set the direction register for LED1 and LED2
    P1DIR |= 0x41;

    // initialize LED1 and LED2 to off
    P1OUT &= 0xBE;

    //empty for loop is an infinite loop
    for (;;)
    {
        P1OUT ^= 0x01;

        // create a delay between toggles
        for(i=0; i< 20000; i++)
        {
            // empty statement, do nothing
        }

        P1OUT ^= 0x40;
    }
}
</code>```

Is it possible the delay for the main for loop is causing this illusion?

答:
The answer is that it is VERY FAST to get back to the start of the loop.

This code looks like it should alternate the LEDs to me.  Your comments look like they're badly lined up though.

The main part of it is in your loop. You start out with both LEDs off.  Then do this (I've changed the comments to what I think they do):

```<code>for (;;) {                   //  infinite loop
    P1OUT ^= 0x01;           // toggle state of LED1
    for(i=0; i< 20000; i++)  // create a delay
        ;
    P1OUT ^= 0x40;           // toggle state of LED2
}
</code>```

So what that does, flattening out the loop is:

```<code>                      LED1          LED2
                      off           off

start into loop

Toggle LED1           on            off
wait
wait
wait
Toggle LED2           on            on    { go back to start of loop - quickly }
Toggle LED1           off           on
wait
wait
wait
Toggle LED2           off           off
Toggle LED1           on            off
wait
...
</code>```

Body:
I am asking this because the code below is what I'm using to make the 2 two leds perfectly alternate their flashing.  But it doesn't really make sense as to why this works. This loop with 2 xor's has 2 states one with pin1(red lit only) active and another with both pin 6 and pin 1 active(both red and green lit). But the lights flash like they are alternating on and off perfectly between each other.

#include <msp430g2553.h>

// counter as a global variable
unsigned int i = 0;

void main(void)
{
    // stop the watchdog timer
    WDTCTL = WDTPW + WDTHOLD;

    // set the direction register for LED1 and LED2
    P1DIR |= 0x41;

    // initialize LED1 and LED2 to off
    P1OUT &= 0xBE;

    //empty for loop is an infinite loop
    for (;;)
    {
        P1OUT ^= 0x01;

        // create a delay between toggles
        for(i=0; i< 20000; i++)
        {
            // empty statement, do nothing
        }

        P1OUT ^= 0x40;
    }
}

Is it possible the delay for the main for loop is causing this illusion?

Body:
The answer is that it is VERY FAST to get back to the start of the loop.

This code looks like it should alternate the LEDs to me.  Your comments look like they're badly lined up though.

The main part of it is in your loop. You start out with both LEDs off.  Then do this (I've changed the comments to what I think they do):

for (;;) {                   //  infinite loop
    P1OUT ^= 0x01;           // toggle state of LED1
    for(i=0; i< 20000; i++)  // create a delay
        ;
    P1OUT ^= 0x40;           // toggle state of LED2
}

So what that does, flattening out the loop is:

                      LED1          LED2
                      off           off

start into loop

Toggle LED1           on            off
wait
wait
wait
Toggle LED2           on            on    { go back to start of loop - quickly }
Toggle LED1           off           on
wait
wait
wait
Toggle LED2           off           off
Toggle LED1           on            off
wait
...


问:
How to dynamically generate VBox like a div in javaFX
I want to automatically generate VBox according to the number of result. For example, if the number of result is 3 then i want to automatically generate 3 VBox.
I have written the following code below by following this example: https://www.javacodegeeks.com/2012/07/javafx-20-layout-panes-hbox-and-vbox.html

but it doesnt work:

```<code>@FXML
private AnchorPane apne;

@FXML
private VBox vbxOuter;

@FXML
private VBox vbxInner;

@Override
public void initialize(URL location, ResourceBundle resources) {
    // TODO Auto-generated method stub
    apne = new AnchorPane();
    vbxOuter = new VBox();

    getnewer(apne, vbxOuter, vbxInner);

}

public void getnewer(AnchorPane apne, VBox vbxtrue, VBox vbxmain){

    for(int i = 0; i<3 ; i++){

        vbxInner = new VBox(i+1);
        vbxOuter.getChildren().add(vbxInner);

    }

    apne.getChildren().addAll(vbxOuter);

}
</code>```

apne is a anchor pane containing vbxOuter. I want vbxOuter to get automatically generated according to the number of result. vbxinner will contain buttons and labels. what should i do?

答:
apne and vbxOuter should already exist and be available to your methods if you made them using FXML. All you have to do is populate vbxOuter in your method.

```<code>@FXML private AnchorPane apne;
@FXML private VBox vbxOuter;

@Override
public void initialize(URL location, ResourceBundle resources) {
    apne.getChildren().add(vbxOuter);

    int numberOfInnerVBoxes = 3;
    getnewer(numberOfInnerVBoxes);
}

public void getnewer(int num){
    for(int i = 0; i<num ; i++){
        vbxOuter.getChildren().add(new VBox(i+1));
    }
}
</code>```

Body:
I want to automatically generate VBox according to the number of result. For example, if the number of result is 3 then i want to automatically generate 3 VBox.
I have written the following code below by following this example: https://www.javacodegeeks.com/2012/07/javafx-20-layout-panes-hbox-and-vbox.html

but it doesnt work:

@FXML
private AnchorPane apne;

@FXML
private VBox vbxOuter;

@FXML
private VBox vbxInner;

@Override
public void initialize(URL location, ResourceBundle resources) {
    // TODO Auto-generated method stub
    apne = new AnchorPane();
    vbxOuter = new VBox();

    getnewer(apne, vbxOuter, vbxInner);

}

public void getnewer(AnchorPane apne, VBox vbxtrue, VBox vbxmain){

    for(int i = 0; i<3 ; i++){

        vbxInner = new VBox(i+1);
        vbxOuter.getChildren().add(vbxInner);

    }

    apne.getChildren().addAll(vbxOuter);

}

apne is a anchor pane containing vbxOuter. I want vbxOuter to get automatically generated according to the number of result. vbxinner will contain buttons and labels. what should i do?

Body:
apne and vbxOuter should already exist and be available to your methods if you made them using FXML. All you have to do is populate vbxOuter in your method.

@FXML private AnchorPane apne;
@FXML private VBox vbxOuter;

@Override
public void initialize(URL location, ResourceBundle resources) {
    apne.getChildren().add(vbxOuter);

    int numberOfInnerVBoxes = 3;
    getnewer(numberOfInnerVBoxes);
}

public void getnewer(int num){
    for(int i = 0; i<num ; i++){
        vbxOuter.getChildren().add(new VBox(i+1));
    }
}


问:
Drag shape with touch inside a ScrollViewer UWP
I am trying to drag a shape inside a scroll viewer.
My solution was to temporarily disable the scroll viewer when touching the shape, then re-enabling when releasing. Feels a bit hacky, but couldn't find a better solution. Has anyone a better recommendation?

The XAML code below.

```<code><Page
x:Class="testdragshape.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:testdragshape"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" Height="390.667">

<Grid>
    <ScrollViewer Name="scrollViewer" >
        <Grid Name="pageGrid">
            <TextBlock Name="log" Text="Position:"/>
            <Canvas Name="myCanvas" Width="500" Height="500">
                <Rectangle Name="myTarget"  Width="272" Height="272" Fill="Red" Canvas.Left="41" Canvas.Top="53" />
            </Canvas>
        </Grid>
    </ScrollViewer>

</Grid>
</code>```

The C# UWP code below

```<code>using Windows.Foundation;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;

namespace testdragshape
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            myCanvas.RenderTransform = new TranslateTransform();
            myTarget.PointerPressed += Target_PointerPressed;
            myTarget.PointerMoved += Target_PointerMoved;
            myTarget.PointerReleased += MyTarget_PointerReleased;
        }

        Point _drag0;
        private void Target_PointerPressed(object sender, PointerRoutedEventArgs e)
        {
            // disable the scroll mode
            scrollViewer.HorizontalScrollMode = ScrollMode.Disabled;
            scrollViewer.VerticalScrollMode = ScrollMode.Disabled;

            _drag0 = e.GetCurrentPoint(myCanvas).Position;
            log.Text = "Position - X: " + _drag0.X + " Y: " + _drag0.Y;
        }

        private void Target_PointerMoved(object sender, PointerRoutedEventArgs e)
        {
            if (!e.Pointer.IsInContact) return;

            var point = e.GetCurrentPoint(myCanvas).Position;
            var t = new Point(point.X - _drag0.X, point.Y - _drag0.Y);
            TranslateTransform previous = (TranslateTransform)myCanvas.RenderTransform;
            myCanvas.RenderTransform = new TranslateTransform()
            {
                X = previous.X + t.X,
                Y = previous.Y + t.Y
            };

            log.Text = "Position - X: " + point.X + " Y: " + point.Y;
        }

        private void MyTarget_PointerReleased(object sender, PointerRoutedEventArgs e)
        {
            // re-enable scroll mode
            scrollViewer.HorizontalScrollMode = ScrollMode.Auto;
            scrollViewer.VerticalScrollMode = ScrollMode.Auto;
        }
    }
}
</code>```

答:
You are almost there, except you should disable the direct manipulation of ScrollViewer instead of disabling scrolling, and re-enable it once you are done.

```<code>private void OnPointerPressed(object sender, PointerRoutedEventArgs e)
{
    scrollViewer.CancelDirectManipulations();
}

private void OnPointerReleased(object sender, PointerRoutedEventArgs e)
{
    TryStartDirectManipulation(e.Pointer);
}
</code>```

Body:
I am trying to drag a shape inside a scroll viewer.
My solution was to temporarily disable the scroll viewer when touching the shape, then re-enabling when releasing. Feels a bit hacky, but couldn't find a better solution. Has anyone a better recommendation?

The XAML code below.

<Page
x:Class="testdragshape.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:testdragshape"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" Height="390.667">

<Grid>
    <ScrollViewer Name="scrollViewer" >
        <Grid Name="pageGrid">
            <TextBlock Name="log" Text="Position:"/>
            <Canvas Name="myCanvas" Width="500" Height="500">
                <Rectangle Name="myTarget"  Width="272" Height="272" Fill="Red" Canvas.Left="41" Canvas.Top="53" />
            </Canvas>
        </Grid>
    </ScrollViewer>

</Grid>

The C# UWP code below

using Windows.Foundation;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;

namespace testdragshape
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            myCanvas.RenderTransform = new TranslateTransform();
            myTarget.PointerPressed += Target_PointerPressed;
            myTarget.PointerMoved += Target_PointerMoved;
            myTarget.PointerReleased += MyTarget_PointerReleased;
        }

        Point _drag0;
        private void Target_PointerPressed(object sender, PointerRoutedEventArgs e)
        {
            // disable the scroll mode
            scrollViewer.HorizontalScrollMode = ScrollMode.Disabled;
            scrollViewer.VerticalScrollMode = ScrollMode.Disabled;

            _drag0 = e.GetCurrentPoint(myCanvas).Position;
            log.Text = "Position - X: " + _drag0.X + " Y: " + _drag0.Y;
        }

        private void Target_PointerMoved(object sender, PointerRoutedEventArgs e)
        {
            if (!e.Pointer.IsInContact) return;

            var point = e.GetCurrentPoint(myCanvas).Position;
            var t = new Point(point.X - _drag0.X, point.Y - _drag0.Y);
            TranslateTransform previous = (TranslateTransform)myCanvas.RenderTransform;
            myCanvas.RenderTransform = new TranslateTransform()
            {
                X = previous.X + t.X,
                Y = previous.Y + t.Y
            };

            log.Text = "Position - X: " + point.X + " Y: " + point.Y;
        }

        private void MyTarget_PointerReleased(object sender, PointerRoutedEventArgs e)
        {
            // re-enable scroll mode
            scrollViewer.HorizontalScrollMode = ScrollMode.Auto;
            scrollViewer.VerticalScrollMode = ScrollMode.Auto;
        }
    }
}

Body:
You are almost there, except you should disable the direct manipulation of ScrollViewer instead of disabling scrolling, and re-enable it once you are done.

private void OnPointerPressed(object sender, PointerRoutedEventArgs e)
{
    scrollViewer.CancelDirectManipulations();
}

private void OnPointerReleased(object sender, PointerRoutedEventArgs e)
{
    TryStartDirectManipulation(e.Pointer);
}


问:
YouTube Live Streaming API - LiveChatMessage - userBannedEvent not receiving
liveChatMessages docs defines userBannedEvent as one of the message types, but response data contains only LiveChatMessages with type textMessageEvent.

The question is, can I get userBannedEvents from requests to YouTube API?

答:
Looks like this is a currently known issue with no provided workaround as of the moment. This Reddit thread is from a year ago, but upon looking around, there doesn't seem to be any update so far. From the thread:

Yes, this is a known issue. We don't send userBannedEvent, messageRetractedEvent or messageDeletedEvent through the API right now.


问:
How do you document your development?
I am building my first complex app (in RoR) and as I think about passing it on to new programmers, I have been thinking about the best ways to document what I'm building.

How do you like to document your work?

Are there softwares or websites that allow one to easily accumulate sections of documentation, perhaps with tagging for easy reference later on?

答:
I like to use a wiki. I think it would meet all the goals you named:

an easy way to have various pages and sections

searching and tagging is usually built-in

Plus, there are other features:

You can allow others to help out with the documentation

The docs can grow as they need to: Start out with just a simple one-page site. Then expand when it makes sense.

My two favorites are pbworks.com for private projects: it's free for some uses, and lets you set permissions to private. My other favorite is github, which includes a wiki with every project you create.

Title: How do you document your development?