问:
In Java, why can we use the String class as if it were a primitive?
In Java we usually do:

```<code>Class myObject = new Class();
</code>```

because the new keyword returns an address.

But why can we do this?:

```<code>String myString = "Hello";
</code>```

as if String were a primitive?

I asked this to my teacher and he replied that it is because what is in quotes is equivalent to an address, but he is not sure. Can you confirm?

Is "Hello" stored in an instance variable of the class String?

答:
Other answers are pretty good. Some specific points:

I asked this to my teacher and he replied that it is because what is in quotes is equivalent to an address, but he is not sure. Can you confirm?

Yes. He is right. As others have pointed out, a string literal, i.e. a valid Unicode character sequence enclosed inside a pair of "s is recognized by the Java Language Specification. When the Java compiler (the javac program) encounters such a literal (e.g. "Hello") in your Java source file, it takes it literally and places it in a specific section inside the compiled class file. This section is called the runtime constant pool. It then creates a particular instruction called ldc that it places in the class file where the compiled code for your initialization is stored. For instance, the body of the main method in the following Java source code:

```<code>public class StringAsPrimitive {
    public static void main(String[] args) {
        String s = "Hello";
    }
}
</code>```

gets compiled to:

```<code>     0: ldc           #2                  // String Hello
     2: astore_1
     3: return
</code>```

(There is no magic here. Just compile your code using javac program and view the class file using the javap program. You can even see the contents of the .class file using a hex viewer and you will see the String Hello literally).

This code is then interpreted by the JVM when you ask the java program to run this class file.

The ldc instruction to the JVM is documented here. This is what the JVM then does when it interprets #2 which is a reference to the actual location where the literal string "Hello" is stored in the computer's memory (RAM):

Otherwise, if the run-time constant pool entry is a reference to an
  instance of class String representing a string literal (§5.1), then a
  reference to that instance, value, is pushed onto the operand stack.

So, what your teacher said turns out to be right, although we don't say it quite that way. In Java, there are two kinds of types: primitive and reference. So, it would be more appropriate to say that the value of the String literal is a reference (and not address).

Is "Hello" stored in an instance variable of the class String?

No. The String variable initialized to a String literal could be anything, a static or class variable, an instance variable or a local variable (my code above). It is stored in the class file: StringAsPrimitive.class and later it is available to the JVM in a particular memory location. This happens when the JVM loads the class.

Body:
In Java we usually do:

Class myObject = new Class();

because the new keyword returns an address.

But why can we do this?:

String myString = "Hello";

as if String were a primitive?

I asked this to my teacher and he replied that it is because what is in quotes is equivalent to an address, but he is not sure. Can you confirm?

Is "Hello" stored in an instance variable of the class String?

Body:
Other answers are pretty good. Some specific points:

I asked this to my teacher and he replied that it is because what is in quotes is equivalent to an address, but he is not sure. Can you confirm?

Yes. He is right. As others have pointed out, a string literal, i.e. a valid Unicode character sequence enclosed inside a pair of "s is recognized by the Java Language Specification. When the Java compiler (the javac program) encounters such a literal (e.g. "Hello") in your Java source file, it takes it literally and places it in a specific section inside the compiled class file. This section is called the runtime constant pool. It then creates a particular instruction called ldc that it places in the class file where the compiled code for your initialization is stored. For instance, the body of the main method in the following Java source code:

public class StringAsPrimitive {
    public static void main(String[] args) {
        String s = "Hello";
    }
}

gets compiled to:

     0: ldc           #2                  // String Hello
     2: astore_1
     3: return

(There is no magic here. Just compile your code using javac program and view the class file using the javap program. You can even see the contents of the .class file using a hex viewer and you will see the String Hello literally).

This code is then interpreted by the JVM when you ask the java program to run this class file.

The ldc instruction to the JVM is documented here. This is what the JVM then does when it interprets #2 which is a reference to the actual location where the literal string "Hello" is stored in the computer's memory (RAM):

Otherwise, if the run-time constant pool entry is a reference to an
  instance of class String representing a string literal (§5.1), then a
  reference to that instance, value, is pushed onto the operand stack.

So, what your teacher said turns out to be right, although we don't say it quite that way. In Java, there are two kinds of types: primitive and reference. So, it would be more appropriate to say that the value of the String literal is a reference (and not address).

Is "Hello" stored in an instance variable of the class String?

No. The String variable initialized to a String literal could be anything, a static or class variable, an instance variable or a local variable (my code above). It is stored in the class file: StringAsPrimitive.class and later it is available to the JVM in a particular memory location. This happens when the JVM loads the class.


来源: stackexchange

问:
Is/Should wrapping functions into a monad transformer be considered bad practice?
Let's say we want to use ReaderT [(a,b)] over the Maybe monad, and then we want to do a lookup in the list.

Now an easy, and not too uncommon way to this is:

first possibility

```<code>find a = ReaderT (lookup a)
</code>```

However it does seem like this asserts some non-trivial thing about how the ReaderT transformer works. Looking at the source code for Control.Monad.Reader it's clear that this works just fine. But I haven't read any documentation supporting this. However we could also write find like this:

second possibility

```<code>find a = do  y <- ask
             lift (lookup a y)
</code>```

Similar ideas hold for wrapping MaybeT, StateT, State and Reader. Usually I write something like the first example, but most of the time it is really obvious how to write it like the second example, and you might even say it's more readable. So my question is: should code like the first example be considered bad?

答:
I think the biggest problem with the first way is:

If the mtl authors (or whatever transformer library you use), decide to stop exporting the data constructor for ReaderT then it will stop working.  This happened with the State monad in the version bump from mtl 1 to mtl 2 and it's quite annoying.  Whereas, ask is part of the official api of Reader and you should plan on it sticking around.

On the other hand, I wouldn't consider the first way wrong.

ContentLicense: CC BY-SA 3.0

Body:
Let's say we want to use ReaderT [(a,b)] over the Maybe monad, and then we want to do a lookup in the list.

Now an easy, and not too uncommon way to this is:

first possibility

find a = ReaderT (lookup a)

However it does seem like this asserts some non-trivial thing about how the ReaderT transformer works. Looking at the source code for Control.Monad.Reader it's clear that this works just fine. But I haven't read any documentation supporting this. However we could also write find like this:

second possibility

find a = do  y <- ask
             lift (lookup a y)

Similar ideas hold for wrapping MaybeT, StateT, State and Reader. Usually I write something like the first example, but most of the time it is really obvious how to write it like the second example, and you might even say it's more readable. So my question is: should code like the first example be considered bad?

ContentLicense: CC BY-SA 2.5


问:
How to stop more than one being removed from an integer?
I know the title may seem fairly confusing, was just unsure on how to ask this...
So, I'm working on a basic sample game (not going to be a complete game or anything), where you can move around and are chased by an enemy character that attacks you. The problem is that when the attack function is called, instead of only removing one heart/hitpoint, they continue to be 'spam removed'. Here's what I'm working with...

```<code>void Enemy::attackPlayer()
{
    if (distance < 50)
    {
        Player::health--;
        return;
    }
}
</code>```

Pretty simple, right? Well the problem is that I need some way of I guess 'sleeping' the single function so that instead of continuing to remove health, it stops after one, then after let's say, 3 seconds, allows another attack to occur.

答:
You could probably have the Enemy class contain a method like:

```<code>bool canAttack(){
    if(attackTimer >= 3000){
        attackTimer = 0;
        return true;
    }
    return false;
}
</code>```

Then you could modify your damage condition to be something like:

```<code>if (distance < 50 && canAttack())
</code>```

Of course, you would have to add a timer to the Enemy class and have it start and stop based on proximity to the player.

I'm sure there is a better way to handle this--also, this depends a bit on the implementation of the rest of your code.  If you are using something like SFML, there is a built-in event system that would make this a bit easier to handle.  Hopefully this helps a bit!

Body:
I know the title may seem fairly confusing, was just unsure on how to ask this...
So, I'm working on a basic sample game (not going to be a complete game or anything), where you can move around and are chased by an enemy character that attacks you. The problem is that when the attack function is called, instead of only removing one heart/hitpoint, they continue to be 'spam removed'. Here's what I'm working with...

void Enemy::attackPlayer()
{
    if (distance < 50)
    {
        Player::health--;
        return;
    }
}

Pretty simple, right? Well the problem is that I need some way of I guess 'sleeping' the single function so that instead of continuing to remove health, it stops after one, then after let's say, 3 seconds, allows another attack to occur.

Body:
You could probably have the Enemy class contain a method like:

bool canAttack(){
    if(attackTimer >= 3000){
        attackTimer = 0;
        return true;
    }
    return false;
}

Then you could modify your damage condition to be something like:

if (distance < 50 && canAttack())

Of course, you would have to add a timer to the Enemy class and have it start and stop based on proximity to the player.

I'm sure there is a better way to handle this--also, this depends a bit on the implementation of the rest of your code.  If you are using something like SFML, there is a built-in event system that would make this a bit easier to handle.  Hopefully this helps a bit!


