问:
Haptics don't play in background when bluetooth headphones are connected to Apple Watch
I have a watchOS3 workout app that uses haptic notifications. It setup correctly to run a workout session and haptics work when running in the background.  However, if bluetooth headphones are connected to the apple watch, then you only get the haptic vibration OR the audio chime for the haptic, depending on whether the app is currently showing on the watch face or running in background.

Here's how I'm playing the haptic:

```<code>WKInterfaceDevice.current().play(.notification)
</code>```

Here are the details:

Apple Watch Nike+ Unpaired to Headphones: Haptic and chime sound activate regardless of whether the watch face is on or off.  Chime sound is loud and clear.

Apple Watch Nike+ Paired to Bluetooth Headphones:
Haptic only active if watch face is on, audio chime is off. Audio chime is on when watch face is off, haptic is off.  Chime sound is loud and clear.

I tested the app pairing the Apple Watch separately with the Platronic Backbeat Go 2 (released 7/2013) and the Bose QuietControl 30 (released 10/2016). The results were the same.

Anyone know if this is a limitation of watchOS 3, a bug, or is there something else I need to be doing?

Thanks,
Jeff

答:
There's another factor to consider, which is whether the main Watch mute switch is on or off.

I found the following to be a suitable workaround.

When you want your audio/haptic to be noticed while music is playing on Bluetooth Headphones, have this AVAudioSession category set:

AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: .duckOthers)

Then, when you're done with your audio/haptic, reset the AVAudioSession back to:

AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: .mixWithOthers)

I have this helper class to help manage the states:

```<code>import AVFoundation

enum AudioPlaybackState {
    case playback
    case playbackDuckOthers
}

class AVAudio {
    private init() {}   // strictly a helper class

    static func setAudioState(_ state: AudioPlaybackState) {
        DispatchQueue.main.async {
            do {
                deactivateAudioSession()
                switch state {
                case .playback:
                    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: .mixWithOthers)
                case .playbackDuckOthers:
                    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: .duckOthers)
                }
                activateAudioSession()
            } catch {}
        }
    }

    static func deactivateAudioSession() {
        activateAudioSession(false)
    }

    private static func activateAudioSession(_ value: Bool=true) {
        do {
            try AVAudioSession.sharedInstance().setActive(value)
        } catch {}
    }
}
</code>```

Then, I can switch quickly by: AVAudio.setAudioState(.playbackDuckOthers)

Body:
I have a watchOS3 workout app that uses haptic notifications. It setup correctly to run a workout session and haptics work when running in the background.  However, if bluetooth headphones are connected to the apple watch, then you only get the haptic vibration OR the audio chime for the haptic, depending on whether the app is currently showing on the watch face or running in background.

Here's how I'm playing the haptic:

WKInterfaceDevice.current().play(.notification)

Here are the details:

Apple Watch Nike+ Unpaired to Headphones: Haptic and chime sound activate regardless of whether the watch face is on or off.  Chime sound is loud and clear.

Apple Watch Nike+ Paired to Bluetooth Headphones:
Haptic only active if watch face is on, audio chime is off. Audio chime is on when watch face is off, haptic is off.  Chime sound is loud and clear.

I tested the app pairing the Apple Watch separately with the Platronic Backbeat Go 2 (released 7/2013) and the Bose QuietControl 30 (released 10/2016). The results were the same.

Anyone know if this is a limitation of watchOS 3, a bug, or is there something else I need to be doing?

Thanks,
Jeff

Body:
There's another factor to consider, which is whether the main Watch mute switch is on or off.

I found the following to be a suitable workaround.

When you want your audio/haptic to be noticed while music is playing on Bluetooth Headphones, have this AVAudioSession category set:

AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: .duckOthers)

Then, when you're done with your audio/haptic, reset the AVAudioSession back to:

AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: .mixWithOthers)

I have this helper class to help manage the states:

import AVFoundation

enum AudioPlaybackState {
    case playback
    case playbackDuckOthers
}

class AVAudio {
    private init() {}   // strictly a helper class

    static func setAudioState(_ state: AudioPlaybackState) {
        DispatchQueue.main.async {
            do {
                deactivateAudioSession()
                switch state {
                case .playback:
                    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: .mixWithOthers)
                case .playbackDuckOthers:
                    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: .duckOthers)
                }
                activateAudioSession()
            } catch {}
        }
    }

    static func deactivateAudioSession() {
        activateAudioSession(false)
    }

    private static func activateAudioSession(_ value: Bool=true) {
        do {
            try AVAudioSession.sharedInstance().setActive(value)
        } catch {}
    }
}

Then, I can switch quickly by: AVAudio.setAudioState(.playbackDuckOthers)


来源: stackexchange

问:
How to verify response of any Http Request is valid JSON or not?
Suppose i have a Http request in json/xml when i post this request then we get some JSON response, then First i need to verify  this response is valid json or not in java.how to do that in one go?</p>

答:
You can try to Deserialize, if it passes the Deserialize so it's a valid Json, if your Json is not valid it will return a Exception for you, try something like this:</p>

```<code>  //I'm using proxy with this request
  RESTResponse response = await WebServiceProxy.GetInstance().Request(connection);

           //Check if the response is a OK
            if (response.statusCode == System.Net.HttpStatusCode.OK)
            {

                try
                {
                    var obj = JsonConvert.DeserializeObject(response.content);

                 } catch(Exception ex) {  }
            }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can try to Deserialize, if it passes the Deserialize so it's a valid Json, if your Json is not valid it will return a Exception for you, try something like this:

  //I'm using proxy with this request
  RESTResponse response = await WebServiceProxy.GetInstance().Request(connection);

           //Check if the response is a OK
            if (response.statusCode == System.Net.HttpStatusCode.OK)
            {

                try
                {
                    var obj = JsonConvert.DeserializeObject(response.content);

                 } catch(Exception ex) {  }
            }


问:
Pass Alea GPU kernel a function
Is this possible in F# with Alea GPU?

Declare a function:

```<code>let my_function = fun a b -> a + b
</code>```

Pass the kernel that function, and use it within the kernel:

```<code>let result = my_function 5 9
</code>```

I understand that an alternative is to simply statically declare the function like:

```<code>[<ReflectedDefinition>]
let my_function a b =
    a + b
</code>```

But I want to be able to change my_function based on the parameters of the program.

For example:

```<code>[<ReflectedDefinition>]
let kernel (a:int) (adder:int->int) =
    let result <- adder a

let transformKernel = <@ kernel @> |> Compiler.makeKernel

let add_num b =
    fun (a:int) ->
        a + b

let run num1 num2 =
    let adder = add_num num2
    let gpu = Gpu.Default
    let num1Gpu = gpu.Allocate(num1)
    let adderGpu = gpu.Allocate(adder)
    let lp = LaunchParam(1, 1)
    gpu.Launch transformKernel lp num1Gpu adderGpu
    // return result

let my_result = run 3 7
// my_result should be 10
</code>```

答: I found a solution to this in the Alea GPU sample gallery. The simplest example I could see of this is the F# Generic Transform sample. It uses code quotations to compile kernels based on any given function of some specified type (e.g. int -> int -> int)</p>

Title: Pass Alea GPU kernel a function

Body:
Is this possible in F# with Alea GPU?

Declare a function:

let my_function = fun a b -> a + b

Pass the kernel that function, and use it within the kernel:

let result = my_function 5 9

I understand that an alternative is to simply statically declare the function like:

[<ReflectedDefinition>]
let my_function a b =
    a + b

But I want to be able to change my_function based on the parameters of the program.

For example:

[<ReflectedDefinition>]
let kernel (a:int) (adder:int->int) =
    let result <- adder a

let transformKernel = <@ kernel @> |> Compiler.makeKernel

let add_num b =
    fun (a:int) ->
        a + b

let run num1 num2 =
    let adder = add_num num2
    let gpu = Gpu.Default
    let num1Gpu = gpu.Allocate(num1)
    let adderGpu = gpu.Allocate(adder)
    let lp = LaunchParam(1, 1)
    gpu.Launch transformKernel lp num1Gpu adderGpu
    // return result

let my_result = run 3 7
// my_result should be 10


问:
Mulitline code quotation in markdown
I am trying to quote several lines of code in the following manner

```<br>
Code line 1<br>
Code line 2<br>
Code line 3<br>
```

However that does not seem to work, as the lines appear as one line in the rendered output. Any ideas?

答:
Pre-formatted code blocks are used for writing about programming or
  markup source code. Rather than forming normal paragraphs, the lines
  of a code block are interpreted literally. Markdown wraps a code block
  in both ```</code> and <code><code></code> tags.</p>

  <p>To produce a code block in Markdown, simply indent every line of the
  block by at least 4 spaces or 1 tab.</p>
</blockquote>

<p>— <a href="https://daringfireball.net/projects/markdown/syntax#precode" rel="nofollow noreferrer">https://daringfireball.net/projects/markdown/syntax#precode</a></p>

```This is a Markdown code block:

    Code line 1
    Code line 2
    Code line 3
```

Title: Mulitline code quotation in markdown

Body:
Pre-formatted code blocks are used for writing about programming or
  markup source code. Rather than forming normal paragraphs, the lines
  of a code block are interpreted literally. Markdown wraps a code block
  in both <pre> and <code> tags.

To produce a code block in Markdown, simply indent every line of the
  block by at least 4 spaces or 1 tab.

— https://daringfireball.net/projects/markdown/syntax#precode

This is a Markdown code block:

    Code line 1
    Code line 2
    Code line 3


问:
Quotation marks not shown on display
In my string xml file I have a line like this:

```<code><string name="infoHeader">random "text" here</string>
</code>```

But it is only displayed as

random text here

on the phone's display, that is, without the quotation marks.

I read about it via Google, and tried some HTML styling:

```<code><string name="infoHeader">random "text" here</string>
</code>```

And then used:

```<code>String hej = res.getString(R.string.infoHeader);
Spanned marked_up = Html.fromHtml(hej);
((TextView)findViewById(R.id.infoHeader)).setText(marked_up, BufferType.SPANNABLE);
</code>```

But it still doesn't work. I tried some other HTML, like text, and that works just fine. What's wrong?

答:
Try this:</p>

```<code><string name="infoHeader">random \"text\" here</string>
</code>```

ContentLicense: CC BY-SA 2.5

