问:
how to publish wepback bundles on VSTS for MVC app on azure
I am having trouble figuring out how to use VSTS to deploy an arbitrary directory from my build to an azure web app.

The arbitrary directory is produced during the build step and contains the webpack bundled javascript for my app. Here are the details:

I have an MVC 5 app and I just started using webpack to bundle the output of my typescript files. webpack creates a set of bundles and writes them to $(project_dir)/Scripts/bundles.

All my typescript source are in various other directories under /Scripts as well (App, Api, Lib etc). But from a VS project point of view, bundles is empty, but added to the project.

Everything works great locally. I can do a debug build and webpack-dev-server serves up the bundles. I can do a release build and webpack happily creates the bundles on disk in /Scripts/bundles. And my code happily consumes the bundles.

I have edited the project file to include:

```<code><Content Include="Scripts\Bundles\**" />
</code>```

and if I do a publish from within visual studio it all works great. But VSTS doesn't seem to recognize this part of the project

We use VSTS to do our building and releasing to azure. I can't for the life of me figure out how to get VSTS to publish this /Scripts/bundles directory.

In my project properties, I created a pre-build step that runs webpack. I know that the files are in the Scripts/bundles directory at the end of the build because the closest I have come to getting this working is to have the VSTS build a second artifact that is the zip file of that bundles directory and the files are in there.

I could solve my problem if I knew one of the following (I think):

how to get an arbitrary directory to show up in the main artifact like the normal build output - I can then use my standard release definition to push it to azure

how to publish a second artifact in a release definition?

If you can solve #2, the issue is that in building the artifact for /Scripts/bundle, it put the contents of the bundle directory in the root of the zip file, rather than having bundle as the root of the zip file. So when I unzip the file, It will have to first create /Scripts/bundle and then unzip.

答:
I must have been entering the wrong search terms when I was first trying to figure out how to do this. Once I hit on the right search terms I found a bunch of articles that talk about how to get "extra files" into the deployment package for Azure.

Here is a good article. I basically followed it and things just worked. I added these lines to my csproj file:

```<code>  <PropertyGroup>
    <CopyAllFilesToSingleFolderForPackageDependsOn>
      WebpackBundles;
      $(CopyAllFilesToSingleFolderForPackageDependsOn);
    </CopyAllFilesToSingleFolderForPackageDependsOn>
    <CopyAllFilesToSingleFolderForMsdeployDependsOn>
      WebpackBundles;
      $(CopyAllFilesToSingleFolderForMsdeployDependsOn);
    </CopyAllFilesToSingleFolderForMsdeployDependsOn>
  </PropertyGroup>
  <Target Name="WebpackBundles">
    <ItemGroup>
      <_CustomWebPackFiles Include="Scripts\bundles\*" />
      <_CustomWebPackFiles Include="Scripts\bundles\**\*" />
      <FilesForPackagingFromProject Include="%(_CustomWebPackFiles.Identity)">
        <DestinationRelativePath>Scripts\bundles\%(RecursiveDir)%(Filename)%(Extension)</DestinationRelativePath>
      </FilesForPackagingFromProject>
    </ItemGroup>
  </Target>
</code>```

The PropertyGroup was already there. I just inserted the WebpackBundles; call into those two elements and then defined the WebpackBundles target.

And I ended up removing the

```<code><Content Include="Scripts\Bundles\**" />
</code>```

line and replaced it with the new Target that the article suggests. I am running webpack as a pre-build step only on the release build. I am using webpack-dev-server for the debug build locally. The only change I had to make to our VSTS build was to add two npm steps:

npm install

npm install webpack -g

this allowed the pre-build step to find the webpack executable and run it.

there was no change to the VSTS release definition because the webpack bundles got put into the deployment zip file in the right location.

Body:
I am having trouble figuring out how to use VSTS to deploy an arbitrary directory from my build to an azure web app.

The arbitrary directory is produced during the build step and contains the webpack bundled javascript for my app. Here are the details:

I have an MVC 5 app and I just started using webpack to bundle the output of my typescript files. webpack creates a set of bundles and writes them to $(project_dir)/Scripts/bundles.

All my typescript source are in various other directories under /Scripts as well (App, Api, Lib etc). But from a VS project point of view, bundles is empty, but added to the project.

Everything works great locally. I can do a debug build and webpack-dev-server serves up the bundles. I can do a release build and webpack happily creates the bundles on disk in /Scripts/bundles. And my code happily consumes the bundles.

I have edited the project file to include:

<Content Include="Scripts\Bundles\**" />

and if I do a publish from within visual studio it all works great. But VSTS doesn't seem to recognize this part of the project

We use VSTS to do our building and releasing to azure. I can't for the life of me figure out how to get VSTS to publish this /Scripts/bundles directory.

In my project properties, I created a pre-build step that runs webpack. I know that the files are in the Scripts/bundles directory at the end of the build because the closest I have come to getting this working is to have the VSTS build a second artifact that is the zip file of that bundles directory and the files are in there.

I could solve my problem if I knew one of the following (I think):

how to get an arbitrary directory to show up in the main artifact like the normal build output - I can then use my standard release definition to push it to azure

how to publish a second artifact in a release definition?

If you can solve #2, the issue is that in building the artifact for /Scripts/bundle, it put the contents of the bundle directory in the root of the zip file, rather than having bundle as the root of the zip file. So when I unzip the file, It will have to first create /Scripts/bundle and then unzip.

Body:
I must have been entering the wrong search terms when I was first trying to figure out how to do this. Once I hit on the right search terms I found a bunch of articles that talk about how to get "extra files" into the deployment package for Azure.

Here is a good article. I basically followed it and things just worked. I added these lines to my csproj file:

  <PropertyGroup>
    <CopyAllFilesToSingleFolderForPackageDependsOn>
      WebpackBundles;
      $(CopyAllFilesToSingleFolderForPackageDependsOn);
    </CopyAllFilesToSingleFolderForPackageDependsOn>
    <CopyAllFilesToSingleFolderForMsdeployDependsOn>
      WebpackBundles;
      $(CopyAllFilesToSingleFolderForMsdeployDependsOn);
    </CopyAllFilesToSingleFolderForMsdeployDependsOn>
  </PropertyGroup>
  <Target Name="WebpackBundles">
    <ItemGroup>
      <_CustomWebPackFiles Include="Scripts\bundles\*" />
      <_CustomWebPackFiles Include="Scripts\bundles\**\*" />
      <FilesForPackagingFromProject Include="%(_CustomWebPackFiles.Identity)">
        <DestinationRelativePath>Scripts\bundles\%(RecursiveDir)%(Filename)%(Extension)</DestinationRelativePath>
      </FilesForPackagingFromProject>
    </ItemGroup>
  </Target>

The PropertyGroup was already there. I just inserted the WebpackBundles; call into those two elements and then defined the WebpackBundles target.

And I ended up removing the

<Content Include="Scripts\Bundles\**" />

line and replaced it with the new Target that the article suggests. I am running webpack as a pre-build step only on the release build. I am using webpack-dev-server for the debug build locally. The only change I had to make to our VSTS build was to add two npm steps:

npm install

npm install webpack -g

this allowed the pre-build step to find the webpack executable and run it.

there was no change to the VSTS release definition because the webpack bundles got put into the deployment zip file in the right location.


来源: stackexchange

问:
How to check for a string's "natural" datatype in Python?
I have a user inputting arguments to the command line when running a python3 script, and I wish to check whether specific arguments are floats, ints, booleans, or strings. I'm familiar with the errors that are thrown when a string like 'car' is cast to an int using the int() function, and am also familiar with using a try/except block to attempt to cast a string to an int, and if this is unsuccessful, how to map error messages to helpful output to the user. I've also seen this previous question, which will probably do the job. Was just wondering if there had been any new development.

Not sure if this is possible, but looking for a smart type() function that could operate as such:

```<code>#!/usr/bin/env python3

import sys

smarttype(sys.argv[-1])
</code>```

and is capable of handling the following kinds of inputs:

```<code>./script.py 50
./script.py True
./script.py 50.0
./script.py run
</code>```

and output:

```<code>int
bool
float
str
</code>```

答:
I usually use ast.literal_eval to parse “elementary” data types:

```<code>type(ast.literal_eval('50')) # outputs int
</code>```

You need however a set of quotes to mark something as a string (otherwise every input could be taken as a string):

```<code>type(ast.literal_eval('run')) # error
type(ast.literal_eval('"run"')) # string
</code>```

If you want to allow unqouted strings you could do the following:

```<code>def parse_data(x):
    """Takes a string x and returns the "value" of x"""
    try:
        return ast.literal_eval(x)
    except (ValueError, SyntaxError):
        return x
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a user inputting arguments to the command line when running a python3 script, and I wish to check whether specific arguments are floats, ints, booleans, or strings. I'm familiar with the errors that are thrown when a string like 'car' is cast to an int using the int() function, and am also familiar with using a try/except block to attempt to cast a string to an int, and if this is unsuccessful, how to map error messages to helpful output to the user. I've also seen this previous question, which will probably do the job. Was just wondering if there had been any new development.

Not sure if this is possible, but looking for a smart type() function that could operate as such:

#!/usr/bin/env python3

import sys

smarttype(sys.argv[-1])

and is capable of handling the following kinds of inputs:

./script.py 50
./script.py True
./script.py 50.0
./script.py run

and output:

int
bool
float
str

Body:
I usually use ast.literal_eval to parse “elementary” data types:

type(ast.literal_eval('50')) # outputs int

You need however a set of quotes to mark something as a string (otherwise every input could be taken as a string):

type(ast.literal_eval('run')) # error
type(ast.literal_eval('"run"')) # string

If you want to allow unqouted strings you could do the following:

def parse_data(x):
    """Takes a string x and returns the "value" of x"""
    try:
        return ast.literal_eval(x)
    except (ValueError, SyntaxError):
        return x


问:
How to prevent or stop a denial of revenue attack?
In the case of paid for by advertising appliance ware websites, their fiscal survival depends heavily on revenue from advertising and managing costs.

If someone where to orchestrate a click-fraud campaign through a specific website/publisher, from the advertisers perspective the natural action would be to blame & ban the publisher's accounts and then forfeit unposted revenue.  Subsequently the publisher would have to scramble to a new advertising broke or agency, still leaving them vulnerable to the same thing happening again and again until they're out of advertisers or stop being profitable.

Tack on a random script to repeatedly, but in a throttled manner, fetch expensive resources over time to increase operating costs and eventually the publisher website will be dead.

From a developer standpoint, I can't see any way to avoid or stop such an attack.   Most advertising brokers would not release raw HTTP access records and even if they did, what could a small web company do but pass this on to relevant law enforcement?

答:
note - Was originally part of question, but moved this part to be a standalone answer.  Marked as community wiki.

A simple solution would be to put a proxy script/service between advertisers and the publisher that then used a dedicated memcache array.

```<code>def handle_request(request):
    cache = Cache()
    key = getKeyByInterval(request.remote_ip,  hour = 1 )
    #Key == "YYMMDD_hour_ip"
    cache.add(key, 1)
    if cache.get(request.remote_ip) > threshold:
        redirect("/none_revenue/random_image")
    else:
        serve_advert()
