问:
FIWARE-Keyrock: Why are the OAuth2 credentials related to apps if they do not control access?
We have a scenario where I want to protect a service X with Wilma PEP Proxy. The service X is registered in Keyrock. The Wilma PEP Proxy contains the PEP credentials generated in Keyrock for service X. An application Y gets access to service X with the proper OAuth2 credentials generated for this specific service (client_id and client_secret from Service X). It is ok. But there is a problem: an application Z also gets access to the service X with different OAuth2 credentials (not the service X credentials)!!

If this is possible, why do we have applications with specific OAuth2 credentials generated in Keyrock if they do not control anything?! It does not make sense!

It is a big security issue, because one intruder can register some application in Keyrock and with tokens generated for this specific application (with its own OAuth2 credentials) this intruder can access all the applications registered in this Keyrock instance!

答:
As you can see in PEP Proxy documentation, Level 1 only checks authentication. So every user with a valid token (i.e. authenticated in Keyrock) will be redirected to the server app. If you want to also check authorization you have to configure an AuthZForce server with basic or advanced security authorization levels.

On the other hand, in the token validation response, you will obtain a field application_id that indicates you the scope in which the token was created.


来源: stackexchange

问:
decodeSampledBitmapFromResource what to throw in parameters
Im trying to get my bitmap to fit in my imageview by using the tutorial on android devs but i dont know what to throw in this line imageView.setImageBitmap(
                        decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));

this is my full onActivityResult

```<code> if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE_CONTENT_RESOLVER) {
        if (resultCode == RESULT_OK) {
            // Image saved to a generated MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            String[] projection = {
                    MediaStore.MediaColumns._ID,
                    MediaStore.Images.ImageColumns.ORIENTATION,
                    MediaStore.Images.Media.DATA
            };
            Cursor c = getContentResolver().query(mPhotoUri, projection, null, null, null);
            c.moveToFirst();
            String photoFileName = c.getString(c.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            Bitmap bitmap = BitmapFactory.decodeFile(photoFileName);

            imageView.setImageBitmap(
                    decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));

        } else if (resultCode == RESULT_CANCELED) {
            // User cancelled the image capture
        } else {
            // Image capture failed, advise user
        }

    }
</code>```

these are the methods on the android devs

```<code> public static int calculateInSampleSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) >= reqHeight
                && (halfWidth / inSampleSize) >= reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
                                                     int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}
</code>```

}

Im sorry if this is a not a good question but im trying to learn android developing at the moment.

答: fix it by making the two methods into a class.</p>

ContentLicense: CC BY-SA 3.0

Body:
Im trying to get my bitmap to fit in my imageview by using the tutorial on android devs but i dont know what to throw in this line imageView.setImageBitmap(
                        decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));

this is my full onActivityResult

 if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE_CONTENT_RESOLVER) {
        if (resultCode == RESULT_OK) {
            // Image saved to a generated MediaStore.Images.Media.EXTERNAL_CONTENT_URI
            String[] projection = {
                    MediaStore.MediaColumns._ID,
                    MediaStore.Images.ImageColumns.ORIENTATION,
                    MediaStore.Images.Media.DATA
            };
            Cursor c = getContentResolver().query(mPhotoUri, projection, null, null, null);
            c.moveToFirst();
            String photoFileName = c.getString(c.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            Bitmap bitmap = BitmapFactory.decodeFile(photoFileName);

            imageView.setImageBitmap(
                    decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));

        } else if (resultCode == RESULT_CANCELED) {
            // User cancelled the image capture
        } else {
            // Image capture failed, advise user
        }

    }

these are the methods on the android devs

 public static int calculateInSampleSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) >= reqHeight
                && (halfWidth / inSampleSize) >= reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
                                                     int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

}

Im sorry if this is a not a good question but im trying to learn android developing at the moment.


问:
C# Parse XML with repeated pattern of nodes
Hi I have the following xml file:

```<code><?xml version="1.0" encoding="utf-8"?>
<Resources>
    <Category Cause="ONE">
        <Resource Component="AAA" Name="cBackgroundTextA" />
        <Resource Component="BBB" Name="cBackgroundTextB" />
        <Resource Component="CCC" Name="cBackgroundTextC" />
    </Category>
    <Category Cause="TWO">
        <Resource Component="DDD" Name="cBackgroundTextD" />
        <Resource Component="EEE" Name="cBackgroundTextE" />
        <Resource Component="FFF" Name="cBackgroundTextF" />
    </Category>
    <Category Cause="THREE">
        <Resource Component="GGG" Name="cBackgroundTextG" />
        <Resource Component="HHH" Name="cBackgroundTextH" />
        <Resource Component="III" Name="cBackgroundTextI" />
    </Category>
</Resources>
</code>```

How can i get the following:

ONE , AAA , cBackgroundTextA

ONE , BBB , cBackgroundTextB

ONE , CCC , cBackgroundTextC

TWO , DDD , cBackgroundTextD

TWO , EEE , cBackgroundTextE

...

答:
Try something along the line:</p>

```<code>XElement root;

foreach(var folder in root.Children()) { //For each folder
    var folderType = folder.Attribute("type").Value;
    foreach(var file in folder.Children()) { //For each  file

        Console.WriteLine($"{folderType} AND {file}");
    }
}
</code>```

Body:
Hi I have the following xml file:

<?xml version="1.0" encoding="utf-8"?>
<Resources>
    <Category Cause="ONE">
        <Resource Component="AAA" Name="cBackgroundTextA" />
        <Resource Component="BBB" Name="cBackgroundTextB" />
        <Resource Component="CCC" Name="cBackgroundTextC" />
    </Category>
    <Category Cause="TWO">
        <Resource Component="DDD" Name="cBackgroundTextD" />
        <Resource Component="EEE" Name="cBackgroundTextE" />
        <Resource Component="FFF" Name="cBackgroundTextF" />
    </Category>
    <Category Cause="THREE">
        <Resource Component="GGG" Name="cBackgroundTextG" />
        <Resource Component="HHH" Name="cBackgroundTextH" />
        <Resource Component="III" Name="cBackgroundTextI" />
    </Category>
</Resources>

How can i get the following:

ONE , AAA , cBackgroundTextA

ONE , BBB , cBackgroundTextB

ONE , CCC , cBackgroundTextC

TWO , DDD , cBackgroundTextD

TWO , EEE , cBackgroundTextE

...

Body:
Try something along the line:

XElement root;

foreach(var folder in root.Children()) { //For each folder
    var folderType = folder.Attribute("type").Value;
    foreach(var file in folder.Children()) { //For each  file

        Console.WriteLine($"{folderType} AND {file}");
    }
}


问:
How to flip a byte in python?
I'm trying to decode a file that's a collection of reversed bytes.
Currently, my code reads and copies the file, but I want to edit some of the bytes before I write out the copy. After printing the file's binary in string format, it looks like:

b'r\x00\x00\x00\x06\x00P\x00\x14\x00\x10\x00\x0e\x00P\x00\x15\x00)7\xf8y(=(\xdb(\x8e\x08\x00

...and so on. I would like to flip the bytes that read out as \x** like so:

\x01 → \x10 , \x81 → \x18 , \x40 → \x04 , \xae → \xea