问:
Load local images into an array asynchronously on iOS
I need to load about 200 images in my bundle into an array in memory like this:

let arr = (0..<200).map({UIImage(named: "\($0).png")})

The only problem with this is it takes forever to do.. so I'd like to do it in the background and get a callback when the job finishes..

I suppose I can do it like this:

var arr = []
DispatchQueue.main.async({
  arr = (0..<200).map({UIImage(named: "\($0).png")})
})

But then how would I know when the block completes? Thanks!

EDIT: I need to load of these into memory because I want animate a series of images in UIImageView like this:

```<code>let img: UIImageView()
img.animationImages = arr
img.duration = 1
img.startAnimating()
</code>```

答:
You can create a callback and call it after loading the images on the background thread, since the images will be loaded synchronously there.

I recommend doing something like this:

```<code>func loadImages(callback: @escaping ([UIImage]) -> Void) {
    DispatchQueue.global(qos: .background).async {
        let array = (0..<200).flatMap({ UIImage(named: "\($0).png") })
        callback(array)
    }
}
</code>```

Which can be used like this (using swift trailing closure syntax):

```<code>loadImages { images in
    // do something with the images
}
</code>```

You might have to dispatch the callback(array) back to the DispatchQueue.main.

Body:
I need to load about 200 images in my bundle into an array in memory like this:

let arr = (0..<200).map({UIImage(named: "\($0).png")})

The only problem with this is it takes forever to do.. so I'd like to do it in the background and get a callback when the job finishes..

I suppose I can do it like this:

var arr = []
DispatchQueue.main.async({
  arr = (0..<200).map({UIImage(named: "\($0).png")})
})

But then how would I know when the block completes? Thanks!

EDIT: I need to load of these into memory because I want animate a series of images in UIImageView like this:

let img: UIImageView()
img.animationImages = arr
img.duration = 1
img.startAnimating()

Body:
You can create a callback and call it after loading the images on the background thread, since the images will be loaded synchronously there.

I recommend doing something like this:

func loadImages(callback: @escaping ([UIImage]) -> Void) {
    DispatchQueue.global(qos: .background).async {
        let array = (0..<200).flatMap({ UIImage(named: "\($0).png") })
        callback(array)
    }
}

Which can be used like this (using swift trailing closure syntax):

loadImages { images in
    // do something with the images
}

You might have to dispatch the callback(array) back to the DispatchQueue.main.


问:
Add ImageButton to ListView
Im trying to add an ImageButton to each row in my ListView (which I implemented via CustomAdapter). Each button should open a different WebView. I can't seem to find any tutorials to do this so any advice/tips/links would be highly apreciated.

EDIT 1:

My Listview XML:

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

<ImageView
    android:layout_width="30dp"
    app:srcCompat="@drawable/a"
    android:layout_marginLeft="12dp"
    android:layout_marginStart="12dp"
    android:id="@+id/local"
    android:layout_height="30dp"
    android:layout_alignBottom="@+id/versus"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<TextView
    android:text="TextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/resultsiz"
    android:textColor="@android:color/white"

    android:textStyle="normal|bold"

    android:gravity="center_vertical"
    android:elevation="15dp"
    android:layout_alignBaseline="@+id/resultsde"
    android:layout_alignBottom="@+id/resultsde"
    android:layout_alignRight="@+id/resultsde"
    android:layout_alignEnd="@+id/resultsde"
    android:layout_marginRight="61dp"
    android:layout_marginEnd="61dp" />

<ImageView
    android:layout_width="15dp"
    app:srcCompat="@drawable/a"
    android:id="@+id/versus"
    android:layout_height="15dp"
    android:layout_marginLeft="31dp"
    android:layout_marginStart="31dp"
    android:layout_alignBottom="@+id/visit"
    android:layout_toRightOf="@+id/local"
    android:layout_toEndOf="@+id/local" />

<ImageView
    android:layout_width="30dp"
    app:srcCompat="@drawable/a"
    android:id="@+id/visit"
    android:layout_height="30dp"
    android:layout_marginLeft="19dp"
    android:layout_marginStart="19dp"
    android:layout_alignBottom="@+id/resultsiz"
    android:layout_toRightOf="@+id/versus"
    android:layout_toEndOf="@+id/versus" />

<TextView
    android:text="TextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_alignLeft="@+id/local"
    android:layout_alignStart="@+id/local"
    android:id="@+id/dia"
    android:textColor="@color/white"
    android:textStyle="normal|bold"
    android:textAllCaps="true" />

<TextView
    android:text="TextView"
    android:layout_height="wrap_content"
    android:id="@+id/resultsde"
    android:layout_marginRight="24dp"
    android:layout_marginEnd="24dp"
    android:textColor="@android:color/white"
    android:layout_marginTop="19dp"
    android:textStyle="normal|bold"
    android:textAlignment="viewEnd"
    android:gravity="end"
    android:layout_width="70dp"
    android:layout_below="@+id/dia"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />

<Button
    android:text="Button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/local"
    android:layout_toRightOf="@+id/local"
    android:layout_toEndOf="@+id/local"
    android:layout_marginTop="155dp"
    android:id="@+id/stats" />
</RelativeLayout>
</code>```

And my CustomAdapter:

```<code>protected void onPostExecute(Void aVoid) {
    CustomAdapter customAdapter = new CustomAdapter();
    lista.setAdapter(customAdapter);
}
class CustomAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return resultsizq.length;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View view, ViewGroup parent) {
            view = getLayoutInflater().inflate(R.layout.customlayout,null);

            ImageView versus = (ImageView)view.findViewById(R.id.versus);
            ImageView local = (ImageView)view.findViewById(R.id.local);
            ImageView visit = (ImageView)view.findViewById(R.id.visit);

            TextView dia= (TextView)view.findViewById(R.id.dia);
            TextView resultsiz= (TextView)view.findViewById(R.id.resultsiz);
            TextView resultsde= (TextView)view.findViewById(R.id.resultsde);

            dia.setText(di[position]);
            resultsiz.setText(resultsizq[position]);
            resultsde.setText(resultsder[position]);
            versus.setImageResource(versu[position]);
            local.setImageResource(loc[position]);
            visit.setImageResource(vis[position]);

            if ((position+1)%4==0){
                view.setPadding(0,0,0,150);

            }

            if ((position)%4==0){
                view.setPadding(0,150,0,0);

            }

            return view;
        }}
</code>```

答:
In the getView method, you should assign the onClick function to the Button according to the given position. Probably, you should get the item located at position, generate some url based on the properties of this item, and let this url be opened in the onClick function.

More than that, I have 3 suggestions to improve your code:

Try to use RecyclerView instead of ListView.

Even if you use ListView, have a look at View Holder pattern. This is a good place to start.

Consider using Butterknife, which increases the readability of your code. If I were you, I would keep the item as a property in the view  holder object, which has a function annotated with @OnClick(R.id.stats) so that it opens the preferred WebView accordingly.

I hope these help.

Title: Add ImageButton to ListView

Body:
Im trying to add an ImageButton to each row in my ListView (which I implemented via CustomAdapter). Each button should open a different WebView. I can't seem to find any tutorials to do this so any advice/tips/links would be highly apreciated.

EDIT 1:

My Listview XML:

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

<ImageView
    android:layout_width="30dp"
    app:srcCompat="@drawable/a"
    android:layout_marginLeft="12dp"
    android:layout_marginStart="12dp"
    android:id="@+id/local"
    android:layout_height="30dp"
    android:layout_alignBottom="@+id/versus"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<TextView
    android:text="TextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/resultsiz"
    android:textColor="@android:color/white"

    android:textStyle="normal|bold"

    android:gravity="center_vertical"
    android:elevation="15dp"
    android:layout_alignBaseline="@+id/resultsde"
    android:layout_alignBottom="@+id/resultsde"
    android:layout_alignRight="@+id/resultsde"
    android:layout_alignEnd="@+id/resultsde"
    android:layout_marginRight="61dp"
    android:layout_marginEnd="61dp" />

<ImageView
    android:layout_width="15dp"
    app:srcCompat="@drawable/a"
    android:id="@+id/versus"
    android:layout_height="15dp"
    android:layout_marginLeft="31dp"
    android:layout_marginStart="31dp"
    android:layout_alignBottom="@+id/visit"
    android:layout_toRightOf="@+id/local"
    android:layout_toEndOf="@+id/local" />

<ImageView
    android:layout_width="30dp"
    app:srcCompat="@drawable/a"
    android:id="@+id/visit"
    android:layout_height="30dp"
    android:layout_marginLeft="19dp"
    android:layout_marginStart="19dp"
    android:layout_alignBottom="@+id/resultsiz"
    android:layout_toRightOf="@+id/versus"
    android:layout_toEndOf="@+id/versus" />

<TextView
    android:text="TextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_alignLeft="@+id/local"
    android:layout_alignStart="@+id/local"
    android:id="@+id/dia"
    android:textColor="@color/white"
    android:textStyle="normal|bold"
    android:textAllCaps="true" />

<TextView
    android:text="TextView"
    android:layout_height="wrap_content"
    android:id="@+id/resultsde"
    android:layout_marginRight="24dp"
    android:layout_marginEnd="24dp"
    android:textColor="@android:color/white"
    android:layout_marginTop="19dp"
    android:textStyle="normal|bold"
    android:textAlignment="viewEnd"
    android:gravity="end"
    android:layout_width="70dp"
    android:layout_below="@+id/dia"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />

<Button
    android:text="Button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/local"
    android:layout_toRightOf="@+id/local"
    android:layout_toEndOf="@+id/local"
    android:layout_marginTop="155dp"
    android:id="@+id/stats" />
</RelativeLayout>

And my CustomAdapter:

protected void onPostExecute(Void aVoid) {
    CustomAdapter customAdapter = new CustomAdapter();
    lista.setAdapter(customAdapter);
}
class CustomAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return resultsizq.length;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View view, ViewGroup parent) {
            view = getLayoutInflater().inflate(R.layout.customlayout,null);

            ImageView versus = (ImageView)view.findViewById(R.id.versus);
            ImageView local = (ImageView)view.findViewById(R.id.local);
            ImageView visit = (ImageView)view.findViewById(R.id.visit);

            TextView dia= (TextView)view.findViewById(R.id.dia);
            TextView resultsiz= (TextView)view.findViewById(R.id.resultsiz);
            TextView resultsde= (TextView)view.findViewById(R.id.resultsde);

            dia.setText(di[position]);
            resultsiz.setText(resultsizq[position]);
            resultsde.setText(resultsder[position]);
            versus.setImageResource(versu[position]);
            local.setImageResource(loc[position]);
            visit.setImageResource(vis[position]);

            if ((position+1)%4==0){
                view.setPadding(0,0,0,150);

            }

            if ((position)%4==0){
                view.setPadding(0,150,0,0);

            }

            return view;
        }}


问:
SignalR Hub close cause client freez
I'm connecting to SignalR hub from VB.NET client app. When I close the connection to the hub inside FormClosing of the main form, the application freeze for some seconds. </p>

<p>How can I solve that? </p>

答:
I went through that annoying bug. A workaround is to close the connection in a new thread. (this is C# as I don´t know Visual Basic)</p>

```<code>// connection disposing can block the UI thread for about 20 seconds