Title: Quotation marks not shown on display

Body:
In my string xml file I have a line like this:

<string name="infoHeader">random "text" here</string>

But it is only displayed as

random text here

on the phone's display, that is, without the quotation marks.

I read about it via Google, and tried some HTML styling:

<string name="infoHeader">random "text" here</string>

And then used:

String hej = res.getString(R.string.infoHeader);
Spanned marked_up = Html.fromHtml(hej);
((TextView)findViewById(R.id.infoHeader)).setText(marked_up, BufferType.SPANNABLE);

But it still doesn't work. I tried some other HTML, like text, and that works just fine. What's wrong?

Body:
Try this:

<string name="infoHeader">random \"text\" here</string>


问:
Can I define a common interface for two classes with same property name?
Let's say I have following class hierarchy:

```<code>class A { }
class B : A { }
class C : A { }
</code>```

And I have two container classes:

```<code>class BContainer { public B[] value { get; set; } }
class CContainer { public C[] value { get; set; } }
</code>```

I need to define a method that can accept either of the two class instances and can access the value property without resorting to reflection. Is there a way I can define an interface (say IContainer) that both of the classes can implement? If so, what would be the type of the value property in the interface?

Example usage:

```<code>void ProcessValue(IEnumerable<A> as) { ... }

void ExtractValue(IContainer container)
{
    ProcessValue(container.value);
}
</code>```

答:
You could define the interface as:

```<code>interface IContainer<T>
    where T : A
{
    T[] Value { get; set; }
}
</code>```

Then you classes would be:

```<code>class BContainer : IContainer<B> { public B[] Value { get; set; } }
class CContainer : IContainer<C> { public C[] Value { get; set; } }
</code>```

And then the processing method should be generic too:

```<code>void ExtractValue<T>(IContainer<T> container)
    where T : A
{
    ProcessValue(container.Value);
}
</code>```

Body:
Let's say I have following class hierarchy:

class A { }
class B : A { }
class C : A { }

And I have two container classes:

class BContainer { public B[] value { get; set; } }
class CContainer { public C[] value { get; set; } }

I need to define a method that can accept either of the two class instances and can access the value property without resorting to reflection. Is there a way I can define an interface (say IContainer) that both of the classes can implement? If so, what would be the type of the value property in the interface?

Example usage:

void ProcessValue(IEnumerable as) { ... }

void ExtractValue(IContainer container)
{
    ProcessValue(container.value);
}

Body:
You could define the interface as:

interface IContainer<T>
    where T : A
{
    T[] Value { get; set; }
}

Then you classes would be:

class BContainer : IContainer<B> { public B[] Value { get; set; } }
class CContainer : IContainer<C> { public C[] Value { get; set; } }

And then the processing method should be generic too:

void ExtractValue<T>(IContainer<T> container)
    where T : A
{
    ProcessValue(container.Value);
}


问:
Limiting a transitive dependency to runtime scope in Maven
I've got 2 projects using Maven. The first one is a library containing utility classes and methods. The second project is an actual application that has the library as a dependency. My library uses internally a third-party library.

So these are the dependencies:

My library: depends on the third-party library

My application: depends on my library

However, I don't want the third-party library classes to be available at compile time in my application. This is because the application is supported by a large team and I want to prevent people from accidentally using methods from the third-party library in the application given that some class names and some method names are similar between the two. Of course the third-par ty library will have to be available in my application at runtime.

If the scope for all my dependencies was compile, it wouldn't achieve my goal. Is there a way to achieve this in Maven 3?

答:
You can analyze dependencies with: mvn dependency:analyze or have the dependencies analyzed as part of the verify lifecycle phase:
https://maven.apache.org/plugins/maven-dependency-plugin/examples/failing-the-build-on-dependency-analysis-warnings.html


问:
Angular2 + Jasmine Event Object
I have this simple method which needs to be tested:

```<code>  public onLayerContainerClick(event: Event): void {
    event.stopPropagation();
    event.preventDefault();
    if (event.srcElement.classList.contains('dpm-info__layerContainer')) {
     this.closeInfoLayer(event);
    }
  }
</code>```

My objective is actually to increase code coverage for the component. If I test is like this:

```<code>  it( 'should close on info container click', () => {
    spyOn( component, 'onLayerContainerClick' );
    const el: DebugElement = fixture.debugElement.query( By.css( '.dpm-info__layerContainer' ) );
    el.triggerEventHandler( 'click', null );
    expect( component.onLayerContainerClick ).toHaveBeenCalled();
  } );
</code>```

the test is OK, but instanbul says "function not covered". So I guess, I need to call the function explicitly? To do that, I need to have a full event object, including (at least) srcTarget property. How do I define such an event within the unit test?

答:
Thanks to estus and DrNio I've come up with this test, which makes istanbul code coverage happy and doesn't have any type problems:</p>

```<code>  it( 'should close on info container click', () => {
    spyOn( component, 'closeInfoLayer' );
    const el: HTMLElement = fixture.debugElement.query(By.css('.dpm-info__layerContainer')).nativeElement;
    const mockEvent: Event = <Event><any>{
      srcElement: {
        classList: el.classList
      },
      stopPropagation: <any>( ( e: any ) => { /**/ }),
      preventDefault: <any>( ( e: any ) => { /**/ }),
    };

    component.onLayerContainerClick( mockEvent );
    expect( component.closeInfoLayer ).toHaveBeenCalled();
  } );
</code>```

Title: Angular2 + Jasmine Event Object

Body:
I have this simple method which needs to be tested:

  public onLayerContainerClick(event: Event): void {
    event.stopPropagation();
    event.preventDefault();
    if (event.srcElement.classList.contains('dpm-info__layerContainer')) {
     this.closeInfoLayer(event);
    }
  }

My objective is actually to increase code coverage for the component. If I test is like this:

  it( 'should close on info container click', () => {
    spyOn( component, 'onLayerContainerClick' );
    const el: DebugElement = fixture.debugElement.query( By.css( '.dpm-info__layerContainer' ) );
    el.triggerEventHandler( 'click', null );
    expect( component.onLayerContainerClick ).toHaveBeenCalled();
  } );

the test is OK, but instanbul says "function not covered". So I guess, I need to call the function explicitly? To do that, I need to have a full event object, including (at least) srcTarget property. How do I define such an event within the unit test?

Body:
Thanks to estus and DrNio I've come up with this test, which makes istanbul code coverage happy and doesn't have any type problems:

  it( 'should close on info container click', () => {
    spyOn( component, 'closeInfoLayer' );
    const el: HTMLElement = fixture.debugElement.query(By.css('.dpm-info__layerContainer')).nativeElement;
    const mockEvent: Event = <Event><any>{
      srcElement: {
        classList: el.classList
      },
      stopPropagation: <any>( ( e: any ) => { /**/ }),
      preventDefault: <any>( ( e: any ) => { /**/ }),
    };

    component.onLayerContainerClick( mockEvent );
    expect( component.closeInfoLayer ).toHaveBeenCalled();
  } );


问:
How do I "apply" to results of a parameter-less function
This works:

```<code>List(3, 1, 2).sorted apply 1
res1: Int = 2
</code>```

And this works:

```<code>var x = List(3, 1, 2).sorted
x: List[Int] = List(1, 2, 3)
x(1)
res2: Int = 2
</code>```

but this doesn't:

```<code>List(3, 1, 2).sorted (1)

error: type mismatch;
 found   : Int(1)
 required: Ordering[?]
       List(3, 1, 2).sorted (1)
                             ^
</code>```

And even parentheses don't clue the parser in to what I want:

```<code>(List(3, 1, 2).sorted)(1)

error: type mismatch;
 found   : Int(1)
 required: Ordering[?]
       (List(3, 1, 2).sorted)(1)
</code>```

It seems like a natural expression.  What am I doing wrong?

答:
The shortest you could make it--not without a small performance penalty, however--is

```<code>class Allow_\[A](a: A) { def \ = a }
implicit def allowEveryone[A](a: A) = new Allow_\[A](a)

scala> List(1,3,2).sorted\(1)
res0: Int = 2
</code>```

If you can accept another character, this might be nicer: <> looks like parens anyway, and can be read as "please fill in the implicit parameters like usual":

```<code>class Allow_<>[A](a: A) { def <> = a }
implicit def allowEveryone[A](a: A) = new Allow_<>[A](a)

scala> List(1,3,2).sorted<>(1)
res0: Int = 2
</code>```

Body:
This works:

List(3, 1, 2).sorted apply 1
res1: Int = 2

And this works:

var x = List(3, 1, 2).sorted
x: List[Int] = List(1, 2, 3)
x(1)
res2: Int = 2

but this doesn't:

List(3, 1, 2).sorted (1)

error: type mismatch;
 found   : Int(1)
 required: Ordering[?]
       List(3, 1, 2).sorted (1)
                             ^

And even parentheses don't clue the parser in to what I want:

(List(3, 1, 2).sorted)(1)

error: type mismatch;
 found   : Int(1)
 required: Ordering[?]
       (List(3, 1, 2).sorted)(1)

It seems like a natural expression.  What am I doing wrong?

Body:
The shortest you could make it--not without a small performance penalty, however--is

class Allow_\[A](a: A) { def \ = a }
implicit def allowEveryone[A](a: A) = new Allow_\[A](a)

scala> List(1,3,2).sorted\(1)
res0: Int = 2

If you can accept another character, this might be nicer: <> looks like parens anyway, and can be read as "please fill in the implicit parameters like usual":

class Allow_<>[A](a: A) { def <> = a }
implicit def allowEveryone[A](a: A) = new Allow_<>[A](a)

scala> List(1,3,2).sorted<>(1)
res0: Int = 2


问:
HTML list-style-type dash
Is there a way to create a list-style in HTML with a dash (i.e. - or – – or — —) i.e.

```<code><ul>
  <li>abc</li>
</ul>
</code>```

Outputting:

```<code>- abc
</code>```

It's occurred to me to do this with something like li:before { content: "-" };, though I don't know the cons of that option (and would be much obliged for feedback).

More generically, I wouldn't mind knowing how to use generic characters for list items.

答:
For anyone having this problem today, the solution is simply:

list-style: "- "

Title: HTML list-style-type dash

Body:
Is there a way to create a list-style in HTML with a dash (i.e. - or – – or — —) i.e.