答:
Your question needs some clarification.  Are you swapping nibbles in the string representation or binary.  If in binary, do you want to swap nibbles on printable characters as well (e.g. for the portion ...\x00 )7 \xf8 y(=( \xdb..., the bolded characters are not in \x?? format, so should they swap nibbles?)?

If you want the swap on a string representation and only on \x?? portions, then you could use a regular expression like this:

```<code>import re
preswap = <set to your string>
swapped = re.sub(r'(\\x)(.)(.)',r'\1\3\2',preswap)
</code>```

This creates 3 sequential match elements: '\x', any single char (first), any single char (second).  When this pattern is found, it is replaced with match items 1, then 3 (the second single char), then 2 (the first single char) and the result is in the swapped variable.

Title: How to flip a byte in python?

Body:
Your question needs some clarification.  Are you swapping nibbles in the string representation or binary.  If in binary, do you want to swap nibbles on printable characters as well (e.g. for the portion ...\x00 )7 \xf8 y(=( \xdb..., the bolded characters are not in \x?? format, so should they swap nibbles?)?

If you want the swap on a string representation and only on \x?? portions, then you could use a regular expression like this:

import re
preswap = <set to your string>
swapped = re.sub(r'(\\x)(.)(.)',r'\1\3\2',preswap)

This creates 3 sequential match elements: '\x', any single char (first), any single char (second).  When this pattern is found, it is replaced with match items 1, then 3 (the second single char), then 2 (the first single char) and the result is in the swapped variable.


问:
How to use RLMBool property correctly in realm-cocoa?
There declared a Bool property in subclasses of RLMObject look like so:

```<code>@interface PhotoRealm : RLMObject

@property NSNumber<RLMBool> *isVoted;

- (id)initWithMantleModel:(PhotoModel *)photoModel;

@end
</code>```

In .m file ,I have implemented -defaultPropertyValues to init like this:

```<code>+ (NSDictionary *)defaultPropertyValues {
    return @{@"isVoted" : @NO};
}
</code>```

In somewhere, I need to do something by jungle the bool value, but the result is not expected.
Then, I write the following debug code:

```<code>   if (photoRealm.isVoted) {
        NSLog(@"isVoted");
    } else {
        NSLog(@"unVoted");
    }

    NSLog(@"%ld", (NSInteger)photoRealm.isVoted);
</code>```

log as following:

[15:32:43] -[DTCollectionViewCell setupContentWithPhotoModel:] [306 line] isVoted
  [15:32:43] -[DTCollectionViewCell setupContentWithPhotoModel:] [311 line] 4646266992

in the meantime, the snapshot of realm file as so:

I'm stuck in here.

答:
I think I has resolved it.

Actually, isVoted is NSNumber,  so the code should like this :

```<code>if ([photo.isVoted integerValue]) {
        NSLog(@"isVoted");
    } else {
        NSLog(@"unVoted");
    }

    NSLog(@"%ld", [photo.isVoted integerValue]);
</code>```

Body:
There declared a Bool property in subclasses of RLMObject look like so:

@interface PhotoRealm : RLMObject

@property NSNumber<RLMBool> *isVoted;

- (id)initWithMantleModel:(PhotoModel *)photoModel;

@end

In .m file ,I have implemented -defaultPropertyValues to init like this:

+ (NSDictionary *)defaultPropertyValues {
    return @{@"isVoted" : @NO};
}

In somewhere, I need to do something by jungle the bool value, but the result is not expected.
Then, I write the following debug code:

   if (photoRealm.isVoted) {
        NSLog(@"isVoted");
    } else {
        NSLog(@"unVoted");
    }

    NSLog(@"%ld", (NSInteger)photoRealm.isVoted);

log as following:

[15:32:43] -[DTCollectionViewCell setupContentWithPhotoModel:] [306 line] isVoted
  [15:32:43] -[DTCollectionViewCell setupContentWithPhotoModel:] [311 line] 4646266992

in the meantime, the snapshot of realm file as so:

I'm stuck in here.

Body:
I think I has resolved it.

Actually, isVoted is NSNumber,  so the code should like this :

if ([photo.isVoted integerValue]) {
        NSLog(@"isVoted");
    } else {
        NSLog(@"unVoted");
    }

    NSLog(@"%ld", [photo.isVoted integerValue]);


问:
iOS permission alert issue
I have a view that:

Creates an observer for UIApplicationDidBecomeActiveNotification with invokes a selector

Sequentially asks the user for permissions to: use the camera, location & receiving push notifications.

The view has three UIButtons with state depending on each permission state, which navigate the user to settings if permissions for anything were rejected

Tapping a button which represents a permission with rejected state navigates the user to settings

Once each alert hides, using the observer action, next alert is triggered and all button states are updated to reflect any changes

Once all permissions are granted it pushes next view with the rest of the signup/in flow.

The problem is: on some devices, when running the app from a clean state (app removed and reinstalled), permissions for location & notifications are set to rejected by default, as if the user was presented an alert that was rejected.

I couldn't pinpoint any rational issue behind this, except for leftover settings from some outdated build that don't get deleted when installing a new one. This view seems to be the only place that can possibly trigger these alerts.

Did anyone have a similar issue and can suggest anything?

答:
I would suggest you to try to check for states of location services and notification services before asking user to use it. Since if user is going to disable these the moment you ask him for permission, he will need to go to the settings and enable it there. You should try to detect if user has disabled location/notification/camera.

For camera use:

```<code>func accessToCamera(granted: @escaping (() -> Void)) {
    if UIImagePickerController.isSourceTypeAvailable(.camera) {

        let status = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeAudio)

        if status == .authorized {
            granted()
        } else if status == .denied {
            self.cameraPermissionAlert()
        } else if status == .notDetermined {

            AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { (accessAllowed) in
                if accessAllowed {
                    granted()
                } else {
                    self.cameraPermissionAlert()
                }
            })
        } else if status == .restricted {
            self.cameraPermissionAlert()
        }
    } else {
       print("Camera not available on this device")
    }
}

func cameraPermissionAlert() {
    let alert = UIAlertController(title: "Access to camera not available", message: "Please enable access to camera in order to use this feature", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "Settings", style: .default, handler: { (action) in
        if let url = URL(string: UIApplicationOpenSettingsURLString) {
            if UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            }
        }
    }))

    alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil))
    if let top = UIApplication.topViewController() { // This is extension to UIApplication that finds top view controller and displays it
        top.present(alert, animated: true, completion: nil)
        }
    }
</code>```

For remote notifications you can use something like this:
Determine on iPhone if user has enabled push notifications

And for location services:
Check if location services are enabled

In both of these cases you can detect if this is disabled or not by user and present user with alert controller that has open settings functionality.

Title: iOS permission alert issue

Body:
I would suggest you to try to check for states of location services and notification services before asking user to use it. Since if user is going to disable these the moment you ask him for permission, he will need to go to the settings and enable it there. You should try to detect if user has disabled location/notification/camera.

For camera use:

func accessToCamera(granted: @escaping (() -> Void)) {
    if UIImagePickerController.isSourceTypeAvailable(.camera) {

        let status = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeAudio)

        if status == .authorized {
            granted()
        } else if status == .denied {
            self.cameraPermissionAlert()
        } else if status == .notDetermined {

            AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { (accessAllowed) in
                if accessAllowed {
                    granted()
                } else {
                    self.cameraPermissionAlert()
                }
            })
        } else if status == .restricted {
            self.cameraPermissionAlert()
        }
    } else {
       print("Camera not available on this device")
    }
}

func cameraPermissionAlert() {
    let alert = UIAlertController(title: "Access to camera not available", message: "Please enable access to camera in order to use this feature", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "Settings", style: .default, handler: { (action) in
        if let url = URL(string: UIApplicationOpenSettingsURLString) {
            if UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            }
        }
    }))

    alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil))
    if let top = UIApplication.topViewController() { // This is extension to UIApplication that finds top view controller and displays it
        top.present(alert, animated: true, completion: nil)
        }
    }

For remote notifications you can use something like this:
Determine on iPhone if user has enabled push notifications

And for location services:
Check if location services are enabled

In both of these cases you can detect if this is disabled or not by user and present user with alert controller that has open settings functionality.


问:
Jasper strech subreport
I have Detail band in master report with two subreports

When I form report I see that left subreport more higher then right

Subreport has such structure

How to make, that if in the report there are less lines than in other, it was stretched? Actually, the ColumnFooter band was on the same level.

Subreports attributes:

```<code>Position Type: Float
Strech Type: Relatives to tallest object
Overflow Type: Strech
</code>```

答:
When left grid was with rows
Right didn't strech horizontaly

Title: Jasper strech subreport

Body:
I have Detail band in master report with two subreports

When I form report I see that left subreport more higher then right

Subreport has such structure

How to make, that if in the report there are less lines than in other, it was stretched? Actually, the ColumnFooter band was on the same level.

Subreports attributes:

Position Type: Float
Strech Type: Relatives to tallest object
Overflow Type: Strech


问:
Trying to understand extern in C
By the answer given here, I am trying to construct a working example and try to understand behavior of the extern linkage.

Here is my example:

extern.h

```<code>extern int global_counter;

int file_counter;
</code>```

extern.c

```<code>#include "extern.h"

int global_counter = 5;
</code>```

incrementor1.c

```<code>#include "extern.h"
#include <stdio.h>

void incrementor1_global()
{
    global_counter++;
    printf("From Incrementor1...\n");
    printf("Global counter is: %d\n", global_counter);
}

void incrementor1_local()
{
    file_counter++;
    printf("From Incrementor1...\n");
    printf("File counter is: %d\n", file_counter);
}
</code>```

incrementor2.c

```<code>#include "extern.h"
#include <stdio.h>

void incrementor2_global()
{
    global_counter++;
    printf("From Incrementor2...\n");
    printf("Global counter is: %d\n", global_counter);
}

void incrementor2_local()
{
    file_counter++;
    printf("From Incrementor2...\n");
    printf("File counter is: %d\n", file_counter);
}
</code>```

You can yourself put these into separate files as depicted. Here is my main.c now:

main.c

```<code>void incrementor1_global();
void incrementor1_local();

void incrementor2_global();
void incrementor2_local();

int main(char argc, char* argv[])
{
    incrementor1_global();
    incrementor2_global();

    incrementor1_local();
    incrementor2_local();
}
</code>```

Since I link .o files to my main, I am just declaring the functions and since they are extern by default, they are linked by the linker as I understood. And lastly, here is a makefile if you want to try it yourself.

```<code>CC=gcc

CFLAGS=-I.

DEPS = extern.h

OBJ = main.o extern.o incrementor1.o incrementor2.o

%.o: %.c $(DEPS)
    $(CC) -c -o $@ $< $(CFLAGS)

main: $(OBJ)
    gcc -o $@ $^ $(CFLAGS)

.PHONY: clean

clean:
    rm -f *.o
</code>```

So by the answer linked above, I think global_counter should be shared by all translation units while each should have their own copy of file_counter. But the output I get is:

```<code>From Incrementor1...
Global counter is: 6
From Incrementor2...
Global counter is: 7
From Incrementor1...
File counter is: 1
From Incrementor2...
File counter is: 2
</code>```

So, I think both incrementor have a one copy of file_counter and that is a global variable. But now I don't know how I can replicate the answer given and make them have their own copy. Any suggestions?

By the way, If I want to give a definition to file_counter in extern.h, since it is included in both incrementors I am getting multiple definitions error. This confuses me further on how could I make them have a shared copy.

答:
int file_counter is a tentative definition and is a global variable (with external linkage), as it is defined outside of any function. It is a good practice to have variable definitions in C source files, not in headers.

If you want each translation unit to have its own copy of file_counter, one way is to mark it as static and define it both in incrementor1.c and incrementor2.c. In that case, the visibility of the variable will be restricted only to the file in which it is defined.

Title: Trying to understand extern in C

Body:
By the answer given here, I am trying to construct a working example and try to understand behavior of the extern linkage.

Here is my example:

extern.h

extern int global_counter;

int file_counter;

extern.c

#include "extern.h"

int global_counter = 5;

incrementor1.c

#include "extern.h"
#include <stdio.h>

void incrementor1_global()
{
    global_counter++;
    printf("From Incrementor1...\n");
    printf("Global counter is: %d\n", global_counter);
}

void incrementor1_local()
{
    file_counter++;
    printf("From Incrementor1...\n");
    printf("File counter is: %d\n", file_counter);
}

incrementor2.c

#include "extern.h"
#include <stdio.h>

void incrementor2_global()
{
    global_counter++;
    printf("From Incrementor2...\n");
    printf("Global counter is: %d\n", global_counter);
}

void incrementor2_local()
{
    file_counter++;
    printf("From Incrementor2...\n");
    printf("File counter is: %d\n", file_counter);
}

You can yourself put these into separate files as depicted. Here is my main.c now:

main.c

void incrementor1_global();
void incrementor1_local();

void incrementor2_global();
void incrementor2_local();

int main(char argc, char* argv[])
{
    incrementor1_global();
    incrementor2_global();

    incrementor1_local();
    incrementor2_local();
}

Since I link .o files to my main, I am just declaring the functions and since they are extern by default, they are linked by the linker as I understood. And lastly, here is a makefile if you want to try it yourself.

CC=gcc

CFLAGS=-I.

DEPS = extern.h

OBJ = main.o extern.o incrementor1.o incrementor2.o

%.o: %.c $(DEPS)
    $(CC) -c -o $@ $< $(CFLAGS)

main: $(OBJ)
    gcc -o $@ $^ $(CFLAGS)

.PHONY: clean

clean:
    rm -f *.o

So by the answer linked above, I think global_counter should be shared by all translation units while each should have their own copy of file_counter. But the output I get is:

From Incrementor1...
Global counter is: 6
From Incrementor2...
Global counter is: 7
From Incrementor1...
File counter is: 1
From Incrementor2...
File counter is: 2

