问:
Use a bash script/grep/sed in order to replace class names with the file name itself
I currently have a directory that contains numerous .java files, all with different names. ie. name.java, name2.java, name3.java

I am trying to write a script that loops through all of the files in the directory and changes their class names (inside the file) to match the file name itself.

Currently, all of the .java files contain the class name MyCritter. I want to change all instances of MyCritter in each of the files to the name of the particular java file itself. I wrote a script to try and replace all of the MyCritter terms, however I am getting no change in output. The code is getting frozen after printing the echo line for the first name of the file:

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

dir1="/Users/path to folder"
subs=`ls $dir1`
for a in $subs;
do
  echo a
  [ -f "$a" ]
  grep -lr "MyCritter" * | xargs sed “s/MyCritter/$a/g”
done
</code>```

output to terminal: name.java --> then infinite loop/gets stuck

The above code prints the name of the first file in the directory once, but then gets stuck. When I change my second line to this: [ -f "$a" ] || continue  it runs through the whole code, but fails to update the files.

I've tried other variations of grep including:

```<code>grep -lr -e "MyCritter" * | xargs sed -i “s/MyCritter/$a/g”
grep -lr -e "MyCritter" . | xargs sed -i “s/MyCritter/$a/g”
grep -lr -e "MyCritter" . | xargs sed “s/MyCritter/$a/g”
</code>```

I was primarily using this site to guide me: http://isaacsukin.com/news/2013/06/command-line-tip-replace-word-all-files-directory

Any push in the right direction would be much appreciated!

答:
If you don't need to have a solution is script form, in a terminal, just cd to the directory containing the *.java files and use the following command:

```<code>for f in *.java; do sed -i "s/MyCritter/"${f%.*}"/g" "$f"; done
</code>```

The "${f%.*}" portion of the sed command returns the filename without the extension and uses it to replace MyCritter.

Body:
I currently have a directory that contains numerous .java files, all with different names. ie. name.java, name2.java, name3.java

I am trying to write a script that loops through all of the files in the directory and changes their class names (inside the file) to match the file name itself.

Currently, all of the .java files contain the class name MyCritter. I want to change all instances of MyCritter in each of the files to the name of the particular java file itself. I wrote a script to try and replace all of the MyCritter terms, however I am getting no change in output. The code is getting frozen after printing the echo line for the first name of the file:

#!/bin/bash

dir1="/Users/path to folder"
subs=`ls $dir1`
for a in $subs;
do
  echo a
  [ -f "$a" ]
  grep -lr "MyCritter" * | xargs sed “s/MyCritter/$a/g”
done

output to terminal: name.java --> then infinite loop/gets stuck

The above code prints the name of the first file in the directory once, but then gets stuck. When I change my second line to this: [ -f "$a" ] || continue  it runs through the whole code, but fails to update the files.

I've tried other variations of grep including:

grep -lr -e "MyCritter" * | xargs sed -i “s/MyCritter/$a/g”
grep -lr -e "MyCritter" . | xargs sed -i “s/MyCritter/$a/g”
grep -lr -e "MyCritter" . | xargs sed “s/MyCritter/$a/g”

I was primarily using this site to guide me: http://isaacsukin.com/news/2013/06/command-line-tip-replace-word-all-files-directory

Any push in the right direction would be much appreciated!

Body:
If you don't need to have a solution is script form, in a terminal, just cd to the directory containing the *.java files and use the following command:

for f in *.java; do sed -i "s/MyCritter/"${f%.*}"/g" "$f"; done

The "${f%.*}" portion of the sed command returns the filename without the extension and uses it to replace MyCritter.


来源: stackexchange

问:
SQL Server : insert data set into table with an identity column
I have a table with an auto-incrementing identity column. Typically I might insert data as follows

```<code>INSERT INTO [dbo].[table]
DEFAULT VALUES;

SET @value = SCOPE_IDENTITY();
</code>```

This way I know the identity value I've just inserted. However I need to insert a "set" of values into that table. Preferably also be able to identify the values I just inserted. I was hoping something similar to the following would be possible ...

```<code>INSERT INTO dbo.table DEFAULT VALUES
OUTPUT INSERTED.id INTO @output
SELECT SCOPE_IDENTITY()   -- obviously this isn't possible and doesn't actually make sense
FROM @records
WHERE somecolumn IS NULL
</code>```

I know I might need to set identity_insert on ... I would prefer not to if I don't have to. I am also aware that maybe I could also use some sort of recursive CTE, though I haven't used one of those in a while. Any help would be appreciated.

EDIT: to be clear the question I am asking is: how do I insert a "SET" of data into a table with an auto-incrementing identity column. And hopefully identify the values I just inserted in some way.

答:
Try this query -- </p>

```<code>CREATE TABLE StudentPassMarks (ID INT identity(1, 1))

DECLARE @OutputTable TABLE (ID INT)

    INSERT INTO StudentPassMarks
        OUTPUT inserted.ID
    INTO @OutputTable(ID)
    DEFAULT VALUES

SELECT * FROM @OutputTable

Go 20;

SELECT * FROM StudentPassMarks
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a table with an auto-incrementing identity column. Typically I might insert data as follows

INSERT INTO [dbo].[table]
DEFAULT VALUES;

SET @value = SCOPE_IDENTITY();

This way I know the identity value I've just inserted. However I need to insert a "set" of values into that table. Preferably also be able to identify the values I just inserted. I was hoping something similar to the following would be possible ...

INSERT INTO dbo.table DEFAULT VALUES
OUTPUT INSERTED.id INTO @output
SELECT SCOPE_IDENTITY()   -- obviously this isn't possible and doesn't actually make sense
FROM @records
WHERE somecolumn IS NULL

I know I might need to set identity_insert on ... I would prefer not to if I don't have to. I am also aware that maybe I could also use some sort of recursive CTE, though I haven't used one of those in a while. Any help would be appreciated.

EDIT: to be clear the question I am asking is: how do I insert a "SET" of data into a table with an auto-incrementing identity column. And hopefully identify the values I just inserted in some way.

Body:
Try this query --

CREATE TABLE StudentPassMarks (ID INT identity(1, 1))

DECLARE @OutputTable TABLE (ID INT)

    INSERT INTO StudentPassMarks
        OUTPUT inserted.ID
    INTO @OutputTable(ID)
    DEFAULT VALUES

SELECT * FROM @OutputTable

Go 20;

SELECT * FROM StudentPassMarks


问:
Instagram API hashtag and content use on public app
So I want to use hashtags along with my own data for public sites or businesses, but it seems this is against IG policy.

This use case is not supported. We do not approve the public_content permission for one-off projects such as displaying hashtag based content on your website. As alternative solution, you can show your own Instagram content, or find a company that offers this type of service (content discover, moderation, and display).

Seems I can only show my own content unless the person's IG account gives us permission with IG login.  Otherwise we can't show someone's pictures or hashtags on a public site

I did seem something about paying for the IG api? Is it possible to do this?  I couldn't find anyone to contact.

答:
I recommend that you use a third-party platform that powers this use case.
https://smashballoon.com/instagram-feed/demo/</p>


问:
How can I not escape a character sequence in a string in C#?
I am reading in a value from a resource file (.resx) in C# and in that value, I have added \r\n\r\n so that it gets displayed in the correct format. e.g. blah\r\n\r\nblah
For some reason, the string automatically adds a '\' so effectively text becomes blah\\r\\n\\r\\nblah and thus it escapes the character sequences.

答:
When you stored the string, the escape characters were stored as part of the string literal, and are no longer 'escaping' anything. One thing you could do is replace your placeholder string "\r\n" with a newline character after you read it.

For example:

```<code>private static void Main()
{
    var resourceStr = "blah\\r\\n\\r\\nblah";

    Console.WriteLine("Original resource string:");
    Console.WriteLine(resourceStr);

    Console.WriteLine("\nAfter calling replace:");
    Console.WriteLine(resourceStr.Replace("\\r\\n", Environment.NewLine));

    Console.WriteLine("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}
</code>```

Output

Body:
When you stored the string, the escape characters were stored as part of the string literal, and are no longer 'escaping' anything. One thing you could do is replace your placeholder string "\r\n" with a newline character after you read it.

For example:

private static void Main()
{
    var resourceStr = "blah\\r\\n\\r\\nblah";

    Console.WriteLine("Original resource string:");
    Console.WriteLine(resourceStr);

    Console.WriteLine("\nAfter calling replace:");
    Console.WriteLine(resourceStr.Replace("\\r\\n", Environment.NewLine));

    Console.WriteLine("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}

Output


问:
How can I translate a perl script to Java?

Possible Duplicate:

  How can I convert OO Perl to Java?

Hello.

I have a perl script and I want to translate it to Java.

Is there any translator/conversor from perl script to Java?

By the way, I'm developing an Android 2.2 application.

EDIT

I have closed the question. Stop downvoting me!!!!!! And if you downvote tell us why!!

Thanks.

答:
Just my two cents...

I would convert the Perl to Java by hand that way you are 100% in control of the Java code running in your Android application and that way you will understand what the Perl code is actually doing rather than relying on it to work when there is a bug in your Android app.

ContentLicense: CC BY-SA 2.5


问:
Using DRF serializer to validate a list of dictionaries
How do I write a serializer that validates a list of dictionaries?

Sample payload being sent is:

```<code>"payment_discount": [
    {
        "discount_rule_id": 1,
        "discount_rule_name": "10 day early payment",
        "discount_earned": "298.00"
    },
    {
        "discount_rule_id": 2,
        "discount_rule_name": "Store discount",
        "discount_earned": "5.50"
    },
]
</code>```

Taking from this SO answer and this:

```<code>class PaymentDiscountSerializer(serializers.DictField):

    discount_rule_id = serializers.IntegerField(required=False)
    discount_rule_name = serializers.CharField(max_length=50)
    discount_earned = serializers.DecimalField(max_digits=10, decimal_places=3)

class PaymentDiscountListSerializer(serializers.ListField):
    """Serialize discount object"""
    child = PaymentDiscountSerializer()

class PaymentSerializer(serializers.ModelSerializer):
    payment_discount = PaymentDiscountListSerializer()
    # Other model fields
</code>```

With this, I can get access to the payment_discount object in the payload using serializer.data but unfortunately no validations are being done against the dictionary if e.g. the payload includes discount_earned value of that is not of type Decimal

using: Django==1.10.2 & djangorestframework==3.5.1

答:
I think you can simplify your serializers...
Haven't tested it but you could use something like this:

```<code>class PaymentDiscountSerializer(serializers.Serializer):
    """Serialize discounts"""
    discount_rule_id = serializers.IntegerField(required=False)
    discount_rule_name = serializers.CharField(max_length=50)
    discount_earned = serializers.DecimalField(max_digits=10, decimal_places=3)

class PaymentSerializer(serializers.ModelSerializer):
    payment_discount = PaymentDiscountSerializer(many=True)
    # Other model fields
</code>```

It should give you a list of object like you want.

For the validation, it should work right out of the box like this.

But again, I haven't tested it. If you are having problems with your validations, you can define your own.
Example:

```<code>class PaymentDiscountSerializer(serializers.Serializer):
    """Serialize discounts"""
    discount_rule_id = serializers.IntegerField(required=False)
    discount_rule_name = serializers.CharField(max_length=50)
    discount_earned = serializers.DecimalField(max_digits=10, decimal_places=3)

    def validate_discount_rule_id(self, value):
        # Validation logic of the discount_rule_id field
        #
        return value

    def validate(self, attrs):
        # Validation logic of all the fields
        #
        return attrs
</code>```

see http://www.django-rest-framework.org/api-guide/serializers/#field-level-validation for more infos.

Body:
How do I write a serializer that validates a list of dictionaries?

Sample payload being sent is:

"payment_discount": [
    {
        "discount_rule_id": 1,
        "discount_rule_name": "10 day early payment",
        "discount_earned": "298.00"
    },
    {
        "discount_rule_id": 2,
        "discount_rule_name": "Store discount",
        "discount_earned": "5.50"
    },
]

Taking from this SO answer and this:

class PaymentDiscountSerializer(serializers.DictField):

    discount_rule_id = serializers.IntegerField(required=False)
    discount_rule_name = serializers.CharField(max_length=50)
    discount_earned = serializers.DecimalField(max_digits=10, decimal_places=3)

class PaymentDiscountListSerializer(serializers.ListField):
    """Serialize discount object"""
    child = PaymentDiscountSerializer()

class PaymentSerializer(serializers.ModelSerializer):
    payment_discount = PaymentDiscountListSerializer()
    # Other model fields

With this, I can get access to the payment_discount object in the payload using serializer.data but unfortunately no validations are being done against the dictionary if e.g. the payload includes discount_earned value of that is not of type Decimal

using: Django==1.10.2 & djangorestframework==3.5.1

Body:
I think you can simplify your serializers...
Haven't tested it but you could use something like this:

class PaymentDiscountSerializer(serializers.Serializer):
    """Serialize discounts"""
    discount_rule_id = serializers.IntegerField(required=False)
    discount_rule_name = serializers.CharField(max_length=50)
    discount_earned = serializers.DecimalField(max_digits=10, decimal_places=3)

class PaymentSerializer(serializers.ModelSerializer):
    payment_discount = PaymentDiscountSerializer(many=True)
    # Other model fields

It should give you a list of object like you want.

For the validation, it should work right out of the box like this.

But again, I haven't tested it. If you are having problems with your validations, you can define your own.
Example:

class PaymentDiscountSerializer(serializers.Serializer):
    """Serialize discounts"""
    discount_rule_id = serializers.IntegerField(required=False)
    discount_rule_name = serializers.CharField(max_length=50)
    discount_earned = serializers.DecimalField(max_digits=10, decimal_places=3)

    def validate_discount_rule_id(self, value):
        # Validation logic of the discount_rule_id field
        #
        return value

    def validate(self, attrs):
        # Validation logic of all the fields
        #
        return attrs

see http://www.django-rest-framework.org/api-guide/serializers/#field-level-validation for more infos.


问:
error during dlmalloc compilation for bare-metal (elf) program build
I'm using gnu sparc tool chain. I have sparc-ab-elf-gcc and sparc-ab-linux-gcc. ('ab' is the processor name). I want to compile a program which uses malloc and free (this program is supposed to be run on linux) on baremetal(without os). So I should compile it using sparc-ab-elf-gcc. I heard I can use dlmalloc for this case. (see stdlib-like library on bare metal environment? (memory management and hopefully pthread support) ) but I'm seeing some compile error for simple test program which just does malloc and free once each time.

```<code>// test malloc, realloc and free
#include <aldebaran.h>
#include <malloc.h>

int main()
{
int i;

ab_printf("%s\n",CKIM_XX);
char *buff = dlmalloc(100);
for(i = 0; i < 100; i++) {
    buff[i] = (char) i;
}
ab_printf("buff = %x\n'");
for(i=0; i<100; i++) {
    ab_printf("%d ", buff[i]);
}
ab_printf("\n");
dlfree(buff);
return 0;
}

ckim@stph45:~/prj2/abts/yolo-bare/darknet] make test3
sparc-ab-elf-gcc -c -I./src -I../include -I/opt/abde/sparc-ab-elf/include    -DALDEBARAN_FPGA -DABC_CT -O3 -ffast-math -fcommon -msoft-float -mcpu=v8  -Wa,-xarch=v8plusb -Wall -Wfatal-errors   ./src/malloc.c -o obj/malloc.o
./src/malloc.c:571:40: fatal error: sys/mman.h: No such file or directory
compilation terminated.
make: *** [obj/malloc.o] Error 1
</code>```

My bare-metal system doesn't have sys/mman.h (I searched it on the elf toolchain library) so tried again after defining LACKS_SYS_MMAN_H and got

```<code>ckim@stph45:~/prj2/abts/yolo-bare/darknet] make test3
sparc-ab-elf-gcc -c -I./src -I../include -I/opt/abde/sparc-ab-elf/include    -DALDEBARAN_FPGA -DABC_CT -O3 -ffast-math -fcommon -msoft-float -mcpu=v8  -Wa,-xarch=v8plusb -Wall -Wfatal-errors  -DLACKS_SYS_MMAN_H  ./src/test3.c -o obj/test3.o
sparc-ab-elf-gcc -c -I./src -I../include -I/opt/abde/sparc-ab-elf/include    -DALDEBARAN_FPGA -DABC_CT -O3 -ffast-math -fcommon -msoft-float -mcpu=v8  -Wa,-xarch=v8plusb -Wall -Wfatal-errors  -DLACKS_SYS_MMAN_H  ./src/malloc.c -o obj/malloc.o
./src/malloc.c: In function 'mmap_alloc':
./src/malloc.c:2924:5: warning: implicit declaration of function 'mmap' [-Wimplicit-function-declaration]
./src/malloc.c:2924:24: error: 'PROT_READ' undeclared (first use in this function)
compilation terminated due to -Wfatal-errors.
make: *** [obj/malloc.o] Error 1
</code>```

The dlmalloc.c is a very long program. (I divided it into malloc.h and malloc.c) Below is the function making error..

```<code>/* Malloc using mmap */
static void* mmap_alloc(mstate m, size_t nb) {
  size_t mmsize = mmap_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
  if (m->footprint_limit != 0) {
    size_t fp = m->footprint + mmsize;
    if (fp <= m->footprint || fp > m->footprint_limit)
      return 0;
  }
  if (mmsize > nb) {     /* Check for wrap around 0 */
    char* mm = (char*)(CALL_DIRECT_MMAP(mmsize));    <=== line causing error.
    if (mm != CMFAIL) {
      size_t offset = align_offset(chunk2mem(mm));
      size_t psize = mmsize - offset - MMAP_FOOT_PAD;
      mchunkptr p = (mchunkptr)(mm + offset);
      p->prev_foot = offset;
      p->head = psize;
      mark_inuse_foot(m, p, psize);
      chunk_plus_offset(p, psize)->head = FENCEPOST_HEAD;
      chunk_plus_offset(p, psize+SIZE_T_SIZE)->head = 0;

      if (m->least_addr == 0 || mm < m->least_addr)
        m->least_addr = mm;
      if ((m->footprint += mmsize) > m->max_footprint)
        m->max_footprint = m->footprint;
      assert(is_aligned(chunk2mem(p)));
      check_mmapped_chunk(m, p);
      return chunk2mem(p);
    }
  }
  return 0;
}
</code>```

can somebody give me a light?

答:
I heard I can use dlmalloc for this case

Read that answer again. Note in particular: "... you should be able to adapt ...". You haven't done the adapting part.

Body:
I'm using gnu sparc tool chain. I have sparc-ab-elf-gcc and sparc-ab-linux-gcc. ('ab' is the processor name). I want to compile a program which uses malloc and free (this program is supposed to be run on linux) on baremetal(without os). So I should compile it using sparc-ab-elf-gcc. I heard I can use dlmalloc for this case. (see stdlib-like library on bare metal environment? (memory management and hopefully pthread support) ) but I'm seeing some compile error for simple test program which just does malloc and free once each time.

// test malloc, realloc and free
#include <aldebaran.h>
#include <malloc.h>

int main()
{
int i;

ab_printf("%s\n",CKIM_XX);
char *buff = dlmalloc(100);
for(i = 0; i < 100; i++) {
    buff[i] = (char) i;
}
ab_printf("buff = %x\n'");
for(i=0; i<100; i++) {
    ab_printf("%d ", buff[i]);
}
ab_printf("\n");
dlfree(buff);
return 0;
}

ckim@stph45:~/prj2/abts/yolo-bare/darknet] make test3
sparc-ab-elf-gcc -c -I./src -I../include -I/opt/abde/sparc-ab-elf/include    -DALDEBARAN_FPGA -DABC_CT -O3 -ffast-math -fcommon -msoft-float -mcpu=v8  -Wa,-xarch=v8plusb -Wall -Wfatal-errors   ./src/malloc.c -o obj/malloc.o
./src/malloc.c:571:40: fatal error: sys/mman.h: No such file or directory
compilation terminated.
make: *** [obj/malloc.o] Error 1

My bare-metal system doesn't have sys/mman.h (I searched it on the elf toolchain library) so tried again after defining LACKS_SYS_MMAN_H and got

ckim@stph45:~/prj2/abts/yolo-bare/darknet] make test3
sparc-ab-elf-gcc -c -I./src -I../include -I/opt/abde/sparc-ab-elf/include    -DALDEBARAN_FPGA -DABC_CT -O3 -ffast-math -fcommon -msoft-float -mcpu=v8  -Wa,-xarch=v8plusb -Wall -Wfatal-errors  -DLACKS_SYS_MMAN_H  ./src/test3.c -o obj/test3.o
sparc-ab-elf-gcc -c -I./src -I../include -I/opt/abde/sparc-ab-elf/include    -DALDEBARAN_FPGA -DABC_CT -O3 -ffast-math -fcommon -msoft-float -mcpu=v8  -Wa,-xarch=v8plusb -Wall -Wfatal-errors  -DLACKS_SYS_MMAN_H  ./src/malloc.c -o obj/malloc.o
./src/malloc.c: In function 'mmap_alloc':
./src/malloc.c:2924:5: warning: implicit declaration of function 'mmap' [-Wimplicit-function-declaration]
./src/malloc.c:2924:24: error: 'PROT_READ' undeclared (first use in this function)
compilation terminated due to -Wfatal-errors.
make: *** [obj/malloc.o] Error 1