abc

Outputting:

- abc

It's occurred to me to do this with something like li:before { content: "-" };, though I don't know the cons of that option (and would be much obliged for feedback).

More generically, I wouldn't mind knowing how to use generic characters for list items.


答:
Seems like a good case for generics:</p>

```<code>class Container<T> where T : A
{
    public T[] value { get; set; }
}
</code>```

Title: Can I define a common interface for two classes with same property name?

Body:
Seems like a good case for generics:

class Container<T> where T : A
{
    public T[] value { get; set; }
}


问:
Django rest framework: Listapiview return key:value pair dictionary than an array
I have the following serializer: i am trying to add the key : value representation. After searching on stackoverflow, based on the answer at Return list of objects as dictionary with keys as the objects id with django rest framerwork i have overwritten the to_representation method.

```<code>class IngredientListSerializer(ModelSerializer):
    class Meta:
        model = Ingredient
        fields = '__all__'

    def to_representation(self, data):
        res = super(IngredientListSerializer, self).to_representation(data)
        return {res['id']: res}
</code>```

My view is:

```<code>class IngredientListAPIView(ListAPIView):
    queryset = Ingredient.objects.all()
    serializer_class = IngredientListSerializer
</code>```

The output looks like this:

```<code>"results": [
        {
            "172": {
                "id": 172,
                "name": "rice sevai",
            }
        },
        {
            "218": {
                "id": 218,
                "name": "rocket leaves",
            }
        }
    ]
</code>```

The output i am looking for is:

```<code>"results": {
        "172": {
            "id": 172,
            "name": "rice sevai",
        },
        "218": {
            "id": 218,
            "name": "rocket leaves",
        }
    }
</code>```

答:
I think your code with a bit of modification should work, since the view calls the serializer .to_representation() once per item you can work on the result of the serializer. Though it will be probably better to use a generic view for your case

```<code>class IngredientListAPIView(ListAPIView):
    queryset = Ingredient.objects.all()
    serializer_class = IngredientListSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        data = {obj['id']: obj for obj in serializer.data}
        return Response({'results': data})
</code>```

Body:
I have the following serializer: i am trying to add the key : value representation. After searching on stackoverflow, based on the answer at Return list of objects as dictionary with keys as the objects id with django rest framerwork i have overwritten the to_representation method.

class IngredientListSerializer(ModelSerializer):
    class Meta:
        model = Ingredient
        fields = '__all__'

    def to_representation(self, data):
        res = super(IngredientListSerializer, self).to_representation(data)
        return {res['id']: res}

My view is:

class IngredientListAPIView(ListAPIView):
    queryset = Ingredient.objects.all()
    serializer_class = IngredientListSerializer

The output looks like this:

"results": [
        {
            "172": {
                "id": 172,
                "name": "rice sevai",
            }
        },
        {
            "218": {
                "id": 218,
                "name": "rocket leaves",
            }
        }
    ]

The output i am looking for is:

"results": {
        "172": {
            "id": 172,
            "name": "rice sevai",
        },
        "218": {
            "id": 218,
            "name": "rocket leaves",
        }
    }

Body:
I think your code with a bit of modification should work, since the view calls the serializer .to_representation() once per item you can work on the result of the serializer. Though it will be probably better to use a generic view for your case

class IngredientListAPIView(ListAPIView):
    queryset = Ingredient.objects.all()
    serializer_class = IngredientListSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        data = {obj['id']: obj for obj in serializer.data}
        return Response({'results': data})


问:
how to call function in div tag without using *ngIf In Angular 2
In I want to filter JSON in nested loop I have filters in child loop, but ngFor but I also want that filter at parent level also angular 2 I am using nglf To call the function it working but I want another method because it calls contentiously</p>

```<code><div *ngFor="let partyAddress of addressDataShow?.data" >
    <div class="row bg-greybg"  *ngIf="companyFilter(partyAddress) || selectedaddress === 'ALL' || isAddressAvailabale > 0">
 <div *ngFor="let partyAddressDetails of partyAddress?.company_address">
          <div *ngIf="selectedaddress === 'ALL' || partyAddressDetails.address_type.indexOf(selectedaddress) > -1">
            <p>Filter data</p>
          </div>
        </div>
<div>
</div>
</code>```

答:
or you can define your custom directive:</p>

```<code>// ./app/shared/hidden.directive.ts
import { Directive, ElementRef, Input, Renderer } from '@angular/core';

@Directive({ selector: '[myHidden]' })
export class HiddenDirective {

    constructor(public el: ElementRef, public renderer: Renderer) {}

    @Input() myHidden: boolean;

    ngOnInit(){
        // Use renderer to render the emelemt with styles
        console.log(this.myHidden)
        if(this.myHidden) {
            console.log('hide');
            this.renderer.setElementStyle(this.el.nativeElement, 'display', 'none');
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In I want to filter JSON in nested loop I have filters in child loop, but ngFor but I also want that filter at parent level also angular 2 I am using nglf To call the function it working but I want another method because it calls contentiously

 0">

 -1">

Filter data

Body:
or you can define your custom directive:

// ./app/shared/hidden.directive.ts
import { Directive, ElementRef, Input, Renderer } from '@angular/core';

@Directive({ selector: '[myHidden]' })
export class HiddenDirective {

    constructor(public el: ElementRef, public renderer: Renderer) {}

    @Input() myHidden: boolean;

    ngOnInit(){
        // Use renderer to render the emelemt with styles
        console.log(this.myHidden)
        if(this.myHidden) {
            console.log('hide');
            this.renderer.setElementStyle(this.el.nativeElement, 'display', 'none');
        }
    }
}


问:
How can i Show / Hide Div when i navigate from initial page to another and then come back to initial page?
I have multiple html pages
I have some specific content in Home page, its content should not be changed when the page is refreshed or reloaded.
But when I navigate to other pages and then come back to Home page, I would like to show / hide div or section of html in the Home page.
How this can be achieved?</p>

答:
You can use document.referrer to get the previous page URL and hide the element you want to hide using a condition.

```<code>//element to hide
var boxA = document.querySelector('.boxA');
//last page url
var lastPage = document.referrer.split("/").pop();
//checking if element exist and previous page is page B
if(boxA && lastPage === 'b.html' ){
  boxA.style.display = 'none';
}
</code>```

StackOverflow snippet doesn't support multiple html pages, please check this plunker to understand the above code better https://plnkr.co/edit/sbBIHf1RZA7YMTL4sJfd?p=preview

Body:
You can use document.referrer to get the previous page URL and hide the element you want to hide using a condition.

//element to hide
var boxA = document.querySelector('.boxA');
//last page url
var lastPage = document.referrer.split("/").pop();
//checking if element exist and previous page is page B
if(boxA && lastPage === 'b.html' ){
  boxA.style.display = 'none';
}

StackOverflow snippet doesn't support multiple html pages, please check this plunker to understand the above code better https://plnkr.co/edit/sbBIHf1RZA7YMTL4sJfd?p=preview


问:
Set GPS location in Android Studio while debugging app
(Preface: I have already seen this question, but it doesn't address setting the location while debugging the app.  Opening "Android Device Monitor" closes the ADB connection to the debugger itself.)

I am trying to debug an application that monitors for location changes.  The issue that I have is that I can't figure out how to run the debugger and set the location using adb geo fix ... at the same time.

I have tried running the command in the Android Studio "Debug" -> "Console" tab, but it doesn't seem to do anything.

How can I set the location while still remaining connected in the debugger?

答:
1- go to plugins and look for GPS emulator, and install it then start the emulator from Tools--> Android---> Android device monitor
then find you desired location long and lat (search google for any website that gives you the lang lat for your city, google: get lang lat websites) and send them to the android emulator.

2- or fastes way if android emulator is running On the Right Side of Your Android Emulator Where (Power Button ,Speaker , Camera etc Sign are given Find Three Dot Sign(...) at the last of that column. click on that then Click on location and Set the Latitude and longitude


问:
Creating a separate php file for WooCommerce hooks
I can't seem to find any documentation on this so maybe someone here can help. I have been adding all my WooCommerce hooks to my functions.php file but I would rather have all of them in a separate file to keep things tidy. Obviously I will need another php file for these but how do I link it to the functions.php file so that the code runs as it does now? Thanks </p>

答:
The PHP include/include_once and require/require_once will work fine. However,
create another file with your hooks( woo-hooks.php ) and use WP get_template_directory to require the file.

```<code>require get_template_directory() . '/woo-hooks.php';
</code>```

Body:
The PHP include/include_once and require/require_once will work fine. However,
create another file with your hooks( woo-hooks.php ) and use WP get_template_directory to require the file.

require get_template_directory() . '/woo-hooks.php';


问:
Python Checker: TypeError: list indices must be integers, not str
I am really confused as to why I keep on getting this Error,

```<code>password_strength['has_upper'] = False
TypeError: list indices must be integers, not str
</code>```

,because I have been changing the code around and I still don't understand. I am trying to make a python password checker and I've looked at all other questions and none of them have helped me.

The code is:

```<code>def Check():#menu function. Checks a password
global score
print ('Enter a password')
score = 0#sets the score to zero

while True:
    password = input('Password: ... ')
    if 7 <= len(password) < 24:
        break
    else:
        print ('The password must be between 8 and 24 characters.')

password_scores = {0:'Horrible', 5:'Weak', 10:'Medium', 15:'Strong'}#Choses the strength
password_strength = ['has_upper', 'has_lower', 'has_num']

if re.search(r'[A-Z]', password):
    password_strength['has_upper'] = True#checks if the password has a capital letter
    score=+5
else:
    password_strength['has_upper'] = False
score=-5#Taking away 5 points from the score

if re.search(r'[a-z]', password):
    password_strength['has_lower'] = True#checks if the password has a lower case letter
    score=+5
else:
    password_strength['has_lower'] = False
score= -5

if re.search(r'[0-9]', password):
    password_strength['has_num'] = True#Checking if the password has any numbers
    score=+5
else:
    password_strength['has_num'] = False
score=-5

score = len([b for b in password_strength.values() if b])#comparing the score against the strength