</code>```

Set threshold to 10, and only 10 adverts would be served to a specific IP for 1 hour.... but even that has flaws inherent to most advertising platforms where the advert script widget is an href like "http://Acme-Advertising-co.com/adserve?userid={Some unique id}&zoneid=SomeValue" in which case all the attacker needs to do is copy that script tag and make a curl request with doctored referer headers.

ContentLicense: CC BY-SA 2.5

Body:
note - Was originally part of question, but moved this part to be a standalone answer.  Marked as community wiki.

A simple solution would be to put a proxy script/service between advertisers and the publisher that then used a dedicated memcache array.

def handle_request(request):
    cache = Cache()
    key = getKeyByInterval(request.remote_ip,  hour = 1 )
    #Key == "YYMMDD_hour_ip"
    cache.add(key, 1)
    if cache.get(request.remote_ip) > threshold:
        redirect("/none_revenue/random_image")
    else:
        serve_advert()

Set threshold to 10, and only 10 adverts would be served to a specific IP for 1 hour.... but even that has flaws inherent to most advertising platforms where the advert script widget is an href like "http://Acme-Advertising-co.com/adserve?userid={Some unique id}&zoneid=SomeValue" in which case all the attacker needs to do is copy that script tag and make a curl request with doctored referer headers.


问:
Renaming a single file in python
I'm trying to rename an audio file but I keep getting OSError: [Errno 2] No such file or directory.

In my program, each user has a directory that holds the users files. I obtain the path for each user by doing the following:

```<code>current_user_path = os.path.join(current_app.config['UPLOAD_FOLDER'], user.username)

/Users/johnsmith/Documents/pythonprojects/project/files/john
</code>```

Now I want to obtain the path for the existing file I want to rename:

```<code>current_file_path = os.path.join(current_user_path,form.currentTitle.data)

/Users/johnsmith/Documents/pythonprojects/project/files/john/File1
</code>```

The path for the rename file will be:

```<code>new_file_path = os.path.join(current_user_path, form.newTitle.data)

/Users/johnsmith/Documents/pythonprojects/project/files/john/One
</code>```

Now I'm just running the rename command:

```<code>os.rename(current_file_path, new_file_path)
</code>```

答:
Try changing the current working directory to the one you want to work with. This code below should give you a simple walk through of how you should  go about it:</p>

```<code>import os
print (os.getcwd())
os.chdir(r"D:\Python\Example")
print (os.getcwd())
print ("start")
def rename_files():
    file_list= os.listdir(r"D:\Python\Example")
    print(file_list)
    for file_name in file_list:
            os.rename(file_name,file_name.translate(None,"0123456789")) rename_files()
print("stop")
print (os.getcwd())
</code>```

Title: Renaming a single file in python

Body:
I'm trying to rename an audio file but I keep getting OSError: [Errno 2] No such file or directory.

In my program, each user has a directory that holds the users files. I obtain the path for each user by doing the following:

current_user_path = os.path.join(current_app.config['UPLOAD_FOLDER'], user.username)

/Users/johnsmith/Documents/pythonprojects/project/files/john

Now I want to obtain the path for the existing file I want to rename:

current_file_path = os.path.join(current_user_path,form.currentTitle.data)

/Users/johnsmith/Documents/pythonprojects/project/files/john/File1

The path for the rename file will be:

new_file_path = os.path.join(current_user_path, form.newTitle.data)

/Users/johnsmith/Documents/pythonprojects/project/files/john/One

Now I'm just running the rename command:

os.rename(current_file_path, new_file_path)

Body:
Try changing the current working directory to the one you want to work with. This code below should give you a simple walk through of how you should  go about it:

import os
print (os.getcwd())
os.chdir(r"D:\Python\Example")
print (os.getcwd())
print ("start")
def rename_files():
    file_list= os.listdir(r"D:\Python\Example")
    print(file_list)
    for file_name in file_list:
            os.rename(file_name,file_name.translate(None,"0123456789")) rename_files()
print("stop")
print (os.getcwd())


问:
How can I apply styles online in React with Meteor?
How can I apply styles online in React with Meteor?

I want to use a local image for the background of a container but my code does not work when invoking the image saved in images/borealis.jpg in the public folder.

Try this render but it does not work, it could be wrong with the code

```<code>render() {
        const fondoBorealis = {backgroundImage: 'images/borealis.jpg'};
        return(
            <div className="container-logeo-vitae">
            <div style={{fondoBorealis}} className="logeo-vitae">
                <div className="header wrap">
                    <h1>borealis </h1>
                </div>
                    <div className="form">
                    <center>
                    {this.state.error ? <p>{this.state.error}</p> : undefined}
                        <form className="form-logeo-vitae" onSubmit={this.onSubmit.bind(this)}>
                            <input className="input-logeo" autoComplete="off" type="email" ref="email" placeholder="correo" />
                            <input className="input-logeo" autoComplete="off" type="password" ref="pass" placeholder="••••••••••" />
                            <button className="btn">login</button>
                        </form>
                    <Link to="/registro" className="link-to">crea una cuenta.</Link>
                    </center>
                    </div>
            </div>
            </div>
        );
    }
</code>```

答:
Oh man, you're so close! It's not a pathing issue but a css issue. When using background image in a css file, it would look like this:

```<code>background-image: url(/images/borealis.jpg);
</code>```

In what you have now it looks like you just missed the url part. So it will work if you change it to this:

```<code>const fondoBorealis = {backgroundImage: 'url(/images/borealis.jpg)'};
</code>```

And to use it you would do this (with one set of curly braces. There are two sets in your current code):

```<code>style={fondoBorealis}
</code>```

Body:
How can I apply styles online in React with Meteor?

I want to use a local image for the background of a container but my code does not work when invoking the image saved in images/borealis.jpg in the public folder.

Try this render but it does not work, it could be wrong with the code

render() {
        const fondoBorealis = {backgroundImage: 'images/borealis.jpg'};
        return(

borealis

                    {this.state.error ?
{this.state.error}
 : undefined}
                        <form className="form-logeo-vitae" onSubmit={this.onSubmit.bind(this)}>
                            <input className="input-logeo" autoComplete="off" type="email" ref="email" placeholder="correo" />
                            <input className="input-logeo" autoComplete="off" type="password" ref="pass" placeholder="••••••••••" />
                            <button className="btn">login</button>
                        </form>
                    <Link to="/registro" className="link-to">crea una cuenta.</Link>

        );
    }

Body:
Oh man, you're so close! It's not a pathing issue but a css issue. When using background image in a css file, it would look like this:

background-image: url(/images/borealis.jpg);

In what you have now it looks like you just missed the url part. So it will work if you change it to this:

const fondoBorealis = {backgroundImage: 'url(/images/borealis.jpg)'};

And to use it you would do this (with one set of curly braces. There are two sets in your current code):

style={fondoBorealis}


问:
the -= operator not working properly, not incrementing when its supposed to be
The program is supposed to make heroes fight against each other and the winner and number of rounds that took them to fight against each other and won is displayed.
Like in this format;

```<code>Ancient Battle! Achilles vs Hector : Winner is Hector in 4 rounds.

The thing is, the program would print out like this :

Greek Heroes
Quarter Finals
Ancient Battle!  vs Hector : Winner is  in 7 rounds.
Ancient Battle! Achilles vs Hector : Winner is Hector in 4 rounds.
Ancient Battle! Hercules vs Theseus : Winner is Hercules in 3 rounds.
Ancient Battle! Odysseus vs Ajax : Winner is Ajax in 3 rounds.
Ancient Battle! Atalanta vs Hippolyta : Winner is Atalanta in 3 rounds.

Semi Finals
Ancient Battle! Hector vs Hercules : Winner is Hector in 6 rounds.
Ancient Battle! Ajax vs Atalanta : Winner is Ajax in 2 rounds.

Finals
Ancient Battle! Hector vs Ajax : Winner is Hector in 3 rounds.

However, what it should logically print out is :

Greek Heroes
Quarter Finals
Ancient Battle! vs Hector : Winner is in 7 rounds.
Ancient Battle! Achilles vs Hector : Winner is Hector in 4 rounds.
Ancient Battle! Hercules vs Theseus : Winner is Hercules in 4 rounds.
Ancient Battle! Odysseus vs Ajax : Winner is Ajax in 3 rounds.
Ancient Battle! Atalanta vs Hippolyta : Winner is Atalanta in 4 rounds.

Semi Finals
Ancient Battle! Hector vs Hercules : Winner is Hector in 7 rounds.

Ancient Battle! Ajax vs Atalanta : Winner is Ajax in 2 rounds.

Finals
Ancient Battle! Hector vs Ajax : Winner is Hector in 4 rounds.
</code>```

I am guessing it has something to do with -= operator logic and i can't seem to figure it out. Any help?

Hero.cpp

```<code>#include "Hero.h"
#include <iostream>
#include <cstring>
using namespace std;
namespace sict {

    Hero::Hero()
    {
        m_name[0] = '\0';
        m_health = 0;
        m_attack = 0;

    }

    Hero::Hero(char name[], int health, int attack)
    {

        if (m_name != nullptr || m_name != "") {
            strcpy(m_name, name);

        }
        else {
            m_name[0] = '\0';
        }

        m_attack = attack;
        m_health = health;

    }

    void Hero::operator-=(int attack) {
        if (attack > 0) {
            m_health -= attack;
        }
        if (attack > m_health) {
            m_health = 0;
        }
    }
    bool Hero::isAlive() const {
        if (m_health > 0) {
            return true;
        }
        else {
            return false;
        }
    }
    int Hero::attackStrength() const {
        if (m_attack == 0) {
            return 0;
        }
        else {
            return m_attack;
        }
    }
    ostream& operator<<(ostream& os, const Hero& hero) {
        if (hero.m_name == '\0') {
            os << "No Hero";
        }
        else {
            os << hero.m_name;
        }
        return os;
    }
    const Hero& operator*(const Hero& first, const Hero& second) {
        cout << "Ancient Battle! ";
        cout << first;
        cout << " vs ";
        cout << second;
        cout << " : ";
        Hero A = first;
        Hero B = second;
        const Hero *winner = nullptr;
        int max_rounds = 0;
        while (A.isAlive() && B.isAlive() && max_rounds < 200) {
            max_rounds++;
            A -= B.attackStrength();
            B -= A.attackStrength();

        }

        bool draw;

        if (A.isAlive() && B.isAlive()) { draw = true; }
        else { draw = false; }

        if (draw) {
            winner = &first;
        }
        else if (A.isAlive())
        {
            winner = &first;
        }
        else {
            winner = &second;
        }
        cout << "Winner is ";
        cout << *winner;
        cout << " in " << max_rounds << " rounds. " << endl;
        return *winner;

    }
}
</code>```

Hero.h

```<code>#ifndef SICT_HERO_H_
#define SICT_HERO_H_
#include <iostream>
namespace sict {
    class Hero {
        char m_name[41];
        int m_health;
        int m_attack;
    public:
        Hero();
        Hero(char name[], int health, int attack);
        void operator-=(int attack);
        bool isAlive() const;
        int attackStrength() const;
        friend std::ostream& operator<<(std::ostream& os, const Hero& hero);
    };
    const Hero& operator*(const Hero& first, const Hero& second);
}
#endif
</code>```

Main.cpp

```<code>#include <iostream>
#include "Hero.h"