The dlmalloc.c is a very long program. (I divided it into malloc.h and malloc.c) Below is the function making error..

/* Malloc using mmap */
static void* mmap_alloc(mstate m, size_t nb) {
  size_t mmsize = mmap_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK);
  if (m->footprint_limit != 0) {
    size_t fp = m->footprint + mmsize;
    if (fp <= m->footprint || fp > m->footprint_limit)
      return 0;
  }
  if (mmsize > nb) {     /* Check for wrap around 0 */
    char* mm = (char*)(CALL_DIRECT_MMAP(mmsize));    <=== line causing error.
    if (mm != CMFAIL) {
      size_t offset = align_offset(chunk2mem(mm));
      size_t psize = mmsize - offset - MMAP_FOOT_PAD;
      mchunkptr p = (mchunkptr)(mm + offset);
      p->prev_foot = offset;
      p->head = psize;
      mark_inuse_foot(m, p, psize);
      chunk_plus_offset(p, psize)->head = FENCEPOST_HEAD;
      chunk_plus_offset(p, psize+SIZE_T_SIZE)->head = 0;

      if (m->least_addr == 0 || mm < m->least_addr)
        m->least_addr = mm;
      if ((m->footprint += mmsize) > m->max_footprint)
        m->max_footprint = m->footprint;
      assert(is_aligned(chunk2mem(p)));
      check_mmapped_chunk(m, p);
      return chunk2mem(p);
    }
  }
  return 0;
}

can somebody give me a light?


问:
How to set the callbacks for Android Firebase Phone Authentication?
Im kinda new to firebase and android then I saw this new feature in android the firebase phone Auth. I was looking at this doucumentation Firebase Phone Auth and I am confused on Implementing this mCallbacks .. can someone pls guide me ?

```<code>PhoneAuthProvider.getInstance().verifyPhoneNumber(
                        phoneNum,
                        60,
                        TimeUnit.SECONDS,
                        this,
                        mCallbacks
</code>```

this confused me is I dont know what data type should I use to assign that callback. since there is no sample code I wish someone might able to guide me.

答:
You should use a PhoneAuthProvider.OnVerificationStateChangedCallbacks(). Like so:

```<code>    PhoneAuthProvider.getInstance().verifyPhoneNumber(
            phoneNumber,        // Phone number to verify
            60,                 // Timeout duration
            TimeUnit.SECONDS,   // Unit of timeout
            this,               // Activity (for callback binding)
            new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
                @Override
                public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {

                }

                @Override
                public void onVerificationFailed(FirebaseException e) {

                }
            });
</code>```

Then you could just override the other Verification callbacks that you need.

Body:
Im kinda new to firebase and android then I saw this new feature in android the firebase phone Auth. I was looking at this doucumentation Firebase Phone Auth and I am confused on Implementing this mCallbacks .. can someone pls guide me ?

PhoneAuthProvider.getInstance().verifyPhoneNumber(
                        phoneNum,
                        60,
                        TimeUnit.SECONDS,
                        this,
                        mCallbacks

this confused me is I dont know what data type should I use to assign that callback. since there is no sample code I wish someone might able to guide me.

Body:
You should use a PhoneAuthProvider.OnVerificationStateChangedCallbacks(). Like so:

    PhoneAuthProvider.getInstance().verifyPhoneNumber(
            phoneNumber,        // Phone number to verify
            60,                 // Timeout duration
            TimeUnit.SECONDS,   // Unit of timeout
            this,               // Activity (for callback binding)
            new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
                @Override
                public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {

                }

                @Override
                public void onVerificationFailed(FirebaseException e) {

                }
            });

Then you could just override the other Verification callbacks that you need.


问:
JavaScript file inclusion. Should I not link in ?
I'm watching Douglas Crockfords "Theory of the DOM" and he mentioned that the location of my script tags can greatly affect the load time of my applications.  Furthermore, he asserts that a script tag should be included as far towards the bottom of the document body as possible.

Is this accurate?

OR