print ('Password is %s' % password_scores[score])#prints how strong the password is
print ("Score is: " + str(score))
</code>```

Please could you give any suggestions or ideas what may be the problem, this would be appreciated. Thank-you.

答:
You seem to be confusing lists:

```<code>['value1','value2']
</code>```

with dictionaries:

```<code>{'key1' : 'value1','key2' : 'value2'}
</code>```

A list has a numeral key (position) and a dictionary can have a string as a key. Initialize your password_strength as a dictionary, and it will work:

```<code>password_strength = {'has_upper' : False, 'has_lower' : False, 'has_num': False}
</code>```

Body:
I am really confused as to why I keep on getting this Error,

password_strength['has_upper'] = False
TypeError: list indices must be integers, not str

,because I have been changing the code around and I still don't understand. I am trying to make a python password checker and I've looked at all other questions and none of them have helped me.

The code is:

def Check():#menu function. Checks a password
global score
print ('Enter a password')
score = 0#sets the score to zero

while True:
    password = input('Password: ... ')
    if 7 <= len(password) < 24:
        break
    else:
        print ('The password must be between 8 and 24 characters.')

password_scores = {0:'Horrible', 5:'Weak', 10:'Medium', 15:'Strong'}#Choses the strength
password_strength = ['has_upper', 'has_lower', 'has_num']

if re.search(r'[A-Z]', password):
    password_strength['has_upper'] = True#checks if the password has a capital letter
    score=+5
else:
    password_strength['has_upper'] = False
score=-5#Taking away 5 points from the score

if re.search(r'[a-z]', password):
    password_strength['has_lower'] = True#checks if the password has a lower case letter
    score=+5
else:
    password_strength['has_lower'] = False
score= -5

if re.search(r'[0-9]', password):
    password_strength['has_num'] = True#Checking if the password has any numbers
    score=+5
else:
    password_strength['has_num'] = False
score=-5

score = len([b for b in password_strength.values() if b])#comparing the score against the strength

print ('Password is %s' % password_scores[score])#prints how strong the password is
print ("Score is: " + str(score))

Please could you give any suggestions or ideas what may be the problem, this would be appreciated. Thank-you.

Body:
You seem to be confusing lists:

['value1','value2']

with dictionaries:

{'key1' : 'value1','key2' : 'value2'}

A list has a numeral key (position) and a dictionary can have a string as a key. Initialize your password_strength as a dictionary, and it will work:

password_strength = {'has_upper' : False, 'has_lower' : False, 'has_num': False}


答:
Since the type of the property differs in the two classes the type should be a common type for the two properties. In this case IEnumerable should do fine. The problem is that the two properties you define cannot be the implementation for this interface, you could use explicit interface implementation do define a separate property with the same name that servers as the implementation for the interface property.

```<code>class A { }
class B : A { }
class C : A { }
interface IContainer
{
    IEnumerable<A> value { get; }
}
class BContainer : IContainer
{
    public B[] value { get; set; }

    IEnumerable<A> IContainer.value => this.value;
}
class CContainer : IContainer
{
    public C[] value { get; set; }

    IEnumerable<A> IContainer.value => this.value;
}
</code>```

This property used for explicit implementation will be hidden from the outside and from inside the class. If you access this.value you are accessing the class version of value, unless the reference is cast explicitly to IContainer (ex ((IContainer)this).value this will access the interface version of the property)

Body:
Since the type of the property differs in the two classes the type should be a common type for the two properties. In this case IEnumerable<A> should do fine. The problem is that the two properties you define cannot be the implementation for this interface, you could use explicit interface implementation do define a separate property with the same name that servers as the implementation for the interface property.

class A { }
class B : A { }
class C : A { }
interface IContainer
{
    IEnumerable<A> value { get; }
}
class BContainer : IContainer
{
    public B[] value { get; set; }

    IEnumerable<A> IContainer.value => this.value;
}
class CContainer : IContainer
{
    public C[] value { get; set; }

    IEnumerable<A> IContainer.value => this.value;
}

This property used for explicit implementation will be hidden from the outside and from inside the class. If you access this.value you are accessing the class version of value, unless the reference is cast explicitly to IContainer (ex ((IContainer)this).value this will access the interface version of the property)


问:
Does a network have more than 1 LIN master?
In a network, how many LIN masters can be there? There can be more than one LIN master? According to me, there will be only one LIN master and multiple slaves. Can anyone please let me know.</p>

答: As per the spec it is only one master and multiple slaves</p>


问:
How to compare errors in golang
Context:
I am doing unit tests and was trying to check if I got expected errors.

I didn't have the expected result so I tried something simple which is comparing to exact errors and I was surprise that the comparison returned "false"

```<code>e1 := errors.New("error")
e2 := errors.New("error")
fmt.Println(e1 == e2) // false
</code>```

Run Example: https://play.golang.org/p/cvjjiJT_5T

Can someone explain me why this returns false and how to properly check equality between errors ?

答:
You're creating two different error variables with the same error message. When you compare them with ==, you get false because they're not the same variables.

If you want to compare the error messages, try e1.Error() == e2.Error(). However, comparing error messages still isn't a good idea. You might consider creating some error constants (e.g. e1 == ErrContentNotFound) or adding some ID to your errors and compare that (e.g. e1.ID == ContentNotFoundID). Check https://dave.cheney.net/2016/04/07/constant-errors (and the related posts in that link) for more details.

Title: How to compare errors in golang

Body:
Context:
I am doing unit tests and was trying to check if I got expected errors.

I didn't have the expected result so I tried something simple which is comparing to exact errors and I was surprise that the comparison returned "false"

e1 := errors.New("error")
e2 := errors.New("error")
fmt.Println(e1 == e2) // false

Run Example: https://play.golang.org/p/cvjjiJT_5T

Can someone explain me why this returns false and how to properly check equality between errors ?


问:
Multi-touch detecting & differentiating - Cocos2d for iPhone
I would like to know how to detect and differentiate between touches in a multi-touch view.  I have read about a "hash" code, but I don't understand how to use it.  I want to know when two of my Sprites are touched at the same time, like as if pressing a chord on two keys of a piano.

[EDIT]
Here is an example of what I have for my ccTouchesBegan:

```<code>- (void) ccTouchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {

  NSSet *allTouches = [event allTouches];
  int validTouchCount = 0;
  for (UITouch* touch in allTouches) {

    BOOL touchIsValid = FALSE;

    CGPoint location = [touch locationInView: [touch view]];
    CGPoint convertedLocation = [[CCDirector sharedDirector] convertToGL:location];

    if (CGRectContainsPoint(_fourButtonsRect, convertedLocation)) {
        NSLog(@"Touch is within four buttons");
        touchIsValid = TRUE;
    }

    _playerDidAction = 0;
    NSLog(@"before the loop");
    if (touchIsValid) {

        validTouchCount++;
        NSLog(@"Within ValidTouches loop");
        CGPoint validLocation = [touch locationInView: [touch view]];
        CGPoint convertedValidLocation = [[CCDirector sharedDirector] convertToGL:validLocation];

        if (CGRectContainsPoint(_redButtonSprite.boundingBox, convertedValidLocation)) {
            _redButtonStatus = TRUE;
            [_redButtonSprite setTexture:_redButtonLit];
            if (validTouchCount == 1) {
                _playerDidAction = 1;
            }
        }
            else if (CGRectContainsPoint(_blueButtonSprite.boundingBox, convertedValidLocation)) {
                _blueButtonStatus = TRUE;
                [_blueButtonSprite setTexture:_blueButtonLit];
                if (validTouchCount == 1) {
                    _playerDidAction = 2;
                }
            }
                else if (CGRectContainsPoint(_greenButtonSprite.boundingBox, convertedValidLocation)) {
                    _greenButtonStatus = TRUE;
                    [_greenButtonSprite setTexture:_greenButtonLit];
                    if (validTouchCount == 1) {
                        _playerDidAction = 3;
                    }
                }
                    else if (CGRectContainsPoint(_yellowButtonSprite.boundingBox, convertedValidLocation)) {
                        _yellowButtonStatus = TRUE;
                        [_yellowButtonSprite setTexture:_yellowButtonLit];
                        if (validTouchCount == 1) {
                            _playerDidAction = 4;
                        }
                    }

        if (validTouchCount > 1) {

            if (_redButtonStatus && _blueButtonStatus) {
                _comboRB = TRUE;
                _playerDidAction = 5;
            }
                else if (_redButtonStatus && _greenButtonStatus) {
                    _comboRG = TRUE;
                    _playerDidAction = 6;
                }
                    else if (_redButtonStatus && _yellowButtonStatus) {
                        _comboRY = TRUE;
                        _playerDidAction = 7;
                    }
                        else if (_blueButtonStatus && _greenButtonStatus) {
                            _comboBG = TRUE;
                            _playerDidAction = 8;
                        }
                            else if (_blueButtonStatus && _yellowButtonStatus) {
                                _comboBY = TRUE;
                                _playerDidAction = 9;
                            }
                                else if (_greenButtonStatus && _yellowButtonStatus) {
                                    _comboGY = TRUE;
                                    _playerDidAction = 10;
                                }

        }
    }
  }
}
</code>```

And here is the beginning of my ccTouchesEnded:

```<code>- (void)ccTouchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {

    for (UITouch *touch in touches) {

        CGPoint location = [touch locationInView: [touch view]];
        CGPoint convertedLocation = [[CCDirector sharedDirector] convertToGL:location];
        if (CGRectContainsPoint(_redButtonSprite.boundingBox, convertedLocation)) {
            _redButtonStatus = FALSE;
            [_redButtonSprite setTexture:_redButtonNormal];
        }
        if (CGRectContainsPoint(_blueButtonSprite.boundingBox, convertedLocation)) {
            _blueButtonStatus = FALSE;
            [_blueButtonSprite setTexture:_blueButtonNormal];
        }
        if (CGRectContainsPoint(_greenButtonSprite.boundingBox, convertedLocation)) {
            _greenButtonStatus = FALSE;
            [_greenButtonSprite setTexture:_greenButtonNormal];
        }
        if (CGRectContainsPoint(_yellowButtonSprite.boundingBox, convertedLocation)) {
            _yellowButtonStatus = FALSE;
            [_yellowButtonSprite setTexture:_yellowButtonNormal];
        }

    }
}
</code>```

Could you maybe give me an example of how you would capture touches that began on a sprite and ended on a sprite? I have been struggling and can't get the hash code to work - just not understanding how the hash code can be used to reference a touch later. I guess what I'm trying to make would be called a hash tracker?

I am sure there is a much less convoluted way to do it using the hash codes and less state variables. I haven't fleshed out the ccTouchesEnded method with the other state variable effects because I was hoping to find a simpler way (I know I still need to make the ccTouchesMoved and Canceled methods too).

答:
Here is how I implemented this in case anyone else is trying to do this (I have limited it to 2-button combos but I could easily extend the logic to 3 & 4-button combos as well).  I chose to handle each touch individually using the ccTouchBegan/Ended/Moved instead of using the ccTouchesBegan/Ended/Moved because I just couldn't get it to work with the hash code.  Any alternative ideas would be welcome.

spuButton.h (a CCSprite Subclass)

```<code>#import <Foundation/Foundation.h>
#import "cocos2d.h"