using namespace std;
using namespace sict;

int main() {

    cout << "Greek Heroes";
    Hero moneyhunger("", 40, 4);
    Hero hercules("Hercules", 32, 4);
    Hero theseus("Theseus", 14, 5);
    Hero oddyseus("Odysseus", 15, 3);
    Hero ajax("Ajax", 17, 5);
    Hero achilles("Achilles", 20, 6);
    Hero hector("Hector", 30, 5);
    Hero atalanta("Atalanta", 10, 3);
    Hero hippolyta("Hippolyta", 10, 2);

    cout << endl << "Quarter Finals" << endl;
    const Hero& greek_winner0 = moneyhunger * hector;
    const Hero& greek_winner1 = achilles * hector;
    const Hero& greek_winner2 = hercules * theseus;
    const Hero& greek_winner3 = oddyseus * ajax;
    const Hero& greek_winner4 = atalanta * hippolyta;

    cout << endl << "Semi Finals" << endl;
    const Hero& greek_winner_semifinal1 = greek_winner1  * greek_winner2;
    const Hero& greek_winner_semifinal2 = greek_winner3  * greek_winner4;

    cout << endl << "Finals" << endl;
    greek_winner_semifinal1 * greek_winner_semifinal2;
    system("pause");
    return 0;
}
</code>```

答: The operator needs to return *this and have a Hero& return type. Also you need to use an else statement because you have a logic error .

Body:
The program is supposed to make heroes fight against each other and the winner and number of rounds that took them to fight against each other and won is displayed.
Like in this format;

Ancient Battle! Achilles vs Hector : Winner is Hector in 4 rounds.

The thing is, the program would print out like this :

Greek Heroes
Quarter Finals
Ancient Battle!  vs Hector : Winner is  in 7 rounds.
Ancient Battle! Achilles vs Hector : Winner is Hector in 4 rounds.
Ancient Battle! Hercules vs Theseus : Winner is Hercules in 3 rounds.
Ancient Battle! Odysseus vs Ajax : Winner is Ajax in 3 rounds.
Ancient Battle! Atalanta vs Hippolyta : Winner is Atalanta in 3 rounds.

Semi Finals
Ancient Battle! Hector vs Hercules : Winner is Hector in 6 rounds.
Ancient Battle! Ajax vs Atalanta : Winner is Ajax in 2 rounds.

Finals
Ancient Battle! Hector vs Ajax : Winner is Hector in 3 rounds.

However, what it should logically print out is :

Greek Heroes
Quarter Finals
Ancient Battle! vs Hector : Winner is in 7 rounds.
Ancient Battle! Achilles vs Hector : Winner is Hector in 4 rounds.
Ancient Battle! Hercules vs Theseus : Winner is Hercules in 4 rounds.
Ancient Battle! Odysseus vs Ajax : Winner is Ajax in 3 rounds.
Ancient Battle! Atalanta vs Hippolyta : Winner is Atalanta in 4 rounds.

Semi Finals
Ancient Battle! Hector vs Hercules : Winner is Hector in 7 rounds.

Ancient Battle! Ajax vs Atalanta : Winner is Ajax in 2 rounds.

Finals
Ancient Battle! Hector vs Ajax : Winner is Hector in 4 rounds.

I am guessing it has something to do with -= operator logic and i can't seem to figure it out. Any help?

Hero.cpp

#include "Hero.h"
#include <iostream>
#include <cstring>
using namespace std;
namespace sict {

    Hero::Hero()
    {
        m_name[0] = '\0';
        m_health = 0;
        m_attack = 0;

    }

    Hero::Hero(char name[], int health, int attack)
    {

        if (m_name != nullptr || m_name != "") {
            strcpy(m_name, name);

        }
        else {
            m_name[0] = '\0';
        }

        m_attack = attack;
        m_health = health;

    }

    void Hero::operator-=(int attack) {
        if (attack > 0) {
            m_health -= attack;
        }
        if (attack > m_health) {
            m_health = 0;
        }
    }
    bool Hero::isAlive() const {
        if (m_health > 0) {
            return true;
        }
        else {
            return false;
        }
    }
    int Hero::attackStrength() const {
        if (m_attack == 0) {
            return 0;
        }
        else {
            return m_attack;
        }
    }
    ostream& operator<<(ostream& os, const Hero& hero) {
        if (hero.m_name == '\0') {
            os << "No Hero";
        }
        else {
            os << hero.m_name;
        }
        return os;
    }
    const Hero& operator*(const Hero& first, const Hero& second) {
        cout << "Ancient Battle! ";
        cout << first;
        cout << " vs ";
        cout << second;
        cout << " : ";
        Hero A = first;
        Hero B = second;
        const Hero *winner = nullptr;
        int max_rounds = 0;
        while (A.isAlive() && B.isAlive() && max_rounds < 200) {
            max_rounds++;
            A -= B.attackStrength();
            B -= A.attackStrength();

        }

        bool draw;

        if (A.isAlive() && B.isAlive()) { draw = true; }
        else { draw = false; }

        if (draw) {
            winner = &first;
        }
        else if (A.isAlive())
        {
            winner = &first;
        }
        else {
            winner = &second;
        }
        cout << "Winner is ";
        cout << *winner;
        cout << " in " << max_rounds << " rounds. " << endl;
        return *winner;

    }
}

Hero.h

#ifndef SICT_HERO_H_
#define SICT_HERO_H_
#include <iostream>
namespace sict {
    class Hero {
        char m_name[41];
        int m_health;
        int m_attack;
    public:
        Hero();
        Hero(char name[], int health, int attack);
        void operator-=(int attack);
        bool isAlive() const;
        int attackStrength() const;
        friend std::ostream& operator<<(std::ostream& os, const Hero& hero);
    };
    const Hero& operator*(const Hero& first, const Hero& second);
}
#endif

Main.cpp

#include <iostream>
#include "Hero.h"

using namespace std;
using namespace sict;

int main() {

    cout << "Greek Heroes";
    Hero moneyhunger("", 40, 4);
    Hero hercules("Hercules", 32, 4);
    Hero theseus("Theseus", 14, 5);
    Hero oddyseus("Odysseus", 15, 3);
    Hero ajax("Ajax", 17, 5);
    Hero achilles("Achilles", 20, 6);
    Hero hector("Hector", 30, 5);
    Hero atalanta("Atalanta", 10, 3);
    Hero hippolyta("Hippolyta", 10, 2);

    cout << endl << "Quarter Finals" << endl;
    const Hero& greek_winner0 = moneyhunger * hector;
    const Hero& greek_winner1 = achilles * hector;
    const Hero& greek_winner2 = hercules * theseus;
    const Hero& greek_winner3 = oddyseus * ajax;
    const Hero& greek_winner4 = atalanta * hippolyta;

    cout << endl << "Semi Finals" << endl;
    const Hero& greek_winner_semifinal1 = greek_winner1  * greek_winner2;
    const Hero& greek_winner_semifinal2 = greek_winner3  * greek_winner4;

    cout << endl << "Finals" << endl;
    greek_winner_semifinal1 * greek_winner_semifinal2;
    system("pause");
    return 0;
}


问:
NodeJS Cheerio, scraping & get variables
I need to get some statistics from a site which does not have an API. After checking the source code, I saw the data (which I need) is use to build a statistical graphic.

I was able to get the script tag using Request & Cheerio:

```<code>request(nodeUrl, function(error, res, body) {
    var $ = cheerio.load(body);

    var scripts = $('script').filter(function() {
        return ($(this).html().indexOf('Dygraph(document') > -1);
    });
    if (scripts.length === 1) {
        var text = $(scripts[0]).html();
        console.log(text);
    }
});
</code>```

The data I need (using a js formatter to be easy to read and removing all other scripts around):

```<code>d = new Dygraph(document.getElementById("container"), [
    [new Date("2017/08/01"), 0.0654],
    [new Date("2017/08/02"), 0.257],
    [new Date("2017/08/03"), 0.245],
    [new Date("2017/08/04"), 0.15],
    [new Date("2017/08/05"), 0.107],
    [new Date("2017/08/06"), 0.109],
    [new Date("2017/08/07"), 0.143],
    [new Date("2017/08/08"), 0.222],
    [new Date("2017/08/09"), 0.166],
    [new Date("2017/08/10"), 0.156],
    [new Date("2017/08/11"), 0.143],
    [new Date("2017/08/12"), 0.199]
]);
</code>```

I only need all: [new Date("2017/08/12"), 0.199]

Any suggestions will be great. Thanks in advance.

答:
You can use regular expression to parse the data.</p>

```<code>var re = /new Date\("([0-9]{4}\/[0-9]{2}\/[0-9]{2})"\), ([0-9]+\.[0-9]+)/g;
var m;
do {
    m = re.exec($(scripts[0]).html());

    // scraped data:
    // [new Date(m[1]), m[2]]
}
while (m)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to get some statistics from a site which does not have an API. After checking the source code, I saw the data (which I need) is use to build a statistical graphic.

I was able to get the script tag using Request & Cheerio:

request(nodeUrl, function(error, res, body) {
    var $ = cheerio.load(body);

    var scripts = $('script').filter(function() {
        return ($(this).html().indexOf('Dygraph(document') > -1);
    });
    if (scripts.length === 1) {
        var text = $(scripts[0]).html();
        console.log(text);
    }
});

The data I need (using a js formatter to be easy to read and removing all other scripts around):

d = new Dygraph(document.getElementById("container"), [
    [new Date("2017/08/01"), 0.0654],
    [new Date("2017/08/02"), 0.257],
    [new Date("2017/08/03"), 0.245],
    [new Date("2017/08/04"), 0.15],
    [new Date("2017/08/05"), 0.107],
    [new Date("2017/08/06"), 0.109],
    [new Date("2017/08/07"), 0.143],
    [new Date("2017/08/08"), 0.222],
    [new Date("2017/08/09"), 0.166],
    [new Date("2017/08/10"), 0.156],
    [new Date("2017/08/11"), 0.143],
    [new Date("2017/08/12"), 0.199]
]);

I only need all: [new Date("2017/08/12"), 0.199]

Any suggestions will be great. Thanks in advance.

Body:
You can use regular expression to parse the data.

var re = /new Date\("([0-9]{4}\/[0-9]{2}\/[0-9]{2})"\), ([0-9]+\.[0-9]+)/g;
var m;
do {
    m = re.exec($(scripts[0]).html());

    // scraped data:
    // [new Date(m[1]), m[2]]
}
while (m)


问:
Why setImmediate() execute before fs.readFile() in Nodejs Event Loop's works?

I have read a lot of related documents.But I still can't understand how it works.

```<code>const fs = require('fs')
const now = Date.now();

setTimeout(() => console.log('timer'), 10);
fs.readFile(__filename, () => console.log('readfile'));
setImmediate(() => console.log('immediate'));
while(Date.now() - now < 1000) {
}
</code>```

```<code>const now = Date.now();

setImmediate(() => console.log('immediate'));
setTimeout(() => console.log('timer'), 10);
while(Date.now() - now < 1000) {
}
</code>```