So, I think both incrementor have a one copy of file_counter and that is a global variable. But now I don't know how I can replicate the answer given and make them have their own copy. Any suggestions?

By the way, If I want to give a definition to file_counter in extern.h, since it is included in both incrementors I am getting multiple definitions error. This confuses me further on how could I make them have a shared copy.


问:
Angular2 & RxJS multiple HTTP calls - display as soon as first response returned
I'm trying to use RxJS and Angular2 to build a search field. I have a simple text input field that I'm observing for valueChanges.

I then use the inputted value to call a first REST service which returns a search results object that contains a list of customers.

Then for each customer returned I call a second REST service to get the customer details and store the returned details in the customer object.

My screen then loops over the customers to display them.

But I have two problems that I can't seem to figure out:

I want the results to appear as soon as the first service returns
and then update the screen when the second service returns but at
the moment nothing displays until all the service calls are
completed.

When someone changes the input field I want the results to disappear
immediately but for some reason that is no happening and I can't
figure out why e.g. if I enter in a search term that returns no
matches, the results from the previous search remain on screen.

My code looks like:

this.customers = this.term.valueChanges
            .filter(term => {
                return term !== null;
            })
            .switchMap(term => {
                return this.customerService.search(term)
            })
            .map(searchResults => {
                return searchResults.customers;
            })
            .flatMap(customers => {
                if (customers.length > 0) {
                    // this.customers = customers;
                    return Observable.forkJoin(
                        customers.map((customer: Customer) => {
                            return this.customerDetailService.getDetails(customer)
                                .map((details: any) => {
                                    customer.details = details;
                                    return customer;
                                });
                        }));
                }
                return customers;
            });
```

<p>And the screen looks like:</p>

<pre class="lang-html prettyprint-override"><code><div *ngIf="customers|async; let customers">

    <ul>
        <li *ngFor="let customer of customers">

           {{customer.name}}
           {{customer.details.age}}
        </li>
    </ul>
</div>
</code>```

Any help would be appreciated.

Thanks,
Kevin.

答:
What about this? (look at my comment on your question for explanation behind)</p>

```<code>this.customers = new Rx.BehaviourSubject([]);

this.term.valueChanges
    .filter(term =>  term !== null)
    .do(() => this.customers.onNext([]))
    .switchMap(term => this.customerService.search(term))
    .map(searchResults => searchResults.customers)
    .do((customers) => this.customers.onNext(customers))
    .switchMap(customers => {
        if (customers.length > 0) {
            // this.customers = customers;
            return Observable.forkJoin(
                customers.map((customer: Customer) => {
                    return this.customerDetailService.getDetails(customer)
                        .map((details: any) => {
                            customer.details = details;
                            return customer;
                        });
                }));
        }
        return customers;
    })
    .subscribe(
        (customers) => this.customers.onNext(customers),
        (err) => this.customers.onError(err),
        () => this.customers.onComplete();
    );
</code>```

Body:
I'm trying to use RxJS and Angular2 to build a search field. I have a simple text input field that I'm observing for valueChanges.

I then use the inputted value to call a first REST service which returns a search results object that contains a list of customers.

Then for each customer returned I call a second REST service to get the customer details and store the returned details in the customer object.

My screen then loops over the customers to display them.

But I have two problems that I can't seem to figure out:

I want the results to appear as soon as the first service returns
and then update the screen when the second service returns but at
the moment nothing displays until all the service calls are
completed.

When someone changes the input field I want the results to disappear
immediately but for some reason that is no happening and I can't
figure out why e.g. if I enter in a search term that returns no
matches, the results from the previous search remain on screen.

My code looks like:

this.customers = this.term.valueChanges
            .filter(term => {
                return term !== null;
            })
            .switchMap(term => {
                return this.customerService.search(term)
            })
            .map(searchResults => {
                return searchResults.customers;
            })
            .flatMap(customers => {
                if (customers.length > 0) {
                    // this.customers = customers;
                    return Observable.forkJoin(
                        customers.map((customer: Customer) => {
                            return this.customerDetailService.getDetails(customer)
                                .map((details: any) => {
                                    customer.details = details;
                                    return customer;
                                });
                        }));
                }
                return customers;
            });

And the screen looks like:

           {{customer.name}}
           {{customer.details.age}}

Any help would be appreciated.

Thanks,
Kevin.

Body:
What about this? (look at my comment on your question for explanation behind)

this.customers = new Rx.BehaviourSubject([]);

this.term.valueChanges
    .filter(term =>  term !== null)
    .do(() => this.customers.onNext([]))
    .switchMap(term => this.customerService.search(term))
    .map(searchResults => searchResults.customers)
    .do((customers) => this.customers.onNext(customers))
    .switchMap(customers => {
        if (customers.length > 0) {
            // this.customers = customers;
            return Observable.forkJoin(
                customers.map((customer: Customer) => {
                    return this.customerDetailService.getDetails(customer)
                        .map((details: any) => {
                            customer.details = details;
                            return customer;
                        });
                }));
        }
        return customers;
    })
    .subscribe(
        (customers) => this.customers.onNext(customers),
        (err) => this.customers.onError(err),
        () => this.customers.onComplete();
    );


问:
use google translate API to convert English into text Arabic text in java
Following code i user to convert my string into Arabic

```<code>Translate.setHttpReferrer("http://localhost:8080/crmweb/");
    String arabicString = Translate.execute(englishString, Language.ENGLISH, Language.ARABIC);

    if(arabicString != null){
     System.out.println("This method return as arabic string ==============> ");
     return arabicString;
    }
</code>```

This code work when i run application in main method , but when i tries to run it in web application it gives an error like -- java.lang.NoClassDefFoundError: com/google/api/translate/Translate

答:
The Google Translate API JARs need to be in the WEB-INF/lib directory of the web application.  This is true whether you're building and deploying a WAR file, or simply using a directory structure on disk.

This process is more basically known as "putting the dependency JARs in the webapp's classpath."

ContentLicense: CC BY-SA 2.5

Body:
Following code i user to convert my string into Arabic

Translate.setHttpReferrer("http://localhost:8080/crmweb/");
    String arabicString = Translate.execute(englishString, Language.ENGLISH, Language.ARABIC);

    if(arabicString != null){
     System.out.println("This method return as arabic string ==============> ");
     return arabicString;
    }

This code work when i run application in main method , but when i tries to run it in web application it gives an error like -- java.lang.NoClassDefFoundError: com/google/api/translate/Translate


问:
Connect using SSH to a server through another server in Java
Currently we have 2 Unix servers A and B. To connect to B server, initially we used to first connect server A and then we will login to JumpHost B using SSH  at the Unix prompt.

Now I am working on a simple tool in Java which has to download the files from server B.

In the sample code I got from the link below , if I pass the host details of B server, the host connection is failing.

When I pass the host details of A server the connection is success and able to download the files present in server A.

I need pointers on how to connect to server A and then server B through Java and download files from server B.

SSH Connection Java

答:
What you're actually looking for is what is called in Overthere a Jumpstation.

You want to connect like this: client -> Server A -> Server B

Using overthere you can setup that connection as follows:

```<code>ConnectionOptions jumpStationOptions = new ConnectionOptions();
jumpStationOptions.set(ConnectionOptions.ADDRESS, "Server A");
jumpStationOptions.set(ConnectionOptions.USERNAME, "Username A");
jumpStationOptions.set(ConnectionOptions.PASSWORD, "Password A");
jumpStationOptions.set(ConnectionOptions.PROTOCOL, "ssh-jumpstation");
jumpStationOptions.set(ConnectionOptions.OPERATING_SYSTEM, OperatingSystemFamily.UNIX);
ConnectionOptions options = new ConnectionOptions();
options.set(ConnectionOptions.PASSWORD, "Password B");
options.set(ConnectionOptions.USERNAME, "Username B");
options.set(ConnectionOptions.ADDRESS, "Server B");
options.set(ConnectionOptions.OPERATING_SYSTEM, OperatingSystemFamily.UNIX);
options.set(SshConnectionBuilder.CONNECTION_TYPE, SshConnectionType.SCP);
options.set(ConnectionOptions.JUMPSTATION, jumpStationOptions);
OverthereConnection connection = Overthere.getConnection(SshConnectionBuilder.SSH_PROTOCOL, options);
</code>```

This setup will configure "Server A" to be used as a jumpstation to reach "Server B".

Body:
What you're actually looking for is what is called in Overthere a Jumpstation.

You want to connect like this: client -> Server A -> Server B

Using overthere you can setup that connection as follows:

ConnectionOptions jumpStationOptions = new ConnectionOptions();
jumpStationOptions.set(ConnectionOptions.ADDRESS, "Server A");
jumpStationOptions.set(ConnectionOptions.USERNAME, "Username A");
jumpStationOptions.set(ConnectionOptions.PASSWORD, "Password A");
jumpStationOptions.set(ConnectionOptions.PROTOCOL, "ssh-jumpstation");
jumpStationOptions.set(ConnectionOptions.OPERATING_SYSTEM, OperatingSystemFamily.UNIX);
ConnectionOptions options = new ConnectionOptions();
options.set(ConnectionOptions.PASSWORD, "Password B");
options.set(ConnectionOptions.USERNAME, "Username B");
options.set(ConnectionOptions.ADDRESS, "Server B");
options.set(ConnectionOptions.OPERATING_SYSTEM, OperatingSystemFamily.UNIX);
options.set(SshConnectionBuilder.CONNECTION_TYPE, SshConnectionType.SCP);
options.set(ConnectionOptions.JUMPSTATION, jumpStationOptions);
OverthereConnection connection = Overthere.getConnection(SshConnectionBuilder.SSH_PROTOCOL, options);

This setup will configure "Server A" to be used as a jumpstation to reach "Server B".


问:
Can I show committer's email in bash prompt?
This is my actual prompt:

```<code>username@ current-folder (current-branch) $
</code>```

Could I change username with committer's username? I just want to be sure about the committer data. This because I've different account, a global .gitconfig and many local ./git/config files.

Sometimes I've been committed with wrong email. Is it possible to show committer's email in prompt so then I'll never commit with wrong data?

答:
You can fetch the current committer email with

```<code>git config user.email
</code>```

So just change your prompt to say something like