typedef enum tagButtonState {
    kButtonStatePressed,
    kButtonStateNotPressed
} ButtonState;

typedef enum tagButtonStatus {
    kButtonStatusEnabled,
    kButtonStatusDisabled
} ButtonStatus;

@interface spuButton : CCSprite <CCTargetedTouchDelegate> {
@private
    ButtonState buttonState;
    CCTexture2D *buttonNormal;
    CCTexture2D *buttonLit;
    ButtonStatus buttonStatus;
}

@property(nonatomic, readonly) CGRect rect;

+ (id)spuButtonWithTexture:(CCTexture2D *)normalTexture;

- (void)setNormalTexture:(CCTexture2D *)normalTexture;
- (void)setLitTexture:(CCTexture2D *)litTexture;
- (BOOL)isPressed;
- (BOOL)isNotPressed;
- (void)makeDisabled;
- (void)makeEnabled;
- (BOOL)isEnabled;
- (BOOL)isDisabled;
- (void)makeLit;
- (void)makeNormal;
- (void)dealloc;

@end
</code>```

spuButton.m

```<code>#import "spuButton.h"
#import "cocos2d.h"

@implementation spuButton

- (CGRect)rect {
    CGSize s = [self.texture contentSize];
    return CGRectMake(-s.width / 2, -s.height / 2, s.width, s.height);
}

+ (id)spuButtonWithTexture:(CCTexture2D *)normalTexture {
    return [[[self alloc] initWithTexture:normalTexture] autorelease];
}

- (void)setNormalTexture:(CCTexture2D *)normalTexture {
    buttonNormal = normalTexture;
}
- (void)setLitTexture:(CCTexture2D *)litTexture {
    buttonLit = litTexture;
}

- (BOOL)isPressed {
    if (buttonState== kButtonStateNotPressed) return NO;
    if (buttonState== kButtonStatePressed) return YES;
    return NO;
}

- (BOOL)isNotPressed {
    if (buttonState== kButtonStateNotPressed) return YES;
    if (buttonState== kButtonStatePressed) return NO;
    return YES;
}

- (void)makeDisabled {
    buttonStatus = kButtonStatusDisabled;
    buttonState= kButtonStateNotPressed;
    [self makeNormal];
}
- (void)makeEnabled {
    buttonStatus = kButtonStatusEnabled;
    buttonState= kButtonStateNotPressed;
    [self makeNormal];
}

- (BOOL)isEnabled {
    if (buttonStatus== kButtonStatusDisabled) return NO;
    if (buttonStatus== kButtonStatusEnabled) return YES;
    return NO;
}

- (BOOL)isDisabled {
    if (buttonStatus== kButtonStatusEnabled) return NO;
    if (buttonStatus== kButtonStatusDisabled) return YES;
    return YES;
}

- (void)makeLit {
    [self setTexture:buttonLit];
}

- (void)makeNormal {
    [self setTexture:buttonNormal];
}

- (id)initWithTexture:(CCTexture2D *)aTexture {
    if ((self = [super initWithTexture:aTexture]) ) {
        buttonState = kButtonStateNotPressed;
        buttonStatus = kButtonStatusEnabled;
    }
    return self;
}

- (void)onEnter {
    if (buttonStatus == kButtonStatusDisabled) return;
    [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:NO];
    [super onEnter];
}

- (void)onExit {
    if (buttonStatus == kButtonStatusDisabled) return;
    [[CCTouchDispatcher sharedDispatcher] removeDelegate:self];
    [super onExit];
}

- (BOOL)containsTouchLocation:(UITouch *)touch {
    return CGRectContainsPoint(self.rect, [self convertTouchToNodeSpaceAR:touch]);
}

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    if (buttonStatus == kButtonStatusDisabled) return NO;
    if (buttonState== kButtonStatePressed) return NO;
    if ( ![self containsTouchLocation:touch] ) return NO;

    buttonState= kButtonStatePressed;
    [self makeLit];

    return YES;
}

- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event {
    // If it weren't for the TouchDispatcher, you would need to keep a reference
    // to the touch from touchBegan and check that the current touch is the same
    // as that one.
    // Actually, it would be even more complicated since in the Cocos dispatcher
    // you get NSSets instead of 1 UITouch, so you'd need to loop through the set
    // in each touchXXX method.

    if (buttonStatus == kButtonStatusDisabled) return;
    if ([self containsTouchLocation:touch]) return;

    buttonState= kButtonStateNotPressed;
    [self makeNormal];
}

- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
    if (buttonStatus == kButtonStatusDisabled) return;

    buttonState= kButtonStateNotPressed;
    [self makeNormal];
}

- (void)dealloc {
    [buttonNormal release];
    [buttonLit release];
    [super dealloc];
}