I think the first piece of code should log:

```<code>readfile
immediate
</code>```

And the second piece of code logs.

```<code>timer
immediate
</code>```

I think it is ok.

Problem：
I don't understand why the first piece of code logs

```<code>immediate
readfile
</code>```

I think that the file has been read completely and its callback function enqueue  I/O callbacks phase's queque after 1 second.

And then I think event loop will move to timers(none),I/O callbacks(fs.readFile's callback),idle/prepare(none),poll(none),check(setImmediate's callback)and finally close callbacks(none) in order, but result is that setImmediate() still run first.

答:
```<code>setTimeout(() => console.log('timer'), 10);
fs.readFile(__filename, () => console.log('readfile'));
setImmediate(() => console.log('immediate'));

while(Date.now() - now < 1000) {
}
</code>```

Explanation

The setTimeout schedules to be put in an event loop after 10ms.

Asynchronous file reading starts.

The non-standard setImmediate schedules to show a console output breaking long processes.

A one-second blocking loop runs. Nothing in the console yet.

setImmediate prints immediate console message during the loop.

File reading ends and the callback is executed even after the while loop is
over. The console output readfile is there now.

Finally, the console message timer is printed after about 10 secs later.

Things to note

None of above commands (except the loop) are synchronous. They
schedule something and immediately proceed to the next command.

The callback functions are called only after the current blocking
execution is over.

Timeout commands are not guaranteed to be executed at the designated
interval. The guarantee is that they will run anytime after the
interval.

setImmediate is very experimental.

Body:
I have read a lot of related documents.But I still can't understand how it works.

const fs = require('fs')
const now = Date.now();

setTimeout(() => console.log('timer'), 10);
fs.readFile(__filename, () => console.log('readfile'));
setImmediate(() => console.log('immediate'));
while(Date.now() - now < 1000) {
}

const now = Date.now();

setImmediate(() => console.log('immediate'));
setTimeout(() => console.log('timer'), 10);
while(Date.now() - now < 1000) {
}

I think the first piece of code should log:

readfile
immediate

And the second piece of code logs.

timer
immediate

I think it is ok.

Problem：
I don't understand why the first piece of code logs

immediate
readfile

I think that the file has been read completely and its callback function enqueue  I/O callbacks phase's queque after 1 second.

And then I think event loop will move to timers(none),I/O callbacks(fs.readFile's callback),idle/prepare(none),poll(none),check(setImmediate's callback)and finally close callbacks(none) in order, but result is that setImmediate() still run first.

Body:
setTimeout(() => console.log('timer'), 10);
fs.readFile(__filename, () => console.log('readfile'));
setImmediate(() => console.log('immediate'));

while(Date.now() - now < 1000) {
}

Explanation

The setTimeout schedules to be put in an event loop after 10ms.

Asynchronous file reading starts.

The non-standard setImmediate schedules to show a console output breaking long processes.

A one-second blocking loop runs. Nothing in the console yet.

setImmediate prints immediate console message during the loop.

File reading ends and the callback is executed even after the while loop is
over. The console output readfile is there now.

Finally, the console message timer is printed after about 10 secs later.

Things to note

None of above commands (except the loop) are synchronous. They
schedule something and immediately proceed to the next command.

The callback functions are called only after the current blocking
execution is over.

Timeout commands are not guaranteed to be executed at the designated
interval. The guarantee is that they will run anytime after the
interval.

setImmediate is very experimental.


问:
how to download project from code.google?
i am using tortoise svn client to download code from code.google.If protocol is http i am able to download but how to download the code from url below.

hg clone https://vimeoid.googlecode.com/hg/vimeoid

thankx

答:
Hg represents a Mercurial repository, which is an alternative to subversion for source control, you'll need to download a mercurial client.

Mercurial can be downloaded at here.


问:
Slim framework Message: Callable Homecontroller does not exist

Project Structure

public/index.php

```<code><?php

require __DIR__ . '/../vendor/autoload.php';

ini_set('display_errors', 'On');

if (PHP_SAPI == 'cli-server') {
    // To help the built-in PHP dev server, check if the request was actually for
    // something which should probably be served as a static file
    $url  = parse_url($_SERVER['REQUEST_URI']);
    $file = __DIR__ . $url['path'];
    if (is_file($file)) {
        return false;
    }
}

session_start();

// Instantiate the app
$settings = require __DIR__ . '/../src/settings.php';

$app = new \Slim\App($settings);

// Set up dependencies
require __DIR__ . '/../src/dependencies.php';

// Register middleware
require __DIR__ . '/../src/middleware.php';

// Register routes
require __DIR__ . '/../src/routes.php';

// Run app
$app->run();
</code>```

Here we have the composer.json

```<code>{

"autoload":{
    "psr-4": {
        "App\\": "src"
    }
},

"require": {
    "php": ">=5.5.0",
    "slim/slim": "^3.1",
    "slim/php-view": "^2.0",
    "monolog/monolog": "^1.17",
    "illuminate/database": "~5.1",
    "slim/twig-view": "^2.3"
},
"require-dev": {
    "phpunit/phpunit": ">=4.8 < 6.0"
},

"autoload-dev": {
    "psr-4": {
        "Tests\\": "tests/"
    }
},
"config": {
    "process-timeout" : 0
},
}
</code>```

Here is my controller, i obtain a error with the namespace and in all the examples that i have seen use this so.. I don't know what to do more

```<code><?php

namespace \App\Controllers;

class Homecontroller
{
    protected $container;

    // constructor receives container instance
    public function __construct(ContainerInterface $container) {
        $this->container = $container;
    }

    public function home($request, $response, $args) {
        echo "locura";
        // your code
        // to access items in the container... $this->container->get('');
        return $response;
    }

    public function contact($request, $response, $args) {
        // your code
        // to access items in the container... $this->container->get('');
        return $response;
    }
}
</code>```

Actual configuration
In my routes.php I have put this:

```<code>$app->get('/new', \Homecontroller::class . ':home');
</code>```

Before configuration

In the above code, I tried to create the controller into the container, and then use

```<code>$app->get('/new', '\HomeController:home');
</code>```

And in the dependencies.php I put this code:

```<code>$container['HomeController'] = function($c) {
$view = $c->get("view"); // retrieve the 'view' from the container
return new HomeController($view);
</code>```

};

but I didn't obtain any result with any configuration

I would like to load the HomeController from router

This is the error that I have when I put api.powertv/new

```<code> Type: RuntimeException
 Message: Callable Homecontroller does not exist
File:       /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/CallableResolver.php
Line: 90
</code>```

i come here, and I put this post like my last resource, if this fails I don't know what I am going to do.

答:
Try to use absolute namespace path in your:

dependencies.php

```
 $container['yourController'] = function ($c) {
  $view = $c['view'];
  return new \App\Controllers\YourController($view);
}
```

routes.php

```
  $app->get('your_defined_route_name', \App\Controllers\YourController::class . ':YourControllerMethod');
```

Body:
Project Structure

public/index.php

<?php

require __DIR__ . '/../vendor/autoload.php';

ini_set('display_errors', 'On');

if (PHP_SAPI == 'cli-server') {
    // To help the built-in PHP dev server, check if the request was actually for
    // something which should probably be served as a static file
    $url  = parse_url($_SERVER['REQUEST_URI']);
    $file = __DIR__ . $url['path'];
    if (is_file($file)) {
        return false;
    }
}

session_start();

// Instantiate the app
$settings = require __DIR__ . '/../src/settings.php';

$app = new \Slim\App($settings);

// Set up dependencies
require __DIR__ . '/../src/dependencies.php';

// Register middleware
require __DIR__ . '/../src/middleware.php';

// Register routes
require __DIR__ . '/../src/routes.php';

// Run app
$app->run();

Here we have the composer.json

{

"autoload":{
    "psr-4": {
        "App\\": "src"
    }
},

"require": {
    "php": ">=5.5.0",
    "slim/slim": "^3.1",
    "slim/php-view": "^2.0",
    "monolog/monolog": "^1.17",
    "illuminate/database": "~5.1",
    "slim/twig-view": "^2.3"
},
"require-dev": {
    "phpunit/phpunit": ">=4.8 < 6.0"
},

"autoload-dev": {
    "psr-4": {
        "Tests\\": "tests/"
    }
},
"config": {
    "process-timeout" : 0
},
}

Here is my controller, i obtain a error with the namespace and in all the examples that i have seen use this so.. I don't know what to do more

<?php

namespace \App\Controllers;

class Homecontroller
{
    protected $container;

    // constructor receives container instance
    public function __construct(ContainerInterface $container) {
        $this->container = $container;
    }

    public function home($request, $response, $args) {
        echo "locura";
        // your code
        // to access items in the container... $this->container->get('');
        return $response;
    }

    public function contact($request, $response, $args) {
        // your code
        // to access items in the container... $this->container->get('');
        return $response;
    }
}

Actual configuration
In my routes.php I have put this:

$app->get('/new', \Homecontroller::class . ':home');

Before configuration

In the above code, I tried to create the controller into the container, and then use

$app->get('/new', '\HomeController:home');

And in the dependencies.php I put this code:

$container['HomeController'] = function($c) {
$view = $c->get("view"); // retrieve the 'view' from the container
return new HomeController($view);

};

but I didn't obtain any result with any configuration

I would like to load the HomeController from router

This is the error that I have when I put api.powertv/new

 Type: RuntimeException
 Message: Callable Homecontroller does not exist
File:       /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/CallableResolver.php
Line: 90

i come here, and I put this post like my last resource, if this fails I don't know what I am going to do.

Body:
Try to use absolute namespace path in your:

dependencies.php

 $container['yourController'] = function ($c) {
  $view = $c['view'];
  return new \App\Controllers\YourController($view);
}

routes.php

  $app->get('your_defined_route_name', \App\Controllers\YourController::class . ':YourControllerMethod');


问:
Gcloud ML Engine adds extra dimension to input array
Trying to set up the Gcloud ML Engine with the following code:

import numpy as np
import tensorflow as tf

x = tf.placeholder('float', shape=[None, 3], name='x')
w = tf.Variable(tf.zeros([3, 2]))
y = tf.nn.softmax(tf.matmul(x, w), name='y')

sess = tf.Session()
sess.run(tf.global_variables_initializer())

tensor_info_x = tf.saved_model.utils.build_tensor_info(x)
tensor_info_y = tf.saved_model.utils.build_tensor_info(y)

prediction_signature = (
    tf.saved_model.signature_def_utils.build_signature_def(
        inputs={'inputs': tensor_info_x},
        outputs={'scores': tensor_info_y},
        method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME)
    )

export_path = './test_exports'
builder = tf.saved_model.builder.SavedModelBuilder(export_path)
legacy_init_op = tf.group(tf.tables_initializer(), name='legacy_init_op')
builder.add_meta_graph_and_variables(
      sess, [tf.saved_model.tag_constants.SERVING],
      signature_def_map={
           'predict_images':
               prediction_signature
      },
      legacy_init_op=legacy_init_op)