Is this video out of date? (which he actually sites as a reason he didn't lecture on the DOM sooner).

答:
Files included in the header are loaded before the rest of the page even begins loading.  It's recommended that you load non-essential files as close to the bottom of the page as possible so the rest of the page can be loaded beforehand.

There are some JS libraries (such as LABjs) that you can load in the header instead.  They then allow you to load all of your other JS assets asynchronously and provide a callback so the rest of your code can execute when you know your JS assets have been loaded.

Title: JavaScript file inclusion. Should I not link in <head>?


问:
Set Spring profile in Tomcat web app with no web.xml file
I have a webapp that is a RestEASY JAX-RS application and that uses the latest servlet specifications, such as Java EE annotations so that I don't need to create a web.xml file.

The webapp is bundled as foobar.war and dumped into the webapps directory in Tomcat. In fact the same foobar.war is deployed twice in the same Tomcat instance, once as foobar.war and the other as foobar#demo.war (which maps it to foobar/demo as you know).

I configure each mounted webapp by placing conf/Catalina/localhost/foobar.xml and conf/Catalina/localhost/foobar#demo.xml files, that look like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Context>
  <Environment name="foo" type="java.lang.String" value="bar"/>
</Context>
</code>```

In my JAX-RS application I pull in the value of foo from JNDI using java:comp/env/foo.

So now I added a Java-based Spring configuration named FooBarConfiguration. I load it in my JAX-RS application using new AnnotationConfigApplicationContext(FooBarConfiguration.class). That all works fine.

So now I've added two profiles to FooBarConfiguration, one named foo and one named bar. But now... how do I tell the webapp which Spring profile to use? (Remember that I have no web.xml file.) Obviously I have to set spring.profiles.active somewhere. But where?

Because the documentation spoke of "environment" and "JNDI", I crossed my fingers and added an environment variable to conf/Catalina/localhost/foobar.xml:

```<code>  <Environment name="spring.profiles.active" type="java.lang.String" value="foo"/>
</code>```

No luck.

I can't set a system property, because that will apply to all the webapps, and the idea here is that each foobar.war instance (foobar.war and foobar#demo.war) could each have a different profile specified.

I suppose I could manually pull it out of the Tomcat environment myself, using java:comp/env/spring.profiles.active, but then where do I set the value? (I thought maybe AnnotationConfigApplicationContext would have a constructor where I could set the profile, or at least have a profile setting, but that also seems to be missing.)

(Plus if I'm manually pulling out the setting from JNDI and setting it myself, I might as well switch to the more lightweight Guice and manually load the modules I want. I'm only using the humongous, clunky Spring because it promised to allow easy selection of profiles.)

How can I indicate, external to my WAR file, on a per-webapp basis, which Spring profile I'm using?

答:
You can set active profiles in many ways. Since you were searching for it via AnnotationConfigApplicationContext constructor, the one  described here in spring docs might suit you.

```<code>AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.getEnvironment().setActiveProfiles("development");
ctx.refresh();
</code>```

Body:
I have a webapp that is a RestEASY JAX-RS application and that uses the latest servlet specifications, such as Java EE annotations so that I don't need to create a web.xml file.

The webapp is bundled as foobar.war and dumped into the webapps directory in Tomcat. In fact the same foobar.war is deployed twice in the same Tomcat instance, once as foobar.war and the other as foobar#demo.war (which maps it to foobar/demo as you know).

I configure each mounted webapp by placing conf/Catalina/localhost/foobar.xml and conf/Catalina/localhost/foobar#demo.xml files, that look like this:

<?xml version="1.0" encoding="UTF-8"?>
<Context>
  <Environment name="foo" type="java.lang.String" value="bar"/>
</Context>

In my JAX-RS application I pull in the value of foo from JNDI using java:comp/env/foo.

So now I added a Java-based Spring configuration named FooBarConfiguration. I load it in my JAX-RS application using new AnnotationConfigApplicationContext(FooBarConfiguration.class). That all works fine.

So now I've added two profiles to FooBarConfiguration, one named foo and one named bar. But now... how do I tell the webapp which Spring profile to use? (Remember that I have no web.xml file.) Obviously I have to set spring.profiles.active somewhere. But where?

Because the documentation spoke of "environment" and "JNDI", I crossed my fingers and added an environment variable to conf/Catalina/localhost/foobar.xml:

  <Environment name="spring.profiles.active" type="java.lang.String" value="foo"/>

No luck.

I can't set a system property, because that will apply to all the webapps, and the idea here is that each foobar.war instance (foobar.war and foobar#demo.war) could each have a different profile specified.

I suppose I could manually pull it out of the Tomcat environment myself, using java:comp/env/spring.profiles.active, but then where do I set the value? (I thought maybe AnnotationConfigApplicationContext would have a constructor where I could set the profile, or at least have a profile setting, but that also seems to be missing.)

(Plus if I'm manually pulling out the setting from JNDI and setting it myself, I might as well switch to the more lightweight Guice and manually load the modules I want. I'm only using the humongous, clunky Spring because it promised to allow easy selection of profiles.)

How can I indicate, external to my WAR file, on a per-webapp basis, which Spring profile I'm using?

Body:
You can set active profiles in many ways. Since you were searching for it via AnnotationConfigApplicationContext constructor, the one  described here in spring docs might suit you.

AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.getEnvironment().setActiveProfiles("development");
ctx.refresh();


问:
Read fragment content in viewpager on swipe with talkback accessibility mode
I have a viewpager that contains multiple fragments. When the activity is launched, I can read the content of fragment with a click. But when swipe, talkback only announce the pager position without reading the content. Is there a way to announce the page number then read it's content?</p>

答:
You can set contentsDescription to Fragment's child view.

For example, if you have a TextView and it has contents that you want to speak by talk back, you can do this:

```<code>textView.setContentDescription("Hello world");
</code>```

Or, you can add "android:contentDescription" to xml.

```<code>    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="Hello world"
    </TextView>
</code>```

Body:
You can set contentsDescription to Fragment's child view.

For example, if you have a TextView and it has contents that you want to speak by talk back, you can do this:

textView.setContentDescription("Hello world");

Or, you can add "android:contentDescription" to xml.

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="Hello world"
    </TextView>


问:
TypeScript interface with XOR, {bar:string} xor {can:number}
How do I say that I want an interface to be one or the other, but not both or neither?</p>

```<code>interface IFoo {
    bar: string /*^XOR^*/ can: number;
}
</code>```

答:
You can use union types along with the never type to achieve this:

```<code>type IFoo = {
  bar: string; can?: never
} | {
  bar?: never; can: number
};

let val0: IFoo = { bar: "hello" } // OK only bar
let val1: IFoo = { can: 22 } // OK only can
let val2: IFoo = { bar: "hello",  can: 22 } // Error foo and can
let val3: IFoo = {  } // Error neither foo or can
</code>```

Body:
How do I say that I want an interface to be one or the other, but not both or neither?

interface IFoo {
    bar: string /*^XOR^*/ can: number;
}

Body:
You can use union types along with the never type to achieve this:

type IFoo = {
  bar: string; can?: never
} | {
  bar?: never; can: number
};

let val0: IFoo = { bar: "hello" } // OK only bar
let val1: IFoo = { can: 22 } // OK only can
let val2: IFoo = { bar: "hello",  can: 22 } // Error foo and can
let val3: IFoo = {  } // Error neither foo or can

ContentLicense: CC BY-SA 4.0


问:
Capturing stdout in Azure Linux App Service via NodeJs
I have deployed a NodeJS application to Linux App Service that logs to stderr and stdout.  The diagnostic logs functionality in Linux App Service does not appear to work, as nothing appears in table storage.  The only logs in Kudu are from when the docker container is deployed.  After that, it logs nothing.

The SSH component in Kudu does not work, even after following the official setup documentation.

Has anyone come up with a way to capture stdout and stderr? or can recommend a library that they have gotten to work successfully with NodeJS on the Linux App Service platform?

答:
You could use Azure CLI 2.0 to capture stdout. Try to use the following commands.

```<code>az webapp  log config -g <resource group name> -n <app name> --application-logging true --detailed-error-messages true --level verbose
az webapp  log tail -g <resource group name> -n <app name>
</code>```

You could get help with -h

```<code>root@shui:~# az webapp log config -h

Command
    az webapp log config: Configure web app logs.

Arguments
    --application-logging    : Configure application logging to file system.  Allowed values: false,
                               true.
    --detailed-error-messages: Configure detailed error messages.  Allowed values: false, true.
    --failed-request-tracing : Configure failed request tracing.  Allowed values: false, true.
    --level                  : Logging level.  Allowed values: error, information, verbose, warning.
    --slot -s                : The name of the slot. Default to the productions slot if not
                               specified.
    --web-server-logging     : Configure Web server logging.  Allowed values: filesystem, off,
                               storage.
</code>```

More information about  Azure Cli supports linux webapp please refer to this link.

Body:
You could use Azure CLI 2.0 to capture stdout. Try to use the following commands.

az webapp  log config -g <resource group name> -n <app name> --application-logging true --detailed-error-messages true --level verbose
az webapp  log tail -g <resource group name> -n <app name>

You could get help with -h

root@shui:~# az webapp log config -h

Command
    az webapp log config: Configure web app logs.

Arguments
    --application-logging    : Configure application logging to file system.  Allowed values: false,
                               true.
    --detailed-error-messages: Configure detailed error messages.  Allowed values: false, true.
    --failed-request-tracing : Configure failed request tracing.  Allowed values: false, true.
    --level                  : Logging level.  Allowed values: error, information, verbose, warning.
    --slot -s                : The name of the slot. Default to the productions slot if not
                               specified.
    --web-server-logging     : Configure Web server logging.  Allowed values: filesystem, off,
                               storage.

More information about  Azure Cli supports linux webapp please refer to this link.


问:
Android: Lazy Image Loader causes Gallery to stutter
I'm using a lazy image loader, that sets an ImageView's bitmap. I can drag the gallery, and it drags smoothly until my images load in. Then while I'm dragging the gallery stutters, as if it's trying to recenter on the middle image and doesn't let me drag. I have to do a fling to get it to move and not recenter. Anyone else run into this issue?</p>

答: Ok, it seems I was doing too much in the UI thread, which was causing the animation to stutter. Now I'm doing "less" and it's fixed.</p>


问:
CGFloat * 2 compiles, CGFloat * Variable where variable is an integer fails
I have to wrap my ints in CGFloat() to compile in Swift 2.3

If I just did * 2, then it would compile. Why does this happen?
Is this fixed in Swift 3?

```<code>var multiplier = CGFloat(3)
let y = collectionView.frame.origin.y + (cellSize() * multiplier)
</code>```

答: type inference. When you write out * 2 without explicitly declaring it an int Swift infers it to be a CGFloat. However when you've already declared it to be an int you can't multiply a CGFloat with an Int.</p>

Body:
I have to wrap my ints in CGFloat() to compile in Swift 2.3

If I just did * 2, then it would compile. Why does this happen?
Is this fixed in Swift 3?

var multiplier = CGFloat(3)
let y = collectionView.frame.origin.y + (cellSize() * multiplier)


问:
EXC_BAD_ACCESS code=2 on including Firebase/Auth in Podfile
I am getting EXC_BAD_ACCESS after including 'Firebase/Auth' in Podfile. This happens without adding any line of firebase code. I am using swift3 on xcode 8 and the resultant pods are -

```<code>Installing Firebase (3.8.0)
Installing FirebaseAnalytics (3.5.1)
Installing FirebaseAuth (3.0.6)
Installing FirebaseCore (3.4.4)
Installing FirebaseInstanceID (1.0.8)
Using GTMOAuth2 (1.1.4)
Using GTMSessionFetcher (1.1.7)
Using GoogleAppUtilities (1.1.2)
Installing GoogleInterchangeUtilities (1.2.2)
Using GoogleSignIn (4.0.1)
Using GoogleSymbolUtilities (1.1.2)
Installing GoogleToolboxForMac 2.1.0 (was 2.1.0)
Using Localize-Swift (1.6)
Using ProtocolBuffers-Swift (3.0.6)
Using QorumLogs (0.9)
</code>```

The error comes in Thread 1 in [UIViewController(FIRAScreenClassName) fira_viewDidAppear:]:

This happens only if the pod target is itself a framework which is embedded in an app eventually.

I do have Google analytics as well. Is it because ARC is not enabled? How do I do that on xcode-8?
Any other options to try?

答: I made a silly mistake. Never turned on Google under Authentication -> Sign in methods on Firebase</p>

Body:
I am getting EXC_BAD_ACCESS after including 'Firebase/Auth' in Podfile. This happens without adding any line of firebase code. I am using swift3 on xcode 8 and the resultant pods are -

Installing Firebase (3.8.0)
Installing FirebaseAnalytics (3.5.1)
Installing FirebaseAuth (3.0.6)
Installing FirebaseCore (3.4.4)
Installing FirebaseInstanceID (1.0.8)
Using GTMOAuth2 (1.1.4)
Using GTMSessionFetcher (1.1.7)
Using GoogleAppUtilities (1.1.2)
Installing GoogleInterchangeUtilities (1.2.2)
Using GoogleSignIn (4.0.1)
Using GoogleSymbolUtilities (1.1.2)
Installing GoogleToolboxForMac 2.1.0 (was 2.1.0)
Using Localize-Swift (1.6)
Using ProtocolBuffers-Swift (3.0.6)
Using QorumLogs (0.9)

The error comes in Thread 1 in [UIViewController(FIRAScreenClassName) fira_viewDidAppear:]:

This happens only if the pod target is itself a framework which is embedded in an app eventually.

I do have Google analytics as well. Is it because ARC is not enabled? How do I do that on xcode-8?
Any other options to try?


问:
VBA Loop to find a duplicate of color in a specific range
I've been looking around for a generic code and modify but I am not able to solve my problem.

I have a working file including many rows. Each line is supposed to have only one color fill (RGB 0,204,0). I would like to know if it possible to automatically loop (without using action button) into my document and highlight the rows via MsgBox in which I have the same color.

Thanks !

答:
Thank you very much @Mertinc

My range is (C27:G48)

However, I was wondering if the following can be done : when the loop is going to find the specific color (0,204,0), it's going to look the text of the cell : i.e. EXCELLENT (80) and copy/paste the numerical value into the col H. My numbers are going from 0 ; 5; 20 ; 40 ; 60 ; 80 ; 100.

If the loop find two cells with the color (0,204,0) the B column need to be colored (0,0,255)

Finnaly, if the result in the specific text is 0, the col H related need to be colored in (255,0,0).


问:
How do I send emails outside my domain with Exchange 2007 and c#
I am able to send emails using the typical C# SMTP code across Exchange 2007 as long as both the from and to addresses are within my domain.

As soon as I try to send emails outside the domain I get:

Exception Details: System.Net.Mail.SmtpFailedRecipientException: Mailbox unavailable. The server response was: 5.7.1 Unable to relay

How can I get exchange to accept my email and send it out to the internet?

答:
Authenticate to the exchange server.

http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.credentials.aspx

DefaultNetworkCredentials returns
  empty strings for username etc and
  causes this exception...

Here is an example, and here is another of sending authenticated message with System.Net.Mail.

OwnerDisplayName: jmcd

OwnerDisplayName: Zoredache

LastEditorDisplayName: Zoredache


问:
Delta Propagation in GemFire
When I was trying to implement Delta Propagation in GemFire, I was getting Exception shown below...

Exception...

```<code>com.gemstone.gemfire.pdx.PdxSerializationException: Could not create an instance of a class DeltaTesting with root cause
java.lang.ClassNotFoundException: DeltaTesting
    at org.apache.geode.internal.ClassPathLoader.forName(ClassPathLoader.java:437)
    at org.apache.geode.internal.InternalDataSerializer.getCachedClass(InternalDataSerializer.java:4010)
    at org.apache.geode.pdx.internal.PdxType.getPdxClass(PdxType.java:235)
    at org.apache.geode.pdx.internal.PdxReaderImpl.basicGetObject(PdxReaderImpl.java:687)
    at org.apache.geode.pdx.internal.PdxReaderImpl.getObject(PdxReaderImpl.java:682)
</code>```

Code...

```<code>@Region("deltaTesting")
public class DeltaTesting implements Delta,Serializable {

    private static final long serialVersionUID = 1L;

    public DeltaTesting(){

    }

public DeltaTesting(String id, String firstName, String lastName){
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;

    }

    @Id
    private String id;
    private String firstName;
    private String lastName;

    private transient boolean stringId = false;
    private transient boolean stringFirstName = false;
    private transient boolean stringLastName = false;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.stringId = true;
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.stringFirstName = true;
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.stringLastName = true;
        this.lastName = lastName;
    }

    @Override
    public void fromDelta(DataInput in) throws IOException, InvalidDeltaException {
        // TODO Auto-generated method stub

         System.out.println("Applying delta to " + this.toString());
            // For each field, read whether there is a change
            if (in.readBoolean()) {
                // Read the change and apply it to the object
                this.id = in.readLine();
                System.out.println(" Applied delta to field 'id' = "
                            + this.id);
            }

            if (in.readBoolean()) {
                // Read the change and apply it to the object
                this.firstName = in.readLine();
                System.out.println(" Applied delta to field 'firstname' = "
                            + this.firstName);
            }
            if (in.readBoolean()) {
                // Read the change and apply it to the object
                this.lastName = in.readLine();
                System.out.println(" Applied delta to field 'lastname' = "
                            + this.lastName);
            }
    }

    @Override
    public boolean hasDelta() {
        // TODO Auto-generated method stub
         return this.stringId || this.stringFirstName || this.stringLastName;
    }

    @Override
    public void toDelta(DataOutput out) throws IOException {

         out.writeBoolean(stringId);
        // TODO Auto-generated method stub
        if (stringId) {
            out.writeBytes(this.id);
            this.stringId = false;
            System.out.println(" Extracted delta from field 'id' = " + this.id);
        }
         out.writeBoolean(stringFirstName);
        if (stringFirstName) {
            out.writeBytes(this.firstName);
            this.stringFirstName = false;
            System.out.println(" Extracted delta from field 'firstName' = " + this.firstName);
        }
         out.writeBoolean(stringLastName);
            if (stringLastName) {
                out.writeBytes(this.lastName);
                this.stringLastName = false;
                System.out.println(" Extracted delta from field 'lastName' = " + this.lastName);
            }

    }

}
**cache.xml**
    <pdx>
    <pdx-serializer>
    <class-name>com.gemstone.gemfire.pdx.ReflectionBasedAutoSerializer</class-
    name>
   <parameter name="classes">
   <string>com\.xxx\..+</string>
   </parameter>