@end
</code>```

HelloWorldScene.m (Just my tick: method to keep my other functions from confusing the example)

```<code>-(void)tick:(ccTime)dt {
    if ([[_otherControlsArray objectAtIndex:0] wasPressed]) {
        [[_otherControlsArray objectAtIndex:0] setWasPressed:NO];
        [self removeChild:[_otherControlsArray objectAtIndex:0] cleanup:YES];
        [self addChild:[_otherControlsArray objectAtIndex:1]];
        NSLog(@"Play");

        _gameHasNotBeenPlayedYet = NO;
        Snarfle_s_PowerUPAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
        [delegate makeNotPaused];
        [self gameLogic];
    }

    if (_gameHasNotBeenPlayedYet) {
        return;
    }

    if (_buttonsPressedAndReleased > 0) {  //respond to button(s) released and reset
        NSLog(@"Buttons Pressed and Released-->%d",_buttonsPressedAndReleased);
        if ([self checkButtons:_buttonsPressedAndReleased]);
        _buttonsPressed = 0;
        _buttonsPressedAndReleased = 0;

        return;
    }
    if (_buttonsPressed <= 4) { // two buttons have not already been pressed
        for (spuButton *aButton in _fourButtonsArray) {
            if ([aButton isNotPressed]) continue; //this button is not pressed
            if (_buttonsPressed == 0) { //this button is pressed and no other buttons have been pressed
                _buttonsPressed = aButton.tag;
                continue;
            }
            //this button is pressed while another has been pressed
            //figure out which two buttons have been pressed
            if (_buttonsPressed == 1) {  //red plus another
                switch (aButton.tag) {
                    case 2:   //blue
                        _buttonsPressed = 5;
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 3:  //green
                        _buttonsPressed = 6;
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 4:  //yellow
                        _buttonsPressed = 7;
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        break;
                    default:
                        _buttonsPressed = 1;
                        break;
                }
            }
            if (_buttonsPressed == 2) {  //blue plus another
                switch (aButton.tag) {
                    case 1:   //red
                        _buttonsPressed = 5;
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 3:  //green
                        _buttonsPressed = 8;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 4:  //yellow
                        _buttonsPressed = 9;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        break;
                    default:
                        _buttonsPressed = 2;
                        break;
                }
            }
            if (_buttonsPressed == 3) {  //green plus another
                switch (aButton.tag) {
                    case 1:   //red
                        _buttonsPressed = 6;
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 2:  //blue
                        _buttonsPressed = 8;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 4:  //yellow
                        _buttonsPressed = 10;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        break;
                    default:
                        _buttonsPressed = 3;
                        break;
                }
            }
            if (_buttonsPressed == 4) {  //yellow plus another
                switch (aButton.tag) {
                    case 1:   //red
                        _buttonsPressed = 7;
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        break;
                    case 2:  //blue
                        _buttonsPressed = 9;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        break;
                    case 3:  //green
                        _buttonsPressed = 10;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        break;
                    default:
                        _buttonsPressed = 4;
                        break;
                }
            }
            if (_buttonsPressed > 4) break;  //more than one has been pressed and identified
        }
    }
    //now we know what buttons have been pressed now check to see if they have been released
    //if more than one has been pressed disable the other two
    //also if more than one has been pressed and one of them gets released disable the released one but keep it lit
    switch (_buttonsPressed) {
        case 1:  //red
            if ([[_fourButtonsArray objectAtIndex:0] isNotPressed]) _buttonsPressedAndReleased = 1;
            break;
        case 2:  //blue
            if ([[_fourButtonsArray objectAtIndex:1] isNotPressed]) _buttonsPressedAndReleased = 2;
            break;
        case 3:  //green
            if ([[_fourButtonsArray objectAtIndex:2] isNotPressed]) _buttonsPressedAndReleased = 3;
            break;
        case 4:  //yellow
            if ([[_fourButtonsArray objectAtIndex:3] isNotPressed]) _buttonsPressedAndReleased = 4;
            break;
        case 5:  //red & blue
            if (([[_fourButtonsArray objectAtIndex:0] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:1] isNotPressed])) _buttonsPressedAndReleased = 5;
            else {
                if ([[_fourButtonsArray objectAtIndex:0] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:0] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:1] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:1] makeLit];
                }
            }
            break;
        case 6:  //red & green
            if (([[_fourButtonsArray objectAtIndex:0] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:2] isNotPressed])) _buttonsPressedAndReleased = 6;
            else {
                if ([[_fourButtonsArray objectAtIndex:0] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:0] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:2] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:2] makeLit];
                }
            }
            break;
        case 7:  //red & yellow
            if (([[_fourButtonsArray objectAtIndex:0] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:3] isNotPressed])) _buttonsPressedAndReleased = 7;
            else {
                if ([[_fourButtonsArray objectAtIndex:0] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:0] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:3] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:3] makeLit];
                }
            }
            break;
        case 8:  //blue & green
            if (([[_fourButtonsArray objectAtIndex:1] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:2] isNotPressed])) _buttonsPressedAndReleased = 8;
            else {
                if ([[_fourButtonsArray objectAtIndex:1] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:1] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:2] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:2] makeLit];
                }
            }
            break;
        case 9:  //blue & yellow
            if (([[_fourButtonsArray objectAtIndex:1] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:3] isNotPressed])) _buttonsPressedAndReleased = 9;
            else {
                if ([[_fourButtonsArray objectAtIndex:1] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:1] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:3] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:3] makeLit];
                }
            }
            break;
        case 10:  //green & yellow
            if (([[_fourButtonsArray objectAtIndex:2] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:3] isNotPressed])) _buttonsPressedAndReleased = 10;
            else {
                if ([[_fourButtonsArray objectAtIndex:2] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:2] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:3] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:3] makeLit];
                }
            }
            break;
        default:
            _buttonsPressedAndReleased = 0;
            break;
    }
}
</code>```

Body:
I would like to know how to detect and differentiate between touches in a multi-touch view.  I have read about a "hash" code, but I don't understand how to use it.  I want to know when two of my Sprites are touched at the same time, like as if pressing a chord on two keys of a piano.

[EDIT]
Here is an example of what I have for my ccTouchesBegan:

- (void) ccTouchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {

  NSSet *allTouches = [event allTouches];
  int validTouchCount = 0;
  for (UITouch* touch in allTouches) {

    BOOL touchIsValid = FALSE;

    CGPoint location = [touch locationInView: [touch view]];
    CGPoint convertedLocation = [[CCDirector sharedDirector] convertToGL:location];

    if (CGRectContainsPoint(_fourButtonsRect, convertedLocation)) {
        NSLog(@"Touch is within four buttons");
        touchIsValid = TRUE;
    }

    _playerDidAction = 0;
    NSLog(@"before the loop");
    if (touchIsValid) {

        validTouchCount++;
        NSLog(@"Within ValidTouches loop");
        CGPoint validLocation = [touch locationInView: [touch view]];
        CGPoint convertedValidLocation = [[CCDirector sharedDirector] convertToGL:validLocation];

        if (CGRectContainsPoint(_redButtonSprite.boundingBox, convertedValidLocation)) {
            _redButtonStatus = TRUE;
            [_redButtonSprite setTexture:_redButtonLit];
            if (validTouchCount == 1) {
                _playerDidAction = 1;
            }
        }
            else if (CGRectContainsPoint(_blueButtonSprite.boundingBox, convertedValidLocation)) {
                _blueButtonStatus = TRUE;
                [_blueButtonSprite setTexture:_blueButtonLit];
                if (validTouchCount == 1) {
                    _playerDidAction = 2;
                }
            }
                else if (CGRectContainsPoint(_greenButtonSprite.boundingBox, convertedValidLocation)) {
                    _greenButtonStatus = TRUE;
                    [_greenButtonSprite setTexture:_greenButtonLit];
                    if (validTouchCount == 1) {
                        _playerDidAction = 3;
                    }
                }
                    else if (CGRectContainsPoint(_yellowButtonSprite.boundingBox, convertedValidLocation)) {
                        _yellowButtonStatus = TRUE;
                        [_yellowButtonSprite setTexture:_yellowButtonLit];
                        if (validTouchCount == 1) {
                            _playerDidAction = 4;
                        }
                    }

        if (validTouchCount > 1) {

            if (_redButtonStatus && _blueButtonStatus) {
                _comboRB = TRUE;
                _playerDidAction = 5;
            }
                else if (_redButtonStatus && _greenButtonStatus) {
                    _comboRG = TRUE;
                    _playerDidAction = 6;
                }
                    else if (_redButtonStatus && _yellowButtonStatus) {
                        _comboRY = TRUE;
                        _playerDidAction = 7;
                    }
                        else if (_blueButtonStatus && _greenButtonStatus) {
                            _comboBG = TRUE;
                            _playerDidAction = 8;
                        }
                            else if (_blueButtonStatus && _yellowButtonStatus) {
                                _comboBY = TRUE;
                                _playerDidAction = 9;
                            }
                                else if (_greenButtonStatus && _yellowButtonStatus) {
                                    _comboGY = TRUE;
                                    _playerDidAction = 10;
                                }

        }
    }
  }
}

And here is the beginning of my ccTouchesEnded:

- (void)ccTouchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {

    for (UITouch *touch in touches) {

        CGPoint location = [touch locationInView: [touch view]];
        CGPoint convertedLocation = [[CCDirector sharedDirector] convertToGL:location];
        if (CGRectContainsPoint(_redButtonSprite.boundingBox, convertedLocation)) {
            _redButtonStatus = FALSE;
            [_redButtonSprite setTexture:_redButtonNormal];
        }
        if (CGRectContainsPoint(_blueButtonSprite.boundingBox, convertedLocation)) {
            _blueButtonStatus = FALSE;
            [_blueButtonSprite setTexture:_blueButtonNormal];
        }
        if (CGRectContainsPoint(_greenButtonSprite.boundingBox, convertedLocation)) {
            _greenButtonStatus = FALSE;
            [_greenButtonSprite setTexture:_greenButtonNormal];
        }
        if (CGRectContainsPoint(_yellowButtonSprite.boundingBox, convertedLocation)) {
            _yellowButtonStatus = FALSE;
            [_yellowButtonSprite setTexture:_yellowButtonNormal];
        }

    }
}

Could you maybe give me an example of how you would capture touches that began on a sprite and ended on a sprite? I have been struggling and can't get the hash code to work - just not understanding how the hash code can be used to reference a touch later. I guess what I'm trying to make would be called a hash tracker?

I am sure there is a much less convoluted way to do it using the hash codes and less state variables. I haven't fleshed out the ccTouchesEnded method with the other state variable effects because I was hoping to find a simpler way (I know I still need to make the ccTouchesMoved and Canceled methods too).

Body:
Here is how I implemented this in case anyone else is trying to do this (I have limited it to 2-button combos but I could easily extend the logic to 3 & 4-button combos as well).  I chose to handle each touch individually using the ccTouchBegan/Ended/Moved instead of using the ccTouchesBegan/Ended/Moved because I just couldn't get it to work with the hash code.  Any alternative ideas would be welcome.

spuButton.h (a CCSprite Subclass)

#import <Foundation/Foundation.h>
#import "cocos2d.h"

typedef enum tagButtonState {
    kButtonStatePressed,
    kButtonStateNotPressed
} ButtonState;

typedef enum tagButtonStatus {
    kButtonStatusEnabled,
    kButtonStatusDisabled
} ButtonStatus;

@interface spuButton : CCSprite <CCTargetedTouchDelegate> {
@private
    ButtonState buttonState;
    CCTexture2D *buttonNormal;
    CCTexture2D *buttonLit;
    ButtonStatus buttonStatus;
}

@property(nonatomic, readonly) CGRect rect;

+ (id)spuButtonWithTexture:(CCTexture2D *)normalTexture;

- (void)setNormalTexture:(CCTexture2D *)normalTexture;
- (void)setLitTexture:(CCTexture2D *)litTexture;
- (BOOL)isPressed;
- (BOOL)isNotPressed;
- (void)makeDisabled;
- (void)makeEnabled;
- (BOOL)isEnabled;
- (BOOL)isDisabled;
- (void)makeLit;
- (void)makeNormal;
- (void)dealloc;

@end

spuButton.m

#import "spuButton.h"
#import "cocos2d.h"

@implementation spuButton

- (CGRect)rect {
    CGSize s = [self.texture contentSize];
    return CGRectMake(-s.width / 2, -s.height / 2, s.width, s.height);
}

+ (id)spuButtonWithTexture:(CCTexture2D *)normalTexture {
    return [[[self alloc] initWithTexture:normalTexture] autorelease];
}

- (void)setNormalTexture:(CCTexture2D *)normalTexture {
    buttonNormal = normalTexture;
}
- (void)setLitTexture:(CCTexture2D *)litTexture {
    buttonLit = litTexture;
}

- (BOOL)isPressed {
    if (buttonState== kButtonStateNotPressed) return NO;
    if (buttonState== kButtonStatePressed) return YES;
    return NO;
}

- (BOOL)isNotPressed {
    if (buttonState== kButtonStateNotPressed) return YES;
    if (buttonState== kButtonStatePressed) return NO;
    return YES;
}

- (void)makeDisabled {
    buttonStatus = kButtonStatusDisabled;
    buttonState= kButtonStateNotPressed;
    [self makeNormal];
}
- (void)makeEnabled {
    buttonStatus = kButtonStatusEnabled;
    buttonState= kButtonStateNotPressed;
    [self makeNormal];
}

- (BOOL)isEnabled {
    if (buttonStatus== kButtonStatusDisabled) return NO;
    if (buttonStatus== kButtonStatusEnabled) return YES;
    return NO;
}

- (BOOL)isDisabled {
    if (buttonStatus== kButtonStatusEnabled) return NO;
    if (buttonStatus== kButtonStatusDisabled) return YES;
    return YES;
}

- (void)makeLit {
    [self setTexture:buttonLit];
}

- (void)makeNormal {
    [self setTexture:buttonNormal];
}

- (id)initWithTexture:(CCTexture2D *)aTexture {
    if ((self = [super initWithTexture:aTexture]) ) {
        buttonState = kButtonStateNotPressed;
        buttonStatus = kButtonStatusEnabled;
    }
    return self;
}

- (void)onEnter {
    if (buttonStatus == kButtonStatusDisabled) return;
    [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:NO];
    [super onEnter];
}

- (void)onExit {
    if (buttonStatus == kButtonStatusDisabled) return;
    [[CCTouchDispatcher sharedDispatcher] removeDelegate:self];
    [super onExit];
}

- (BOOL)containsTouchLocation:(UITouch *)touch {
    return CGRectContainsPoint(self.rect, [self convertTouchToNodeSpaceAR:touch]);
}

- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    if (buttonStatus == kButtonStatusDisabled) return NO;
    if (buttonState== kButtonStatePressed) return NO;
    if ( ![self containsTouchLocation:touch] ) return NO;

    buttonState= kButtonStatePressed;
    [self makeLit];

    return YES;
}

- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event {
    // If it weren't for the TouchDispatcher, you would need to keep a reference
    // to the touch from touchBegan and check that the current touch is the same
    // as that one.
    // Actually, it would be even more complicated since in the Cocos dispatcher
    // you get NSSets instead of 1 UITouch, so you'd need to loop through the set
    // in each touchXXX method.

    if (buttonStatus == kButtonStatusDisabled) return;
    if ([self containsTouchLocation:touch]) return;

    buttonState= kButtonStateNotPressed;
    [self makeNormal];
}

- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event {
    if (buttonStatus == kButtonStatusDisabled) return;

    buttonState= kButtonStateNotPressed;
    [self makeNormal];
}

- (void)dealloc {
    [buttonNormal release];
    [buttonLit release];
    [super dealloc];
}

@end

HelloWorldScene.m (Just my tick: method to keep my other functions from confusing the example)

-(void)tick:(ccTime)dt {
    if ([[_otherControlsArray objectAtIndex:0] wasPressed]) {
        [[_otherControlsArray objectAtIndex:0] setWasPressed:NO];
        [self removeChild:[_otherControlsArray objectAtIndex:0] cleanup:YES];
        [self addChild:[_otherControlsArray objectAtIndex:1]];
        NSLog(@"Play");

        _gameHasNotBeenPlayedYet = NO;
        Snarfle_s_PowerUPAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
        [delegate makeNotPaused];
        [self gameLogic];
    }

    if (_gameHasNotBeenPlayedYet) {
        return;
    }

    if (_buttonsPressedAndReleased > 0) {  //respond to button(s) released and reset
        NSLog(@"Buttons Pressed and Released-->%d",_buttonsPressedAndReleased);
        if ([self checkButtons:_buttonsPressedAndReleased]);
        _buttonsPressed = 0;
        _buttonsPressedAndReleased = 0;

        return;
    }
    if (_buttonsPressed <= 4) { // two buttons have not already been pressed
        for (spuButton *aButton in _fourButtonsArray) {
            if ([aButton isNotPressed]) continue; //this button is not pressed
            if (_buttonsPressed == 0) { //this button is pressed and no other buttons have been pressed
                _buttonsPressed = aButton.tag;
                continue;
            }
            //this button is pressed while another has been pressed
            //figure out which two buttons have been pressed
            if (_buttonsPressed == 1) {  //red plus another
                switch (aButton.tag) {
                    case 2:   //blue
                        _buttonsPressed = 5;
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 3:  //green
                        _buttonsPressed = 6;
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 4:  //yellow
                        _buttonsPressed = 7;
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        break;
                    default:
                        _buttonsPressed = 1;
                        break;
                }
            }
            if (_buttonsPressed == 2) {  //blue plus another
                switch (aButton.tag) {
                    case 1:   //red
                        _buttonsPressed = 5;
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 3:  //green
                        _buttonsPressed = 8;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 4:  //yellow
                        _buttonsPressed = 9;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        break;
                    default:
                        _buttonsPressed = 2;
                        break;
                }
            }
            if (_buttonsPressed == 3) {  //green plus another
                switch (aButton.tag) {
                    case 1:   //red
                        _buttonsPressed = 6;
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 2:  //blue
                        _buttonsPressed = 8;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                        break;
                    case 4:  //yellow
                        _buttonsPressed = 10;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        break;
                    default:
                        _buttonsPressed = 3;
                        break;
                }
            }
            if (_buttonsPressed == 4) {  //yellow plus another
                switch (aButton.tag) {
                    case 1:   //red
                        _buttonsPressed = 7;
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        break;
                    case 2:  //blue
                        _buttonsPressed = 9;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                        break;
                    case 3:  //green
                        _buttonsPressed = 10;
                        [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                        [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                        break;
                    default:
                        _buttonsPressed = 4;
                        break;
                }
            }
            if (_buttonsPressed > 4) break;  //more than one has been pressed and identified
        }
    }
    //now we know what buttons have been pressed now check to see if they have been released
    //if more than one has been pressed disable the other two
    //also if more than one has been pressed and one of them gets released disable the released one but keep it lit
    switch (_buttonsPressed) {
        case 1:  //red
            if ([[_fourButtonsArray objectAtIndex:0] isNotPressed]) _buttonsPressedAndReleased = 1;
            break;
        case 2:  //blue
            if ([[_fourButtonsArray objectAtIndex:1] isNotPressed]) _buttonsPressedAndReleased = 2;
            break;
        case 3:  //green
            if ([[_fourButtonsArray objectAtIndex:2] isNotPressed]) _buttonsPressedAndReleased = 3;
            break;
        case 4:  //yellow
            if ([[_fourButtonsArray objectAtIndex:3] isNotPressed]) _buttonsPressedAndReleased = 4;
            break;
        case 5:  //red & blue
            if (([[_fourButtonsArray objectAtIndex:0] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:1] isNotPressed])) _buttonsPressedAndReleased = 5;
            else {
                if ([[_fourButtonsArray objectAtIndex:0] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:0] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:1] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:1] makeLit];
                }
            }
            break;
        case 6:  //red & green
            if (([[_fourButtonsArray objectAtIndex:0] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:2] isNotPressed])) _buttonsPressedAndReleased = 6;
            else {
                if ([[_fourButtonsArray objectAtIndex:0] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:0] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:2] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:2] makeLit];
                }
            }
            break;
        case 7:  //red & yellow
            if (([[_fourButtonsArray objectAtIndex:0] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:3] isNotPressed])) _buttonsPressedAndReleased = 7;
            else {
                if ([[_fourButtonsArray objectAtIndex:0] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:0] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:0] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:3] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:3] makeLit];
                }
            }
            break;
        case 8:  //blue & green
            if (([[_fourButtonsArray objectAtIndex:1] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:2] isNotPressed])) _buttonsPressedAndReleased = 8;
            else {
                if ([[_fourButtonsArray objectAtIndex:1] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:1] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:2] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:2] makeLit];
                }
            }
            break;
        case 9:  //blue & yellow
            if (([[_fourButtonsArray objectAtIndex:1] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:3] isNotPressed])) _buttonsPressedAndReleased = 9;
            else {
                if ([[_fourButtonsArray objectAtIndex:1] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:1] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:1] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:3] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:3] makeLit];
                }
            }
            break;
        case 10:  //green & yellow
            if (([[_fourButtonsArray objectAtIndex:2] isNotPressed]) && ([[_fourButtonsArray objectAtIndex:3] isNotPressed])) _buttonsPressedAndReleased = 10;
            else {
                if ([[_fourButtonsArray objectAtIndex:2] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:2] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:2] makeLit];
                }
                if ([[_fourButtonsArray objectAtIndex:3] isNotPressed]) {
                    [[_fourButtonsArray objectAtIndex:3] makeDisabled];
                    [[_fourButtonsArray objectAtIndex:3] makeLit];
                }
            }
            break;
        default:
            _buttonsPressedAndReleased = 0;
            break;
    }
}


问:
how to create test plan in jmeter
i'm a beginner in jmeter, I'm trying to make a test plan for test website (www.barablu.com), but i don't get what is server name means here? and do i need http request default for this?

thanks anyway
wait the reply

答:
Create a Test plan with the option available on top. Choose thread group. Add it.  Make your server settings.Port change is required.Also you can pass the URL else run directly without it too. you need to change it.

You can view the google page not working, that's when your J Meter is ready for usage.

Title: how to create test plan in jmeter


问:
Get first few elements of tuples from list of list of tuples
I have a structure of list of list of tuples like:-

```<code>[[(1, 1, 96),
  (1, 2, 95),
  (0, 5, 23),
  (0, 6, 22)],
 [(2, 1, 145),
  (1, 2, 144),
  (10, 3, 143),
  (2, 4, 142)]]