builder.save()
```

<p>A sample input JSON file I used for prediction is:</p>

<pre class="lang-json prettyprint-override"><code>{ "inputs" : [[ 0.32439028, 0.07830289, 0.30881251], [ 0.32439028, 0.07830289, 0.30881251]] }
</code>```

As you can see, the shape of the input array is (2, 3). However, when feeding this as input to the model, I'm facing an error:

Cannot feed value of shape (1, 2, 3) for Tensor u'x:0', which has
  shape '(?, 3)' (Error code: 2)

To test this further, on giving an input of size (1, 3), the model works perfectly. Any idea how the extra dimension is getting added?

EDIT :

Command used to test:

gcloud ml-engine local predict --model-dir=./test_exports --json-instances inputs.json
```

答:
ML Engine predicts for a batch of inputs, not just one.  So you should change your serving input placeholder to [ None, 2, 3 ]

Incidentally, having your model process a batch would be better for training as well.

Body:
Trying to set up the Gcloud ML Engine with the following code:

import numpy as np
import tensorflow as tf

x = tf.placeholder('float', shape=[None, 3], name='x')
w = tf.Variable(tf.zeros([3, 2]))
y = tf.nn.softmax(tf.matmul(x, w), name='y')

sess = tf.Session()
sess.run(tf.global_variables_initializer())

tensor_info_x = tf.saved_model.utils.build_tensor_info(x)
tensor_info_y = tf.saved_model.utils.build_tensor_info(y)

prediction_signature = (
    tf.saved_model.signature_def_utils.build_signature_def(
        inputs={'inputs': tensor_info_x},
        outputs={'scores': tensor_info_y},
        method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME)
    )

export_path = './test_exports'
builder = tf.saved_model.builder.SavedModelBuilder(export_path)
legacy_init_op = tf.group(tf.tables_initializer(), name='legacy_init_op')
builder.add_meta_graph_and_variables(
      sess, [tf.saved_model.tag_constants.SERVING],
      signature_def_map={
           'predict_images':
               prediction_signature
      },
      legacy_init_op=legacy_init_op)
builder.save()

A sample input JSON file I used for prediction is:

{ "inputs" : [[ 0.32439028, 0.07830289, 0.30881251], [ 0.32439028, 0.07830289, 0.30881251]] }

As you can see, the shape of the input array is (2, 3). However, when feeding this as input to the model, I'm facing an error:

Cannot feed value of shape (1, 2, 3) for Tensor u'x:0', which has
  shape '(?, 3)' (Error code: 2)

To test this further, on giving an input of size (1, 3), the model works perfectly. Any idea how the extra dimension is getting added?

EDIT :

Command used to test:

gcloud ml-engine local predict --model-dir=./test_exports --json-instances inputs.json


问:
SAS - Transpose all colums by unique records in each column with counts
I am trying to find efficient, transpose-like code that can convert the Test table below into the Final table. I have code below that works for this example, but for practical purposes, the split data step can produce a very deep table (137 million records in my case, vs 2k as aggregated).

I was hoping there was some Proc or Data step trick I was missing that could skip that intermediate step and be more efficient.

```<code>Data test;
    Input f1 $ f2 $ f3 $ f4 $ f5 $ f6 $ f7 $ f8 $;

    DataLines;
a c f h k l o q
a c f h k l o q
a c g h k m o q
b c g h k m o q
b d g i k m o r
b d g i k n o r
b e g j k n o s
b e g j k n p s
    ;

Run;

Data final;
    Input field $ values $ records;

    DataLines;
f1 a 3
f1 b 5
f2 c 4
f2 d 2
f2 e 2
f3 f 2
f3 g 6
f4 h 4
f4 i 2
f4 j 2
f5 k 8
f6 l 2
f6 m 3
f6 n 3
f7 o 7
f7 p 1
f8 q 4
f8 r 2
f8 s 2
    ;

Run;

/*Working solution - could it be done more efficiently?*/
Data split;
    Set test;

    Array f{8} f1-f8;
    Do i=1 To 8;
        field = 'f'||PUT(i,best2.);
        values = f{i};
        Output;
    End;

    Drop i f1-f8;
Run;

Proc SQL;
    Create Table final As
    Select
        field
        ,values
        ,COUNT(*) As records Format=comma8.0
    From split
    Group By 1,2
    Order By 1,2
    ;
Quit;
</code>```

答:
Massar:

Frequency counting can be done in a DATA Step hash object that uses the suminc: and keysum: features:

```<code>Data have;
    Input f1 $ f2 $ f3 $ f4 $ f5 $ f6 $ f7 $ f8 $;

    DataLines;
a c f h k l o q
a c f h k l o q
a c g h k m o q
b c g h k m o q
b d g i k m o r
b d g i k n o r
b e g j k n o s
b e g j k n p s
    ;

Run;

data want(keep=field value count);
  length field $32 value $8 count 8;
  one = 1;
  call missing (field, value, count);

  declare hash freq(suminc:'one', keysum:'count', ordered:'a', hashexp:20);
  freq.defineKey('field', 'value');
  freq.defineDone();

  do while ( not end );
    set have end=end;
    array f f1-f8;
    do over f; field = vname(f); value=f; freq.ref(); end;
  end;

  declare hiter iter("freq");
  rc = iter.first();
  do while(rc = 0);
    rc = freq.sum(sum: count);
    output;
    rc = iter.next();
  end;

  stop;
run;
</code>```

Body:
I am trying to find efficient, transpose-like code that can convert the Test table below into the Final table. I have code below that works for this example, but for practical purposes, the split data step can produce a very deep table (137 million records in my case, vs 2k as aggregated).

I was hoping there was some Proc or Data step trick I was missing that could skip that intermediate step and be more efficient.

Data test;
    Input f1 $ f2 $ f3 $ f4 $ f5 $ f6 $ f7 $ f8 $;

    DataLines;
a c f h k l o q
a c f h k l o q
a c g h k m o q
b c g h k m o q
b d g i k m o r
b d g i k n o r
b e g j k n o s
b e g j k n p s
    ;

Run;

Data final;
    Input field $ values $ records;

    DataLines;
f1 a 3
f1 b 5
f2 c 4
f2 d 2
f2 e 2
f3 f 2
f3 g 6
f4 h 4
f4 i 2
f4 j 2
f5 k 8
f6 l 2
f6 m 3
f6 n 3
f7 o 7
f7 p 1
f8 q 4
f8 r 2
f8 s 2
    ;

Run;

/*Working solution - could it be done more efficiently?*/
Data split;
    Set test;

    Array f{8} f1-f8;
    Do i=1 To 8;
        field = 'f'||PUT(i,best2.);
        values = f{i};
        Output;
    End;

    Drop i f1-f8;
Run;

Proc SQL;
    Create Table final As
    Select
        field
        ,values
        ,COUNT(*) As records Format=comma8.0
    From split
    Group By 1,2
    Order By 1,2
    ;
Quit;

Body:
Massar:

Frequency counting can be done in a DATA Step hash object that uses the suminc: and keysum: features:

Data have;
    Input f1 $ f2 $ f3 $ f4 $ f5 $ f6 $ f7 $ f8 $;

    DataLines;
a c f h k l o q
a c f h k l o q
a c g h k m o q
b c g h k m o q
b d g i k m o r
b d g i k n o r
b e g j k n o s
b e g j k n p s
    ;

Run;

data want(keep=field value count);
  length field $32 value $8 count 8;
  one = 1;
  call missing (field, value, count);

  declare hash freq(suminc:'one', keysum:'count', ordered:'a', hashexp:20);
  freq.defineKey('field', 'value');
  freq.defineDone();

  do while ( not end );
    set have end=end;
    array f f1-f8;
    do over f; field = vname(f); value=f; freq.ref(); end;
  end;

  declare hiter iter("freq");
  rc = iter.first();
  do while(rc = 0);
    rc = freq.sum(sum: count);
    output;
    rc = iter.next();
  end;

  stop;
run;


问:
How do I exit a While(true) loop with a key?
So I have this while loop that looks something like this.

```<code>bool isTrue = true;
while(isTrue)
{
  //Do work over and over
}
</code>```

I'm wondering.. Can I add if statement that checks if a key has been pressed during the current loop to break out of it? WITHOUT INTERRUPTING THE LOOP so some sort of async task maybe? Because it's automating the task over and over again. For the sake of the question let's say it's printing out "Hello World!" to the console every third second.

答: Couldn't you simply just have it as a condition in your while loop. While (true and condition) {} or you can just do an if statement in the body with a break.</p>

Body:
So I have this while loop that looks something like this.

bool isTrue = true;
while(isTrue)
{
  //Do work over and over
}

I'm wondering.. Can I add if statement that checks if a key has been pressed during the current loop to break out of it? WITHOUT INTERRUPTING THE LOOP so some sort of async task maybe? Because it's automating the task over and over again. For the sake of the question let's say it's printing out "Hello World!" to the console every third second.


问:
high order component throws an invalid react element error (reactjs)
So I've been reading about HOCs lately and decided to use them in my application to pass down authorisation logic to the child components.

I'm trying to render a <Route /> component through the HOC but it logs the error:

Uncaught Error: AuthRoute(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

Here's the code for the HOC:

```<code>const AuthRoute = ({ component: Component }) => {
  class AuthComponent extends Component {
    // Authorisation logic here
    render() {
      return (
          <Route render={props => <Component {...props}/>} />
      )
    }
  }
  return AuthComponent;
};
</code>```

And then I'm using this HOC as an alias of <Route /> component like this:

```<code><BrowserRouter>
  <AuthRoute path="/account" component={PrivateComponent} />
</BrowserRouter>
</code>```

EDIT:

But this approach works fine:

```<code>const AuthRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
      checkAuth() ? (<Component {...props}/>) : (<Redirect to={{pathname: '/', state: { from: props.location }}}/>)
    )}/>
);

<BrowserRouter>
  <AuthRoute path="/account" component={PrivateComponent} />
</BrowserRouter>
</code>```

答:
You need to review your architecture . Indeed, Your approach is totally contradictory regarding HOC pattern . You may need to do the following instead :

```<code><BrowserRouter>
  <Route path="/account" component={AuthRoute(PrivateComponent)} />