Task.Run(() =>
{
    try
    {
        connectionToDispose.Dispose();
    }
    catch (Exception ex)
    {
        // do something
    }
});
</code>```

Title: SignalR Hub close cause client freez

Body:
I'm connecting to SignalR hub from VB.NET client app. When I close the connection to the hub inside FormClosing of the main form, the application freeze for some seconds.

How can I solve that?

Body:
I went through that annoying bug. A workaround is to close the connection in a new thread. (this is C# as I don´t know Visual Basic)

// connection disposing can block the UI thread for about 20 seconds

Task.Run(() =>
{
    try
    {
        connectionToDispose.Dispose();
    }
    catch (Exception ex)
    {
        // do something
    }
});


问:
Benefits of using bin files over .js in express-generator
If one wants to jump start a project in Node.js with express. one would use express-generator. After creating a new project your file tree will look like this

```<code>.
├── app.js
├── bin
│   └── www
├── package.json
├── public
│   ├── images
│   ├── javascripts
│   └── stylesheets
│       └── style.css
├── routes
│   ├── index.js
│   └── users.js
└── views
    ├── error.pug
    ├── index.pug
    └── layout.pug
</code>```

One thing that stood out for me is that to run the app you need to do node bin/www or a predefined shortcut npm run. My question is why would one use the www the way it is and not add a .js extension and remove #!/usr/bin/env node from the top of the file? Are there any benefits of doing it this way or is it a personal preference?

答:
Let's look at the first line of the bin/www file:

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

This shebang tells the *nix operating system how to interpret the file if you try to run it as a program.

So this file can be started as a program. And in Linux traditionally executable files do not have an extension.

Body:
If one wants to jump start a project in Node.js with express. one would use express-generator. After creating a new project your file tree will look like this

.
├── app.js
├── bin
│   └── www
├── package.json
├── public
│   ├── images
│   ├── javascripts
│   └── stylesheets
│       └── style.css
├── routes
│   ├── index.js
│   └── users.js
└── views
    ├── error.pug
    ├── index.pug
    └── layout.pug

One thing that stood out for me is that to run the app you need to do node bin/www or a predefined shortcut npm run. My question is why would one use the www the way it is and not add a .js extension and remove #!/usr/bin/env node from the top of the file? Are there any benefits of doing it this way or is it a personal preference?

Body:
Let's look at the first line of the bin/www file:

#!/usr/bin/env node

This shebang tells the *nix operating system how to interpret the file if you try to run it as a program.

So this file can be started as a program. And in Linux traditionally executable files do not have an extension.


问:
git --bare clone analogue for Hg (Mercurial)
I want to checkout only history of a repository.

Does there any option to clone history as like as git --bare clone <repo_url> option?

答:
I don't use Mercurial, but from the help I'd say the nearest you will get is

-U    --noupdate  the clone will include an empty working directory (only a repository)

Update as per answer of @Ry4anBrase:

For an existing repository hg update null deletes all local files. This checks out the null revision, which is the revision before revision 0, and contains no files. If you check out that revision you local files go away and you've got a bare clone as a result.


问:
Sending a rigidbody2d towards a certain point
Im spawning an object outside of the screen and i want to send it towards the middle. The DrawLine shows me that the targets direction is correct. But the object goes of in any random direction. Whats wrong with my calculation? </p>

```<code>// add force towards center of screen
    var targetPosition = new Vector3(Random.Range(-3, 3), Random.Range(-3, 3),00);
    var forceAmount = 10f;
    rb2d.AddForce((bigasteroid.transform.position - targetPosition).normalized * forceAmount);
    Debug.DrawLine(targetPosition, bigasteroid.transform.position,Color.red,3f);
</code>```

答:
It seems you are passing the opposite direction to AddForce. Try this:</p>

```<code>rb2d.AddForce((targetPosition - bigasteroid.transform.position).normalized * forceAmount);
</code>```

Body:
Im spawning an object outside of the screen and i want to send it towards the middle. The DrawLine shows me that the targets direction is correct. But the object goes of in any random direction. Whats wrong with my calculation?

// add force towards center of screen
    var targetPosition = new Vector3(Random.Range(-3, 3), Random.Range(-3, 3),00);
    var forceAmount = 10f;
    rb2d.AddForce((bigasteroid.transform.position - targetPosition).normalized * forceAmount);
    Debug.DrawLine(targetPosition, bigasteroid.transform.position,Color.red,3f);

Body:
It seems you are passing the opposite direction to AddForce. Try this:

rb2d.AddForce((targetPosition - bigasteroid.transform.position).normalized * forceAmount);


问:
Java Hashmap/Hashtable and numbering
the question is simple - I have to implement JTree TreeModel interface which requires that every object has a number. The tree will represent data that are kept in hashmap/hashtable. Keys in that hashmap are client objects and values are arrays of resources (or ArrayLists) so numbering is only a problem at the top level. What would be the easiest way to number keys in Hashmap/Hashtable?</p>

答:
Sounds like the user-object keys need to be ordered - their "number" would be derived from their spot in the ordering.

Are the keys Comparable? If so, maybe use a TreeMap. If not, I suppose insertion order is your best bet (LinkedHashMap)

Title: Java Hashmap/Hashtable and numbering


问:
Scala union operation on binary search tree
I'm new to Scala and I got stuck with undestanding how does following code from this link works on binary search tree:

```<code>def union(that: TweetSet): TweetSet = {
    (left union (right union that)).incl(elem)
}