</code>```

I basically want to obtain 2 list of list of tuples from this. One tuple for the first 2 columns, and the other tuple for the third column.
Desired output:-

```<code>[[(1, 1),
  (1, 2),
  (0, 5),
  (0, 6)],
 [(2, 1),
  (1, 2),
  (10, 3),
  (2, 4)]]
</code>```

&&

```<code>[[(96,),
  (95,),
  (23,),
  (22,)],
 [(145,),
  (144,),
  (143,),
  (142,)]]
</code>```

How can this be done in python?

答:
Even though Amadan's answer worked fine, I wanted to write a generic function to achieve the desired result. Here is the final code:-

```<code>def fn(data, one_shot_columns, scalar_columns):
     zipped=list(zip(*data))
     one_shot_zipped=[zipped[i] for i in one_shot_columns]
     one_shot=list(zip(*one_shot_zipped))
     scalar_zipped=[zipped[i] for i in scalar_columns]
     scalar=list(zip(*scalar_zipped))
     return (one_shot,scalar)
</code>```

used like:-

```<code>hist_oneshot,hist_scalar = fn(hist,[0,1],[2])
</code>```

Body:
I have a structure of list of list of tuples like:-

[[(1, 1, 96),
  (1, 2, 95),
  (0, 5, 23),
  (0, 6, 22)],
 [(2, 1, 145),
  (1, 2, 144),
  (10, 3, 143),
  (2, 4, 142)]]

I basically want to obtain 2 list of list of tuples from this. One tuple for the first 2 columns, and the other tuple for the third column.
Desired output:-

[[(1, 1),
  (1, 2),
  (0, 5),
  (0, 6)],
 [(2, 1),
  (1, 2),
  (10, 3),
  (2, 4)]]

&&

[[(96,),
  (95,),
  (23,),
  (22,)],
 [(145,),
  (144,),
  (143,),
  (142,)]]

How can this be done in python?

Body:
Even though Amadan's answer worked fine, I wanted to write a generic function to achieve the desired result. Here is the final code:-

def fn(data, one_shot_columns, scalar_columns):
     zipped=list(zip(*data))
     one_shot_zipped=[zipped[i] for i in one_shot_columns]
     one_shot=list(zip(*one_shot_zipped))
     scalar_zipped=[zipped[i] for i in scalar_columns]
     scalar=list(zip(*scalar_zipped))
     return (one_shot,scalar)

used like:-

hist_oneshot,hist_scalar = fn(hist,[0,1],[2])


问:
Font Awesome 5 Bundle via NPM
I'm trying to bundle only required Font Awesome 5 icons via webpack, but the icons are not replaced in the DOM.

I've added all required packages from the documentation:

```<code>yarn add -D @fortawesome/fontawesome
yarn add -D @fortawesome/fontawesome-pro-solid
yarn add -D @fortawesome/fontawesome-pro-regular
yarn add -D @fortawesome/fontawesome-free-brands
</code>```

The following custom JS is included:

```<code>"use strict";