</BrowserRouter>
</code>```

If you agree with this design of calling the HOC, The HOC implementation  will be :

```<code>const AuthRoute = (Composed) => {
  class AuthComponent extends React.Component {
    // Authorisation logic here
    componentWillMount() {
       if (!checkAuth()) {
         this.props.history.push({pathname: '/', state: { from: this.props.location }});
       }
    }

    render() {
      return (
          <Composed {...this.props} />
      )
    }
  }
  return AuthComponent;
};
</code>```

Body:
So I've been reading about HOCs lately and decided to use them in my application to pass down authorisation logic to the child components.

I'm trying to render a <Route /> component through the HOC but it logs the error:

Uncaught Error: AuthRoute(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

Here's the code for the HOC:

const AuthRoute = ({ component: Component }) => {
  class AuthComponent extends Component {
    // Authorisation logic here
    render() {
      return (
          <Route render={props => <Component {...props}/>} />
      )
    }
  }
  return AuthComponent;
};

And then I'm using this HOC as an alias of <Route /> component like this:

<BrowserRouter>
  <AuthRoute path="/account" component={PrivateComponent} />
</BrowserRouter>

EDIT:

But this approach works fine:

const AuthRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
      checkAuth() ? (<Component {...props}/>) : (<Redirect to={{pathname: '/', state: { from: props.location }}}/>)
    )}/>
);

<BrowserRouter>
  <AuthRoute path="/account" component={PrivateComponent} />
</BrowserRouter>

Body:
You need to review your architecture . Indeed, Your approach is totally contradictory regarding HOC pattern . You may need to do the following instead :

<BrowserRouter>
  <Route path="/account" component={AuthRoute(PrivateComponent)} />
</BrowserRouter>

If you agree with this design of calling the HOC, The HOC implementation  will be :

const AuthRoute = (Composed) => {
  class AuthComponent extends React.Component {
    // Authorisation logic here
    componentWillMount() {
       if (!checkAuth()) {
         this.props.history.push({pathname: '/', state: { from: this.props.location }});
       }
    }

    render() {
      return (
          <Composed {...this.props} />
      )
    }
  }
  return AuthComponent;
};


问:
How to keep my image caption grid floating correctly with different sized text content
I have an issue here where if a caption is too long, if it extends beyond one line it causes the elements following to not float correctly. I would like to have it, so that no matter on the content of the caption, the following row adjusts to the space. I have seen another site achieve something very similar.

I can't work out what else I need.

body {
 padding: 0;
 margin: 0 auto;
}
.container:after, .group:before, .group:after, .clearfix:before, .clearfix:after, .row:before, .row:after {
 content: '\0020';
 display: block;
 overflow: hidden;
 visibility: hidden;
 width: 0;
 height: 0;
}
.container:after, .row:after, .clearfix:after, .group:after {
 clear: both;
}
.row, .clearfix, .group {
 zoom: 1;
}
*, *::before, *::after {
 margin: 0;
 padding: 0;
 box-sizing: border-box;
}
body, html {
 height: 100%;
}
body {
 color: #000;
 background: #FFF
}
.column {
 float: left;
 display: block
}
.constraint {
 padding-right: 2%;
 padding-left: 2%;
 margin-right: auto;
 margin-left: auto;
 width: 100%
}
.col-4 {
 width: 33.33333333%
}
.columns {
 padding-left: 25px;
 padding-right: 25px
}
.row {
 max-width: 100%;
 margin: 0px auto;
 width: auto
}
.picture {
 height: 0;
 position: relative;
 background-size: cover;
 background-position: center center;
 background-repeat: no-repeat
}
.thumb,
.thumb-title,
.thumb-description {
  margin-bottom: 1rem
}
.picture.portrait {
 padding-bottom: 65%
}
section#projects .picture.portrait {
 padding-bottom: 75%;
 background-position: inherit
}
.project-thumbnail {
 margin-bottom: 80px;
 margin-bottom: 3rem;
  overflow: hidden
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div class="constraint">
    <section id="projects">
      <!-- Row -->
      <div class="row">
        <!-- Project previews -->
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview with some content that makes it extend onto another line.</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
        <article class="project-thumbnail col-4 columns column">
            <div class="picture portrait" style="background-image:url('http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg'); background-position: 50%"> </div>
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>
      </div>
    </section>
  </div></code>```

CSS Tricks say:

The Overflow Method relies on setting the overflow CSS property on a parent element. If this property is set to auto or hidden on the parent element, the parent will expand to contain the floats

Reading this, I set the container div.project-thumbnail, but no change:

```<code>.project-thumbnail {
  overflow: auto
}
</code>```

jsFiddle

EDIT

As the comment suggests, setting a height to the caption div div.thumb would enable it to float correctly. A fixed height will cut off content that becomes too big for it. Adding overflow: auto to this div will just add a scrollbar to it, this is not what I am after.

EDIT

This site here has a similar system. Items with a width are floated, no row separator, but if the content within their div extends beyond a few lines, the bottom of the div will adjust, aligning the next row neatly.

答:
This all seems like a bit too much code.

I have simplified it using Flexbox (as shown below).

Here is what I did:

For .center
I added a class called "center" to the div that contains the container of the grid. It basically centers your section.

For section
The section is the container of all the grid elements. I added display, flex-direction, flex-wrap and width. You do not necessary need to declare all of them (except for display) since some of them are defaults that come with using display:flex. I encourage you to test it all out in your console.

For article
You need to declare the width and margin here. I am declaring 4 columns.
Here is an example of how to calculate with 2 columns:

Since my margin is at 1.66%, my total margin space is 6.64%
How did I come up with that number? The first grid element has a margin to the right and to the left. The second grid element has a margin to the right and to the left. So, 1.66% X 4

I then substract 6.64 from 100, which gives me 93.36. I divide that in two because I have two columns. So every column width will be 46.68%. */

If you were to add padding, you would need to declare the following:

```<code>article { box-sizing:border-box; }
</code>```

This will keep your columns from breaking.

CSS Tricks has a great tutorial on how to use flexbox: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

.center {
  display: flex;
  flex-direction: column;
  align-items: center;
}
section {
  display:flex;
  flex-direction:row;
  flex-wrap:wrap;
  width:80%;
}
article {
  background: grey;
  width:21.68%;
  margin: 1.66%;
}

img {
  max-width:100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="center">
    <section>
        <!-- Project previews -->
        <article>
            <img src="http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg" alt="image">
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>

        <article>
            <img src="http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg" alt="image">
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview with some content that makes it extend onto another line.</p>
             </div>
        </article>

        <article>
            <img src="http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg" alt="image">
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>

        <article>
            <img src="http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg" alt="image">
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>

        <article>
            <img src="http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg" alt="image">
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>

        <article>
            <img src="http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg" alt="image">
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>

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

Body:
I have an issue here where if a caption is too long, if it extends beyond one line it causes the elements following to not float correctly. I would like to have it, so that no matter on the content of the caption, the following row adjusts to the space. I have seen another site achieve something very similar.

I can't work out what else I need.

body {
 padding: 0;
 margin: 0 auto;
}
.container:after, .group:before, .group:after, .clearfix:before, .clearfix:after, .row:before, .row:after {
 content: '\0020';
 display: block;
 overflow: hidden;
 visibility: hidden;
 width: 0;
 height: 0;
}
.container:after, .row:after, .clearfix:after, .group:after {
 clear: both;
}
.row, .clearfix, .group {
 zoom: 1;
}
*, *::before, *::after {
 margin: 0;
 padding: 0;
 box-sizing: border-box;
}
body, html {
 height: 100%;
}
body {
 color: #000;
 background: #FFF
}
.column {
 float: left;
 display: block
}
.constraint {
 padding-right: 2%;
 padding-left: 2%;
 margin-right: auto;
 margin-left: auto;
 width: 100%
}
.col-4 {
 width: 33.33333333%
}
.columns {
 padding-left: 25px;
 padding-right: 25px
}
.row {
 max-width: 100%;
 margin: 0px auto;
 width: auto
}
.picture {
 height: 0;
 position: relative;
 background-size: cover;
 background-position: center center;
 background-repeat: no-repeat
}
.thumb,
.thumb-title,
.thumb-description {
  margin-bottom: 1rem
}
.picture.portrait {
 padding-bottom: 65%
}
section#projects .picture.portrait {
 padding-bottom: 75%;
 background-position: inherit
}
.project-thumbnail {
 margin-bottom: 80px;
 margin-bottom: 3rem;
  overflow: hidden
}

Box One

Item preview

Box One

Item preview with some content that makes it extend onto another line.

Box One

Item preview

Box One

Item preview

Box One

Item preview

Box One

Item preview

CSS Tricks say:

The Overflow Method relies on setting the overflow CSS property on a parent element. If this property is set to auto or hidden on the parent element, the parent will expand to contain the floats

Reading this, I set the container div.project-thumbnail, but no change:

.project-thumbnail {
  overflow: auto
}

jsFiddle

EDIT

As the comment suggests, setting a height to the caption div div.thumb would enable it to float correctly. A fixed height will cut off content that becomes too big for it. Adding overflow: auto to this div will just add a scrollbar to it, this is not what I am after.

EDIT

This site here has a similar system. Items with a width are floated, no row separator, but if the content within their div extends beyond a few lines, the bottom of the div will adjust, aligning the next row neatly.

Body:
This all seems like a bit too much code.

I have simplified it using Flexbox (as shown below).

Here is what I did:

For .center
I added a class called "center" to the div that contains the container of the grid. It basically centers your section.

For section
The section is the container of all the grid elements. I added display, flex-direction, flex-wrap and width. You do not necessary need to declare all of them (except for display) since some of them are defaults that come with using display:flex. I encourage you to test it all out in your console.

For article
You need to declare the width and margin here. I am declaring 4 columns.
Here is an example of how to calculate with 2 columns:

Since my margin is at 1.66%, my total margin space is 6.64%
How did I come up with that number? The first grid element has a margin to the right and to the left. The second grid element has a margin to the right and to the left. So, 1.66% X 4

I then substract 6.64 from 100, which gives me 93.36. I divide that in two because I have two columns. So every column width will be 46.68%. */

If you were to add padding, you would need to declare the following:

article { box-sizing:border-box; }

This will keep your columns from breaking.

CSS Tricks has a great tutorial on how to use flexbox: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

.center {
  display: flex;
  flex-direction: column;
  align-items: center;
}
section {
  display:flex;
  flex-direction:row;
  flex-wrap:wrap;
  width:80%;
}
article {
  background: grey;
  width:21.68%;
  margin: 1.66%;
}

img {
  max-width:100%;
}

<div class="center">
    <section>
        <!-- Project previews -->
        <article>
            <img src="http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg" alt="image">
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>

        <article>
            <img src="http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg" alt="image">
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview with some content that makes it extend onto another line.</p>
             </div>
        </article>

        <article>
            <img src="http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg" alt="image">
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>

        <article>
            <img src="http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg" alt="image">
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>

        <article>
            <img src="http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg" alt="image">
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>

        <article>
            <img src="http://images.all-free-download.com/images/graphiclarge/hd_sky_picture_05_hd_pictures_166299.jpg" alt="image">
             <div class="thumb">
               <h3 class="thumb-title">Box One</h3>
               <p class="thumb-description">Item preview</p>
             </div>
        </article>

    </section>
  </div>


问:
Confirm Java ArrayList contains a specific value
I have a "bank" program, with the following chunk of code:

```<code>private void doPayment(JTextField accountNumField, JTextField paymentField)
    {
        int accountNum = Integer.parseInt(accountNumField.getText());
        double paymentAmt = Double.parseDouble(paymentField.getText());
        String paymentProcessed = "-RECEIPT OF PAYMENT-" + "\n\n" + "Account Number:" + " " + accountObject.getAccountNum() + "Beginning Balance:" + " " + accountObject.getBegBalance()
        + "Payment Amount:" + " " + accountObject.getPaymentAmount() + "Ending Balance:" + " " + accountObject.getEndBalance();
        String errorMsg = "ERROR: ACCOUNT NUMBER" + " " + "[" + accountObject.getAccountNum() + "]" + " " + "NOT FOUND. PLEASE VERIFY THAT THE ACCOUNT INFORMATION IS VALID AND CORRECT.";

        if (accountsArrayList.contains(accountNum))
        {
            accountObject.transactionTwo(paymentAmt);
            JOptionPane.showMessageDialog(null, paymentProcessed, "PAYMENT PROCESSED SUCCESSFULLY", JOptionPane.PLAIN_MESSAGE);
        }
        else
        {
            JOptionPane.showMessageDialog(null, errorMsg, "INVALID ACCOUNT ERROR", JOptionPane.PLAIN_MESSAGE);
        }

    }
</code>```