def incl(x: Tweet): TweetSet = {
    if (x.text < elem.text) new NonEmpty(elem, left.incl(x), right)
    else if (elem.text < x.text) new NonEmpty(elem, left, right.incl(x))
    else this
}
</code>```

Thing that I don't get is how does union operation creating new Tree in sorted order and how it exactly works, is it going to the end of tree and then adding elements one-by-one ?
Also I don't get how does this recursion would terminate, in terms of Java it should probably give us NullPointerException

答:
To sum up how the algorithm works (since only part of it is in the question, the termination being in the Empty case):

To make the union of two TweetSets, look at the left one:

if it is empty, the union should be the other one, so Empty union that == that

if it is non-empty, then it has a root element elem, a left sub-tree and a right sub-tree. The union is then formed by all the elements in left, in right, in that, and the element elem, so we call recursively union on all of those.

In this last case, to ensure that we get to termination, the left element in each union call should be smaller than the initial call (otherwise, we will get caught in a recursion loop where the left-hand-side of union will be bigger and bigger). The expression

```<code>left union (right union that)
</code>```

does precisely that:

right is smaller than the initial NonEmpty(elem, left, right) (being its right sub-tree), so right union that will eventually get computed

left is also smaller than the initial tree, so left union (...) will also get computed eventually.

Then we add the final missing element elem to build the final TweetSet. Note that if you try and apply this algorithm for small sets, it comes back to adding all the elements of the first set to the second, one by one, starting with the greatest one (the furthest one on the right in the initial tree). In particular, the size of the second set does not influence the length of the algorithm.

Body:
I'm new to Scala and I got stuck with undestanding how does following code from this link works on binary search tree:

def union(that: TweetSet): TweetSet = {
    (left union (right union that)).incl(elem)
}

def incl(x: Tweet): TweetSet = {
    if (x.text < elem.text) new NonEmpty(elem, left.incl(x), right)
    else if (elem.text < x.text) new NonEmpty(elem, left, right.incl(x))
    else this
}

Thing that I don't get is how does union operation creating new Tree in sorted order and how it exactly works, is it going to the end of tree and then adding elements one-by-one ?
Also I don't get how does this recursion would terminate, in terms of Java it should probably give us NullPointerException

Body:
To sum up how the algorithm works (since only part of it is in the question, the termination being in the Empty case):

To make the union of two TweetSets, look at the left one:

if it is empty, the union should be the other one, so Empty union that == that

if it is non-empty, then it has a root element elem, a left sub-tree and a right sub-tree. The union is then formed by all the elements in left, in right, in that, and the element elem, so we call recursively union on all of those.

In this last case, to ensure that we get to termination, the left element in each union call should be smaller than the initial call (otherwise, we will get caught in a recursion loop where the left-hand-side of union will be bigger and bigger). The expression

left union (right union that)

does precisely that:

right is smaller than the initial NonEmpty(elem, left, right) (being its right sub-tree), so right union that will eventually get computed

left is also smaller than the initial tree, so left union (...) will also get computed eventually.

Then we add the final missing element elem to build the final TweetSet. Note that if you try and apply this algorithm for small sets, it comes back to adding all the elements of the first set to the second, one by one, starting with the greatest one (the furthest one on the right in the initial tree). In particular, the size of the second set does not influence the length of the algorithm.


问:
How to schedule a job using FluentScheduler library with Web Api?
I am unable to get FluentScheduler working in .Net Framework 4.5.2 Web api. Few days ago, I asked a similar question about scheduling through Console application and could get it to work with help but unfortunately facing issues with Web Api now. Below is the code.

```<code>    [HttpPost]
    [Route("Schedule")]
    public IHttpActionResult Schedule([FromBody] SchedulerModel schedulerModel)
    {
        var registry = new Registry();
        registry.Schedule<MyJob>().ToRunNow();
        JobManager.Initialize(registry);
        JobManager.StopAndBlock();
        return Json(new { success = true, message = "Scheduled!" });
    }