</pdx-serializer>
   </pdx>
</code>```

答:
@Vigneshwara-

Delta Propagation is not supported by PDX Serialization in GemFire.  You must use the GemFire Data Serialization framework (i.e. DataSerializable and DataSerializers) with Deltas instead.

In short... if you use PDX, then you cannot use Deltas.  If you use Deltas, then you cannot use PDX.

Sorry,
-j

Title: Delta Propagation in GemFire

Body:
When I was trying to implement Delta Propagation in GemFire, I was getting Exception shown below...

Exception...

com.gemstone.gemfire.pdx.PdxSerializationException: Could not create an instance of a class DeltaTesting with root cause
java.lang.ClassNotFoundException: DeltaTesting
    at org.apache.geode.internal.ClassPathLoader.forName(ClassPathLoader.java:437)
    at org.apache.geode.internal.InternalDataSerializer.getCachedClass(InternalDataSerializer.java:4010)
    at org.apache.geode.pdx.internal.PdxType.getPdxClass(PdxType.java:235)
    at org.apache.geode.pdx.internal.PdxReaderImpl.basicGetObject(PdxReaderImpl.java:687)
    at org.apache.geode.pdx.internal.PdxReaderImpl.getObject(PdxReaderImpl.java:682)

Code...

@Region("deltaTesting")
public class DeltaTesting implements Delta,Serializable {

    private static final long serialVersionUID = 1L;

    public DeltaTesting(){

    }

public DeltaTesting(String id, String firstName, String lastName){
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;

    }

    @Id
    private String id;
    private String firstName;
    private String lastName;

    private transient boolean stringId = false;
    private transient boolean stringFirstName = false;
    private transient boolean stringLastName = false;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.stringId = true;
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.stringFirstName = true;
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.stringLastName = true;
        this.lastName = lastName;
    }

    @Override
    public void fromDelta(DataInput in) throws IOException, InvalidDeltaException {
        // TODO Auto-generated method stub

         System.out.println("Applying delta to " + this.toString());
            // For each field, read whether there is a change
            if (in.readBoolean()) {
                // Read the change and apply it to the object
                this.id = in.readLine();
                System.out.println(" Applied delta to field 'id' = "
                            + this.id);
            }

            if (in.readBoolean()) {
                // Read the change and apply it to the object
                this.firstName = in.readLine();
                System.out.println(" Applied delta to field 'firstname' = "
                            + this.firstName);
            }
            if (in.readBoolean()) {
                // Read the change and apply it to the object
                this.lastName = in.readLine();
                System.out.println(" Applied delta to field 'lastname' = "
                            + this.lastName);
            }
    }

    @Override
    public boolean hasDelta() {
        // TODO Auto-generated method stub
         return this.stringId || this.stringFirstName || this.stringLastName;
    }

    @Override
    public void toDelta(DataOutput out) throws IOException {

         out.writeBoolean(stringId);
        // TODO Auto-generated method stub
        if (stringId) {
            out.writeBytes(this.id);
            this.stringId = false;
            System.out.println(" Extracted delta from field 'id' = " + this.id);
        }
         out.writeBoolean(stringFirstName);
        if (stringFirstName) {
            out.writeBytes(this.firstName);
            this.stringFirstName = false;
            System.out.println(" Extracted delta from field 'firstName' = " + this.firstName);
        }
         out.writeBoolean(stringLastName);
            if (stringLastName) {
                out.writeBytes(this.lastName);
                this.stringLastName = false;
                System.out.println(" Extracted delta from field 'lastName' = " + this.lastName);
            }

    }

}
**cache.xml**
    <pdx>
    <pdx-serializer>
    <class-name>com.gemstone.gemfire.pdx.ReflectionBasedAutoSerializer</class-
    name>
   <parameter name="classes">
   <string>com\.xxx\..+</string>
   </parameter>

</pdx-serializer>
   </pdx>


答:
Swift does not directly support mixed type arithmetic. Check what the type of 2 is in Swift, it's probably not what you assume. Your use of CGFloat() is converting the value so the operands of * have the same type.

HTH

Title: CGFloat * 2 compiles, CGFloat * Variable where variable is an integer fails


问:
HTTPS and HTTP connection in java
I know that HTTPS extends http. So does that mean i can do this?

```<code>HttpUrlConnection connect = passmyurl.openconnection(url);
</code>```

and

```<code>HttpsUrlConnection connect = passmyurl.openconnection(url);