In theory, after the user creates the account for the client, he/she navigates to a "Process Payment" window and enters two things: accountNum and paymentAmt then hits submit, at which point the doPayment method is called.

This method is supposed to work such that the program iterates through the accountsArrayList which contains THREE items: lastName, firstName, and accountNum. If it finds that the accountNum provided matches a prexisting accountNum in the arrayList, then the transaction is processed accordingly. If no matching accountNum can be found then it returns an error message.

At present, it just returns the error message in the else part of the if-else. I thought that the contains(item) method automatically iterates through the Arraylist. If that isn't the case, do I need an enhanced FOR-loop?

答:
```<code>    if (accountsArrayList.contains(accountNum))
</code>```

accountsArrayList is a ArrayList which contains Objects of type Account.

contains returns true only if accountsArrayList contains an Object type Account given as argument. In your code, accountNum is a int
so the compiler reads it like if(Account == INTEGER)

You have to go throw each Account in your ArrayList and get it's accountNum and than compare the values.

```<code>for(int i = 0; i < accountsArrayList.size; i++){
   if(accountsArrayList.get(i).accountNum == accountNum){
     //success
   }
   else {
     //error
   }
}
</code>```

Body:
I have a "bank" program, with the following chunk of code:

private void doPayment(JTextField accountNumField, JTextField paymentField)
    {
        int accountNum = Integer.parseInt(accountNumField.getText());
        double paymentAmt = Double.parseDouble(paymentField.getText());
        String paymentProcessed = "-RECEIPT OF PAYMENT-" + "\n\n" + "Account Number:" + " " + accountObject.getAccountNum() + "Beginning Balance:" + " " + accountObject.getBegBalance()
        + "Payment Amount:" + " " + accountObject.getPaymentAmount() + "Ending Balance:" + " " + accountObject.getEndBalance();
        String errorMsg = "ERROR: ACCOUNT NUMBER" + " " + "[" + accountObject.getAccountNum() + "]" + " " + "NOT FOUND. PLEASE VERIFY THAT THE ACCOUNT INFORMATION IS VALID AND CORRECT.";

        if (accountsArrayList.contains(accountNum))
        {
            accountObject.transactionTwo(paymentAmt);
            JOptionPane.showMessageDialog(null, paymentProcessed, "PAYMENT PROCESSED SUCCESSFULLY", JOptionPane.PLAIN_MESSAGE);
        }
        else
        {
            JOptionPane.showMessageDialog(null, errorMsg, "INVALID ACCOUNT ERROR", JOptionPane.PLAIN_MESSAGE);
        }

    }

In theory, after the user creates the account for the client, he/she navigates to a "Process Payment" window and enters two things: accountNum and paymentAmt then hits submit, at which point the doPayment method is called.

This method is supposed to work such that the program iterates through the accountsArrayList which contains THREE items: lastName, firstName, and accountNum. If it finds that the accountNum provided matches a prexisting accountNum in the arrayList, then the transaction is processed accordingly. If no matching accountNum can be found then it returns an error message.

At present, it just returns the error message in the else part of the if-else. I thought that the contains(item) method automatically iterates through the Arraylist. If that isn't the case, do I need an enhanced FOR-loop?

Body:
    if (accountsArrayList.contains(accountNum))

accountsArrayList is a ArrayList which contains Objects of type Account.

contains returns true only if accountsArrayList contains an Object type Account given as argument. In your code, accountNum is a int
so the compiler reads it like if(Account == INTEGER)

You have to go throw each Account in your ArrayList and get it's accountNum and than compare the values.

for(int i = 0; i < accountsArrayList.size; i++){
   if(accountsArrayList.get(i).accountNum == accountNum){
     //success
   }
   else {
     //error
   }
}


问:
docker build go app private github
I'm trying to build a docker image from my go app. The github repo is private. I'm a bit new to go (and docker), but I thought that the /vendor file managed through glide should circumvent the problem? Also why does docker have to get everything from github? Everything is available locally.

command:

```<code>docker build -t testimage .
</code>```

Dockerfile

```<code>FROM golang:1.8-onbuild
</code>```

It fails at the step

```<code>exec go get -v -d
.......
fatal: could not read Username for 'https://github.com': No such device or address
</code>```

How can I get around this? Thx

答: If you have /vendor inside the root directory of your project/package, it should not pull anything from the internet. Here's how I did mine: https://gist.github.com/orvyl/7000f973abe88d40c8c91d4e28e139a7

Title: docker build go app private github

Body:
I'm trying to build a docker image from my go app. The github repo is private. I'm a bit new to go (and docker), but I thought that the /vendor file managed through glide should circumvent the problem? Also why does docker have to get everything from github? Everything is available locally.

command:

docker build -t testimage .

Dockerfile

FROM golang:1.8-onbuild

It fails at the step

exec go get -v -d
.......
fatal: could not read Username for 'https://github.com': No such device or address

How can I get around this? Thx


问:
I got this error: Error 1: Cannot implicitly convert type 'double[][]' to 'double[]'
I got this code:

```<code>double[][] ou = new double[h][w];

for(i=0;i<h;i++)
   for(int j=0;j<w;j++)
      ou[i][j] = sortie[z++];

return ou;
</code>```

And I get this 2 errors:

```<code>Error 1: Cannot implicitly convert type 'double[][]' to 'double[]'
</code>```

referred to "return ou"

```<code>Error 2: Invalid rank specifier: expected ',' or ']'
</code>```

referred to "double[][] ou = new double[h][w];"

EDIT:
I try to convert a code from Java to C# and that is were I have                  "double[][] ou = new double[h][w];"

答:
Try this:

```<code>double[,] ou = new double[h,w];
for(i=0;i<h;i++)
       for(int j=0;j<w;j++)
          ou[i,j] = sortie[z++];

return ou;
</code>```

The syntax for a multi-dimensional array uses a comma between the dimensions, not double-brackets.

Body:
I got this code:

double[][] ou = new double[h][w];

for(i=0;i<h;i++)
   for(int j=0;j<w;j++)
      ou[i][j] = sortie[z++];

return ou;

And I get this 2 errors:

Error 1: Cannot implicitly convert type 'double[][]' to 'double[]'

referred to "return ou"

Error 2: Invalid rank specifier: expected ',' or ']'

referred to "double[][] ou = new double[h][w];"

EDIT:
I try to convert a code from Java to C# and that is were I have                  "double[][] ou = new double[h][w];"

Body:
Try this:

double[,] ou = new double[h,w];
for(i=0;i<h;i++)
       for(int j=0;j<w;j++)
          ou[i,j] = sortie[z++];

return ou;

The syntax for a multi-dimensional array uses a comma between the dimensions, not double-brackets.


问:
How can I delete all local Docker images?
I recently started using Docker and never realized that I should use docker-compose down instead of ctrl-c or docker-compose stop to get rid of my experiments. I now have a large number of unneeded docker images locally.

Is there a flag I can run to delete all the local docker images & containers?

Something like docker rmi --all --force --all flag does not exist but I am looking for something with similar idea.

答:
```<code>docker image prune -a
</code>```

Remove all unused images, not just dangling ones. Add -f option to
force.

Local docker version: 17.09.0-ce, Git commit: afdb6d4, OS/Arch: darwin/amd64

```<code>$ docker image prune -h
Flag shorthand -h has been deprecated, please use --help

Usage:  docker image prune [OPTIONS]

Remove unused images

Options:
  -a, --all             Remove all unused images, not just dangling ones
      --filter filter   Provide filter values (e.g. 'until=<timestamp>')
  -f, --force           Do not prompt for confirmation
      --help            Print usage
</code>```

Body:
docker image prune -a

Remove all unused images, not just dangling ones. Add -f option to
force.

Local docker version: 17.09.0-ce, Git commit: afdb6d4, OS/Arch: darwin/amd64

$ docker image prune -h
Flag shorthand -h has been deprecated, please use --help

Usage:  docker image prune [OPTIONS]

Remove unused images

Options:
  -a, --all             Remove all unused images, not just dangling ones
      --filter filter   Provide filter values (e.g. 'until=<timestamp>')
  -f, --force           Do not prompt for confirmation
      --help            Print usage


问:
Does mysql have the fill function() when I use month() to fill data?
I use the month() function to select the data,the sql and the result is :

select month(loan_date)  mon,sum(loan_amount) total_loan from t_loan
 group by mon;
 ---  mon   total_loan
 ---  6   1000
 ---  12   2000

```<code>Now I want the result is:
---mon   total_loan
---1     0
--- 2    0
---3   0
--- 4  0
--- 5   0
---  6   1000
---  7   0
--- 8  0
--- 9   0
---  10   0
--- 11  0
---  12   2000`
</code>```

Does mysql have the fill function() when I use month() to fill data?

答:
The easiest way to solve this is just a simple 12 row union all subquery</p>

```<code>SELECT
      mon.n, coalesce(total_loan,0) total_loan
FROM (
      select 1  n union all
      select 2  n union all
      select 3  n union all
      select 4  n union all
      select 5  n union all
      select 6  n union all
      select 7  n union all
      select 8  n union all
      select 9  n union all
      select 10 n union all
      select 11 n union all
      select 12
      ) mon
LEFT JOIN (
      SELECT
            MONTH(loan_date) mon
          , SUM(loan_amount) total_loan
      FROM t_loan
      GROUP BY
            mon
      ) g ON g.mon = mon.n
</code>```

Body:
I use the month() function to select the data,the sql and the result is :

select month(loan_date)  mon,sum(loan_amount) total_loan from t_loan
 group by mon;
 ---  mon   total_loan
 ---  6   1000
 ---  12   2000

Now I want the result is:
---mon   total_loan
---1     0
--- 2    0
---3   0
--- 4  0
--- 5   0
---  6   1000
---  7   0
--- 8  0
--- 9   0
---  10   0
--- 11  0
---  12   2000`

Does mysql have the fill function() when I use month() to fill data?

Body:
The easiest way to solve this is just a simple 12 row union all subquery

SELECT
      mon.n, coalesce(total_loan,0) total_loan
FROM (
      select 1  n union all
      select 2  n union all
      select 3  n union all
      select 4  n union all
      select 5  n union all
      select 6  n union all
      select 7  n union all
      select 8  n union all
      select 9  n union all
      select 10 n union all
      select 11 n union all
      select 12
      ) mon
LEFT JOIN (
      SELECT
            MONTH(loan_date) mon
          , SUM(loan_amount) total_loan
      FROM t_loan
      GROUP BY
            mon
      ) g ON g.mon = mon.n


问:
Show 'Free' if the price is 0.00 in Easy digital download
I want to show 'Free' if the price is 0.00. Could you guys check my code below is it correct? </p>