import fontawesome from '@fortawesome/fontawesome';
import faCheck from '@fortawesome/fontawesome-pro-regular/faCheck';

fontawesome.icon(faCheck);

function iconsDoneRendering () {
    console.log('Icons have rendered'); // No output in console
}

fontawesome.dom.i2svg({
    callback: iconsDoneRendering,
})
</code>```

The HTML template:

```<code><head>
    <link rel="stylesheet" href="/css/app.css?v2.1.4"> <!-- contains fa-svg-with-js.css -->
</head>
<body>
    <ul class="fa-ul">
        <li><span class="fa-li"><i class="far fa-phone"></i></span>List item 1</li>
        <li><span class="fa-li"><i class="far fa-check"></i></span>List item 2</li>
    </ul>
    <script src="/js/app.js?v2.1.4"></script>
</body>
</code>```

The svg path is inside the bundled JS file, but I can't figure out which method needs to be called.

The following JS code solves the problem (since v5.0.2):

```<code>"use strict";

import fontawesome from '@fortawesome/fontawesome';
import faCheck from '@fortawesome/fontawesome-pro-regular/faCheck';
import faPhone from '@fortawesome/fontawesome-pro-regular/faPhone';

fontawesome.library.add(faCheck,faPhone);
</code>```

答:
Try to use

```<code>fontawesome.library.add(faCheck);
</code>```

instead of

```<code>fontawesome.icon(faCheck);
</code>```

If it does not work, please update your question with your DOM template, to see how it's defined in there.

Title: Font Awesome 5 Bundle via NPM

Body:
I'm trying to bundle only required Font Awesome 5 icons via webpack, but the icons are not replaced in the DOM.

I've added all required packages from the documentation:

yarn add -D @fortawesome/fontawesome
yarn add -D @fortawesome/fontawesome-pro-solid
yarn add -D @fortawesome/fontawesome-pro-regular
yarn add -D @fortawesome/fontawesome-free-brands

The following custom JS is included:

"use strict";

import fontawesome from '@fortawesome/fontawesome';
import faCheck from '@fortawesome/fontawesome-pro-regular/faCheck';

fontawesome.icon(faCheck);

function iconsDoneRendering () {
    console.log('Icons have rendered'); // No output in console
}

fontawesome.dom.i2svg({
    callback: iconsDoneRendering,
})

The HTML template:

    <link rel="stylesheet" href="/css/app.css?v2.1.4">

List item 1

List item 2

The svg path is inside the bundled JS file, but I can't figure out which method needs to be called.

The following JS code solves the problem (since v5.0.2):

"use strict";

import fontawesome from '@fortawesome/fontawesome';
import faCheck from '@fortawesome/fontawesome-pro-regular/faCheck';
import faPhone from '@fortawesome/fontawesome-pro-regular/faPhone';

fontawesome.library.add(faCheck,faPhone);

Body:
Try to use

fontawesome.library.add(faCheck);

instead of

fontawesome.icon(faCheck);

If it does not work, please update your question with your DOM template, to see how it's defined in there.


问:
Can I define a common interface for two classes with same property name?
Let's say I have following class hierarchy:

```<code>class A { }
class B : A { }
class C : A { }
</code>```

And I have two container classes:

```<code>class BContainer { public B[] value { get; set; } }
class CContainer { public C[] value { get; set; } }
</code>```

I need to define a method that can accept either of the two class instances and can access the value property without resorting to reflection. Is there a way I can define an interface (say IContainer) that both of the classes can implement? If so, what would be the type of the value property in the interface?

Example usage:

```<code>void ProcessValue(IEnumerable<A> as) { ... }

void ExtractValue(IContainer container)
{
    ProcessValue(container.value);
}
</code>```

答:
You could do this:

```<code>public class A { }
public class B : A { }
public class C : A { }

public interface IContainer
{
    A[] value { get; }
}

class BContainer : IContainer { public B[] value { get; set; } A[] IContainer.value { get { return this.value; } } }
class CContainer : IContainer { public C[] value { get; set; } A[] IContainer.value { get { return this.value; } } }

void ProcessValue(IEnumerable<A> arg) { }

void ExtractValue(IContainer container)
{
    ProcessValue(container.value);
}
</code>```

This compiles at the very least.

Body:
Let's say I have following class hierarchy:

class A { }
class B : A { }
class C : A { }

And I have two container classes:

class BContainer { public B[] value { get; set; } }
class CContainer { public C[] value { get; set; } }

I need to define a method that can accept either of the two class instances and can access the value property without resorting to reflection. Is there a way I can define an interface (say IContainer) that both of the classes can implement? If so, what would be the type of the value property in the interface?

Example usage:

void ProcessValue(IEnumerable as) { ... }

void ExtractValue(IContainer container)
{
    ProcessValue(container.value);
}

Body:
You could do this:

public class A { }
public class B : A { }
public class C : A { }

public interface IContainer
{
    A[] value { get; }
}

class BContainer : IContainer { public B[] value { get; set; } A[] IContainer.value { get { return this.value; } } }
class CContainer : IContainer { public C[] value { get; set; } A[] IContainer.value { get { return this.value; } } }

void ProcessValue(IEnumerable<A> arg) { }

void ExtractValue(IContainer container)
{
    ProcessValue(container.value);
}

This compiles at the very least.


问:
Ignore Sundays from jQuery date range picker
I'm using the following jQuery date range picker library : http://longbill.github.io/jquery-date-range-picker/

I would like to remove / hide all Sundays from all date range pickers while keeping a normal behavior on the date range pickers.

I tried to do something with beforeShowDay option :

```<code>beforeShowDay: function(t) {
  var valid = t.getDay() !== 0; //disable sunday
  var _class = '';
  // var _tooltip = valid ? '' : 'weekends are disabled';
  return [valid, _class];
}
</code>```

but it only "disables" all Sundays whereas I want to remove / hide them:

Here's the fiddle I'm working on : https://jsfiddle.net/maximelafarie/dnbd01do/11/

EDIT:
Updated fiddle with @Swanand code: https://jsfiddle.net/maximelafarie/dnbd01do/18/

答:
You could do it with just a little CSS but it does leave a gap:

```<code>.week-name th:nth-child(7),
.month1 tbody tr td:nth-child(7) {
    display: none;
}
</code>```

Hope this helps a little.

Body:
I'm using the following jQuery date range picker library : http://longbill.github.io/jquery-date-range-picker/

I would like to remove / hide all Sundays from all date range pickers while keeping a normal behavior on the date range pickers.

I tried to do something with beforeShowDay option :

beforeShowDay: function(t) {
  var valid = t.getDay() !== 0; //disable sunday
  var _class = '';
  // var _tooltip = valid ? '' : 'weekends are disabled';
  return [valid, _class];
}

but it only "disables" all Sundays whereas I want to remove / hide them:

Here's the fiddle I'm working on : https://jsfiddle.net/maximelafarie/dnbd01do/11/

EDIT:
Updated fiddle with @Swanand code: https://jsfiddle.net/maximelafarie/dnbd01do/18/

Body:
You could do it with just a little CSS but it does leave a gap:

.week-name th:nth-child(7),
.month1 tbody tr td:nth-child(7) {
    display: none;
}

Hope this helps a little.


问:
How do I validate and create a new model for each line in a text area
Users have many websites, and Websites have many Keywords. (Keywords being nested resources of the Websites resource)

Right now, with the default scaffolding setup, it's very tedious to add many keywords at once. I'd like a text area instead of a text field that allows users to type many keywords, each on their own line, and submit them all at once. The only input on the form is for the keyword's "text" column.

How can I do this?

I can figure out things like params[:keyword][:text].split("\r\n").each do |text|, but I'm not sure how to interact it with the Rails form.

```<code><%= form_for [@website, @keyword] do |f| %>
  <% if @keyword.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@keyword.errors.count, "error") %> prohibited this keyword from being saved:</h2>

      <ul>
      <% @keyword.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :text %><br />
    <%= f.text_area :text %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
</code>```

答:
Websites could have many keywords.

I recommend you have look at: http://railscasts.com/episodes/197-nested-model-form-part-2

Body:
Users have many websites, and Websites have many Keywords. (Keywords being nested resources of the Websites resource)

Right now, with the default scaffolding setup, it's very tedious to add many keywords at once. I'd like a text area instead of a text field that allows users to type many keywords, each on their own line, and submit them all at once. The only input on the form is for the keyword's "text" column.

How can I do this?

I can figure out things like params[:keyword][:text].split("\r\n").each do |text|, but I'm not sure how to interact it with the Rails form.

<%= form_for [@website, @keyword] do |f| %>
  <% if @keyword.errors.any? %>

<%= pluralize(@keyword.errors.count, "error") %> prohibited this keyword from being saved:

      <% @keyword.errors.full_messages.each do |msg| %>

<%= msg %>

      <% end %>

  <% end %>

    <%= f.label :text %>

    <%= f.text_area :text %>

    <%= f.submit %>

<% end %>


问:
get value from key in sessionStorage javascript
Is it possible to check if a specific value exists in a key in sessionStorage?

Let's say that I have a key that is named "item" and I got digits in that key. I want to check if the digit "5" exists in item.

I have tested to write like this:

```<code>  if(sessionStorage.getItem("item") == "5");
</code>```

but It doesn't respond as i want.

Is there another way I can check if the digit 5 exists in item?

答:
Use this:</p>

```<code>sessionStorage.setItem("item", "53");
if (sessionStorage.getItem("item").indexOf("5") > -1) {
    // sessionStorage item has number "5"
}
</code>```

Body:
Is it possible to check if a specific value exists in a key in sessionStorage?

Let's say that I have a key that is named "item" and I got digits in that key. I want to check if the digit "5" exists in item.

I have tested to write like this:

  if(sessionStorage.getItem("item") == "5");

but It doesn't respond as i want.

Is there another way I can check if the digit 5 exists in item?

Body:
Use this:

sessionStorage.setItem("item", "53");
if (sessionStorage.getItem("item").indexOf("5") > -1) {
    // sessionStorage item has number "5"
}