public static HttpsURLConnection passmyurl(URL url) throws IOException {
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        return connection;
    }
</code>```

Does this mean that both will work? Since the HTTps extends HTTP, it means I can also pass a HTTP url to this function?

答:
In your code:

```<code>public static HttpsURLConnection passmyurl(URL url) throws IOException {
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    return connection;
}
</code>```

You should change the return type HttpsURLConnection to URLConnection.Because the url.openConnection() result's type is subtype of URLConnection,and the exact type depends on the paramter url's protocol.The implemention document of openConnection() in the URL class:

```<code>If for the URL's protocol (such as HTTP or JAR), there exists a public, specialized URLConnection subclass belonging to one of the following packages or one of their subpackages: java.lang, java.io, java.util, java.net, the connection returned will be of that subclass. For example, for HTTP an HttpURLConnection will be returned, and for JAR a JarURLConnection will be returned.
</code>```

So you can pass the Http url or Https url to your method.

See the following code:

```<code>    URLConnection httpConnection = new URL("http://test").openConnection();
    System.out.println(httpConnection.getClass());
    URLConnection httpsConnection = new URL("https://test").openConnection();
    System.out.println(httpsConnection.getClass());
    URLConnection ftpConnection = new URL("ftp://test").openConnection();
    System.out.println(ftpConnection.getClass());`
</code>```

the print is:

```<code>class sun.net.www.protocol.http.HttpURLConnection
class sun.net.www.protocol.https.HttpsURLConnectionImpl
class sun.net.www.protocol.ftp.FtpURLConnection
</code>```

Title: HTTPS and HTTP connection in java

Body:
I know that HTTPS extends http. So does that mean i can do this?

HttpUrlConnection connect = passmyurl.openconnection(url);

and

HttpsUrlConnection connect = passmyurl.openconnection(url);

public static HttpsURLConnection passmyurl(URL url) throws IOException {
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        return connection;
    }

Does this mean that both will work? Since the HTTps extends HTTP, it means I can also pass a HTTP url to this function?

Body:
In your code:

public static HttpsURLConnection passmyurl(URL url) throws IOException {
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    return connection;
}

You should change the return type HttpsURLConnection to URLConnection.Because the url.openConnection() result's type is subtype of URLConnection,and the exact type depends on the paramter url's protocol.The implemention document of openConnection() in the URL class:

If for the URL's protocol (such as HTTP or JAR), there exists a public, specialized URLConnection subclass belonging to one of the following packages or one of their subpackages: java.lang, java.io, java.util, java.net, the connection returned will be of that subclass. For example, for HTTP an HttpURLConnection will be returned, and for JAR a JarURLConnection will be returned.

So you can pass the Http url or Https url to your method.

See the following code:

    URLConnection httpConnection = new URL("http://test").openConnection();
    System.out.println(httpConnection.getClass());
    URLConnection httpsConnection = new URL("https://test").openConnection();
    System.out.println(httpsConnection.getClass());
    URLConnection ftpConnection = new URL("ftp://test").openConnection();
    System.out.println(ftpConnection.getClass());`

the print is:

class sun.net.www.protocol.http.HttpURLConnection
class sun.net.www.protocol.https.HttpsURLConnectionImpl
class sun.net.www.protocol.ftp.FtpURLConnection


问:
SQL Server Merging two records into one
I have this table:

```<code>--------------------------------
|ID|SN|SEC|Qty|DONE_CON|DONE_BY|
|--+--+---+---+--------+-------|
|1A|1A|ETC|124|YES     |       |
|2B|1A|CON|   |        |David  |
|1H|1H|ETC|764|YES     |       |
|2R|1H|CON|   |        |Maria  |
--------------------------------
</code>```

What I want to do is to get all the CON as the SEC and show its ID, Qty and DONE_BY values.

My problem is Qty will come from its reference record (RF column).

Example:

CON record with ID 2B has 1A as its RF. So the Qty will be 124.

CON record with ID 2R has 1H as its RF. So the Qty will be 764.

Final Output should look like this:

```<code>----------------
|ID|Qty|DONE_BY|
|--+---+-------|
|2B|124|David  |
|2R|764|Maria  |
----------------
</code>```

Currently, I only have this query:

```<code>SELECT ID, Qty, DONE_BY FROM TBL_TEST WHERE SEC='CON'
</code>```

Please, help me. Thank you in advance.

答:
I believe you are wanting a self join here so you can grab the qty from your matching SN->ID;</p>

```<code>SELECT
    t1.id,
    t2.qty as qty,
    t1.Done_By
FROM yourTable t1
    INNER JOIN yourTable t2
        ON t1.sn = t2.id