```<code><?php edd_price($download_id = 0); ?>
if( edd_get_download_price( get_the_ID() ) == 0 ) {
?>Free
</code>```

答:
I dont know about EDD but your code has syntax issues:

```<code><?php edd_price($download_id = 0); ?>
if( edd_get_download_price( get_the_ID() ) == 0 ) {
?>Free
</code>```

Here, if( edd_get_download_price( get_the_ID() ) == 0 ) is not enclosed by <?php tag. You should remove the ?> in the line before. Also, you are missing the closing braces for you if.Not sure if thats because you have more codes that you did not show here.

Update:

As per the comment below, the code should be updated as below:

```<code><?php if( edd_get_download_price( get_the_ID() ) == 0 ) { ?>
    <h5>Free</h5></span>
<?php } ?>
</code>```

Body:
I want to show 'Free' if the price is 0.00. Could you guys check my code below is it correct?

<?php edd_price($download_id = 0); ?>
if( edd_get_download_price( get_the_ID() ) == 0 ) {
?>Free

Body:
I dont know about EDD but your code has syntax issues:

<?php edd_price($download_id = 0); ?>
if( edd_get_download_price( get_the_ID() ) == 0 ) {
?>Free

Here, if( edd_get_download_price( get_the_ID() ) == 0 ) is not enclosed by <?php tag. You should remove the ?> in the line before. Also, you are missing the closing braces for you if.Not sure if thats because you have more codes that you did not show here.

Update:

As per the comment below, the code should be updated as below:

<?php if( edd_get_download_price( get_the_ID() ) == 0 ) { ?>
    <h5>Free</h5></span>
<?php } ?>


问:
Can you tell on runtime if you're running java from within a jar?
I have an application that some of my users run from Eclipse, and others run it by using a jar file.

I want some actions to be done when running from within the jar, but I don't want them to be done when running from Eclipse.

Is there a way to know on runtime whether the current application is running from within a jar?

Thanks!

Dikla

答:
I have two better solutions. first:

```<code>URL url = this.getClass().getClassLoader().getResource("input.txt");
URLConnection urlConnection = url.openConnection();
if (urlConnection instanceof JarURLConnection) {
    // run in jar
} else {
    // run in ide
}
</code>```

second:

```<code>String protocol = this.getClass().getResource(this.getClass.getName() + ".class").getProtocol();
if(Objects.equals(protocol, "jar")){
    // run in jar
} else if(Objects.equals(protocol, "file")) {
    // run in ide
}
</code>```

OwnerDisplayName: Dikla

Body:
I have two better solutions. first:

URL url = this.getClass().getClassLoader().getResource("input.txt");
URLConnection urlConnection = url.openConnection();
if (urlConnection instanceof JarURLConnection) {
    // run in jar
} else {
    // run in ide
}

second:

String protocol = this.getClass().getResource(this.getClass.getName() + ".class").getProtocol();
if(Objects.equals(protocol, "jar")){
    // run in jar
} else if(Objects.equals(protocol, "file")) {
    // run in ide
}


问:
Trying to reach values of one column in table
I am jQuery/JS newbie, trying substract discount value (user input) from prices of one column and put the result to another column of the table.

HTML

```<code><div>
 <table id='table_one' border='1'>
  <thead>
   <tr>
    <th>Name</th>
    <th>No</th>
    <th>Qty</th>
    <th>Price A</th>
    <th>Price B</th>
   </tr>
  </thead>
   <tr>
   </tr>
 </table>
</div><br>

<form id="discount_form">Discount:
 <input type="text" id="discount">
 <input id="submit" type="button" value="Count">
</form>
</code>```

JS

```<code>var data = '[{"Name" : "Art 1","No" : "01","Qty" : "1","Price_A": 5}';
data+= ',{"Name" : "Art 2","No" : "02","Qty" : "2","Price_A": 10}';
data+= ',{"Name" : "Art 3","No" : "03","Qty" : "5","Price_A": 1.5}]';

data = $.parseJSON(data);

$(function() {
 $.each(data, function(i, item) {
  $('<tr>').append(
  $('<td>').text(item.Name),
  $('<td>').text(item.No),
  $('<td>').text(item.Qty),
  $('<td>').text(item.Price_A),
  $('<td>').text(item.Price_B)).appendTo('#table_one');
 });
});

$(document).ready(function() {
 $('#submit').click(function() {
  var discount = parseFloat($('#discount').val() , 10);
  update_amounts();
 });
});

function update_amounts() {
 $('#table_one tr').each(function() {
  var pricea = parseFloat($(this).find(item.Price_A).val(), 10);
  var priceb = (pricea - discount);
  $(this).find(item.Price_B).text(''+priceb);
  alert($(this).text(priceb));
 });
}
</code>```

I think this I am doing wrong, getting values from column Price_A:

```<code>var pricea = parseFloat($(this).find(item.Price_A).val(), 10);
</code>```

Also this, it suppose to put result data to column Price_B

```<code>$(this).find(item.Price_B).text(''+priceb);
</code>```

Help will be much appreciated.

https://jsfiddle.net/w42zk7uy/

答:
There you using a wrong item.Price_A in  update_amounts.Because you not pass it or assign it to this function. I think you want to want to work on table column priceA and priceB. So you can use the following code instead.

```<code>var data = '[{"Name" : "Art 1","No" : "01","Qty" : "1","Price_A": 5}';
data+= ',{"Name" : "Art 2","No" : "02","Qty" : "2","Price_A": 10}';
data+= ',{"Name" : "Art 3","No" : "03","Qty" : "5","Price_A": 1.5}]';

// convert string to JSON
data = $.parseJSON(data);

$(function() {
    $.each(data, function(i, item) {
    $('<tr>').append(
    $('<td>').text(item.Name),
    $('<td>').text(item.No),
    $('<td>').text(item.Qty),
    $('<td>').text(item.Price_A),
    $('<td>').text(item.Price_B)).appendTo('#table_one');
  });
});

$(document).ready(function() {
        $('#submit').click(function() {
    var discount = parseFloat($('#discount').val() , 10);
    update_amounts();
  });
});

function update_amounts() {
 $('#table_one tbody tr').each(function() {

  var pricea = parseFloat($(this).find("td:nth-child(4)").text());
  var priceb = (pricea - parseFloat($("#discount").val())); // get discount from input text
  $(this).find("td:nth-child(5)").text(''+priceb); //Store value in priceB
 });
}
</code>```

Fiddle Ans

Body:
I am jQuery/JS newbie, trying substract discount value (user input) from prices of one column and put the result to another column of the table.

HTML

    Name
    No
    Qty
    Price A
    Price B

<form id="discount_form">Discount:
 <input type="text" id="discount">
 <input id="submit" type="button" value="Count">
</form>

JS

var data = '[{"Name" : "Art 1","No" : "01","Qty" : "1","Price_A": 5}';
data+= ',{"Name" : "Art 2","No" : "02","Qty" : "2","Price_A": 10}';
data+= ',{"Name" : "Art 3","No" : "03","Qty" : "5","Price_A": 1.5}]';

data = $.parseJSON(data);

$(function() {
 $.each(data, function(i, item) {
  $('
').append(
  $('').text(item.Name),
  $('').text(item.No),
  $('').text(item.Qty),
  $('').text(item.Price_A),
  $('').text(item.Price_B)).appendTo('#table_one');
 });
});

$(document).ready(function() {
 $('#submit').click(function() {
  var discount = parseFloat($('#discount').val() , 10);
  update_amounts();
 });
});

function update_amounts() {
 $('#table_one tr').each(function() {
  var pricea = parseFloat($(this).find(item.Price_A).val(), 10);
  var priceb = (pricea - discount);
  $(this).find(item.Price_B).text(''+priceb);
  alert($(this).text(priceb));
 });
}

I think this I am doing wrong, getting values from column Price_A:

var pricea = parseFloat($(this).find(item.Price_A).val(), 10);

Also this, it suppose to put result data to column Price_B

$(this).find(item.Price_B).text(''+priceb);

Help will be much appreciated.

https://jsfiddle.net/w42zk7uy/

Body:
There you using a wrong item.Price_A in  update_amounts.Because you not pass it or assign it to this function. I think you want to want to work on table column priceA and priceB. So you can use the following code instead.

var data = '[{"Name" : "Art 1","No" : "01","Qty" : "1","Price_A": 5}';
data+= ',{"Name" : "Art 2","No" : "02","Qty" : "2","Price_A": 10}';
data+= ',{"Name" : "Art 3","No" : "03","Qty" : "5","Price_A": 1.5}]';

// convert string to JSON
data = $.parseJSON(data);

$(function() {
    $.each(data, function(i, item) {
    $('<tr>').append(
    $('<td>').text(item.Name),
    $('<td>').text(item.No),
    $('<td>').text(item.Qty),
    $('<td>').text(item.Price_A),
    $('<td>').text(item.Price_B)).appendTo('#table_one');
  });
});

$(document).ready(function() {
        $('#submit').click(function() {
    var discount = parseFloat($('#discount').val() , 10);
    update_amounts();
  });
});

function update_amounts() {
 $('#table_one tbody tr').each(function() {

  var pricea = parseFloat($(this).find("td:nth-child(4)").text());
  var priceb = (pricea - parseFloat($("#discount").val())); // get discount from input text
  $(this).find("td:nth-child(5)").text(''+priceb); //Store value in priceB
 });
}

Fiddle Ans


问:
Algorithm for Least Edge Intersections
(Before anyone asks, it's not homework.)

Say you have 2 Arrays y0 and y1 where

y0 = [1,2,3,4,5,6] and
y1 = [2,1,6,3,4,5]

Notice y0[0] = y1[1] = 1, it essentially means y0[0] is connected to y1[1]. Similarly, y0[2] = y1[3] = 3 so they are "connected" as well.

(Image courtesy : belisarius)

Each element in one array has a corresponding entry in the second array. Imagine each element in the array as a vertex, and these connections as Edges being drawn from one array to the other.

I need to find a set of edges (of maximum size) such that none of the "edges" (or lines) will intersect.

In the above example, notice,

Edge 1 and Edge 2 will intersect.

Edge 6  will intersect with  Edge 3, Edge 4, Edge 5.

Therefore, the solution can be be 1,3,4,5 or 2,3,4,5 (size = 4) since none of those lines will intersect each other. There can be multiple solutions, but I need just one.

My Question, Is there any known CS Problem that resembles this? What algorithm should i be using?

I've tried to explain my problem with an example, however, incase it's still not clear i'll clarify any queries.
Thanks in advance.

答:
Assuming that no element is repeated in a single array, this is simply longest increasing subsequence.

Without loss of generality, assume that the first array, A1, is just [1, 2, 3, ..., n]. This transformation can be done in O(n) with a hash-set, or O(nlogn) with a BST.

Note that our set has a crossing if and only if it contains i and j with i < j but j appearing before i in the second array A2 (we know since i < j that i appears before j in A1).

Then if a set has no crossing it clearly corresponds to an increasing subsequence of A2 and vice versa.

Longest increasing subsequence has a simple O(n^2) solution and a slightly more complex O(nlogn) solution.

Title: Algorithm for Least Edge Intersections