PS1='$(git config user.email)@ \w$(__git_ps1)\$ '
#    ^~~~~~~~~~~~~~~~~~~~~~~~
```

Body:
This is my actual prompt:

username@ current-folder (current-branch) $

Could I change username with committer's username? I just want to be sure about the committer data. This because I've different account, a global .gitconfig and many local ./git/config files.

Sometimes I've been committed with wrong email. Is it possible to show committer's email in prompt so then I'll never commit with wrong data?

Body:
You can fetch the current committer email with

git config user.email

So just change your prompt to say something like

PS1='$(git config user.email)@ \w$(__git_ps1)\$ '
#    ^~~~~~~~~~~~~~~~~~~~~~~~


问:
Splicing Buffer vs Reading into a Buffer
Hoping someone can help explain why this is incorrect.

From my understanding fs.read reads into a buffer whereas readFile returns a buffer. I assume there's some in-equivalency just not sure where or why.

The end result is I'm hoping for is mimicking the fs.read operation but with an already pre-loaded buffer.

```<code>const fs = require('fs')
const file = 'file.bin'
const crypto = require('crypto')
const assert = require('assert')

let start = 10
let length = 20

let data = fs.readFileSync(file)
let md5sum = crypto.createHash('md5')
md5sum.update(data.slice(start, length))

let fd = fs.openSync(file, 'r')
let data2 = new Buffer(length)
let md5sum2 = crypto.createHash('md5')
fs.readSync(fd, data2, 0, length, start)
md5sum2.update(data2)

assert.equal(md5sum.digest('hex'), md5sum2.digest('hex'))
</code>```

答:
Seems like I found the error in that:

```<code>md5sum.update(data.slice(start, length))
</code>```

should be:

```<code>md5sum.update(data.slice(start, start + length))
</code>```

Looks like end should be the end element not the length.

Body:
Hoping someone can help explain why this is incorrect.

From my understanding fs.read reads into a buffer whereas readFile returns a buffer. I assume there's some in-equivalency just not sure where or why.

The end result is I'm hoping for is mimicking the fs.read operation but with an already pre-loaded buffer.

const fs = require('fs')
const file = 'file.bin'
const crypto = require('crypto')
const assert = require('assert')

let start = 10
let length = 20

let data = fs.readFileSync(file)
let md5sum = crypto.createHash('md5')
md5sum.update(data.slice(start, length))

let fd = fs.openSync(file, 'r')
let data2 = new Buffer(length)
let md5sum2 = crypto.createHash('md5')
fs.readSync(fd, data2, 0, length, start)
md5sum2.update(data2)

assert.equal(md5sum.digest('hex'), md5sum2.digest('hex'))

Body:
Seems like I found the error in that:

md5sum.update(data.slice(start, length))

should be:

md5sum.update(data.slice(start, start + length))

Looks like end should be the end element not the length.


问:
Is it correct to attach code through volume in kubernetes?
In order to do ease development in Docker, the code is attached to the containers through volumes. In that way, there is no need to rebuild the images each time the code is changed.

So, is it correct to think to use the same idea in Kubernetes?

PS: I know that the concepts PersistentVolume and PersistentVolumeClaim allow to attach volume, but they are intended for data.

Update

To ease the development, I do need to use the volume for both code and data. This will avoid me to rebuild the images at each change of code.

Below this is what I am trying to do in minikube:

the deployment

```<code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: php-hostpath
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: php-hostpath
    spec:
      containers:
      - name: php-hostpath
        image: php:7.0-apache
        ports:
        - containerPort: 80
        volumeMounts:
          - name: vol-php-hostpath
            mountPath: /var/www/html
      volumes:
      - name: vol-php-hostpath
        hostPath:
          path: '/home/amine/DockerProjects/gcloud-kubernetes/application/06-hostPath-volume-example-minikube/src/'
</code>```

the service

```<code>apiVersion: v1
kind: Service
metadata:
  name: php-hostpath
  namespace: default
  labels:
    app: php-hostpath
spec:
  selector:
    app: php-hostpath
  ports:
  - port: 80
    targetPort: 80
  type: "LoadBalancer"
</code>```

The service and the deployment are well created in minikube:

```<code>$ kubectl get pods -l app=php-hostpath
NAME                            READY     STATUS    RESTARTS   AGE
php-hostpath-3796606162-bt94w   1/1       Running   0          19m

$ kubectl get service -l app=php-hostpath
NAME           CLUSTER-IP   EXTERNAL-IP   PORT(S)        AGE
php-hostpath   10.0.0.110   <pending>     80:30135/TCP   27m
</code>```

The folder src and the file src/index.php are also well created.

```<code><?php
echo "This is my first docker project";
</code>```

Now I want to check that every thing is running:

```<code>$ kubectl exec -ti php-hostpath-3796606162-bt94w bash
root@php-hostpath-3796606162-bt94w:/var/www/html# ls
root@php-hostpath-3796606162-bt94w:/var/www/html# exit
exit
</code>```

The folder src and the file index.php are not in /var/www/html!

Have I missed something?

PS: if I were in production env, I will not put my code in a volume.
Thanks,

答:
In my honest opinion, you can do it, but you shouldn't. One of the features of using containers is that you can have artifacts (containers) with always the same behaviour. A new version of your code should generate a new container. This way you can be sure, when testing, that any new issue detected will be directly related to the new code.

An hybrid approach (that I don't like either but I think is better) is to create a docker that downloads your code (selecting the correct release with envs) and runs it.

Using hostPaths is not a bad idea but can be a mess, if you have a not-so-small cluster.
Of course you can use PV, after all your code is data. You can use a distributed storage filesystem like NFS to do it.

Body:
In order to do ease development in Docker, the code is attached to the containers through volumes. In that way, there is no need to rebuild the images each time the code is changed.

So, is it correct to think to use the same idea in Kubernetes?

PS: I know that the concepts PersistentVolume and PersistentVolumeClaim allow to attach volume, but they are intended for data.

Update

To ease the development, I do need to use the volume for both code and data. This will avoid me to rebuild the images at each change of code.

Below this is what I am trying to do in minikube:

the deployment

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: php-hostpath
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: php-hostpath
    spec:
      containers:
      - name: php-hostpath
        image: php:7.0-apache
        ports:
        - containerPort: 80
        volumeMounts:
          - name: vol-php-hostpath
            mountPath: /var/www/html
      volumes:
      - name: vol-php-hostpath
        hostPath:
          path: '/home/amine/DockerProjects/gcloud-kubernetes/application/06-hostPath-volume-example-minikube/src/'

the service

apiVersion: v1
kind: Service
metadata:
  name: php-hostpath
  namespace: default
  labels:
    app: php-hostpath
spec:
  selector:
    app: php-hostpath
  ports:
  - port: 80
    targetPort: 80
  type: "LoadBalancer"

The service and the deployment are well created in minikube:

$ kubectl get pods -l app=php-hostpath
NAME                            READY     STATUS    RESTARTS   AGE
php-hostpath-3796606162-bt94w   1/1       Running   0          19m

$ kubectl get service -l app=php-hostpath
NAME           CLUSTER-IP   EXTERNAL-IP   PORT(S)        AGE
php-hostpath   10.0.0.110   <pending>     80:30135/TCP   27m

The folder src and the file src/index.php are also well created.

<?php
echo "This is my first docker project";

Now I want to check that every thing is running:

$ kubectl exec -ti php-hostpath-3796606162-bt94w bash
root@php-hostpath-3796606162-bt94w:/var/www/html# ls
root@php-hostpath-3796606162-bt94w:/var/www/html# exit
exit

The folder src and the file index.php are not in /var/www/html!

Have I missed something?

PS: if I were in production env, I will not put my code in a volume.
Thanks,


问:
Node pointer to current Node during mutile function call
I have declared a global pointer ptr and want that it should point to current node during different function call.

This is a sample code where I am creating a new node in fun1 and inserting in link list. In func2 I want to update the other members of newNode in linklist with a different value.

Currently I am traversing the link list to get the current Node or last Node which I dont want since during insertion of new Records already we have to traverse to reach to last Node thus storing the address of last Node.

But by doing the below I am not getting the proper values. Kindly someone suggest where I went wrong.

I am doing like this :

```<code>#include<stdio.h>
#include <stdlib.h>
struct Node
{
    int data1;
    int data2;
    struct Node* next;
};
struct Node* head=NULL;
struct Node* ptr =NULL;                    /* Global pointer  */
void insertNode(struct Node ** , struct Node* );
void fun1();
void fun2();

void fun1()
{
    struct Node* ptr1 =NULL;
    ptr1 = (struct Node*)malloc(sizeof(struct Node*));
    ptr1->data1=1; /* intilaizing with some values */
    insertNode(&head,ptr1);
}

void fun2()
{
    /* Updating the current Node in the linklist with new value . */
    ptr->data2=2;

}

void insertNode(struct Node ** head, struct Node* NewRec)
{

if(*head ==NULL )
{
    NewRec->next = *head;
   *head = NewRec;
    ptr=*head;
}
else
{
/* Locate the node before the point of insertion */
    struct Node* current=NULL;
    current = *head;
    while (current->next!=NULL )
    {
        current = current->next;
    }
    NewRec->next = current->next;
    current->next = NewRec;
    ptr=current->next;

    }
}
int main ()
{
    fun1();
    fun2();
    while(head!=NULL)
    {
        printf("%d", head->data1);
        printf("%d",head->data2);
        head=head->next;
    }
    return 0;

}
</code>```

答:
You made a classic mistake.

This is wrong:

```<code>ptr1 = (struct Node*)malloc(sizeof(struct Node*));
</code>```

The allocated space here is sizeof(struct Node*) which is the size of a pointer (usually 4 or 8 bytes depending on the platform). But you need to allocate space for the whole struct Node structure, whose size is sizeof(struct Node).

So you simply need this:

```<code>ptr1 = (struct Node*)malloc(sizeof(struct Node));
</code>```

BTW: in C you don't cast the return value of malloc so you actually should write this:

```<code>ptr1 = malloc(sizeof(struct Node));
</code>```

Body:
I have declared a global pointer ptr and want that it should point to current node during different function call.

This is a sample code where I am creating a new node in fun1 and inserting in link list. In func2 I want to update the other members of newNode in linklist with a different value.

Currently I am traversing the link list to get the current Node or last Node which I dont want since during insertion of new Records already we have to traverse to reach to last Node thus storing the address of last Node.

But by doing the below I am not getting the proper values. Kindly someone suggest where I went wrong.

I am doing like this :

#include<stdio.h>
#include <stdlib.h>
struct Node
{
    int data1;
    int data2;
    struct Node* next;
};
struct Node* head=NULL;
struct Node* ptr =NULL;                    /* Global pointer  */
void insertNode(struct Node ** , struct Node* );
void fun1();
void fun2();

void fun1()
{
    struct Node* ptr1 =NULL;
    ptr1 = (struct Node*)malloc(sizeof(struct Node*));
    ptr1->data1=1; /* intilaizing with some values */
    insertNode(&head,ptr1);
}

void fun2()
{
    /* Updating the current Node in the linklist with new value . */
    ptr->data2=2;

}

void insertNode(struct Node ** head, struct Node* NewRec)
{

if(*head ==NULL )
{
    NewRec->next = *head;
   *head = NewRec;
    ptr=*head;
}
else
{
/* Locate the node before the point of insertion */
    struct Node* current=NULL;
    current = *head;
    while (current->next!=NULL )
    {
        current = current->next;
    }
    NewRec->next = current->next;
    current->next = NewRec;
    ptr=current->next;

    }
}
int main ()
{
    fun1();
    fun2();
    while(head!=NULL)
    {
        printf("%d", head->data1);
        printf("%d",head->data2);
        head=head->next;
    }
    return 0;

}

Body:
You made a classic mistake.

This is wrong:

ptr1 = (struct Node*)malloc(sizeof(struct Node*));

The allocated space here is sizeof(struct Node*) which is the size of a pointer (usually 4 or 8 bytes depending on the platform). But you need to allocate space for the whole struct Node structure, whose size is sizeof(struct Node).

So you simply need this:

ptr1 = (struct Node*)malloc(sizeof(struct Node));

BTW: in C you don't cast the return value of malloc so you actually should write this:

ptr1 = malloc(sizeof(struct Node));


问:
Get Text from SVG selenium java
I am uable to getText from Text tag in SVG. I am Attaching HTML

```<code><svg width="553" height="200" style="overflow: hidden;" aria-label="A chart.">
     <defs id="defs">
     <rect x="0" y="0" width="553" height="200" stroke="none" stroke-width="0" fill="#ffffff">
     <g>
         <text text-anchor="start" x="77" y="22.85" font-family="Arial" font-size="11" font-weight="bold" stroke="none" stroke-width="0" fill="#000000">Clustering done on Mar 30, 2017 11:13 AM</text>
         <rect x="77" y="13.5" width="400" height="11" stroke="none" stroke-width="0" fill-opacity="0" fill="#ffffff">
     </g>