WHERE t1.sec='con';
</code>```

Title: SQL Server Merging two records into one

Body:
I have this table:

--------------------------------
|ID|SN|SEC|Qty|DONE_CON|DONE_BY|
|--+--+---+---+--------+-------|
|1A|1A|ETC|124|YES     |       |
|2B|1A|CON|   |        |David  |
|1H|1H|ETC|764|YES     |       |
|2R|1H|CON|   |        |Maria  |
--------------------------------

What I want to do is to get all the CON as the SEC and show its ID, Qty and DONE_BY values.

My problem is Qty will come from its reference record (RF column).

Example:

CON record with ID 2B has 1A as its RF. So the Qty will be 124.

CON record with ID 2R has 1H as its RF. So the Qty will be 764.

Final Output should look like this:

----------------
|ID|Qty|DONE_BY|
|--+---+-------|
|2B|124|David  |
|2R|764|Maria  |
----------------

Currently, I only have this query:

SELECT ID, Qty, DONE_BY FROM TBL_TEST WHERE SEC='CON'

Please, help me. Thank you in advance.

Body:
I believe you are wanting a self join here so you can grab the qty from your matching SN->ID;

SELECT
    t1.id,
    t2.qty as qty,
    t1.Done_By
FROM yourTable t1
    INNER JOIN yourTable t2
        ON t1.sn = t2.id
WHERE t1.sec='con';


问:
SQL INSERT INTO VALUE statement using a SELECT statement with a variable
I have 2 tables:

Tbl_Task - Has all the tasks for a process (TaskNum is unique. TaskName is what i'm writing to Tbl_Proc)

Tbl_Proc - Will hold the status of each task for a customer

When a new customer is created, I'm using the forms on close event to write each task from Tbl_Task into Tbl_Proc. I'm using the customer name from the form to complete the record in the Tbl_Proc.

My thought is to use an integer to increment the TaskNum and assign that task numbers TaskName to the Tbl_Proc[ProcTaskName].  Then loop through all task numbers. As you can see, I'm stuck on the use of my integer variable.

Here is what I have. I can successfully write the Company name but I can't get the ProcTaskName:

```<code>Private Sub Form_Close()
    On Error GoTo Err_Form_Close

    Dim strCompany As String
    Dim sqls As String
    Dim x As Integer

    strCompany = Me![CoName]
    'MsgBox strCompany
    x = 1

    sqls = "INSERT INTO Tbl_Proc(ProcCo, ProcTaskName)" & _
                    "VALUES ('" & strCompany & "', SELECT TaskName FROM Tbl_Task WHERE TaskNum=""" & x & """)"
    DoCmd.RunSQL sqls
'This works - "VALUES ('" & strCompany & "', 'cat')"

Exit_Form_Close:
    Exit Sub

Err_Form_Close:
    MsgBox Err.Description
    Resume Exit_Form_Close

End Sub
</code>```

答:
If I understand what you are asking correctly, you want your sql to look something like this:

```<code>INSERT INTO Tbl_Proc(ProcCo, ProcTaskName)
    SELECT <yourCompanyVariable>, TaskName
    FROM Tbl_Task
    WHERE TaskNum=<whateverItIsYouHaveHere>
</code>```

The select will return all of the tasks with your given number, each marked with your company variable. All of that will be inserted into your table.

If you can define everything you want in tbl_task easily, like where defaultTasks = 1 you can insert all of the tasks you need in one query without having to loop.

Body:
I have 2 tables:

Tbl_Task - Has all the tasks for a process (TaskNum is unique. TaskName is what i'm writing to Tbl_Proc)

Tbl_Proc - Will hold the status of each task for a customer

When a new customer is created, I'm using the forms on close event to write each task from Tbl_Task into Tbl_Proc. I'm using the customer name from the form to complete the record in the Tbl_Proc.

My thought is to use an integer to increment the TaskNum and assign that task numbers TaskName to the Tbl_Proc[ProcTaskName].  Then loop through all task numbers. As you can see, I'm stuck on the use of my integer variable.

Here is what I have. I can successfully write the Company name but I can't get the ProcTaskName:

Private Sub Form_Close()
    On Error GoTo Err_Form_Close

    Dim strCompany As String
    Dim sqls As String
    Dim x As Integer

    strCompany = Me![CoName]
    'MsgBox strCompany
    x = 1

    sqls = "INSERT INTO Tbl_Proc(ProcCo, ProcTaskName)" & _
                    "VALUES ('" & strCompany & "', SELECT TaskName FROM Tbl_Task WHERE TaskNum=""" & x & """)"
    DoCmd.RunSQL sqls
'This works - "VALUES ('" & strCompany & "', 'cat')"

Exit_Form_Close:
    Exit Sub

Err_Form_Close:
    MsgBox Err.Description
    Resume Exit_Form_Close

End Sub

Body:
If I understand what you are asking correctly, you want your sql to look something like this:

INSERT INTO Tbl_Proc(ProcCo, ProcTaskName)
    SELECT <yourCompanyVariable>, TaskName
    FROM Tbl_Task
    WHERE TaskNum=<whateverItIsYouHaveHere>

The select will return all of the tasks with your given number, each marked with your company variable. All of that will be inserted into your table.

If you can define everything you want in tbl_task easily, like where defaultTasks = 1 you can insert all of the tasks you need in one query without having to loop.


问:
How to manually call onSaveInstanceState()
I am writing a program where I call multiple layouts on the same activity but then i noted that when i switch layouts, the changes made before the switch are not restored and onSavedInstanceState(Bundle outState) is not called. I have tried to manually call the method but i can't get the Bundle outState.

So the question really is: How do I get and store the current state of an activity to be recalled and/or restored at a time of my choosing?

```<code>@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_contact_view);
// more code
}

@Override
public void onBackPressed() {
    if (layoutId == R.layout.activity_contact_view) exit();
    else if (layoutId == R.layout.main) {
        Toast.makeText(NsdChatActivity.this, "Successful back button action", Toast.LENGTH_SHORT).show();
        setContentView(R.layout.activity_contact_view);
        refreshContactList();
    }
}
</code>```

And then from a seperate class

```<code>public void updateList(final int found) {
    LinearLayout layxout = (LinearLayout) ((Activity)mContext).getWindow().getDecorView().findViewById(R.id.others);
    TextView t = new TextView(mContext);
    t.setClickable(true);
    t.setText(found + ". " + activity.sNames.get(found));
    t.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    t.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //show chat view
            activity.setContentView(R.layout.main);
            TextView name = (TextView)activity.findViewById(R.id.clientName);
            name.setText(activity.sNames.get(found).split(" \\(")[0]);
            final ScrollView scroll = (ScrollView)activity.findViewById(R.id.scroll);
            scroll.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View view, boolean b) {
                    scroll.fullScroll(View.FOCUS_DOWN);
                }
            });
        }
    });
    layxout.addView(t);
}
</code>```

答:
May be you should have a look at Application Fundamentals

Android calls onSaveInstanceState() before the activity becomes vulnerable to being destroyed by the system, but does not bother calling it when the instance is actually being destroyed by a user action (such as pressing the BACK key)

so you call multiple layouts on the same activity may not cause the above situation. For more details, you can refer to the question Android: Saving a state during Android lifecycle. Hope that helps!

Body:
I am writing a program where I call multiple layouts on the same activity but then i noted that when i switch layouts, the changes made before the switch are not restored and onSavedInstanceState(Bundle outState) is not called. I have tried to manually call the method but i can't get the Bundle outState.

So the question really is: How do I get and store the current state of an activity to be recalled and/or restored at a time of my choosing?

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_contact_view);
// more code
}

@Override
public void onBackPressed() {
    if (layoutId == R.layout.activity_contact_view) exit();
    else if (layoutId == R.layout.main) {
        Toast.makeText(NsdChatActivity.this, "Successful back button action", Toast.LENGTH_SHORT).show();
        setContentView(R.layout.activity_contact_view);
        refreshContactList();
    }
}

And then from a seperate class

public void updateList(final int found) {
    LinearLayout layxout = (LinearLayout) ((Activity)mContext).getWindow().getDecorView().findViewById(R.id.others);
    TextView t = new TextView(mContext);
    t.setClickable(true);
    t.setText(found + ". " + activity.sNames.get(found));
    t.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    t.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //show chat view
            activity.setContentView(R.layout.main);
            TextView name = (TextView)activity.findViewById(R.id.clientName);
            name.setText(activity.sNames.get(found).split(" \\(")[0]);
            final ScrollView scroll = (ScrollView)activity.findViewById(R.id.scroll);
            scroll.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View view, boolean b) {
                    scroll.fullScroll(View.FOCUS_DOWN);
                }
            });
        }
    });
    layxout.addView(t);
}


问:
$.inArray deep search
I have a json file like this:

```<code>{
    items:
        [{  id: 1,
            catalog: {
                supplier: {
                    priority: 1
                },
            }
        },
        {   id: 2,
            catalog: {
                supplier: {
                    priority: 3
                },
            }
        },
        {   id: 3,
            catalog: {
                supplier: {
                    priority: 1
                },
            }
        }]
</code>```

Now I want to use the $.inArray function to make a deep search of the items array.
For example all items whose catalog/supplier/priority is 1.

Something like this:

```<code>$.inArray(1, data.items(.catalog.supplier.priority)) > -1
</code>```

How do I accomplish this kind of deep search?

答:
I have another solution using Javascript.

<!doctype html>

  <meta charset="utf-8">
  <title>Demo</title>

```

Title: $.inArray deep search

Body:
I have a json file like this:

{
    items:
        [{  id: 1,
            catalog: {
                supplier: {
                    priority: 1
                },
            }
        },
        {   id: 2,
            catalog: {
                supplier: {
                    priority: 3
                },
            }
        },
        {   id: 3,
            catalog: {
                supplier: {
                    priority: 1
                },
            }
        }]

Now I want to use the $.inArray function to make a deep search of the items array.
For example all items whose catalog/supplier/priority is 1.

Something like this:

$.inArray(1, data.items(.catalog.supplier.priority)) > -1

How do I accomplish this kind of deep search?

Body:
I have another solution using Javascript.

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>Demo</title>
  <style>
    div {
      color: blue;
    }

    span {
      color: red;
    }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>

<body>

  <span></span>

  <script>
    var arr = {
      items: [{
          id: 1,
          catalog: {
            supplier: {
              priority: 1
            },
          }
        },
        {
          id: 2,
          catalog: {
            supplier: {
              priority: 3
            },
          }
        },
        {
          id: 3,
          catalog: {
            supplier: {
              priority: 1
            },
          }
        }
      ]
    };
    var $spans = $("span");

    var results = [];
    for (var i=0 ; i < arr.items.length ; i++)
    {
        if (arr.items[i].catalog.supplier.priority === 1) {
            results.push(arr.items[i]);
        }
    }

    $spans.eq(0).text(JSON.stringify(results));
  </script>

</body>

</html>


问:
How do I get a Bootstrap 4 nav to appear on the same line as a header?
Here you can see what it looks like right now.

What it looks like now

How do I get the nav to appear on the right side of the screen while making it be on the same line as the copyright? I cannot seem to get anything to work that I have seen on here so far.

Here is my current code:

```<code><div class="container-fluid footer">
    <div class="spacer"></div>
    <div class="container">
        <h5 style="display: inline">Copyright © 2017 Custom Prop Shop</h5>
        <ul class="nav flex-column flex-sm-row justify-content-end pull-right">
            <li class="nav-item">
                <a class="nav-link" href="request-estimate.html">Request an Estimate</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="our-work.html">Our Work</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="our-clients.html">Our Clients</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="our-story.html">Our Story</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="contact.html">Contact</a>
            </li>
        </ul>
    </div>
    <div class="spacer"></div>
</div>
</code>```

CSS is only controlling color of the text/background and the font-size for this part.

答:
add float: left on the h5.

or float: right on the ul

Body:
Here you can see what it looks like right now.

What it looks like now

How do I get the nav to appear on the right side of the screen while making it be on the same line as the copyright? I cannot seem to get anything to work that I have seen on here so far.

Here is my current code:

Copyright © 2017 Custom Prop Shop

                Request an Estimate

                Our Work

                Our Clients

                Our Story

                Contact

CSS is only controlling color of the text/background and the font-size for this part.


问:
Codeigniter doctrine
I try to use doctrine with Codeigniter.

I have two tables in db, authors and books.

Authors table has fields id, name and lastname.
Books table has fields id, title and author_id.

I know how to write data into table, but I don't know how to get list of all authors and books which that author wrote. Can someone helps me with that?

Authors model

```<code><?php
use Doctrine\Common\Collections\ArrayCollection;
/**
 * @Entity @Table(name="authors")
 **/
class Author
{
    /** @Id @Column(type="integer") @GeneratedValue **/
    protected $id;
    /** @Column(type="string") **/
    protected $name;
    /** @Column(type="string") **/
    protected $lastname;

    /**
     * @OneToMany(targetEntity="Book", mappedBy="author")
     */

    private $books;

    public function __construct()
    {
        $this->books = new ArrayCollection();
    }

    public function setAuthor($name,$lastname)
    {
        $this->name = $name;
        $this->lastname = $lastname;
    }

    public function authorName()
    {
        return $this->name.' '.$this->lastname;
    }

    public function updateAuthor($name,$lastname)
    {
        $this->name = $name;
        $this->lastname = $lastname;
    }

    public function setFirstName($name)
    {
        $this->name = $name;
    }

    public function setLastName($lastname)
    {
        $this->lastname = $lastname;
    }

    public function getBooks()
    {
        return $this->books;
    }

}
</code>```

Book model

```<code><?php
use Doctrine\Common\Collections\ArrayCollection;
/**
 * @Entity @Table(name="books")
 **/
class Book
{
    /** @Id @Column(type="integer") @GeneratedValue **/
    protected $id;
    /** @Column(type="string") **/
    protected $title;

    /**
     * @ManyToOne(targetEntity="Author", inversedBy="books")
     * @oinColumn(name="author_id", referencedColumnName="id")
     */

    private $author;

    public function setTitle($title)
    {
        $this->title = $title;
    }

    public function setAuthor($author)
    {
        $this->author = $author;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function getAuthor()
    {
        return $this->author;
    }
}
</code>```

Thanks in advance

答:
You have an entity class Author and Book. So you can use this code. You can modify as per your need.

```<code>$authors = $em->getRepository("Author")->findAll();
</code>```

Now you can get books of perticular author by calling getBooks()
For example:

```<code>$authors = $em->getRepository("Author")->findAll();//$em is entity manager
    if (count($authors)):
        foreach ($authors as $author):
            $books= $author->getBooks(); //all books of current author
        endforeach;
    endif;
</code>```

Advice: You should define namespace in your entities.

Title: Codeigniter doctrine

Body:
I try to use doctrine with Codeigniter.

I have two tables in db, authors and books.

Authors table has fields id, name and lastname.
Books table has fields id, title and author_id.

I know how to write data into table, but I don't know how to get list of all authors and books which that author wrote. Can someone helps me with that?

Authors model

<?php
use Doctrine\Common\Collections\ArrayCollection;
/**
 * @Entity @Table(name="authors")
 **/
class Author
{
    /** @Id @Column(type="integer") @GeneratedValue **/
    protected $id;
    /** @Column(type="string") **/
    protected $name;
    /** @Column(type="string") **/
    protected $lastname;

    /**
     * @OneToMany(targetEntity="Book", mappedBy="author")
     */

    private $books;

    public function __construct()
    {
        $this->books = new ArrayCollection();
    }

    public function setAuthor($name,$lastname)
    {
        $this->name = $name;
        $this->lastname = $lastname;
    }

    public function authorName()
    {
        return $this->name.' '.$this->lastname;
    }

    public function updateAuthor($name,$lastname)
    {
        $this->name = $name;
        $this->lastname = $lastname;
    }

    public function setFirstName($name)
    {
        $this->name = $name;
    }

    public function setLastName($lastname)
    {
        $this->lastname = $lastname;
    }

    public function getBooks()
    {
        return $this->books;
    }

}

Book model

<?php
use Doctrine\Common\Collections\ArrayCollection;
/**
 * @Entity @Table(name="books")
 **/
class Book
{
    /** @Id @Column(type="integer") @GeneratedValue **/
    protected $id;
    /** @Column(type="string") **/
    protected $title;

    /**
     * @ManyToOne(targetEntity="Author", inversedBy="books")
     * @oinColumn(name="author_id", referencedColumnName="id")
     */

    private $author;

    public function setTitle($title)
    {
        $this->title = $title;
    }

    public function setAuthor($author)
    {
        $this->author = $author;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function getAuthor()
    {
        return $this->author;
    }
}

Thanks in advance

Body:
You have an entity class Author and Book. So you can use this code. You can modify as per your need.

$authors = $em->getRepository("Author")->findAll();

Now you can get books of perticular author by calling getBooks()
For example:

$authors = $em->getRepository("Author")->findAll();//$em is entity manager
    if (count($authors)):
        foreach ($authors as $author):
            $books= $author->getBooks(); //all books of current author
        endforeach;
    endif;

Advice: You should define namespace in your entities.


问:
URL with brackets compared to full URL
Why would #1 work, but not #2 or 3 when used in a $$Return field if database is being accessed using IE11?  The field is hidden.

[db_path/db_filename/Page?OpenPage]

http://server_dns/db_path/db_filename/Page?OpenPage

server_dns/db_path/db_filename/Page?OpenPage

答:
A URL in brackets (e.g., [db_path/db_filename/Page?OpenPage]) is interpreted by the Domino server as a command to send an HTTP 30x REDIRECT response (probably a 303, but I'm not sure) to the browser. Upon receipt of this response, the browser interprets it as an instruction to retrieve the specified URL. That's simply a matter of compliance with standards, so all browsers will do it.

The other choices you list are not treated as anything special by the Domino server. They are simply sent as ordinary content in a 200 OK response to the browser's POST request. No standards apply to this, so a browser may or may not choose to recognize that the response text looks like a URL and may or may not choose to do something with it - e.g., follow the link. Based on your question, it appears that IE11 does not do anything with it. It doesn't follow the URL. Frankly, I had no idea that any browser would do actually follow a URL if it is received as the sole content with a 200 OK response.

Title: URL with brackets compared to full URL


问:
Wildcard in Java doesn't work for Spark cogroup function
I am trying to cogroup two RDDs in java, one of the RDD v2 has type like this: JavaPairRDD<Key, ? extends Value> (actually it is defined with ? extends because it is a function parameter).

Then when I cogroup them, like:

```<code>void f(JavaPairRDD<Key, ? extends Value> v2){
    TYPE v = v1. cogroup(v2);
    // ERROR. I cannot get the correct type for this cogroup function
}
</code>```

Compiler complains because it cannot infer the type of v2 when I try to get a returned value from this cogroup function.

Interesting is that if I don't care the returned value, simply call:

```<code>v1.cogroup(v2).collectAsMap();
</code>```

It seems work. At least it can be compiled.

It seems that the java can only accept wildcard (like ) as an argument when it is just defined as wildcard in function parameter. Am I right about it?

I would like to ask whether there is another way to do it correctly? Or maybe I shouldn't do it like this, what is actually wrong here?

Thanks very much.

答:
It seems that the java can only accept wildcard (like ? extends Base) as an argument when it is just defined as wildcard in function parameter.

cogroup is defined in scala, since scala's type system support co-variant inheritence, its interface doesn't contains the keyward extends for java

```<code>  def cogroup[W](other: JavaPairRDD[K, W]): JavaPairRDD[K, (JIterable[V], JIterable[W])] =
    fromRDD(cogroupResultToJava(rdd.cogroup(other)))
</code>```

But in Java, if the parameter in function signature doesn't has wildcard, the argument when it is called must NOT be some type defined as wildcard.

Body:
I am trying to cogroup two RDDs in java, one of the RDD v2 has type like this: JavaPairRDD<Key, ? extends Value> (actually it is defined with ? extends because it is a function parameter).

Then when I cogroup them, like:

void f(JavaPairRDD<Key, ? extends Value> v2){
    TYPE v = v1. cogroup(v2);
    // ERROR. I cannot get the correct type for this cogroup function
}

Compiler complains because it cannot infer the type of v2 when I try to get a returned value from this cogroup function.

Interesting is that if I don't care the returned value, simply call:

v1.cogroup(v2).collectAsMap();

It seems work. At least it can be compiled.

It seems that the java can only accept wildcard (like ) as an argument when it is just defined as wildcard in function parameter. Am I right about it?

I would like to ask whether there is another way to do it correctly? Or maybe I shouldn't do it like this, what is actually wrong here?

Thanks very much.

Body:
It seems that the java can only accept wildcard (like ? extends Base) as an argument when it is just defined as wildcard in function parameter.

cogroup is defined in scala, since scala's type system support co-variant inheritence, its interface doesn't contains the keyward extends for java

  def cogroup[W](other: JavaPairRDD[K, W]): JavaPairRDD[K, (JIterable[V], JIterable[W])] =
    fromRDD(cogroupResultToJava(rdd.cogroup(other)))

But in Java, if the parameter in function signature doesn't has wildcard, the argument when it is called must NOT be some type defined as wildcard.


问:
Waiting on an indeterminate number of goroutines
I have code where a single goroutine will fire off an indeterminate number of child goroutines, which in turn will fire off more goroutines, etc.  My goal is to wait for all of the child goroutines to finish.

I do not know the total number of goroutines I will be firing off in advance, so I cannot use a sync.WaitGroup, and ideally I wouldn't have to artificially limit the total number of goroutines running via the channel-as-semaphore pattern.

Briefly I thought of having a local channel or waitgroup in each goroutine that serves as a semaphore to wait for all its children, but that results in each goroutine hanging around consuming stack space while all of its decendants finish.

Right now my idea is to increment an atomic counter when a goroutine is fired off (in the parent, to avoid spuriously hitting zero if the child starts running after the parent finishes), decrement it when a goroutine finishes, and periodically check whether it's equal to zero.

Am I basically on the right track, or is there a more elegant solution?

答:
I love WaitGroup's simplicity. The one thing I do not like about WaitGroup is having to pass a reference to it in your goroutines because you would be mixing your concurrency logic with your business logic. Moreover, in your case it could get even more complicated and error prone if you are not careful.

So I came up with this generic function to solve this problem for me:

```<code>// Parallelize parallelizes the function calls
func Parallelize(functions ...func()) {
    var waitGroup sync.WaitGroup
    waitGroup.Add(len(functions))

    defer waitGroup.Wait()

    for _, function := range functions {
        go func(copy func()) {
            defer waitGroup.Done()
            copy()
        }(function)
    }
}
</code>```

So here is how I would use it to solve your problem:

```<code>func1 := func() {
        for char := 'a'; char < 'a' + 3; char++ {
            fmt.Printf("%c ", char)
        }
}

func2 := func() {
        for number := 1; number < 4; number++ {
            fmt.Printf("%d ", number)
        }
}

func3 := func() {
        Parallelize(func1, func2)
}

Parallelize(func3, func3)  // a a 1 1 b b 2 2 c c 3 3
</code>```

If you would like to use it, you can find it here https://github.com/shomali11/util

Body:
I love WaitGroup's simplicity. The one thing I do not like about WaitGroup is having to pass a reference to it in your goroutines because you would be mixing your concurrency logic with your business logic. Moreover, in your case it could get even more complicated and error prone if you are not careful.

So I came up with this generic function to solve this problem for me:

// Parallelize parallelizes the function calls
func Parallelize(functions ...func()) {
    var waitGroup sync.WaitGroup
    waitGroup.Add(len(functions))

    defer waitGroup.Wait()

    for _, function := range functions {
        go func(copy func()) {
            defer waitGroup.Done()
            copy()
        }(function)
    }
}

So here is how I would use it to solve your problem:

func1 := func() {
        for char := 'a'; char < 'a' + 3; char++ {
            fmt.Printf("%c ", char)
        }
}

func2 := func() {
        for number := 1; number < 4; number++ {
            fmt.Printf("%d ", number)
        }
}

func3 := func() {
        Parallelize(func1, func2)
}

Parallelize(func3, func3)  // a a 1 1 b b 2 2 c c 3 3

If you would like to use it, you can find it here https://github.com/shomali11/util