</code>```

Below is the job I want to schedule which for now is just writing text to a file

```<code>public class SampleJob: IJob, IRegisteredObject
{
    private readonly object _lock = new object();
    private bool _shuttingDown;

    public SampleJob()
    {
        HostingEnvironment.RegisterObject(this);
    }

    public void Execute()
    {
        lock (_lock)
        {
            if (_shuttingDown)
                return;
          //Schedule writing to a text file
           WriteToFile();
        }
    }

    public void WriteToFile()
    {
        string text = "Random text";
        File.WriteAllText(@"C:\Users\Public\TestFolder\WriteText.txt", text);
    }

    public void Stop(bool immediate)
    {
        lock (_lock)
        {
            _shuttingDown = true;
        }
        HostingEnvironment.UnregisterObject(this);
    }
</code>```

答:
Got this resolved finally. It turns out the issue was with my Registry class. I had to change it as follows.

```<code>public class ScheduledJobRegistry: Registry
{
    public ScheduledJobRegistry(DateTime appointment)
    {
      //Removed the following line and replaced with next two lines
      //Schedule<SampleJob>().ToRunOnceIn(5).Seconds();
      IJob job = new SampleJob();
      JobManager.AddJob(job, s => s.ToRunOnceIn(5).Seconds());
    }

}

    [HttpPost]
    [Route("Schedule")]
    public IHttpActionResult Schedule([FromBody] SchedulerModel schedulerModel)
    {
        JobManager.Initialize(new ScheduledJobRegistry());
        JobManager.StopAndBlock();
        return Json(new { success = true, message = "Scheduled!" });
    }
</code>```

Another point to note: I could get this to work but hosting Api in IIS makes it tricky because we have to deal with App Pool recycles, idle time etc. But this looks like a good start.

Body:
I am unable to get FluentScheduler working in .Net Framework 4.5.2 Web api. Few days ago, I asked a similar question about scheduling through Console application and could get it to work with help but unfortunately facing issues with Web Api now. Below is the code.

    [HttpPost]
    [Route("Schedule")]
    public IHttpActionResult Schedule([FromBody] SchedulerModel schedulerModel)
    {
        var registry = new Registry();
        registry.Schedule<MyJob>().ToRunNow();
        JobManager.Initialize(registry);
        JobManager.StopAndBlock();
        return Json(new { success = true, message = "Scheduled!" });
    }

Below is the job I want to schedule which for now is just writing text to a file

public class SampleJob: IJob, IRegisteredObject
{
    private readonly object _lock = new object();
    private bool _shuttingDown;

    public SampleJob()
    {
        HostingEnvironment.RegisterObject(this);
    }

    public void Execute()
    {
        lock (_lock)
        {
            if (_shuttingDown)
                return;
          //Schedule writing to a text file
           WriteToFile();
        }
    }

    public void WriteToFile()
    {
        string text = "Random text";
        File.WriteAllText(@"C:\Users\Public\TestFolder\WriteText.txt", text);
    }

    public void Stop(bool immediate)
    {
        lock (_lock)
        {
            _shuttingDown = true;
        }
        HostingEnvironment.UnregisterObject(this);
    }

Body:
Got this resolved finally. It turns out the issue was with my Registry class. I had to change it as follows.

public class ScheduledJobRegistry: Registry
{
    public ScheduledJobRegistry(DateTime appointment)
    {
      //Removed the following line and replaced with next two lines
      //Schedule<SampleJob>().ToRunOnceIn(5).Seconds();
      IJob job = new SampleJob();
      JobManager.AddJob(job, s => s.ToRunOnceIn(5).Seconds());
    }

}

    [HttpPost]
    [Route("Schedule")]
    public IHttpActionResult Schedule([FromBody] SchedulerModel schedulerModel)
    {
        JobManager.Initialize(new ScheduledJobRegistry());
        JobManager.StopAndBlock();
        return Json(new { success = true, message = "Scheduled!" });
    }

Another point to note: I could get this to work but hosting Api in IIS makes it tricky because we have to deal with App Pool recycles, idle time etc. But this looks like a good start.


问:
react-hot-loader configuration error: not updating the browser on component change
I'm using rect-redux-universal-hot-example as a base for my isomorphic app loader using ReactJs.

I'm using react-hot-loader and following this migration guide to remove the deprecated hmr react-transform.

I did the configuration below, but my page in browser is not being reloaded automatically once I change some App component data. No errors at all on both console or brower.

Here is my setup:

.babelrc

```<code>{
  "presets": ["react", "es2015", "stage-0"],

  "plugins": [
    "transform-runtime",
    "add-module-exports",
    "transform-react-display-name",
    "flow-runtime",
    "react-hot-loader/babel"
  ]
}
</code>```

client.js

```<code>import ReactDOM from 'react-dom';
import React from 'react';
import { AppContainer } from 'react-hot-loader'
import App from './component/App';

const dest = document.getElementById('content');

const render = Component => {
  ReactDOM.render(
    <AppContainer>
      <Component />
    </AppContainer>,
    document.getElementById('root')
  )
}

render(App)

if (module.hot) {
  module.hot.accept('./component/App', () => { render(App) })
}
</code>```

dev.config

```<code>require('babel-polyfill');

// Webpack config for development
var fs = require('fs');
var path = require('path');
var webpack = require('webpack');
var assetsPath = path.resolve(__dirname, '../static/dist');
var host = (process.env.HOST || 'localhost');
var port = (+process.env.PORT + 1) || 3001;

// https://github.com/halt-hammerzeit/webpack-isomorphic-tools
var WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin');
var webpackIsomorphicToolsPlugin = new WebpackIsomorphicToolsPlugin(require('./webpack-isomorphic-tools'));

module.exports = {
  devtool: 'inline-source-map',
  context: path.resolve(__dirname, '..'),
  entry: {
    'main': [
      'react-hot-loader/patch',
      './src/client.js'
    ]
  },
  output: {
    path: assetsPath,
    filename: '[name]-[hash].js',
    chunkFilename: '[name]-[chunkhash].js',
    publicPath: 'http://' + host + ':' + port + '/dist/'
  },
  module: {
    loaders: [
      { test: /\.jsx?$/, exclude: /node_modules/, loaders: ['babel-loader', 'eslint-loader']},
      { test: /\.json$/, loader: 'json-loader' },
      { test: /\.less$/, loader: 'style-loader!css?modules&importLoaders=2&sourceMap&localIdentName=[local]___[hash:base64:5]!autoprefixer?browsers=last 2 version!less?outputStyle=expanded&sourceMap' },
      { test: /\.scss$/, loader: 'style-loader!css?modules&importLoaders=2&sourceMap&localIdentName=[local]___[hash:base64:5]!autoprefixer?browsers=last 2 version!sass?outputStyle=expanded&sourceMap' },
      { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&mimetype=application/font-woff" },
      { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&mimetype=application/font-woff" },
      { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&mimetype=application/octet-stream" },
      { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader" },
      { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&mimetype=image/svg+xml" },
      { test: webpackIsomorphicToolsPlugin.regular_expression('images'), loader: 'url-loader?limit=10240' }
    ]
  },
  resolve: {
    modules: [
      'src',
      'node_modules'
    ],
    extensions: ['*', '.json', '.js', '.jsx']
  },
  plugins: [
    // hot reload
    new webpack.HotModuleReplacementPlugin(),
    new webpack.IgnorePlugin(/webpack-stats\.json$/),
    new webpack.DefinePlugin({
      __CLIENT__: true,
      __SERVER__: false,
      __DEVELOPMENT__: true,
      __DEVTOOLS__: true  // <-------- DISABLE redux-devtools HERE
    }),
    webpackIsomorphicToolsPlugin.development()
  ]
};
</code>```

I'm pretty sure something is wrong in my setup, but I can't find what.

答:
I think you're missing a few things here:

In your dev.config.js, you would also need webpack-hot-middleware/client in your main entry.

In your client.js:

```<code>import ReactDOM from 'react-dom';
import React from 'react';
import { AppContainer } from 'react-hot-loader'

// this import path doesn't match import path below
import App from './component/App/app';

const dest = document.getElementById('content');

const render = Component => {
  ReactDOM.render(
    <AppContainer>
      <Component />
    </AppContainer>,
    document.getElementById('root')
  )
}

render(App)

if (module.hot) {
  // Are you sure this is your correct path? This
  // doesn't match the import path above.
  module.hot.accept('./containers/App', () => {
    // import App
    const NextApp = require('./containers/App').default;
    render(NextApp);
  })
}
</code>```

For more reference, you can checkout this thread

ContentLicense: CC BY-SA 4.0

Body:
I'm using rect-redux-universal-hot-example as a base for my isomorphic app loader using ReactJs.

I'm using react-hot-loader and following this migration guide to remove the deprecated hmr react-transform.

I did the configuration below, but my page in browser is not being reloaded automatically once I change some App component data. No errors at all on both console or brower.

Here is my setup:

.babelrc

{
  "presets": ["react", "es2015", "stage-0"],

  "plugins": [
    "transform-runtime",
    "add-module-exports",
    "transform-react-display-name",
    "flow-runtime",
    "react-hot-loader/babel"
  ]
}

client.js

import ReactDOM from 'react-dom';
import React from 'react';
import { AppContainer } from 'react-hot-loader'
import App from './component/App';

const dest = document.getElementById('content');

const render = Component => {
  ReactDOM.render(
    <AppContainer>
      <Component />
    </AppContainer>,
    document.getElementById('root')
  )
}

render(App)

if (module.hot) {
  module.hot.accept('./component/App', () => { render(App) })
}

dev.config

require('babel-polyfill');

// Webpack config for development
var fs = require('fs');
var path = require('path');
var webpack = require('webpack');
var assetsPath = path.resolve(__dirname, '../static/dist');
var host = (process.env.HOST || 'localhost');
var port = (+process.env.PORT + 1) || 3001;

// https://github.com/halt-hammerzeit/webpack-isomorphic-tools
var WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin');
var webpackIsomorphicToolsPlugin = new WebpackIsomorphicToolsPlugin(require('./webpack-isomorphic-tools'));

module.exports = {
  devtool: 'inline-source-map',
  context: path.resolve(__dirname, '..'),
  entry: {
    'main': [
      'react-hot-loader/patch',
      './src/client.js'
    ]
  },
  output: {
    path: assetsPath,
    filename: '[name]-[hash].js',
    chunkFilename: '[name]-[chunkhash].js',
    publicPath: 'http://' + host + ':' + port + '/dist/'
  },
  module: {
    loaders: [
      { test: /\.jsx?$/, exclude: /node_modules/, loaders: ['babel-loader', 'eslint-loader']},
      { test: /\.json$/, loader: 'json-loader' },
      { test: /\.less$/, loader: 'style-loader!css?modules&importLoaders=2&sourceMap&localIdentName=[local]___[hash:base64:5]!autoprefixer?browsers=last 2 version!less?outputStyle=expanded&sourceMap' },
      { test: /\.scss$/, loader: 'style-loader!css?modules&importLoaders=2&sourceMap&localIdentName=[local]___[hash:base64:5]!autoprefixer?browsers=last 2 version!sass?outputStyle=expanded&sourceMap' },
      { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&mimetype=application/font-woff" },
      { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&mimetype=application/font-woff" },
      { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&mimetype=application/octet-stream" },
      { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file-loader" },
      { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url-loader?limit=10000&mimetype=image/svg+xml" },
      { test: webpackIsomorphicToolsPlugin.regular_expression('images'), loader: 'url-loader?limit=10240' }
    ]
  },
  resolve: {
    modules: [
      'src',
      'node_modules'
    ],
    extensions: ['*', '.json', '.js', '.jsx']
  },
  plugins: [
    // hot reload
    new webpack.HotModuleReplacementPlugin(),
    new webpack.IgnorePlugin(/webpack-stats\.json$/),
    new webpack.DefinePlugin({
      __CLIENT__: true,
      __SERVER__: false,
      __DEVELOPMENT__: true,
      __DEVTOOLS__: true  // <-------- DISABLE redux-devtools HERE
    }),
    webpackIsomorphicToolsPlugin.development()
  ]
};

I'm pretty sure something is wrong in my setup, but I can't find what.

Body:
I think you're missing a few things here:

In your dev.config.js, you would also need webpack-hot-middleware/client in your main entry.

In your client.js:

import ReactDOM from 'react-dom';
import React from 'react';
import { AppContainer } from 'react-hot-loader'

// this import path doesn't match import path below
import App from './component/App/app';

const dest = document.getElementById('content');

const render = Component => {
  ReactDOM.render(
    <AppContainer>
      <Component />
    </AppContainer>,
    document.getElementById('root')
  )
}

render(App)

if (module.hot) {
  // Are you sure this is your correct path? This
  // doesn't match the import path above.
  module.hot.accept('./containers/App', () => {
    // import App
    const NextApp = require('./containers/App').default;
    render(NextApp);
  })
}

For more reference, you can checkout this thread


问:
How can I change the billing frequency in Firebase?
I want to change the billing frequency in my Firebase account to Annually or something else? However, there is no way to change it.

Can someone help, please?

答:
firebaser here

Firebase subscriptions are charged monthly. There are no other options available at the moment.


问:
Swift3 JSON using Alamofire
I'm new to Alamofire and Swift.

Now, I'm trying to convert JSON from the API, but I don't know how to convert it.

API like this :

```<code>[
{
  "myid": "10303210302003",
  "mySubid": "10303210302003",
  "area_pkid": "3"
},

{
  "myid": "10303210302004",
  "mySubid": "10303210302004",
  "area_pkid": "4"
},
....]
</code>```

I'm so confused about "[" and "]" , I don't know how to convert it and get myid.

Here is my code

```<code>    Alamofire.request(MyURL, method: .get).responseJSON { (response) in

       guard let totalJSON = response.result.value as? [String : Any] else { return } // My code is just return !! WHY??

    }
</code>```

答:
It's simply

```<code>guard let totalJSON = response.result.value as? [[String : Any]] else { return }
for item in totalJSON {
   print(item["myid"] as? String ?? "n/a")
}
</code>```

since the enclosing object is an array ([])

You can even cast the array to [[String:String]] if all values are String

Title: Swift3 JSON using Alamofire

Body:
I'm new to Alamofire and Swift.

Now, I'm trying to convert JSON from the API, but I don't know how to convert it.

API like this :

[
{
  "myid": "10303210302003",
  "mySubid": "10303210302003",
  "area_pkid": "3"
},

{
  "myid": "10303210302004",
  "mySubid": "10303210302004",
  "area_pkid": "4"
},
....]

I'm so confused about "[" and "]" , I don't know how to convert it and get myid.

Here is my code

    Alamofire.request(MyURL, method: .get).responseJSON { (response) in

       guard let totalJSON = response.result.value as? [String : Any] else { return } // My code is just return !! WHY??

    }

Body:
It's simply

guard let totalJSON = response.result.value as? [[String : Any]] else { return }
for item in totalJSON {
   print(item["myid"] as? String ?? "n/a")
}

since the enclosing object is an array ([])

You can even cast the array to [[String:String]] if all values are String


问:
How Do I Cancel and Restart a Timed Event in Swift?
I have a sliderValueChange function which updates a UILabel's text.  I want for it to have a time limit until it clears the label's text, but I also want this "timed clear" action to be cancelled & restarted or delayed whenever the UISlider is moved within the time limit before the "timed clear" action takes place.

So far this is what I have:

```<code>let task = DispatchWorkItem {
  consoleLabel.text = ""
}
func volumeSliderValueChange(sender: UISlider) {

  task.cancel()

  let senderValue = String(format: "%.2f", sender.value)
  consoleLabel.text = "Volume: \(senderValue)"

  DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3, execute: task)
}
</code>```

Obviously, this approach does not work, since cancel() apparently cannot be reversed.. (or at least I don't know how).  I also don't know how to start a new task at the end of this function which will be cancelled if the function is recalled..

Am I going about this the wrong way?  Is there something I am overlooking to make this work?

答:
The problem is that you are cancelling the wrong thing. You don't want to cancel the task; you want to cancel the countdown which you got going when you said asyncAfter.

So use a DispatchTimer or an NSTimer (now called a Timer in Swift). Those are counters-down that can be cancelled. And then you can start counting again.

Body:
I have a sliderValueChange function which updates a UILabel's text.  I want for it to have a time limit until it clears the label's text, but I also want this "timed clear" action to be cancelled & restarted or delayed whenever the UISlider is moved within the time limit before the "timed clear" action takes place.

So far this is what I have:

let task = DispatchWorkItem {
  consoleLabel.text = ""
}
func volumeSliderValueChange(sender: UISlider) {

  task.cancel()

  let senderValue = String(format: "%.2f", sender.value)
  consoleLabel.text = "Volume: \(senderValue)"

  DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3, execute: task)
}

Obviously, this approach does not work, since cancel() apparently cannot be reversed.. (or at least I don't know how).  I also don't know how to start a new task at the end of this function which will be cancelled if the function is recalled..

Am I going about this the wrong way?  Is there something I am overlooking to make this work?


问:
How do I pass an std::string to a function that expects char*?

Possible Duplicate:

  Can I get a non-const C string back from a C++ string?

Do I need to convert it first? I saw in another post that .c_str() can be used if the function expected const char*. What about for just char*?

答: If you are certain that the char* will not be modified, you can use const_cast to remove the const.</p>


问:
Understanding HTML 5 and CSS Styling
I am used to abusing divs in my web pages. However, I am trying to become better and use html 5 tags.

Generally my HTML5 code looks like this:

```<code><header></header>
<nav></nav>
<section></section>
<footer></footer>
</code>```

then I will style the section where the majority of the page's content is.

```<code>section {
   width:960px;
   height:960px;
   background-image:url("images/bg-img");
}
</code>```

Suppose I want to add another section to this code with different styling. How would I do this to make it semantically correct and SEO friendly?

What I've been doing is

 Is that bad?

What are your thoughts guys?

答:
If you want to see what elements are available for HTML5: https://www.w3schools.com/html/html5_new_elements.asp

Here are some examples of how to target specific elements. CSS is incredibly powerful and I suggest you check out w3 schools for a quick teach.

When trying to decide when to use a Class vs an ID, consider if that element will be a one-of-a-kind element, or if there will be multiple of them. If there will be more elements like it, make it a class. If it will be the only one of its type then it is okay to give it an ID. There are arguments towards using only classes (has to do with specificity) rather than giving some elements ID's, but there is no 'Correct' method.

section.tree {
  width: 50%;
  background: red;
}

section.wall {
  width: 50%;
  background: orange;
}

section.tree .acorn {
  width: 50%;
  background: yellow;
}

section.library>p {
  background: pink;
}

.first {
  font-size: 23pt;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="tree">
  This is the tree section
</section>

<section class="wall">
  This is the wall section
</section>

<section class="tree">
  <section class="acorn">
    This is the acorn section
  </section>
</section>

<section class="library">
  <p>A paragraph</p>
  <p>Another paragraph</p>
  <p>The last paragraph</p>
</section>

<section class="tree library">
  <p class='first'>A paragraph</p>
  <p>Another paragraph</p>
  <p>The last paragraph</p>
</section></code>```

Title: Understanding HTML 5 and CSS Styling

Body:
I am used to abusing divs in my web pages. However, I am trying to become better and use html 5 tags.

Generally my HTML5 code looks like this:

then I will style the section where the majority of the page's content is.

section {
   width:960px;
   height:960px;
   background-image:url("images/bg-img");
}

Suppose I want to add another section to this code with different styling. How would I do this to make it semantically correct and SEO friendly?

What I've been doing is

 Is that bad?

What are your thoughts guys?

Body:
If you want to see what elements are available for HTML5: https://www.w3schools.com/html/html5_new_elements.asp

Here are some examples of how to target specific elements. CSS is incredibly powerful and I suggest you check out w3 schools for a quick teach.

When trying to decide when to use a Class vs an ID, consider if that element will be a one-of-a-kind element, or if there will be multiple of them. If there will be more elements like it, make it a class. If it will be the only one of its type then it is okay to give it an ID. There are arguments towards using only classes (has to do with specificity) rather than giving some elements ID's, but there is no 'Correct' method.

section.tree {
  width: 50%;
  background: red;
}

section.wall {
  width: 50%;
  background: orange;
}

section.tree .acorn {
  width: 50%;
  background: yellow;
}

section.library>p {
  background: pink;
}

.first {
  font-size: 23pt;
}

<section class="tree">
  This is the tree section
</section>

<section class="wall">
  This is the wall section
</section>

<section class="tree">
  <section class="acorn">
    This is the acorn section
  </section>
</section>

<section class="library">
  <p>A paragraph</p>
  <p>Another paragraph</p>
  <p>The last paragraph</p>
</section>

<section class="tree library">
  <p class='first'>A paragraph</p>
  <p>Another paragraph</p>
  <p>The last paragraph</p>
</section>


问:
django python optimize filter queries
I have several params:
age, height, weight and so on.

I need to make search by this params.
Right now I can do it like this:

```<code>persons.vip = Person.get_vip()
params.search.age = request.GET.get('age')
    if params.search.age:
        range = params.search.age
        persons.vip = persons.vip.filter(age__gte=range)
    else:
        do somethin

params.search.weight= request.GET.get('weight')
    if params.search.weight:
        range = params.search.weight
        persons.vip = persons.vip.filter(age__gte=range)
    else:
        do somethin
</code>```

And the same code block for other params like height and so on.

How do I optimize this code and get rid off code repetition?

答:
It depends on what your do somethin block does.

If we could assume it's empty, you can have a simple map like:

```<code>param_filters_map = {
    'weight': 'age__gte',
    'height': 'weight__gte',
    ...}
</code>```

And then iterate over it:

```<code>for request_param_name, filter_name in param_filters_map.items():
    request_param = request.GET.get(request_param_name):
    if request_param:
        persons.vip = persons.vip.filter(**{filter_name: request_param})
</code>```

If it's not empty than I would try to think if it's possible to apply the logic in those blocks before the cycle over parameters (if there's some default behavior which we should overwrite with request params).

Title: django python optimize filter queries

Body:
I have several params:
age, height, weight and so on.

I need to make search by this params.
Right now I can do it like this:

persons.vip = Person.get_vip()
params.search.age = request.GET.get('age')
    if params.search.age:
        range = params.search.age
        persons.vip = persons.vip.filter(age__gte=range)
    else:
        do somethin

params.search.weight= request.GET.get('weight')
    if params.search.weight:
        range = params.search.weight
        persons.vip = persons.vip.filter(age__gte=range)
    else:
        do somethin

And the same code block for other params like height and so on.

How do I optimize this code and get rid off code repetition?

Body:
It depends on what your do somethin block does.

If we could assume it's empty, you can have a simple map like:

param_filters_map = {
    'weight': 'age__gte',
    'height': 'weight__gte',
    ...}

And then iterate over it:

for request_param_name, filter_name in param_filters_map.items():
    request_param = request.GET.get(request_param_name):
    if request_param:
        persons.vip = persons.vip.filter(**{filter_name: request_param})

If it's not empty than I would try to think if it's possible to apply the logic in those blocks before the cycle over parameters (if there's some default behavior which we should overwrite with request params).


问:
Pushed changes in staging area
So I pushed some code to gerrit for review . Shortly after I did something along the lines of git reset --soft HEAD-1 now all the changes I pushed are showing back up in the staging area. Is there any way to undo this ?I ran the reset command by mistake dropped something on the keyboard.</p>

答:
Interesting thing that you dropped and that hit the keys in that order exactly. :-D.

If you didn't do anything else, git reset --soft HEAD@{1} should undo what you did. A --soft reset does nothing more than changing the branch pointer, leaving the index and worktree as they are. So if you just repoint the branch pointer where it belongs you are fine. You can verify with git reflog before you do the command, whehter HEAD@{1} is really what you want to reset to. Alternatively if you know the correct SHA, you can also reset to that directly.

Title: Pushed changes in staging area


问:
C Socket recv()ing weird characters
So i've stuck mainly to MAC/Linux with sockets and it all works fine so i've tried to somewhat of base my windows sockets off that maybe i am wrong for doing that and that's the whole issue, but the issue i am trying to fix right now is the console printing random characters after the actual string sent by the server.
Server.c

```<code>#include <stdio.h>
#include <winsock.h>
#include <stdlib.h>
#include "stdafx.h"
#include <conio.h>
#include <io.h>
#define bzero(b,len) (memset((b), '\0', (len)), (void) 0)
#pragma comment(lib,"ws2_32.lib") //Winsock Library

char message[4040];
int main()
{
    WSADATA wsa;
    SOCKET sock, newsock;
    int c;
    struct sockaddr_in server, client;
    char smesg[155];
    printf("\nInitialising Winsock...");
    if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
    {
        printf("Failed. Error Code : %d", WSAGetLastError());
        return 1;
    }

    printf("Initialised.\n");

    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
        printf("Could not create socket! Error: %d", WSAGetLastError());
        return 1;
    }
    //textcolor(2);
    printf("Socket Created!\n");

    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons(3939);

    //bind
    if (bind(sock, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR) {
        printf("Bind failed! Error Code: %d", WSAGetLastError());
    }
    puts("Binded!");
    printf("\nNow Listening...\n");
    listen(sock, 1);
    //Accept!
    c = sizeof(struct sockaddr_in);
    newsock = accept(sock, (struct sockaddr *)&client, &c);
    if (newsock == INVALID_SOCKET) {
        printf("Couldn't Accept connection!");
    }
    printf("Accepted Connection!\n");
        //char *client_ip = inet_ntoa(client.sin_addr);
        //int client_port = ntohs(client.sin_port);
        while (1) {
            printf("Command: ");
            fgets(smesg, 4040, stdin);
            send(newsock, smesg, strlen(smesg), 0);
            bzero(smesg, sizeof(smesg));
            //memset(0, smesg, 4040);
        }
    return 0;
}
</code>```

Client.c

```<code>#include <stdio.h>
#include <winsock.h>
#include <stdlib.h>
#include "stdafx.h"
#include <conio.h>
#define bzero(b,len) (memset((b), '\0', (len)), (void) 0)
#pragma comment(lib,"ws2_32.lib") //Winsock Library

int main(int argc, char *argv[])
{
    int reader;
    WSADATA wsa;
    SOCKET sock;
    struct sockaddr_in server;
    char message[2000];
    printf("\nInitialising Winsock...");
    if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
    {
        printf("Failed. Error Code : %d", WSAGetLastError());
        return 1;
    }

    printf("Initialised.\n");

    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
        printf("Could not create socket! Error: %d", WSAGetLastError());
        return 1;
    }
    //textcolor(2);
    printf("Socket Created!\n");

    server.sin_addr.s_addr = inet_addr("127.0.0.1");
    server.sin_family = AF_INET;
    server.sin_port = htons(3939);

    //Connect
    if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0) {
        puts("Connect Error");
        return 1;
    }
    puts("Connected\n");
    while (1) {
        //memset(0, message, 4040);
        reader = recv(sock, message, 2000, 0);
        fprintf(stdout, "%s", message);
        bzero(message, 2000);
    }
    return 0;
}
</code>```

I type "Hello" into the server console and the client console recv()s/Prints
Due to the fact i can't C&P from console ill just have a picture of it instead
Console Output

Update to the question the null terminator as posted by many what i did to fix it was switch

```<code>        printf("Command: ");
        fgets(smesg, 155, stdin);
</code>```

In server.c to

```<code>        bzero(smesg, sizeof(smesg));
        printf("Command: ");
        fgets(smesg, 155, stdin);
        strcat(smesg, "\0");
</code>```

答:
It is really hard to tell exactly why you are experiencing this exact erratic behavior, because you are misusing several things at the same time, so really weird things can be happening as a result.

First of all, sockets are streams, they are not a message-passing mechanism.  This means that the sockets have no notion of a "message" that you are trying to send and receive. The socket at the receiving end has no clue whatsoever that you wrote 10 bytes at the sending end.  So, if you want to use sockets to send messages, then you have to implement a messaging protocol on top of the stream.

The simplest version of a messaging protocol on top of a stream protocol is to prefix each message with the length of the message.  So: on the sending end, first you write the length of the message to the socket, and then you write the message itself.  On the reading end, first you read the length, then the message.  The length is a fixed number of bytes, (usually 4,) so you always know exactly how many bytes to read/write.

Then, since sockets are streams, you have to pay attention to exactly how many bytes are read from the socket each time.  Just because you asked for 10 bytes it does not mean that you are going to receive 10 bytes.  If you ask for 10 bytes and you receive less than 10 bytes, then you have to repeat the call, to read more bytes.  The recv() function does not return any "reader". It returns the number of bytes that it successfully read. And it is not to be stored in a variable which is never examined afterwards.  It is to be taken into account so that you know whether you have received the entire message that you are expecting.

Also, do not forget the asciiz null-char terminators.  When you send a string, it is okay to consider the length of the message to be the strlen() of the string.  But when you receive that string, it will not be null-char terminated, so you cannot proceed to feed it to printf() without first appending a \0 to it.  If you omit the null-char terminator, then printf() will print your string followed by whatever garbage happen to already be in your receiving buffer.

Title: C Socket recv()ing weird characters

Body:
So i've stuck mainly to MAC/Linux with sockets and it all works fine so i've tried to somewhat of base my windows sockets off that maybe i am wrong for doing that and that's the whole issue, but the issue i am trying to fix right now is the console printing random characters after the actual string sent by the server.
Server.c

#include <stdio.h>
#include <winsock.h>
#include <stdlib.h>
#include "stdafx.h"
#include <conio.h>
#include <io.h>
#define bzero(b,len) (memset((b), '\0', (len)), (void) 0)
#pragma comment(lib,"ws2_32.lib") //Winsock Library

char message[4040];
int main()
{
    WSADATA wsa;
    SOCKET sock, newsock;
    int c;
    struct sockaddr_in server, client;
    char smesg[155];
    printf("\nInitialising Winsock...");
    if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
    {
        printf("Failed. Error Code : %d", WSAGetLastError());
        return 1;
    }

    printf("Initialised.\n");

    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
        printf("Could not create socket! Error: %d", WSAGetLastError());
        return 1;
    }
    //textcolor(2);
    printf("Socket Created!\n");

    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons(3939);

    //bind
    if (bind(sock, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR) {
        printf("Bind failed! Error Code: %d", WSAGetLastError());
    }
    puts("Binded!");
    printf("\nNow Listening...\n");
    listen(sock, 1);
    //Accept!
    c = sizeof(struct sockaddr_in);
    newsock = accept(sock, (struct sockaddr *)&client, &c);
    if (newsock == INVALID_SOCKET) {
        printf("Couldn't Accept connection!");
    }
    printf("Accepted Connection!\n");
        //char *client_ip = inet_ntoa(client.sin_addr);
        //int client_port = ntohs(client.sin_port);
        while (1) {
            printf("Command: ");
            fgets(smesg, 4040, stdin);
            send(newsock, smesg, strlen(smesg), 0);
            bzero(smesg, sizeof(smesg));
            //memset(0, smesg, 4040);
        }
    return 0;
}

Client.c

#include <stdio.h>
#include <winsock.h>
#include <stdlib.h>
#include "stdafx.h"
#include <conio.h>
#define bzero(b,len) (memset((b), '\0', (len)), (void) 0)
#pragma comment(lib,"ws2_32.lib") //Winsock Library

int main(int argc, char *argv[])
{
    int reader;
    WSADATA wsa;
    SOCKET sock;
    struct sockaddr_in server;
    char message[2000];
    printf("\nInitialising Winsock...");
    if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
    {
        printf("Failed. Error Code : %d", WSAGetLastError());
        return 1;
    }

    printf("Initialised.\n");

    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
        printf("Could not create socket! Error: %d", WSAGetLastError());
        return 1;
    }
    //textcolor(2);
    printf("Socket Created!\n");

    server.sin_addr.s_addr = inet_addr("127.0.0.1");
    server.sin_family = AF_INET;
    server.sin_port = htons(3939);

    //Connect
    if (connect(sock, (struct sockaddr *)&server, sizeof(server)) < 0) {
        puts("Connect Error");
        return 1;
    }
    puts("Connected\n");
    while (1) {
        //memset(0, message, 4040);
        reader = recv(sock, message, 2000, 0);
        fprintf(stdout, "%s", message);
        bzero(message, 2000);
    }
    return 0;
}

I type "Hello" into the server console and the client console recv()s/Prints
Due to the fact i can't C&P from console ill just have a picture of it instead
Console Output

Update to the question the null terminator as posted by many what i did to fix it was switch

        printf("Command: ");
        fgets(smesg, 155, stdin);

In server.c to

        bzero(smesg, sizeof(smesg));
        printf("Command: ");
        fgets(smesg, 155, stdin);
        strcat(smesg, "\0");


问:
Add a spinning wheel while application is searching database
I have an application that searches in a database for some information.

Since the database is quite big, it sometimes takes a lot of time before the application returns the results to the interface.

I want to add some sort of spinning wheel to inform the user that the application is still searching the database and did not freeze. Once the results are returned, the wheel should disappear.

Any idea how to do this or is there a good tutorial explaining how to do this?

答:
You could use the Environments Default wait cursor, which for Vista/7 is a circle with the outside spinning, or the XP tumbling hourglass.

You could launch your DB access on a BackgroundWorker and show an animated control such as a Marquee progress bar, or you could show a custom animation to show Busy status.


问:
Is there a way to make large HTML snippets in my post more manageable?
In a post, I have an html table that is hundreds of lines long!

In "text" view this is very unwieldy (but OK in "visual" view for the post).

Can I move all of the code somewhere else and replace it in the post with a [shortcode] or something?

答:
Yes, using a Custom Post Type for your code is a good idea. You can then register a shortcode to embed the code in a different post. This offers a bunch of benefits, you can maintain one snippet of code, and display that snippet in multiple places. If you want to code your own solution there are plenty of resources for doing so:

Registering Custom Post Types

Creating Shortcodes

Of course there are already plugins that do this for you. I really like this one:

Code Snippets CPT

It registers a CPT called "Code Snippets". You just create a new Code Snippet, put your code in the content of that Code Snippet. And  has styling options and syntax highlighting for tons of different kind of code (including HTML). Above the post editor it will give you a shortcode like the one below that you can use to embed the code anywhere else on your site:

```<code>[snippet slug=my-example-html-snippet lang=html]
</code>```

Here's an example of a post that has multiple snippets embedded in it.

Body:
Yes, using a Custom Post Type for your code is a good idea. You can then register a shortcode to embed the code in a different post. This offers a bunch of benefits, you can maintain one snippet of code, and display that snippet in multiple places. If you want to code your own solution there are plenty of resources for doing so:

Registering Custom Post Types

Creating Shortcodes

Of course there are already plugins that do this for you. I really like this one:

Code Snippets CPT

It registers a CPT called "Code Snippets". You just create a new Code Snippet, put your code in the content of that Code Snippet. And  has styling options and syntax highlighting for tons of different kind of code (including HTML). Above the post editor it will give you a shortcode like the one below that you can use to embed the code anywhere else on your site:

[snippet slug=my-example-html-snippet lang=html]

Here's an example of a post that has multiple snippets embedded in it.


问:
find all possible combinations of a set in java
okay so we basically have this question to answer, but I am very confused and don't know how to use recursion to get all possible combinations.. Please someone save me!

Write a public static method threadings, which takes an int n (representing the number of beads on each necklace) and a Set of Strings (representing the available bead colours; your code must not alter this Set),and returns a Set of ArrayLists of Strings, representing all the orders in which n beads of the given colours can be threaded. If n < 1, return a Set containing just one, empty, ArrayList.

Examples of correct behaviour:

• threadings(0, {red,green}) = {[]}

• threadings(1, {red,green}) = {[red],[green]}

• threadings(2, {red,green})
= {[red,red],[red,green],[green,red],[green,green]}

• threadings(3, {red}) = {[red,red,red]}

Hint: you will probably want threadings to call itself recursively, although
full marks are available for any correct method.

This is what I have written until now:

```<code> public static HashSet<ArrayList<String>> threadings (int n, Set<String> colours){
    HashSet<ArrayList<String>> result= new HashSet<ArrayList<String>>();
    ArrayList<String> inresult= new ArrayList<String>();
    String[] col= new String[colours.size()];
    if (n==0){
        result.add(inresult);
        return result;
    }else{

    }
}
</code>```

答:
Try this:</p>

```<code>public static HashSet<ArrayList<String>> threadings (int n, Set<String> colours) {
    List<String> colorsList = new ArrayList<>(colours);
    ArrayList<String> resultList = new ArrayList<>();
    HashSet<ArrayList<String>> result = new HashSet<ArrayList<String>>();
    int carry;
    int[] indices = new int[n];
    do
    {
        for(int index : indices) {
            resultList.add(colorsList.get(index));
        }
        result.add(resultList);
        resultList = new ArrayList<>();

        carry = 1;
        for(int i = indices.length - 1; i >= 0; i--)
        {
            if(carry == 0)
                break;

            indices[i] += carry;
            carry = 0;

            if(indices[i] == colorsList.size())
            {
                carry = 1;
                indices[i] = 0;
            }
        }
    }
    while(carry != 1);

    return result;
}
</code>```

Body:
okay so we basically have this question to answer, but I am very confused and don't know how to use recursion to get all possible combinations.. Please someone save me!

Write a public static method threadings, which takes an int n (representing the number of beads on each necklace) and a Set of Strings (representing the available bead colours; your code must not alter this Set),and returns a Set of ArrayLists of Strings, representing all the orders in which n beads of the given colours can be threaded. If n < 1, return a Set containing just one, empty, ArrayList.

Examples of correct behaviour:

• threadings(0, {red,green}) = {[]}

• threadings(1, {red,green}) = {[red],[green]}

• threadings(2, {red,green})
= {[red,red],[red,green],[green,red],[green,green]}

• threadings(3, {red}) = {[red,red,red]}

Hint: you will probably want threadings to call itself recursively, although
full marks are available for any correct method.

This is what I have written until now:

 public static HashSet<ArrayList<String>> threadings (int n, Set<String> colours){
    HashSet<ArrayList<String>> result= new HashSet<ArrayList<String>>();
    ArrayList<String> inresult= new ArrayList<String>();
    String[] col= new String[colours.size()];
    if (n==0){
        result.add(inresult);
        return result;
    }else{

    }
}

Body:
Try this:

public static HashSet<ArrayList<String>> threadings (int n, Set<String> colours) {
    List<String> colorsList = new ArrayList<>(colours);
    ArrayList<String> resultList = new ArrayList<>();
    HashSet<ArrayList<String>> result = new HashSet<ArrayList<String>>();
    int carry;
    int[] indices = new int[n];
    do
    {
        for(int index : indices) {
            resultList.add(colorsList.get(index));
        }
        result.add(resultList);
        resultList = new ArrayList<>();

        carry = 1;
        for(int i = indices.length - 1; i >= 0; i--)
        {
            if(carry == 0)
                break;

            indices[i] += carry;
            carry = 0;

            if(indices[i] == colorsList.size())
            {
                carry = 1;
                indices[i] = 0;
            }
        }
    }
    while(carry != 1);

    return result;
}


问:
Python unittest ends with failure
I run the following unit test in python, the result should be correct, but the unit test goes wrong.

What is the mistake?

This is the Class I have to test

```<code>class Strategy:
    _a = 0
    _b = 0
    _result = 0

    def __init__(self, a, b):

        try:
            int(a)
            int(b)
        except ValueError:
            raise ValueError()

        self._a = a
        self._b = b
</code>```

This is my unittest

```<code>def test_invalideValue(self):
    with self.assertRaises(ValueError) as cm:
        StrategyAddition('A', 3)

    self.assertEqual(cm.exception, ValueError())
</code>```

and this the put

```<code>Failure
Traceback (most recent call last):
  File "C:\Users\Michi\workspace_python\DesignPatternPython\Strategy\TestStrategy.py", line 24, in test_invalideValue
    self.assertEqual(cm.exception, ValueError())
AssertionError: ValueError() != ValueError()
</code>```

答:
Exception objects do not implement custom equality tests, and without a __eq__ method only identity tests are going to be true:

```<code>>>> a = ValueError()
>>> a == a
True
>>> a == ValueError()
False
</code>```

You don't need to test for equality at all, as self.assertRaises would only catch a ValueError instance anyway.

If you did have a different reason to test for the exception being a ValueError, use isinstance() instead:

```<code>self.assertTrue(isinstance(cm.exception, ValueError))
</code>```

Otherwise, cm.exception is only there to test other aspects of the exception, like specific attributes.

Title: Python unittest ends with failure

Body:
I run the following unit test in python, the result should be correct, but the unit test goes wrong.

What is the mistake?

This is the Class I have to test

class Strategy:
    _a = 0
    _b = 0
    _result = 0

    def __init__(self, a, b):

        try:
            int(a)
            int(b)
        except ValueError:
            raise ValueError()

        self._a = a
        self._b = b

This is my unittest

def test_invalideValue(self):
    with self.assertRaises(ValueError) as cm:
        StrategyAddition('A', 3)

    self.assertEqual(cm.exception, ValueError())

and this the put

Failure
Traceback (most recent call last):
  File "C:\Users\Michi\workspace_python\DesignPatternPython\Strategy\TestStrategy.py", line 24, in test_invalideValue
    self.assertEqual(cm.exception, ValueError())
AssertionError: ValueError() != ValueError()

Body:
Exception objects do not implement custom equality tests, and without a __eq__ method only identity tests are going to be true:

>>> a = ValueError()
>>> a == a
True
>>> a == ValueError()
False

You don't need to test for equality at all, as self.assertRaises would only catch a ValueError instance anyway.

If you did have a different reason to test for the exception being a ValueError, use isinstance() instead:

self.assertTrue(isinstance(cm.exception, ValueError))

Otherwise, cm.exception is only there to test other aspects of the exception, like specific attributes.