</code>```

The get I want to get is Clustering done on Mar 30, 2017 11:13 AM

答:
Try below:</p>

```<code>driver.findElement(By.cssSelector("#divClusters svg > g > text")).getText();
</code>```

Title: Get Text from SVG selenium java

Body:
I am uable to getText from Text tag in SVG. I am Attaching HTML

<svg width="553" height="200" style="overflow: hidden;" aria-label="A chart.">
     <defs id="defs">
     <rect x="0" y="0" width="553" height="200" stroke="none" stroke-width="0" fill="#ffffff">
     <g>
         <text text-anchor="start" x="77" y="22.85" font-family="Arial" font-size="11" font-weight="bold" stroke="none" stroke-width="0" fill="#000000">Clustering done on Mar 30, 2017 11:13 AM</text>
         <rect x="77" y="13.5" width="400" height="11" stroke="none" stroke-width="0" fill-opacity="0" fill="#ffffff">
     </g>

The get I want to get is Clustering done on Mar 30, 2017 11:13 AM

Body:
Try below:

driver.findElement(By.cssSelector("#divClusters svg > g > text")).getText();


问:
not able to make TextView as focusable
hi im using 3 text views ..i have made them as clickable and i have written action part for those ..but theyr not focussing ...even i have set android:focusable to true  ..please help </p>

答: Are you using an image as the background of the button. if so the focus will not appear on button.</p>

Title: not able to make TextView as focusable


问:
HTML Send selected option to PHP via Ajax on same page
What I want to acheive:
I have a HTML/PHP page where I display the home page of the website. I have a highscore section on this page. The data for the highscore page is retrived from a database. There is a Select box where you can choose how the highscores are sorted.

The highscore section on the page

I want to be able to select an option from the dropdown. When an option is selected, the way that the data is displayed changes dynamically, without the page refreshing.

Here is the code on the home.php page (Where the highscore section is)

```<code><div class="third third-center">
            <h2>Highscores</h2>
            <div class="sortby">
                <form id="" method="post" action="home.php">
                    <select id="selectForm" name="sort">
                      <option value="score ASC">Score Ascending</option>
                      <option value="score DESC">Score Descending</option>
                      <option value="userName ASC">Name Ascending</option>
                      <option value="userName DESC">Name Descending</option>
                    </select>
                </form>
            </div>
            <div class="inner">
                <table>
                    <tr>
                        <th style="font-size: 20px">Position</th>
                        <th style="font-size: 20px">Name</th>
                        <th style="font-size: 20px">Score</th>
                    </tr>
                    <?php
                        $i = 0;

                        $choice = "score ASC";

                        $search = mysqli_query($connect, "SELECT * FROM accounts ORDER BY ".$choice."") or die(mysqli_error($connect));

                        while($row = mysqli_fetch_array($search)){
                            $i++;
                            echo "<tr>";
                            echo "<th>" . $i . "</th>";
                            echo "<th>" . $row['userName'] . "</th>";
                            echo "<th>" . $row['score'] . "</th>";
                            echo "</tr>";
                        }
                    ?>
                </table>
            </div>
        </div>
</code>```

I am using the Mysqli_Query to get all the data from the database. I am passing in a variable in place of the ORDER BY so that I can change the way the data is retrieved.

I know I can use Ajax to get the data, but Im not sure how to do it, I have looked at many other questions posted on this forum.

Any help would be greatly appreciated!

答:
There are couple of changes to be done by you, first you need to change the selection box code such that you need to write an on change function  and read the value in the javascript and then execute your AJAX call. Second is after the ajax call get the response from the server you need to do a DOM manipulation and populate the value in your desired format.

For example

```<code>$(document).on("change", "#select_box_id", function(){
  //your ajax call here based on the value
});
</code>```

I don't know whether you use jquery, if not import the library in your file and use it, which will make your life simpler

Look at this for basic AJAX http://api.jquery.com/jquery.ajax/

Body:
What I want to acheive:
I have a HTML/PHP page where I display the home page of the website. I have a highscore section on this page. The data for the highscore page is retrived from a database. There is a Select box where you can choose how the highscores are sorted.

The highscore section on the page

I want to be able to select an option from the dropdown. When an option is selected, the way that the data is displayed changes dynamically, without the page refreshing.

Here is the code on the home.php page (Where the highscore section is)

Highscores

                <form id="" method="post" action="home.php">
                    <select id="selectForm" name="sort">
                      <option value="score ASC">Score Ascending</option>
                      <option value="score DESC">Score Descending</option>
                      <option value="userName ASC">Name Ascending</option>
                      <option value="userName DESC">Name Descending</option>
                    </select>
                </form>

                        Position
                        Name
                        Score

                    <?php
                        $i = 0;

                        $choice = "score ASC";

                        $search = mysqli_query($connect, "SELECT * FROM accounts ORDER BY ".$choice."") or die(mysqli_error($connect));

                        while($row = mysqli_fetch_array($search)){
                            $i++;
                            echo "
";
                            echo "" . $i . "	";
                            echo "" . $row['userName'] . "	";
                            echo "" . $row['score'] . "	";
                            echo "
";
                        }
                    ?>

I am using the Mysqli_Query to get all the data from the database. I am passing in a variable in place of the ORDER BY so that I can change the way the data is retrieved.

I know I can use Ajax to get the data, but Im not sure how to do it, I have looked at many other questions posted on this forum.

Any help would be greatly appreciated!

Body:
There are couple of changes to be done by you, first you need to change the selection box code such that you need to write an on change function  and read the value in the javascript and then execute your AJAX call. Second is after the ajax call get the response from the server you need to do a DOM manipulation and populate the value in your desired format.

For example

$(document).on("change", "#select_box_id", function(){
  //your ajax call here based on the value
});

I don't know whether you use jquery, if not import the library in your file and use it, which will make your life simpler

Look at this for basic AJAX http://api.jquery.com/jquery.ajax/


问:
Visual Studio 2015 “non-standard syntax; use '&' to create pointer for member”
While creating thread using CreateThread() in Win32 Application , I am getting this error .
In CreateThread(NULL,0,pSample->Resize(),NULL,0,NULL);  It shows error in function calling .

I do have several files as :

Main.cpp

```<code>WinMain()
 {
   //Create sample
    return Win32Appliaction::Run(&sample);
  }
</code>```

Win32Application.cpp

```<code>int Win32Application::Run(DXSample* pSample)
  {
     //Create Window
     pSample->Init();
     pSample->Render();
     CreateThread(NULL,0,pSample->Resize,NULL,0,NULL);//error occurs
     pSample->Destroy();
  }
</code>```

DXSample.h

```<code>class DXSample
   {
     public:
           virtual void Init() =0; //and rest all functions
   };
</code>```

HelloTexture.h

```<code> class HelloTexture:public DXSample
   {
       public :
             virtual void Init();//all other functions similarly
    }
</code>```

HelloTexture.cpp

```<code>void Hellotexture::Init()
 { //code
  }
 void Hellotexture::Resize()
 {
    //code
  }
</code>```

答:
You are calling the pSample->Resize() function, passing the returned value to the CreateFunction as the function to run.

If you want the Resize function to be run in its own thread there are two things you need to do:

Pass a pointer to the function instead, e.g. &HelloTexture::Resize.

Make the function static.

The first point is about passing a pointer to the function itself to CreateThread, who will create the thread and call the function from the new thread.

The second point is because non-static member function needs an object, an instance of the class to be called on.

There are also another problem with the code you have. Remember that threads are running parallel to each other. If you create a thread it will run independently from other threads. That means the object you use, and all its data, must be kept alive until the end of the thread.

I'm bringing this up because you seemingly want to create the thread, and then immediately call pSample->Destroy() which is like pulling the rug out from under some other persons feet.

Do you really want to create a thread here?

Body:
While creating thread using CreateThread() in Win32 Application , I am getting this error .
In CreateThread(NULL,0,pSample->Resize(),NULL,0,NULL);  It shows error in function calling .

I do have several files as :

Main.cpp

WinMain()
 {
   //Create sample
    return Win32Appliaction::Run(&sample);
  }

Win32Application.cpp

int Win32Application::Run(DXSample* pSample)
  {
     //Create Window
     pSample->Init();
     pSample->Render();
     CreateThread(NULL,0,pSample->Resize,NULL,0,NULL);//error occurs
     pSample->Destroy();
  }

DXSample.h

class DXSample
   {
     public:
           virtual void Init() =0; //and rest all functions
   };

HelloTexture.h

 class HelloTexture:public DXSample
   {
       public :
             virtual void Init();//all other functions similarly
    }

HelloTexture.cpp

void Hellotexture::Init()
 { //code
  }
 void Hellotexture::Resize()
 {
    //code
  }


问:
Letter-spacing on selectbox option not working
I tried to add some letter-spacing to the options of a selectbox. It seems that this do not work. To test if i touch the right element I added some color to the option.

letter-spacing

select {
  letter-spacing:10px;
}

option {
  letter-spacing: 10px;
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select class="form-control" name="select" id="myselect">
   <option value="105">Option 1</option>
   <option value="106">Option 2</option>
   <option value="107">Option 3</option>
</select></code>```

答:
If you want to style dropdown selection, you will have to use some js lib to do so... There are many browsers, that complety ignore dropdown styling (in addition - mobile browsers will pop up the dropdown list with system visuals - fonts, sizes, color and so on)

Check out something like this http://www.jqueryscript.net/demo/Easy-jQuery-Based-Drop-Down-Builder-EasyDropDown/

I personally don't recommend trying to style native <select><option> for the sake of visual integrity

Body:
I tried to add some letter-spacing to the options of a selectbox. It seems that this do not work. To test if i touch the right element I added some color to the option.

letter-spacing

select {
  letter-spacing:10px;
}

option {
  letter-spacing: 10px;
  color: red;
}

<select class="form-control" name="select" id="myselect">
   <option value="105">Option 1</option>
   <option value="106">Option 2</option>
   <option value="107">Option 3</option>
</select>


问:
How do I find cosine similarity between two text documents using Java?
I need to compare a large number of tweets containing a particular hashtag to display the tweet which has the highest content in it. For the same, I need to find pair-wise cosine similarity between each one of them and display the tweet with highest pair-wise cosine similarity as output. I've been reading a lot about vector space Models, tf-idf vectors, word2vec/doc2vec etc. but couldn't grasp anything completely. I need to implement the same using Java. Is there any alternative to scikit-learn's TfidfVectorizer or NLTK's synsets?</p>

答:
You can use Apache Mahout for vectorizing all text documents residing in a folder.

The first step is to create sequence files and then create vectors from these sequence files.

This page describes how to do it. Then you can use the RowSimilarityJob class to compute the cosine similarities.


问:
Is it possible to accumulate values with increment in a Django template?
I would like to know if there is any way to sum values in a variable in a Django template using {% for obj in objects %}. Something like this:

```<code>for student in students:
         notes += student.note
</code>```

Using the mathfilters or something similar to make the sum

Thanks!

答:
If you want sum values in template you can use with tag
please read this link for more information
https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#with

Body:
I would like to know if there is any way to sum values in a variable in a Django template using {% for obj in objects %}. Something like this:

for student in students:
         notes += student.note

Using the mathfilters or something similar to make the sum

Thanks!


问:
LeafletJS - Default selection of layers
I'm using leaflet-groupedlayercontrol to add my grouped layers to the map and I have a problem:

All the layers are deselected, but I want to select all by default. I am using checkboxes, not radio buttons.

```<code>var groupedOverlays = {
    "Select": {}
};

groupedOverlays["Select"]["Group 1"] = groups[0];
groupedOverlays["Select"]["Group 2"] = groups[1];
groupedOverlays["Select"]["Group 3"] = groups[2];

// Use the custom grouped layer control, not "L.control.layers"
L.control.groupedLayers(null, groupedOverlays, {collapsed:false}).addTo(map);
</code>```

I tried to select them with JS, but didn't worked.

If you know a solution for LeafletJS, but not for that particular plugin, it's ok too.

答:
Whether a Leaflet layer is ""selected"" or not in the built-in L.Control.Layers depends on whether the layer is added to the map or not.

e.g. this will display a L.Control.Layers with the checkbox off:

```<code>L.control.layers({}, {
    Foo: L.marker([0,0])
}).addTo(map)
</code>```

...while this will display it with the checkbox on:

```<code>L.control.layers({}, {
    Foo: L.marker([0,0]).addTo(map)
}).addTo(map)
</code>```

I expect the behaviour of the GroupedLayers control to be similar. Just double-check whether you add the layers to the map or not. Also notice that the checkboxes' state updates whenever layers are added/removed to/from the map by any means, at any time.

Title: LeafletJS - Default selection of layers

Body:
I'm using leaflet-groupedlayercontrol to add my grouped layers to the map and I have a problem:

All the layers are deselected, but I want to select all by default. I am using checkboxes, not radio buttons.

var groupedOverlays = {
    "Select": {}
};

groupedOverlays["Select"]["Group 1"] = groups[0];
groupedOverlays["Select"]["Group 2"] = groups[1];
groupedOverlays["Select"]["Group 3"] = groups[2];

// Use the custom grouped layer control, not "L.control.layers"
L.control.groupedLayers(null, groupedOverlays, {collapsed:false}).addTo(map);

I tried to select them with JS, but didn't worked.

If you know a solution for LeafletJS, but not for that particular plugin, it's ok too.

Body:
Whether a Leaflet layer is ""selected"" or not in the built-in L.Control.Layers depends on whether the layer is added to the map or not.

e.g. this will display a L.Control.Layers with the checkbox off:

L.control.layers({}, {
    Foo: L.marker([0,0])
}).addTo(map)

...while this will display it with the checkbox on:

L.control.layers({}, {
    Foo: L.marker([0,0]).addTo(map)
}).addTo(map)

I expect the behaviour of the GroupedLayers control to be similar. Just double-check whether you add the layers to the map or not. Also notice that the checkboxes' state updates whenever layers are added/removed to/from the map by any means, at any time.


问:
Laravel - Fullcalendar doesn't load but show html code
I'm using FullCalendar package in my laravel project, I think that works but I don't know why don´t show the calendar but shows html code in my view.

```<code><div id="calendar-TcJ9C2VA"></div>
<script> $(document).ready(function()
{ $('#calendar-TcJ9C2VA').fullCalendar({"header":{"left":"prev,next today","center":"title","right":"month,agendaWeek,agendaDay"},"eventLimit":true,"firstDay":1,"events":[{"id":1,"title":"moradia","allDay":false,"start":"2017-03-29T00:00:00+00:00","end":"2017-03-30T08:00:00+00:00"}]}); });
</script>
</code>```

sources

```<code><script src={{ asset('https://code.jquery.com/jquery-1.12.4.min.js') }}></script>
    <script src={{ asset('//cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js') }}></script>
    <script src={{ asset('//cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.2.7/fullcalendar.min.js') }}></script>
    <script src={{ asset('//cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.2.7/fullcalendar.min.css') }}></script>
    <script src={{ asset('//cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.2.7/fullcalendar.print.css') }}></script>
</code>```

in console gives me errors, but I already changes jquery/moment sources, and always same errors.

EDIT: now I have this errors and same html code in view

答:
First you should import css like this:

```<code><link rel="stylesheet" type="text/css" href="{{ asset("//cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.2.7/fullcalendar.min.css")}}" />
<link rel="stylesheet" type="text/css" href="{{ asset("//cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.2.7/fullcalendar.print.css")}}" />
</code>```

second, try to import the lang js to your site, after the fullcalendar js import.

```<code><script src="{{ asset('//cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.2.7/lang-all.js') }}"></script>
</code>```

And I suggest you to use the latest fullcalendar.

I hope I could help! I tried out jsfiddle and it works.

Edit:

The other problem is that the {{asset('#'}} does not return between the double quote so you shuold define like this: "{{asset('#'}}"

ContentLicense: CC BY-SA 4.0

Body:
I'm using FullCalendar package in my laravel project, I think that works but I don't know why don´t show the calendar but shows html code in my view.

sources

in console gives me errors, but I already changes jquery/moment sources, and always same errors.

EDIT: now I have this errors and same html code in view

Body:
First you should import css like this:

<link rel="stylesheet" type="text/css" href="{{ asset("//cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.2.7/fullcalendar.min.css")}}" />
<link rel="stylesheet" type="text/css" href="{{ asset("//cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.2.7/fullcalendar.print.css")}}" />

second, try to import the lang js to your site, after the fullcalendar js import.

<script src="{{ asset('//cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.2.7/lang-all.js') }}"></script>

And I suggest you to use the latest fullcalendar.

I hope I could help! I tried out jsfiddle and it works.

Edit:

The other problem is that the {{asset('#'}} does not return between the double quote so you shuold define like this: "{{asset('#'}}"


问:
Assign a sub class to an interface, with generics and covariant involved
I defined 3 interfaces:

```<code>public interface IManufacturerInput
{
}
public interface IManufacturerOutput
{
}
public interface IManufacturerApi<in S, out T>
    where S : IManufacturerInput
    where T : IManufacturerOutput
{
    T Calculate(S);
}
</code>```

And I defined a specific Manufacturer:

```<code>public class ManufacturerAInput : IManufacturerInput
{
}
public class ManufacturerAOutput : IManufacturerOutput
{
}
public class ManufacturerAApi : IManufacturerApi<ManufacturerAInput, ManufacturerAOutput>
{
     public ManufacturerAOutput Calculate(ManufacturerAInput)
     {
         return null;
     }
}
</code>```

And In Main() I created a ManufacturerAApi, and try assign it to IManufacturerApi.

```<code>IManufacturerApi<IManufacturerInput, IManufacturerOutput> api = new ManufacturerAApi();
</code>```

But it failed. The error message said (just abstract meaning):

```<code>Can't convert from ManufacturerAApi to IManufacturerApi<IManufacturerInput, IManufacturerOutput>
</code>```

So is there any way I can make the assignment work? Thanks in advance.

答:
What you are proposing isn't type safe. Let's change the names of your types to make the issue clearer:

```<code>public interface IPetFood { }
public interface IPetSound { }

public interface IPetCage<in S, out T>
    where S : IPetFood
    where T : IPetSound
{
    T Feed(S s);
}

public class DogFood : IPetFood { }
public class CatFood : IPetFood { }
public class Bark : IPetSound { }

public class DogCage : IPetCage<DogFood, Bark>
{
    public Bark Feed(DogFood input)
    {
        return new Bark();
    }
}
</code>```

And now suppose this is legal:

```<code>IPetCage<IPetFood, IPetSound> api = new DogCage();
</code>```

Then we could do the following:

```<code>api.Feed(new CatFood()); //oops we've just given the dog some catfood.
</code>```

The assignment will not work because S is contravariant, which means that any possible IPetFood passed into api.Feed would need to be a subtype of DogFood and you have the opposite; IPetFood is a superset of DogFood.

Body:
I defined 3 interfaces:

public interface IManufacturerInput
{
}
public interface IManufacturerOutput
{
}
public interface IManufacturerApi<in S, out T>
    where S : IManufacturerInput
    where T : IManufacturerOutput
{
    T Calculate(S);
}

And I defined a specific Manufacturer:

public class ManufacturerAInput : IManufacturerInput
{
}
public class ManufacturerAOutput : IManufacturerOutput
{
}
public class ManufacturerAApi : IManufacturerApi<ManufacturerAInput, ManufacturerAOutput>
{
     public ManufacturerAOutput Calculate(ManufacturerAInput)
     {
         return null;
     }
}

And In Main() I created a ManufacturerAApi, and try assign it to IManufacturerApi.

IManufacturerApi<IManufacturerInput, IManufacturerOutput> api = new ManufacturerAApi();

But it failed. The error message said (just abstract meaning):

Can't convert from ManufacturerAApi to IManufacturerApi<IManufacturerInput, IManufacturerOutput>

So is there any way I can make the assignment work? Thanks in advance.

Body:
What you are proposing isn't type safe. Let's change the names of your types to make the issue clearer:

public interface IPetFood { }
public interface IPetSound { }

public interface IPetCage<in S, out T>
    where S : IPetFood
    where T : IPetSound
{
    T Feed(S s);
}

public class DogFood : IPetFood { }
public class CatFood : IPetFood { }
public class Bark : IPetSound { }

public class DogCage : IPetCage<DogFood, Bark>
{
    public Bark Feed(DogFood input)
    {
        return new Bark();
    }
}

And now suppose this is legal:

IPetCage<IPetFood, IPetSound> api = new DogCage();

Then we could do the following:

api.Feed(new CatFood()); //oops we've just given the dog some catfood.

The assignment will not work because S is contravariant, which means that any possible IPetFood passed into api.Feed would need to be a subtype of DogFood and you have the opposite; IPetFood is a superset of DogFood.


问:
Auto switch between sentences
I would like my joomla site to automatically change which sentence it will echo to the user, so I wrote 3 different sentences:

```<code>$sentence1 = "Everything okay?";
$sentence2 = "Have a good day";
$sentence3 = "What are you doing today?";
</code>```

I would like it to switch between the sentences, so I'm aware I can't just put $sentence1 in the echo but I don't know how to write it then. I have the echo line like this:

```<code>echo "Hey {user->name}." . "<br />" . $sentence1
</code>```

By the way, the {user->name} is from Joomla's own "codes" so that worked fine :)

答:
In my opinion, you can put your 3 sentences or 3 strings in an array, and then you can print every sentence when you loop in it. Example:</p>

```<code>$array = array(sentence1, sentence2, sentence3 , ... , sentence n);
for ($index = 0; $index < sizeof($array); $index++) {
    echo 'This is sentence ' + index ':' + $array[index];
}
</code>```

Title: Auto switch between sentences

Body:
I would like my joomla site to automatically change which sentence it will echo to the user, so I wrote 3 different sentences:

$sentence1 = "Everything okay?";
$sentence2 = "Have a good day";
$sentence3 = "What are you doing today?";

I would like it to switch between the sentences, so I'm aware I can't just put $sentence1 in the echo but I don't know how to write it then. I have the echo line like this:

echo "Hey {user->name}." . "
" . $sentence1

By the way, the {user->name} is from Joomla's own "codes" so that worked fine :)

Body:
In my opinion, you can put your 3 sentences or 3 strings in an array, and then you can print every sentence when you loop in it. Example:

$array = array(sentence1, sentence2, sentence3 , ... , sentence n);
for ($index = 0; $index < sizeof($array); $index++) {
    echo 'This is sentence ' + index ':' + $array[index];
}


问:
js: how to access a class defined inside require from the outside (accessibility issue)
This question is bothering me for a while.
I'm trying to call a class from outside require (accessibility issue), my code looks like the above.

```<code>require(['foo'],
    (foo) => {
        class Bar {
            hello() {
                return "hello";
            }
        }
    });
bar = new Bar();
//uncaught ReferenceError: Chart is not defined
</code>```

I've found one workaround, this is done by using window.Bar = class Bar...

```<code>require(['foo'],
    (foo) => {
        window.Bar = class Bar {
            hello() {
                return "hello";
            }
        }
    });
bar = new Bar();
//OK
</code>```

However, this is not a convenient solution when it comes to converting it using Babel.

Do you know any other more correct way to export/define this class so that it could be called from an upper level?

Thanx in advance

答:
You wouldn't. Instead, you'd write your full module code inside the callback:

```<code>require(['foo'], foo => {
    class Bar {
        hello() {
            return "hello";
        }
    }
    const bar = new Bar();
    // ...rest of code here...
});
</code>```

That's the normal way Require-style modules are written. You don't write anything at the top-level of the script, it's all within the callback, not least so that Require can call it when appropriate.

Body:
This question is bothering me for a while.
I'm trying to call a class from outside require (accessibility issue), my code looks like the above.

require(['foo'],
    (foo) => {
        class Bar {
            hello() {
                return "hello";
            }
        }
    });
bar = new Bar();
//uncaught ReferenceError: Chart is not defined

I've found one workaround, this is done by using window.Bar = class Bar...

require(['foo'],
    (foo) => {
        window.Bar = class Bar {
            hello() {
                return "hello";
            }
        }
    });
bar = new Bar();
//OK

However, this is not a convenient solution when it comes to converting it using Babel.

Do you know any other more correct way to export/define this class so that it could be called from an upper level?

Thanx in advance

Body:
You wouldn't. Instead, you'd write your full module code inside the callback:

require(['foo'], foo => {
    class Bar {
        hello() {
            return "hello";
        }
    }
    const bar = new Bar();
    // ...rest of code here...
});

That's the normal way Require-style modules are written. You don't write anything at the top-level of the script, it's all within the callback, not least so that Require can call it when appropriate.


问:
AWS SNS - How to get topic arn by topic name
In my application i need to send messages to the given topic name. The topic is already created by other person and in a config file they give only the topic Name. My work is to push the messages in the given topic Name. Is there any way to get topic ARN by topic NAME in java?</p>

答: As stated in this answer using createTopic(topicName) is more direct approach. In case topic have been created before, it will just return you topic ARN.</p>


问:
Load package into current namespace
How can I load the contents of a package into the current namespace instead of the global namespace?

Suppose I have the following package.tcl

```<code>package provide pgkTest 1.0

variable _value ""
proc get_value {} {
  variable _value
  return _value
}
</code>```

The package is listed in pkgIndex.tcl and is found. Now in the main script in another folder I would like to do:

```<code>namespace eval myns1 {
   package require pgkTest 1.0
   package forget pgkTest
}

namespace eval myns2 {
   package require pgkTest 1.0
   package forget pgkTest
}
</code>```

However, this does not seem to work because the package is loaded into the global namespace :: by default.

答:
What you're trying to do won't work, because each package (as determined by its name) is loaded at most once into an interpreter. Instead, the package probably ought to provide a command that sets up a given namespace with the features you're after:

```<code>package provide pgkTest 1.0

namespace eval ::pgkTest {}
proc ::pgkTest::setup {{targetNamespace ""}} {
    # If caller doesn't give a namespace, get the caller's namespace
    if {$targetNamespace eq ""} {
        set targetNamespace [uplevel 1 {namespace current}]
    }
    namespace eval $targetNamespace {
        variable _value ""
        proc get_value {} {
          variable _value
          return _value
        }
    }
}
</code>```

Then you can do this to get the effect you want:

```<code>package require pgkTest 1.0

namespace eval myns1 {
    ::pgkTest::setup
}

namespace eval myns2 {
   ::pgkTest::setup
}
</code>```

If you're really doing this sort of thing a lot, consider switching to using an object system like TclOO, [incr Tcl], or XOTcl. They're designed much more for tackling the problem of stamping out lots of copies of things that are all the same (or have minor variations).

Title: Load package into current namespace

Body:
How can I load the contents of a package into the current namespace instead of the global namespace?

Suppose I have the following package.tcl

package provide pgkTest 1.0

variable _value ""
proc get_value {} {
  variable _value
  return _value
}

The package is listed in pkgIndex.tcl and is found. Now in the main script in another folder I would like to do:

namespace eval myns1 {
   package require pgkTest 1.0
   package forget pgkTest
}

namespace eval myns2 {
   package require pgkTest 1.0
   package forget pgkTest
}

However, this does not seem to work because the package is loaded into the global namespace :: by default.

Body:
What you're trying to do won't work, because each package (as determined by its name) is loaded at most once into an interpreter. Instead, the package probably ought to provide a command that sets up a given namespace with the features you're after:

package provide pgkTest 1.0

namespace eval ::pgkTest {}
proc ::pgkTest::setup {{targetNamespace ""}} {
    # If caller doesn't give a namespace, get the caller's namespace
    if {$targetNamespace eq ""} {
        set targetNamespace [uplevel 1 {namespace current}]
    }
    namespace eval $targetNamespace {
        variable _value ""
        proc get_value {} {
          variable _value
          return _value
        }
    }
}

Then you can do this to get the effect you want:

package require pgkTest 1.0

namespace eval myns1 {
    ::pgkTest::setup
}

namespace eval myns2 {
   ::pgkTest::setup
}

If you're really doing this sort of thing a lot, consider switching to using an object system like TclOO, [incr Tcl], or XOTcl. They're designed much more for tackling the problem of stamping out lots of copies of things that are all the same (or have minor variations).


问:
Jsoup casting Element as TextNode causes exception
what am trying to parse using jsoup is the following Numéro d'arrêt : 5216 and Numéro NOR : 63066, but nothing seems to works any advice and suggestions will be greatly appreciated:

`

```<code><div class="1st">
<p>
<h3>Numérotation : </h3>
Numéro d'arrêt : 5216
<br />
Numéro NOR : 63066
</div>
</code>```

`

UPDATE :

i got this code to work but it keep giving me this exception org.jsoup.nodes.Element cannot be cast to org.jsoup.nodes.TextNode :

```<code>Document tunisie = Jsoup.connect("http://www.juricaf.org/arret/TUNISIE-COURDECASSATION-20060126-5216").get();

for (Element titres : tunisie.select("div.arret")){

                    String titre = titres.select("h1#titre").first().text();
                    System.out.println(titre);
                    System.out.println("\n");
                }

                for (Element node : tunisie.select("h3")) {
                    TextNode numérodarrêt = (TextNode) node.nextSibling();
                    System.out.println(" " + numérodarrêt.text());
                    System.out.println("\n");

                }

                //NuméroNOR et Identifiant URN LEX
                for (Element element2 : tunisie.select("br")) {
                    TextNode NuméroNOR_IdentifiantURNLEX = (TextNode) element2.nextSibling();
                    System.out.println(" " + NuméroNOR_IdentifiantURNLEX.text());
                    System.out.println("\n");
                }
</code>```

UPDATE :

here is what am trying to parse image link is below.

Parsing text outside html tags

答:
```<code>import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

public class JsoupTest {

    public static void main(String[] args) throws IOException {
       Document tunisie = Jsoup.connect("http://www.juricaf.org/arret/TUNISIE-COURDECASSATION-20060126-5216").get();
       // get the first div in class arret
       Element arret = tunisie.select("div.arret").first();
       // select h1 tag by its ID to get the title
       String  titre = arret.select("#titre").text();
       System.out.println(titre);
       // to get the text after h3 select h3 and go to next sibling
       String txtAfterFirstH3    = arret.select("h3").first().nextSibling().toString();
       System.out.println(txtAfterFirstH3);
       // select first br by its index; note first br has the index 0; and call nextSibling to get the text after the br tag
       String txtAfterFirstBr    = arret.getElementsByTag("br").get(0).nextSibling().toString();
       System.out.println(txtAfterFirstBr);
       // the same as above only with next index
       String txtAfterSecondBr    = arret.getElementsByTag("br").get(1).nextSibling().toString();
       System.out.println(txtAfterSecondBr);
    }
}
</code>```

Body:
what am trying to parse using jsoup is the following Numéro d'arrêt : 5216 and Numéro NOR : 63066, but nothing seems to works any advice and suggestions will be greatly appreciated:

`

Numérotation :

Numéro d'arrêt : 5216

Numéro NOR : 63066

`

UPDATE :

i got this code to work but it keep giving me this exception org.jsoup.nodes.Element cannot be cast to org.jsoup.nodes.TextNode :

Document tunisie = Jsoup.connect("http://www.juricaf.org/arret/TUNISIE-COURDECASSATION-20060126-5216").get();

for (Element titres : tunisie.select("div.arret")){

                    String titre = titres.select("h1#titre").first().text();
                    System.out.println(titre);
                    System.out.println("\n");
                }

                for (Element node : tunisie.select("h3")) {
                    TextNode numérodarrêt = (TextNode) node.nextSibling();
                    System.out.println(" " + numérodarrêt.text());
                    System.out.println("\n");

                }

                //NuméroNOR et Identifiant URN LEX
                for (Element element2 : tunisie.select("br")) {
                    TextNode NuméroNOR_IdentifiantURNLEX = (TextNode) element2.nextSibling();
                    System.out.println(" " + NuméroNOR_IdentifiantURNLEX.text());
                    System.out.println("\n");
                }

UPDATE :

here is what am trying to parse image link is below.

Parsing text outside html tags


问:
Find the most frequent items among the arrays - PHP
I have 3 arrays in my code.

```<code>array1 = ['apple', 'orange', 'banana', 'guava', 'grapes'];
array2 = ['apple', 'jackfruits', 'banana', 'malta'];
array3 = ['banana', 'grapes, 'apple'];
</code>```

Now i want to get one array from high frequency to low frequency repetation in arrays.

like the result would be

```<code>array_result = ['apple', 'banana', 'grapes', 'orange', 'malta', 'jackfrouits'];
</code>```

答:
```<code>$array1 = ['apple', 'orange', 'banana', 'guava', 'grapes'];
$array2 = ['apple', 'jackfruits', 'banana', 'malta'];
$array3 = ['banana', 'grapes', 'apple'];
// Merge them and count all the values
$array_counts = array_count_values(array_merge($array1, $array2, $array3));
// Reverse order by counts
arsort($array_counts);
// Make an array based on the keys
$array_result = array_keys($array_counts);
</code>```

Body:
I have 3 arrays in my code.

array1 = ['apple', 'orange', 'banana', 'guava', 'grapes'];
array2 = ['apple', 'jackfruits', 'banana', 'malta'];
array3 = ['banana', 'grapes, 'apple'];

Now i want to get one array from high frequency to low frequency repetation in arrays.

like the result would be

array_result = ['apple', 'banana', 'grapes', 'orange', 'malta', 'jackfrouits'];


答:
You could use a random function, such as mt_rand():

```<code>$sentence1 = "Everything okay?";
$sentence2 = "Have a good day";
$sentence3 = "What are you doing today?";
$nb = mt_rand(1, 3); // Gets a random number from 1 to 3
$sentence_shown = ${'sentence' . $nb}; // Equals $sentence1, $sentence2 or $sentence3

echo "Hey {user->name}." . "<br />" . $sentence_shown;
</code>```

Or even better, put your three strings in an array :

```<code>$sentences = array();
$sentences[] = "Everything okay?";
$sentences[] = "Have a good day";
$sentences[] = "What are you doing today?";
$nb = mt_rand(0, 2); // Gets a random number from 0 to 2
$sentence_shown = $sentences[$nb];

echo "Hey {user->name}." . "<br />" . $sentence_shown;
</code>```

Title: Auto switch between sentences

Body:
You could use a random function, such as mt_rand():

$sentence1 = "Everything okay?";
$sentence2 = "Have a good day";
$sentence3 = "What are you doing today?";
$nb = mt_rand(1, 3); // Gets a random number from 1 to 3
$sentence_shown = ${'sentence' . $nb}; // Equals $sentence1, $sentence2 or $sentence3

echo "Hey {user->name}." . "<br />" . $sentence_shown;

Or even better, put your three strings in an array :

$sentences = array();
$sentences[] = "Everything okay?";
$sentences[] = "Have a good day";
$sentences[] = "What are you doing today?";
$nb = mt_rand(0, 2); // Gets a random number from 0 to 2
$sentence_shown = $sentences[$nb];

echo "Hey {user->name}." . "<br />" . $sentence_shown;


问:
.SelectMany with C#
I found this post and I need something similar

stackoverflow.com/questions/41282053/groupby-multiple-date-properties-by-month-and-year-in-linq/43112774#43112774

I need to group by month and year, but at the same time I need a property of the main element, which I can not access

```<code>var departments = stops
    .SelectMany(x => new[] { x.InitDate.Month, x.InitDate.Year }
    .Where(dt => dt != null).Select(dt => x.InitDate))
    .GroupBy(dt => new { dt.Month, dt.Year })
    .OrderBy(g => g.Key.Month)
    .ThenBy(g => g.Key.Year)
    .Select(g => new
    {
        Key = g.Key.Month,
        Año = g.Key.Year,
        Duration = 0,
        Count = g.Count()
    });
</code>```

I would need access to "stops.Duration" but if i do this: .SelectMany(x => new[] { x.InitDate.Month, x.InitDate.Year, x.Duration }

it does not group me by month-year

Can anybody help me?

Sorry for my english and thank you very much

答:
This code should do:

```<code>var departments = stops
    .Where(stop => stop.InitDate != null)
    .SelectMany(stop => new[] { Month = stop.InitDate.Month, Year = stop.InitDate.Year, Duration = stop.Duration })
    .GroupBy(dt => new { dt.Month, dt.Year })
    .OrderBy(g => g.Key.Month)
    .ThenBy(g => g.Key.Year)
    .Select(g => new
    {
        Key = g.Key.Month,
        Año = g.Key.Year,
        Duration = g.Sum(v => v.Duration),
        Count = g.Count()
    });
</code>```

It selects the duration, groups on month and year, and uses the sum of the duration from the grouped result.

Title: .SelectMany with C#

Body:
I found this post and I need something similar

stackoverflow.com/questions/41282053/groupby-multiple-date-properties-by-month-and-year-in-linq/43112774#43112774

I need to group by month and year, but at the same time I need a property of the main element, which I can not access

var departments = stops
    .SelectMany(x => new[] { x.InitDate.Month, x.InitDate.Year }
    .Where(dt => dt != null).Select(dt => x.InitDate))
    .GroupBy(dt => new { dt.Month, dt.Year })
    .OrderBy(g => g.Key.Month)
    .ThenBy(g => g.Key.Year)
    .Select(g => new
    {
        Key = g.Key.Month,
        Año = g.Key.Year,
        Duration = 0,
        Count = g.Count()
    });

I would need access to "stops.Duration" but if i do this: .SelectMany(x => new[] { x.InitDate.Month, x.InitDate.Year, x.Duration }

it does not group me by month-year

Can anybody help me?

Sorry for my english and thank you very much

Body:
This code should do:

var departments = stops
    .Where(stop => stop.InitDate != null)
    .SelectMany(stop => new[] { Month = stop.InitDate.Month, Year = stop.InitDate.Year, Duration = stop.Duration })
    .GroupBy(dt => new { dt.Month, dt.Year })
    .OrderBy(g => g.Key.Month)
    .ThenBy(g => g.Key.Year)
    .Select(g => new
    {
        Key = g.Key.Month,
        Año = g.Key.Year,
        Duration = g.Sum(v => v.Duration),
        Count = g.Count()
    });

It selects the duration, groups on month and year, and uses the sum of the duration from the grouped result.


问:
How to trigger a function from dropdown in angular 2
I have a drop down with the following code,

```<code><select class="form-control">
     <option value="">Select Draft</option>
     <option (change)="getDetails(event.name)" *ngFor="let event of eventasdraft">{{ event.name }}
     </option>
</select>
</code>```

When I execute the above code,it is not triggering the function.Can anyone please help me.Thanks.

答:
```<code><div class="btn-group custom-drop-down" dropdown>
  <button id="single-button" type="button" class="btn" dropdownToggle>
    <span style="float: left;">{{selected}}</span>
    <span class="caret" [ngClass]="{'marginCaret': selected !== null}"></span>
  </button>
  <ul dropdownMenu role="menu" aria-labelledby="single-button" style="width: 100%;">
    <li *ngFor="let item of list" role="menuitem"><a class="dropdown-item" target="_self" (click)="toggleDropdown($event,item)">{{item}}</a></li>
  </ul>
</div>

selectOption(item : String){
    this.selected = item;
    this.selectOptionEventEmitter.emit(item);
  }

  public toggleDropdown($event: MouseEvent, item : String): void {
    $event.preventDefault();
    $event.stopPropagation();
    this.selectOption(item);
  }
</code>```

Body:
I have a drop down with the following code,

<select class="form-control">
     <option value="">Select Draft</option>
     <option (change)="getDetails(event.name)" *ngFor="let event of eventasdraft">{{ event.name }}
     </option>
</select>

When I execute the above code,it is not triggering the function.Can anyone please help me.Thanks.