问:
Reading values from BLE device
I'm owning a Polar H10 chest strap which operates with blueooth low energy and provides heart rate and heart rate variability.

I want to read out these values with an Android app. I'm able to connect to the device thanks to the help in the official BLE tutorial. The problem now is to read out the heart rate and heart rate variability values from the device. Everytime a new value is available on the device I want to read out this value (and there are at least every second new values).

I have found the following pieces of code:

```<code>private static double extractHeartRate(
            BluetoothGattCharacteristic characteristic) {

        int flag = characteristic.getProperties();
        Log.d(TAG, "Heart rate flag: " + flag);
        int format = -1;
        // Heart rate bit number format
        if ((flag & 0x01) != 0) {
            format = BluetoothGattCharacteristic.FORMAT_UINT16;
            Log.d(TAG, "Heart rate format UINT16.");
        } else {
            format = BluetoothGattCharacteristic.FORMAT_UINT8;
            Log.d(TAG, "Heart rate format UINT8.");
        }
        final int heartRate = characteristic.getIntValue(format, 1);
        Log.d(TAG, String.format("Received heart rate: %d", heartRate));
        return heartRate;
    }

private static Integer[] extractBeatToBeatInterval(
            BluetoothGattCharacteristic characteristic) {

        int flag = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0);
        int format = -1;
        int energy = -1;
        int offset = 1; // This depends on hear rate value format and if there is energy data
        int rr_count = 0;

        if ((flag & 0x01) != 0) {
            format = BluetoothGattCharacteristic.FORMAT_UINT16;
            Log.d(TAG, "Heart rate format UINT16.");
            offset = 3;
        } else {
            format = BluetoothGattCharacteristic.FORMAT_UINT8;
            Log.d(TAG, "Heart rate format UINT8.");
            offset = 2;
        }
        if ((flag & 0x08) != 0) {
            // calories present
            energy = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, offset);
            offset += 2;
            Log.d(TAG, "Received energy: {}"+ energy);
        }
        if ((flag & 0x16) != 0){
            // RR stuff.
            Log.d(TAG, "RR stuff found at offset: "+ offset);
            Log.d(TAG, "RR length: "+ (characteristic.getValue()).length);
            rr_count = ((characteristic.getValue()).length - offset) / 2;
            Log.d(TAG, "RR length: "+ (characteristic.getValue()).length);
            Log.d(TAG, "rr_count: "+ rr_count);
            if (rr_count > 0) {
                Integer[] mRr_values = new Integer[rr_count];
                for (int i = 0; i < rr_count; i++) {
                    mRr_values[i] = characteristic.getIntValue(
                            BluetoothGattCharacteristic.FORMAT_UINT16, offset);
                    offset += 2;
                    Log.d(TAG, "Received RR: " + mRr_values[i]);
                }
                return mRr_values;
            }
        }
        Log.d(TAG, "No RR data on this update: ");
        return null;
    }
</code>```

How can I use it to extract the heart rate and r-r intervals (beat to beat intervals) assuming that I have a connection to the device? I would be happy if somebody could make a short example. Addtionally, I would like to use a service so that it runs in the background and I can do other work and it drains less battery. But the service should have highest priority so that it get not killed.

In the extractBeatToBeatInterval() method there is a int offset = 1; with the description

This depends on hear rate value format and if there is energy data

I don't understand the meaning of this offest. What offset value should I use?

Second, if the connection breaks I would like to get a notification so that I can handle it (e.g. displaying a message). How can I do that?

答:
I can help you with a few things on this matter.
For connection breaks you can handle it like this

```<code>public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            if (newState == BluetoothGatt.STATE_CONNECTED) {
                Log.e(Constants.TAGGattConnectThread, "Connected to the GATT Server " + status + " " +newState);
                Log.e(Constants.TAGGattConnectThread, "Attempting to discover services");
                bluetoothGatt.discoverServices();
            }
            else if(newState == BluetoothGatt.STATE_DISCONNECTED)
            {
                Log.e(Constants.TAGGattConnectThread,"Band disconnected");
               //Write you disconnect handling code here
            }
</code>```

Also you can set the 'AutoConnect option to 'True' while connecting to Gatt

```<code>bluetoothGatt = bluetoothDevice.connectGatt(context, true, bluetoothGattCallback);
</code>```

For creating a service, You can create a Sticky service that will restart itself unless force stopped.

Title: Reading values from BLE device

Body:
I'm owning a Polar H10 chest strap which operates with blueooth low energy and provides heart rate and heart rate variability.

I want to read out these values with an Android app. I'm able to connect to the device thanks to the help in the official BLE tutorial. The problem now is to read out the heart rate and heart rate variability values from the device. Everytime a new value is available on the device I want to read out this value (and there are at least every second new values).

I have found the following pieces of code:

private static double extractHeartRate(
            BluetoothGattCharacteristic characteristic) {

        int flag = characteristic.getProperties();
        Log.d(TAG, "Heart rate flag: " + flag);
        int format = -1;
        // Heart rate bit number format
        if ((flag & 0x01) != 0) {
            format = BluetoothGattCharacteristic.FORMAT_UINT16;
            Log.d(TAG, "Heart rate format UINT16.");
        } else {
            format = BluetoothGattCharacteristic.FORMAT_UINT8;
            Log.d(TAG, "Heart rate format UINT8.");
        }
        final int heartRate = characteristic.getIntValue(format, 1);
        Log.d(TAG, String.format("Received heart rate: %d", heartRate));
        return heartRate;
    }

private static Integer[] extractBeatToBeatInterval(
            BluetoothGattCharacteristic characteristic) {

        int flag = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT8, 0);
        int format = -1;
        int energy = -1;
        int offset = 1; // This depends on hear rate value format and if there is energy data
        int rr_count = 0;

        if ((flag & 0x01) != 0) {
            format = BluetoothGattCharacteristic.FORMAT_UINT16;
            Log.d(TAG, "Heart rate format UINT16.");
            offset = 3;
        } else {
            format = BluetoothGattCharacteristic.FORMAT_UINT8;
            Log.d(TAG, "Heart rate format UINT8.");
            offset = 2;
        }
        if ((flag & 0x08) != 0) {
            // calories present
            energy = characteristic.getIntValue(BluetoothGattCharacteristic.FORMAT_UINT16, offset);
            offset += 2;
            Log.d(TAG, "Received energy: {}"+ energy);
        }
        if ((flag & 0x16) != 0){
            // RR stuff.
            Log.d(TAG, "RR stuff found at offset: "+ offset);
            Log.d(TAG, "RR length: "+ (characteristic.getValue()).length);
            rr_count = ((characteristic.getValue()).length - offset) / 2;
            Log.d(TAG, "RR length: "+ (characteristic.getValue()).length);
            Log.d(TAG, "rr_count: "+ rr_count);
            if (rr_count > 0) {
                Integer[] mRr_values = new Integer[rr_count];
                for (int i = 0; i < rr_count; i++) {
                    mRr_values[i] = characteristic.getIntValue(
                            BluetoothGattCharacteristic.FORMAT_UINT16, offset);
                    offset += 2;
                    Log.d(TAG, "Received RR: " + mRr_values[i]);
                }
                return mRr_values;
            }
        }
        Log.d(TAG, "No RR data on this update: ");
        return null;
    }

How can I use it to extract the heart rate and r-r intervals (beat to beat intervals) assuming that I have a connection to the device? I would be happy if somebody could make a short example. Addtionally, I would like to use a service so that it runs in the background and I can do other work and it drains less battery. But the service should have highest priority so that it get not killed.

In the extractBeatToBeatInterval() method there is a int offset = 1; with the description

This depends on hear rate value format and if there is energy data

I don't understand the meaning of this offest. What offset value should I use?

Second, if the connection breaks I would like to get a notification so that I can handle it (e.g. displaying a message). How can I do that?

Body:
I can help you with a few things on this matter.
For connection breaks you can handle it like this

public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            if (newState == BluetoothGatt.STATE_CONNECTED) {
                Log.e(Constants.TAGGattConnectThread, "Connected to the GATT Server " + status + " " +newState);
                Log.e(Constants.TAGGattConnectThread, "Attempting to discover services");
                bluetoothGatt.discoverServices();
            }
            else if(newState == BluetoothGatt.STATE_DISCONNECTED)
            {
                Log.e(Constants.TAGGattConnectThread,"Band disconnected");
               //Write you disconnect handling code here
            }

Also you can set the 'AutoConnect option to 'True' while connecting to Gatt

bluetoothGatt = bluetoothDevice.connectGatt(context, true, bluetoothGattCallback);

For creating a service, You can create a Sticky service that will restart itself unless force stopped.


来源: stackexchange

问:
Wagtail form builder with additional constant fields
I have created a quiz with wagtail form builder, but I need the form to contain some fields which are constant. For example, I have the following:

Name

Email

Employee id

[form builder fields]

How do I integrate fields [1-3] in the form builder to show up on all quizzes?

答:
A simple way to do this is to override the get_form_fields method on your FormPage model.

This method simply returns a query for all stored FormFields on the FormPage model. We can add instances of FormField as needed and this will make the fields available in the form (view). They will also be available in form reports and emails.

1 - Override get_form_fields in your FormPage class.

In myapp/models.py wherever you have defined your FormPage model, add the following:

```<code>    class FormPage(AbstractEmailForm):

        # ...additional FormPage fiels and content_panels

        def get_form_fields(self):
            # get form_fields as defined by the super class & convert to list
            # otherwise returns queryset
            fields = list(super(FormPage, self).get_form_fields())

            # append instances of FormField - not actually stored in the db
            # field_type can only be one of the following:
            # 'singleline', 'multiline', 'email', 'number', 'url', 'checkbox',
            # 'checkboxes', 'dropdown', 'multiselect', 'radio', 'date',
            # 'datetime', 'hidden'
            # Important: Label MUST be unique in each form

            # `insert(0` will prepend these items, so here ID will be first

            fields.insert(0, FormField(
                label='Employee Name',
                field_type='singleline',
                required=False,
                help_text="Employee's Name"))

            fields.insert(0, FormField(
                label='Employee Email',
                field_type='email',
                required=False,
                help_text="Employee's Email"))

            fields.insert(0, FormField(
                label='Employee ID',
                field_type='number',
                required=False,
                help_text="Employee's ID"))

            return fields
</code>```

Note: When creating our FormField instances, these are not stored in the database, but their responses will be. You should provide the attributes label, field_type, required and help_text.

2 - Ensure there are no label conflicts on existing Forms

If the form label 'Employee ID' is used already in a form - not sure what will happen but it will likely break things so check you do not have conflicts in existing form pages.

Note: If the label is the same, you will not loose your data from previous submissions. All data is stored for past submissions even if you change the FormFields in use.

3 - Override the label field on FormField with some validation

In myapp/models.py wherever you have defined your FormField model, add the following:

```<code>from django.core.exceptions import ValidationError

# ... other imports and then models

RESERVED_LABELS = ['Employee Name', 'Employee Email', 'Employee ID']

def validate_label(value):
    if value in RESERVED_LABELS:
        raise ValidationError("'%s' is reserved." % value)

class FormField(AbstractFormField):
    # page = ...
    # redefine 'label' field so we can ensure there will be no conflicts with constant fields
    label = models.CharField(
        verbose_name='label',
        max_length=255,
        help_text='The label of the form field, cannot be one of the following: %s.'
        % ', '.join(RESERVED_LABELS),
        validators=[validate_label]
    )
</code>```

RESERVED_VALUES should match the labels used in your FormPage model.

This creates a simple Django Field Validator to check that you will not have conflicting labels. It also adds some nice help text so users do not get confused.

4 - Migrate

You should also do a migrations as you have now changed the label field on the FormField model.

ContentLicense: CC BY-SA 3.0

Body:
A simple way to do this is to override the get_form_fields method on your FormPage model.

This method simply returns a query for all stored FormFields on the FormPage model. We can add instances of FormField as needed and this will make the fields available in the form (view). They will also be available in form reports and emails.

1 - Override get_form_fields in your FormPage class.

In myapp/models.py wherever you have defined your FormPage model, add the following:

    class FormPage(AbstractEmailForm):

        # ...additional FormPage fiels and content_panels

        def get_form_fields(self):
            # get form_fields as defined by the super class & convert to list
            # otherwise returns queryset
            fields = list(super(FormPage, self).get_form_fields())

            # append instances of FormField - not actually stored in the db
            # field_type can only be one of the following:
            # 'singleline', 'multiline', 'email', 'number', 'url', 'checkbox',
            # 'checkboxes', 'dropdown', 'multiselect', 'radio', 'date',
            # 'datetime', 'hidden'
            # Important: Label MUST be unique in each form

            # `insert(0` will prepend these items, so here ID will be first

            fields.insert(0, FormField(
                label='Employee Name',
                field_type='singleline',
                required=False,
                help_text="Employee's Name"))

            fields.insert(0, FormField(
                label='Employee Email',
                field_type='email',
                required=False,
                help_text="Employee's Email"))

            fields.insert(0, FormField(
                label='Employee ID',
                field_type='number',
                required=False,
                help_text="Employee's ID"))

            return fields

Note: When creating our FormField instances, these are not stored in the database, but their responses will be. You should provide the attributes label, field_type, required and help_text.

2 - Ensure there are no label conflicts on existing Forms

If the form label 'Employee ID' is used already in a form - not sure what will happen but it will likely break things so check you do not have conflicts in existing form pages.

Note: If the label is the same, you will not loose your data from previous submissions. All data is stored for past submissions even if you change the FormFields in use.

3 - Override the label field on FormField with some validation

In myapp/models.py wherever you have defined your FormField model, add the following:

from django.core.exceptions import ValidationError

# ... other imports and then models

RESERVED_LABELS = ['Employee Name', 'Employee Email', 'Employee ID']

def validate_label(value):
    if value in RESERVED_LABELS:
        raise ValidationError("'%s' is reserved." % value)

class FormField(AbstractFormField):
    # page = ...
    # redefine 'label' field so we can ensure there will be no conflicts with constant fields
    label = models.CharField(
        verbose_name='label',
        max_length=255,
        help_text='The label of the form field, cannot be one of the following: %s.'
        % ', '.join(RESERVED_LABELS),
        validators=[validate_label]
    )

RESERVED_VALUES should match the labels used in your FormPage model.

This creates a simple Django Field Validator to check that you will not have conflicting labels. It also adds some nice help text so users do not get confused.

4 - Migrate

You should also do a migrations as you have now changed the label field on the FormField model.


问:
Coalesce over Rows in MSSQL 2008,
I'm trying to determine the best approach here in MSSQL 2008.

Here is my sample data

```<code>TransDate  Id     Active
-------------------------
1/18 1pm   5      1
1/18 2pm   5      0
1/18 3pm   5      Null
1/18 4pm   5      1
1/18 5pm   5      0
1/18 6pm   5      Null
</code>```

If grouped by Id and ordered by the TransDate, I want the last Non Null Value for the Active Column, and the MAX of TransDate

```<code>SELECT MAX(TransDate) AS TransDate,
       Id,
       --LASTNonNull(Active) AS Active
</code>```

Here would be the results:

```<code>TransDate  Id  Active
---------------------
1/18 6pm   5   0
</code>```

It would be like a Coalesce but over the rows, instead of two values/columns.

There would be many other columns that would also have this similiar method applied, so I really don't want to make a seperate join for each of the columns.

Any ideas?

答:
Assuming a table named "test1", how about using ROW_NUMBER, OVER and PARTITION BY?</p>

```<code>SELECT transdate, id, active FROM
    (SELECT transdate, ROW_NUMBER() OVER(PARTITION BY id ORDER BY transdate desc) AS rownumber, id, active
     FROM test1
     WHERE active is not null) a
WHERE a.rownumber = 1
</code>```

ContentLicense: CC BY-SA 2.5

Title: Coalesce over Rows in MSSQL 2008,

Body:
I'm trying to determine the best approach here in MSSQL 2008.

Here is my sample data

TransDate  Id     Active
-------------------------
1/18 1pm   5      1
1/18 2pm   5      0
1/18 3pm   5      Null
1/18 4pm   5      1
1/18 5pm   5      0
1/18 6pm   5      Null

If grouped by Id and ordered by the TransDate, I want the last Non Null Value for the Active Column, and the MAX of TransDate

SELECT MAX(TransDate) AS TransDate,
       Id,
       --LASTNonNull(Active) AS Active

Here would be the results:

TransDate  Id  Active
---------------------
1/18 6pm   5   0

It would be like a Coalesce but over the rows, instead of two values/columns.

There would be many other columns that would also have this similiar method applied, so I really don't want to make a seperate join for each of the columns.

Any ideas?

Body:
Assuming a table named "test1", how about using ROW_NUMBER, OVER and PARTITION BY?

SELECT transdate, id, active FROM
    (SELECT transdate, ROW_NUMBER() OVER(PARTITION BY id ORDER BY transdate desc) AS rownumber, id, active
     FROM test1
     WHERE active is not null) a
WHERE a.rownumber = 1


问:
How do I prevent google oauth from auto signing in?
This is related to this question about google plus: Prevent auto sign in with Google plus

The difference is that I'm using the google sign in platform instead of google plus, which has a different api.

Background:

I have a pricing page that has a free trial signup form. The form has the google sign in button. I would like a signed in user to be able to still see the pricing page without the google sign-in causing a redirect.

My Code

I have the meta tag at the top of my page that identifies my application. <meta name="google-signin-client_id" content="MY_CLIENT_ID">

I include this script on my page:

I have this div that renders the button:

My onSignIn function looks like this:

```<code>function onSignIn(googleUser) {
  var id_token = googleUser.getAuthResponse().id_token;

  $('#google_token').val(id_token); //hidden form value
  $('#google-oauth').submit(); //hidden form
}
</code>```

The hidden form is submitted to the backend, where the token is used to retrieve the user's email address and name, and then creates a user account and logs them in.

My problem is that if the user is already signed in, google will automatically call the onSignIn function causing the form to be submitted when the page is loaded. Is there a way for me to prevent the onSignIn function being automatically called?

Reference: https://developers.google.com/identity/sign-in/web/sign-in

答:
try this:</p>

```<code>function onSignIn(googleUser) {
     var id_token = googleUser.getAuthResponse().id_token;

     var auth2 = gapi.auth2.getAuthInstance();
     auth2.disconnect();

     //if this did not had time to sign out put below lines in setTimeout to make a delay
     $('#google_token').val(id_token); //hidden form value
     $('#google-oauth').submit(); //hidden form
}
</code>```

Body:
This is related to this question about google plus: Prevent auto sign in with Google plus

The difference is that I'm using the google sign in platform instead of google plus, which has a different api.

Background:

I have a pricing page that has a free trial signup form. The form has the google sign in button. I would like a signed in user to be able to still see the pricing page without the google sign-in causing a redirect.

My Code

I have the meta tag at the top of my page that identifies my application. <meta name="google-signin-client_id" content="MY_CLIENT_ID">

I include this script on my page:

I have this div that renders the button:

My onSignIn function looks like this:

function onSignIn(googleUser) {
  var id_token = googleUser.getAuthResponse().id_token;

  $('#google_token').val(id_token); //hidden form value
  $('#google-oauth').submit(); //hidden form
}

The hidden form is submitted to the backend, where the token is used to retrieve the user's email address and name, and then creates a user account and logs them in.

My problem is that if the user is already signed in, google will automatically call the onSignIn function causing the form to be submitted when the page is loaded. Is there a way for me to prevent the onSignIn function being automatically called?

Reference: https://developers.google.com/identity/sign-in/web/sign-in

Body:
try this:

function onSignIn(googleUser) {
     var id_token = googleUser.getAuthResponse().id_token;

     var auth2 = gapi.auth2.getAuthInstance();
     auth2.disconnect();

     //if this did not had time to sign out put below lines in setTimeout to make a delay
     $('#google_token').val(id_token); //hidden form value
     $('#google-oauth').submit(); //hidden form
}


问:
C how to show all unused functions (including ones defined in h files)
Somewhat related to this, but it still doesn't quite answer my question

I have a C project, and i would like to enumerate all unreferenced functions (including non-static, so setting compiler option for werror=unused-function only partially works...) in order to identify and clean up the codebase.

One way I thought is to enumerate all the functions in the project, and then make a script to go through each and see if it is called via cscope... but I'm not sure how to get a list-form of all the functions in the first place. That link above has a solution that is failing for me.

Any other ideas are welcome.

答:
Knowing if a function will be called or not is an undecidable problem (analogous to the stop issue for Turing machines).  As you can call a function through a pointer (as it is done by callbacks) you cannot actually determine if a function will be called until you actually take it out from the code and run the code.

Linker only links functions that are referenced in the code, and doesn't know if they belong to dead code that will not be called.

If you want to know all the referenced functions in your code, just grep the output of nm(1) command on all your .o files, to get all the U undefined references (this is the list of functions that must be externally linked to your code).  This will list all the external references to functions that must be resolved by the linker.  If your function is not there, then it is not used by that module.  You can match this list with the list of external functions (the ones marked as T in nm(1) output) of the .o files that you want to check (or shared objects .so) and you'll see (as the linker does) which ones are published to the linker but not referenced in your code.  Think twice, as this only represents a direct reference, you have to manage also for indirect references (your module asks for a function in another module, that finally asks for the function you are trying to check).

In case your functions are static (only file visibility) just surround the function definition by a #if 0 directive, and you'll get if the function is being referenced somewhere.

I repeat, you cannot easily know if a function will be called in your code, you can know if it is referenced somewhere.

I don't know what are you trying to identify with this question, but you can run into the XY problem instance (what you ask is not what you try to solve)

By the way, defined functions in .h header files are commonly declared inline by developers to optimice function call/return execution.  For this reason, they will be inlined where they are used and so, no reference appears to them on linking, so you have to search for them in the code (with the added problem of being macro expanded, so you need to run the preprocessor first to find the references to those functions)


问:
How to modify a specific @type from DefinitelyTyped npm
I am adding a package(ng2-vis) to my angular 4 project and
need to add a new event name to the type definitions package
https://www.npmjs.com/package/@types/vis, which it is a dependency from ng2-vis. What I have donde before in a similar case is to fork the repository, modify the files, rename it and then publish it to the npm repository, but in this case @types/vis is inside the DefinitelyTyped repo. I also tried to add the event name modifying directly my node_modules/@types/vis/index.d.ts from the project but its not working (like they recommend here https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md on How can I contribute?->Test)</p>

答:
You can use type augmentation, see https://www.typescriptlang.org/docs/handbook/declaration-merging.html.

You can do it by creating your own typings file and include this in your typescript compiling. If done correctly, the compiler will merge the declarations.


问:
FileReader buffer different from different safari
I have two iPhones who upload jpg files to Node.js server via websockets with help of socket.io like this

```<code>var reader = new FileReader();
reader.onload = function () {
    socket.emit(
        'chat_file',
        {
            body: reader.result
        }
    );
};
reader.readAsArrayBuffer(uploadedFile);
</code>```

Problem is if all modern browser upload looks like this on Node.js side

```<code>Oct 04 11:01:01 test-chat1.bnk.ef.lan node[30130]: { name: 'image2.jpg',
Oct 04 11:01:01 test-chat1.bnk.ef.lan node[30130]: body: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 01 00 f0 00 f0 00 00 ff db 00 43 00 03 02 02 03 02 02 03 03 03 03 04 03 03 04 05 08 05 05 04 04 05 0a 07 07 06 ... >,
Oct 04 11:01:01 test-chat1.bnk.ef.lan node[30130]: size: 95712 } }
</code>```

File body is a buffer, on old iPhone 4, with Safari version 8 i am getting

```<code>Oct 04 11:00:25 test-chat1.bnk.ef.lan node[30088]: { room: '1','image.jpg', body: { byteLength: 889942 }, size: 889942 } }
</code>```

here body type is not a buffer, i've tried Buffer.alloc() and Buffer.from() but no luck (logically), in case of from i am getting

```<code>TypeError: First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.
</code>```

and in case of alloc it is

```<code>TypeError: Data must be a string or a buffer
</code>```

p.s. On client side on both old and new version of safari reader.result is typeof ArrayBuffer but old safari have slice method in it

p.p.s But ArrayBuffers body are different (old safari on the right side)

答: Reason was simple, old Safari doesn't send file body over WebSockets, so server side you will just get event about file being send, but without file actually. </p>

Body:
I have two iPhones who upload jpg files to Node.js server via websockets with help of socket.io like this

var reader = new FileReader();
reader.onload = function () {
    socket.emit(
        'chat_file',
        {
            body: reader.result
        }
    );
};
reader.readAsArrayBuffer(uploadedFile);

Problem is if all modern browser upload looks like this on Node.js side

Oct 04 11:01:01 test-chat1.bnk.ef.lan node[30130]: { name: 'image2.jpg',
Oct 04 11:01:01 test-chat1.bnk.ef.lan node[30130]: body: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 01 00 f0 00 f0 00 00 ff db 00 43 00 03 02 02 03 02 02 03 03 03 03 04 03 03 04 05 08 05 05 04 04 05 0a 07 07 06 ... >,
Oct 04 11:01:01 test-chat1.bnk.ef.lan node[30130]: size: 95712 } }

File body is a buffer, on old iPhone 4, with Safari version 8 i am getting

Oct 04 11:00:25 test-chat1.bnk.ef.lan node[30088]: { room: '1','image.jpg', body: { byteLength: 889942 }, size: 889942 } }

here body type is not a buffer, i've tried Buffer.alloc() and Buffer.from() but no luck (logically), in case of from i am getting

TypeError: First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.

and in case of alloc it is

TypeError: Data must be a string or a buffer

p.s. On client side on both old and new version of safari reader.result is typeof ArrayBuffer but old safari have slice method in it

p.p.s But ArrayBuffers body are different (old safari on the right side)


问:
Static assets don't show up for flask on elastic beanstalk
How do you get aws elastic beanstalk to recognize your static assets in your flask app? I did the standard /.ebextensions/python.config couple of YAML lines a la:

```<code>option_settings:
  "aws:elasticbeanstalk:container:python:staticfiles":
    "/static/": "static/"
</code>```

All of my calls to assets in templates are wrapped in "{{url_for('static', filename='img/office.jpg')}}" type things.

But no images, styles or javascript shows up on page load. Here is an example log file 404.
IP - - [25/Feb/2013:21:48:13 +0000] "GET /static/css/bootstrap.css HTTP/1.1" 404 328 "http://xyz.elasticbeanstalk.com/"

Am I missing something obvious? Everything runs great on my local, just static assets dont load once i git aws.push

答:
It can be done also through Elastic Beanstalk Panel:

Configuration -> Software Configuration - > Static Files

and then

just as an alternative option

Body:
How do you get aws elastic beanstalk to recognize your static assets in your flask app? I did the standard /.ebextensions/python.config couple of YAML lines a la:

option_settings:
  "aws:elasticbeanstalk:container:python:staticfiles":
    "/static/": "static/"

All of my calls to assets in templates are wrapped in "{{url_for('static', filename='img/office.jpg')}}" type things.

But no images, styles or javascript shows up on page load. Here is an example log file 404.
IP - - [25/Feb/2013:21:48:13 +0000] "GET /static/css/bootstrap.css HTTP/1.1" 404 328 "http://xyz.elasticbeanstalk.com/"

Am I missing something obvious? Everything runs great on my local, just static assets dont load once i git aws.push


问:
Tomcat NTLM Username lookup in Win7 AD environment - samba or waffle?
I'm writing a Java Tomcat intranet app that uses NTLM to lookup a user's name. This is in a Win7 Active Directory environment.

Is it better to use Waffle or Spnego for this? (Or something better?)

答: Waffle has a huge following now, and will do the job well. But I am bias :)</p>


问:
Stanford Classifier ColumnDataClassifier
I am using the Maximum Entropy algorithm provided by the Stanford Classifier in order to perform a customized Named Entity Recognition.
The output file provides 5 columns --> word \t ground-truth \t label \t P(clAnswer) \t P(goldAnswer))

Which is the difference between P(clAnswer) and P(goldAnswer) and how are these calculated?

答:
P(clAnswer) is the probability the model gives the guess.
P(goldAnswer) is the probability the model gives the true gold answer.

If you want to understand the algorithm behind the classifier you can find resources at this link: https://nlp.stanford.edu/software/classifier.shtml

I should note that it is standard to use the CRFClassifier to train NER models.  There is exhaustive documentation here about training an NER model:

https://nlp.stanford.edu/software/crf-faq.html#a

ContentLicense: CC BY-SA 4.0


问:
wordpress plugin -> Call to undefined function wp_get_current_user()
I'm trying to get the current user info in my plugin using the func wp_get_current_user(). But am getting
Call to undefined function wp_get_current_user()

Apparently this is happening because the file /wp-includes/pluggable which contains the function doesn't get loaded until after the plugins are loaded.

Anybody any ideas on how to get the user details in my plugin?

答:
NOT wp-includes but :

```<code>include_once(ABSPATH . "wp-admin/includes/plugin.php");
</code>```

Body:
NOT wp-includes but :

include_once(ABSPATH . "wp-admin/includes/plugin.php");


问:
How to subscribe to a specific child route parameter?
I have these two route definitions, product list and product detail:

```<code>const routes: Routes = [
    ...
    {
        path: 'product',
        component: ProductListComponent,
        resolve: {
            products: ProductListResolverService
        },
        children: [
            {
                path: ':productcode',
                component: ProductDetailComponent,
                resolve: {
                    product: ProductDetailResolverService
                }
            },
            ...
        ]
    }
    ...
</code>```

Inside the product list component I have a set of radio buttons to indicate which product is selected, while the router outlet displays the product detail component:

```<code><div *ngFor="let product of Products" class="radio">
    <label>
        <input [(ngModel)]="SelectedProduct"
            [value]="product"
            (change)="RefreshDetail()"
            name="selectedProduct"
            type="radio">
            {{product.Name}} {{product.Code}}
    </label>
</div>
<router-outlet></router-outlet>
</code>```

When the user clicks the radio button, the URL, the product detail component, and the radio button are synchronized correctly.

But when the user goes directly to a certain product URL, the URL and product detail component display the correct product, but the radio button doesn't. What I mean by going directly to a certain product URL is the user inputs the URL to the browser address bar and press enter.

I tried to get the value of :productcode from ActivatedRoute but it didn't work:

```<code>this.route.paramMap.subscribe(params => {
  let productcode = params.get("productcode");

  let product = this.Products.find(product => product.Code == productcode);

  if (!!product) {
    this.SelectedProduct = product;
  }
});
</code>```

The paramMap.get("productcode") is always null. Probably because it is not available in the product list route, but in the child route, the product detail route.

I haven't found a way to subscribe to product detail route from product list component. Besides product detail route is not the only child of product list route.

How do I subscribe to a specific child route parameter?

答:
One of the better way is to use the service and  observable. So that, whenever the child component changes, the new data will get immediately reflected in the parent component (especially when u refresh the page you can retain your parent component status).

In your ProductDetailComponent,

```<code>import { Subscription } from 'rxjs';
import { Router, ActivatedRoute } from '@angular/router';
import { ProductService } from './product.service';

export class ProductDetailComponent {
    private subscription:Subscription;

    constructor(private activatedRoute:ActivatedRoute, private productService:productService){
    }

    public ngOnInit() {
      let vm = this;
      this.subscription = this.activatedRoute.params.subscribe(
          (param: any) => {
            if(typeof param['productcode'] !== 'undefined' && param['productcode'].trim !='' &&  typeof param['productcode']!=null){
               vm.productService.changedProductCode(param['productcode']);
            }
      });
    }
}
</code>```

in your product.service.ts,

```<code>import { Subject } from 'rxjs/Subject'
import { Observable } from 'rxjs/Rx';

@Injectable()
export class myService {

  private productCode = new Subject<string>();

  productCodeChange$ = this.productCode.asObservable();
  changedProductCode(option:any){
        this.productCode.next(option);
  }
}
</code>```

Now, to get the changed product id in your parent component,

ProductListComponent.ts

```<code>import { Subscription } from 'rxjs';
import { ProductService } from './product.service';

export class ProductListComponent {

    private subscription:Subscription;

    constructor(private productService:productService){

        this.productService.productCodeChange$.subscribe( /* get called on every child page changes*/
         code => {

        console.log(code); // you get your passed code value in 'code' variable

        let product = this.Products.find(product => product.Code == code);

        if (!!product) {
          this.SelectedProduct = product;
        }
    });
  }
}
</code>```

Body:
I have these two route definitions, product list and product detail:

const routes: Routes = [
    ...
    {
        path: 'product',
        component: ProductListComponent,
        resolve: {
            products: ProductListResolverService
        },
        children: [
            {
                path: ':productcode',
                component: ProductDetailComponent,
                resolve: {
                    product: ProductDetailResolverService
                }
            },
            ...
        ]
    }
    ...

Inside the product list component I have a set of radio buttons to indicate which product is selected, while the router outlet displays the product detail component:

        <input [(ngModel)]="SelectedProduct"
            [value]="product"
            (change)="RefreshDetail()"
            name="selectedProduct"
            type="radio">
            {{product.Name}} {{product.Code}}

<router-outlet></router-outlet>

When the user clicks the radio button, the URL, the product detail component, and the radio button are synchronized correctly.

But when the user goes directly to a certain product URL, the URL and product detail component display the correct product, but the radio button doesn't. What I mean by going directly to a certain product URL is the user inputs the URL to the browser address bar and press enter.

I tried to get the value of :productcode from ActivatedRoute but it didn't work:

this.route.paramMap.subscribe(params => {
  let productcode = params.get("productcode");

  let product = this.Products.find(product => product.Code == productcode);

  if (!!product) {
    this.SelectedProduct = product;
  }
});

The paramMap.get("productcode") is always null. Probably because it is not available in the product list route, but in the child route, the product detail route.

I haven't found a way to subscribe to product detail route from product list component. Besides product detail route is not the only child of product list route.

How do I subscribe to a specific child route parameter?

Body:
One of the better way is to use the service and  observable. So that, whenever the child component changes, the new data will get immediately reflected in the parent component (especially when u refresh the page you can retain your parent component status).

In your ProductDetailComponent,

import { Subscription } from 'rxjs';
import { Router, ActivatedRoute } from '@angular/router';
import { ProductService } from './product.service';

export class ProductDetailComponent {
    private subscription:Subscription;

    constructor(private activatedRoute:ActivatedRoute, private productService:productService){
    }

    public ngOnInit() {
      let vm = this;
      this.subscription = this.activatedRoute.params.subscribe(
          (param: any) => {
            if(typeof param['productcode'] !== 'undefined' && param['productcode'].trim !='' &&  typeof param['productcode']!=null){
               vm.productService.changedProductCode(param['productcode']);
            }
      });
    }
}

in your product.service.ts,

import { Subject } from 'rxjs/Subject'
import { Observable } from 'rxjs/Rx';

@Injectable()
export class myService {

  private productCode = new Subject<string>();

  productCodeChange$ = this.productCode.asObservable();
  changedProductCode(option:any){
        this.productCode.next(option);
  }
}

Now, to get the changed product id in your parent component,

ProductListComponent.ts

import { Subscription } from 'rxjs';
import { ProductService } from './product.service';

export class ProductListComponent {

    private subscription:Subscription;

    constructor(private productService:productService){

        this.productService.productCodeChange$.subscribe( /* get called on every child page changes*/
         code => {

        console.log(code); // you get your passed code value in 'code' variable

        let product = this.Products.find(product => product.Code == code);

        if (!!product) {
          this.SelectedProduct = product;
        }
    });
  }
}


问:
removing certain objects from list of objects in c#
i have a list of objects </p>

```<code>    public int id { get; set; }
    public string device_code { get; set; }
    public string device_type { get; set; }
    public string authentication_token { get; set; }
    public string Status { get; set; }
</code>```

<p>while returning the list i want to remove "device_code" and "device_type" from the list and return the list only with "id","authentication_token" and "status".
How can I delete certain objects? </p>

答:
It's simple, create another class containing properties that are required and then return its object using the list you have created.

Original Class

```<code>public class Data {
    public int id { get; set; }
    public string device_code { get; set; }
    public string device_type { get; set; }
    public string authentication_token { get; set; }
    public string Status { get; set; }
}
</code>```

Class That will be returned

```<code>public class DataTobeReturned {
    public int id { get; set; }
    public string authentication_token { get; set; }
    public string Status { get; set; }
}
</code>```

Suppose you have list like

```<code>List<Data> list = // some data;
</code>```

You can do

```<code>List<DataTobeReturned> list2 = list.Select(x => new DataTobeReturned { x.id, x.Status, x.authentication_token}).ToList();
</code>```

Simply return the list2 object.

Body:
i have a list of objects

    public int id { get; set; }
    public string device_code { get; set; }
    public string device_type { get; set; }
    public string authentication_token { get; set; }
    public string Status { get; set; }

while returning the list i want to remove "device_code" and "device_type" from the list and return the list only with "id","authentication_token" and "status".
How can I delete certain objects?

Body:
It's simple, create another class containing properties that are required and then return its object using the list you have created.

Original Class

public class Data {
    public int id { get; set; }
    public string device_code { get; set; }
    public string device_type { get; set; }
    public string authentication_token { get; set; }
    public string Status { get; set; }
}

Class That will be returned

public class DataTobeReturned {
    public int id { get; set; }
    public string authentication_token { get; set; }
    public string Status { get; set; }
}

Suppose you have list like

List<Data> list = // some data;

You can do

List<DataTobeReturned> list2 = list.Select(x => new DataTobeReturned { x.id, x.Status, x.authentication_token}).ToList();

Simply return the list2 object.


问:
Python merge all child list into parent list and remove duplicates
I have a huge list of lists.
I want to Merge all child lists to parent list
and remove duplicates item from parent list after merge.

What is the optimized way to do this?

For Example:

```<code>x = [['a', 'b', 'c', 2, 4], ['x', 1, 2, 3, 'z'], ['z', 'b', 'y', 'a' 'x']]
</code>```

How we can get the value of x like:

['a', 'b', 'c', 1, 2, 3, 4, 'z', 'y', 'x']

答:
Use set and chain:</p>

```<code>x = [['a', 'b', 'c', 2, 4], ['x', 1, 2, 3, 'z'], ['z', 'b', 'y', 'a' 'x']]

from itertools import chain

result = list(set(chain.from_iterable(x)))
print(result)
</code>```

Body:
I have a huge list of lists.
I want to Merge all child lists to parent list
and remove duplicates item from parent list after merge.

What is the optimized way to do this?

For Example:

x = [['a', 'b', 'c', 2, 4], ['x', 1, 2, 3, 'z'], ['z', 'b', 'y', 'a' 'x']]

How we can get the value of x like:

['a', 'b', 'c', 1, 2, 3, 4, 'z', 'y', 'x']

Body:
Use set and chain:

x = [['a', 'b', 'c', 2, 4], ['x', 1, 2, 3, 'z'], ['z', 'b', 'y', 'a' 'x']]

from itertools import chain

result = list(set(chain.from_iterable(x)))
print(result)


问:
Doctrine query builder find by interests
today i have an interest task - realize search on DB by some groups and sort it by most relevant criteria

We have 2 entities (User and Interests) on Symfony with ManyToMany relation

We need create query for find users which have most similar interests
ex:

user1 have interests [1,2,3,4,5]

user2 have interests [1,2,4,5,7]

user3 have interests [3,5]

we try find user with interests [2,6,7] and result must be:

```<code>[user2, user1, user0]

user2 - 2 similar interests

user1 - 1 similar interests

user3 - 0
</code>```

Code example:

```<code>class User
{
    // ...

    /**
     * Many Users have Many Interests.
     * @ManyToMany(targetEntity="Interest")
     * @JoinTable(name="users_interests",
     *      joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")},
     *      inverseJoinColumns={@JoinColumn(name="interest_id", referencedColumnName="id")}
     *      )
     */
    private $interests;
...
</code>```

I have no idea how to organize it nicely, can somebody help me?
Thanks!

答:
One way of doing it

Find user with at least 1 interest of your list (Simple Dql Query)

Count number of common interest in php.

For example using count(array_intersect($userInterestsIds, $wantedIds))

You have all the wanted info, display it as you want

Body:
today i have an interest task - realize search on DB by some groups and sort it by most relevant criteria

We have 2 entities (User and Interests) on Symfony with ManyToMany relation

We need create query for find users which have most similar interests
ex:

user1 have interests [1,2,3,4,5]

user2 have interests [1,2,4,5,7]

user3 have interests [3,5]

we try find user with interests [2,6,7] and result must be:

[user2, user1, user0]

user2 - 2 similar interests

user1 - 1 similar interests

user3 - 0

Code example:

class User
{
    // ...

    /**
     * Many Users have Many Interests.
     * @ManyToMany(targetEntity="Interest")
     * @JoinTable(name="users_interests",
     *      joinColumns={@JoinColumn(name="user_id", referencedColumnName="id")},
     *      inverseJoinColumns={@JoinColumn(name="interest_id", referencedColumnName="id")}
     *      )
     */
    private $interests;
...

I have no idea how to organize it nicely, can somebody help me?
Thanks!


问:
Missing fuzzystringmatch extension pg admin
I had a problem recentley with the following output from java with hibernate trying to execute a query.

```<code>Caused by: org.postgresql.util.PSQLException: ERRORE: la funzione levenshtein_less_equal(text, character varying, integer) non esiste
  Suggerimento: Nessuna funzione trovata con nome e tipi di argomenti forniti. Potrebbe essere necessario convertire i tipi esplicitamente.
  Posizione: 464
</code>```

Sorry for the italian log for error, basically says that function doesn't exists with that kind of parameters. I checked on my functions on the DB and I had a function called:

```<code>levenshtein_less_equal(text, text, integer)
</code>```

Now, first I don't understand why query.setparameter on java, which sets both the 1st and the 2nd argument of the function with a string would end up with such function call

```<code>levenshtein_less_equal(text, character varying, integer)
</code>```

Both are strings but one is mapped to text and one to character varying??

Second I don't understand why I solved this by adding the fuzzystrmatch extension to the DB extensions.

答:
levenshtein_less_equal(text, text, integer) is a function to compare two strings in postgres, it's part of the Fuzzymatch module that contains functions to get the distance between strings see: fuzzystrmatch, one of the ways to compare string is called the Levenshtein distance.

When you do setParameter()in Hibernate you indirectly trigger a string comparison, I don't see your data but I think your data has special characters, here is a link to a stack overflow question that disscusses the same problem: link.

So what is basically happening here is that Postgres is trying to get an approximation for the strings that it doesn't understand in order to get a match and it's using the Levenshtein Distance to do so.

Body:
I had a problem recentley with the following output from java with hibernate trying to execute a query.

Caused by: org.postgresql.util.PSQLException: ERRORE: la funzione levenshtein_less_equal(text, character varying, integer) non esiste
  Suggerimento: Nessuna funzione trovata con nome e tipi di argomenti forniti. Potrebbe essere necessario convertire i tipi esplicitamente.
  Posizione: 464

Sorry for the italian log for error, basically says that function doesn't exists with that kind of parameters. I checked on my functions on the DB and I had a function called:

levenshtein_less_equal(text, text, integer)

Now, first I don't understand why query.setparameter on java, which sets both the 1st and the 2nd argument of the function with a string would end up with such function call

levenshtein_less_equal(text, character varying, integer)

Both are strings but one is mapped to text and one to character varying??

Second I don't understand why I solved this by adding the fuzzystrmatch extension to the DB extensions.


问:
How to Use 1st Class Properties and Methods in 2nd Class?
I have two classes. Lets call them 'Class_A' and 'Class_B'. I want to use 'Class_A' properties and methods in 'Class B'. Like this...

```<code>$a = new Class_A;

class Class_B {

    function __construct() {

        $a->foo = 2;

        $a->magic();

    }

}
</code>```

Of course, it do not work. What is the best practice to deal with it?

'global' keyword?

Make properties and methods of 'Class_A' static?

Another way...?

答:
If you need an instance of class Class_A, then pass it to class Class_Bs constructor:

```<code>class Class_B {
    function __construct($a) {
        $a->foo = 2;
        $a->magic();
    }
}

$a_instance = new Class_A();

$b = new Class_B($a_instance);
</code>```

If class Class_A does not need to be instantiated in order to perform its tasks, define properties and methods as static instead and call them with Class_A::method();

Avoid globals. If Class_B is also a Class_B (e.g. a banana is a fruit), then you probably go better with inheritance.

Body:
I have two classes. Lets call them 'Class_A' and 'Class_B'. I want to use 'Class_A' properties and methods in 'Class B'. Like this...

$a = new Class_A;

class Class_B {

    function __construct() {

        $a->foo = 2;

        $a->magic();

    }

}

Of course, it do not work. What is the best practice to deal with it?

'global' keyword?

Make properties and methods of 'Class_A' static?

Another way...?

Body:
If you need an instance of class Class_A, then pass it to class Class_Bs constructor:

class Class_B {
    function __construct($a) {
        $a->foo = 2;
        $a->magic();
    }
}

$a_instance = new Class_A();

$b = new Class_B($a_instance);

If class Class_A does not need to be instantiated in order to perform its tasks, define properties and methods as static instead and call them with Class_A::method();

Avoid globals. If Class_B is also a Class_B (e.g. a banana is a fruit), then you probably go better with inheritance.


问:
Use text field to add a record in Yii2
How can I add a record via a text  field in yii2?

Please explain what I have to do in the Controller and View and models and anything that I need

```<code>public function actionAdd() {
  ????
}
</code>```

答:
you must have form with the action name like this

controller :

```<code>public function actionCreate()
{
  $model = new News();
  if($model->load(Yii::$app->request->post())){
     if($model->save())
         return $this->redirect(['view', 'id' => $model->id ]);
     }
}
</code>```

in view folder:

create.php:

```<code><?php $form = ActiveForm::begin() ?>

    <?= $form->field($model, 'text') ?>

    <?= Html::submitButton('submit') ?>

 <?php ActiveForm::end() ?>
</code>```

Title: Use text field to add a record in Yii2

Body:
How can I add a record via a text  field in yii2?

Please explain what I have to do in the Controller and View and models and anything that I need

public function actionAdd() {
  ????
}

Body:
you must have form with the action name like this

controller :

public function actionCreate()
{
  $model = new News();
  if($model->load(Yii::$app->request->post())){
     if($model->save())
         return $this->redirect(['view', 'id' => $model->id ]);
     }
}

in view folder:

create.php:

<?php $form = ActiveForm::begin() ?>

    <?= $form->field($model, 'text') ?>

    <?= Html::submitButton('submit') ?>

 <?php ActiveForm::end() ?>


问:
Apache couchdb system minimum requirements
I checked all the documentation of couch DB. There is no mention of the system requirements.
I want to install CouchDB on AWS nano machine and wondering if it is possible.

Question
What are the CoupchDB minimum system requirements? (RAM, CPU, disk)

答: I have not seen any official minimum requirements. I have the smallest DigitalOcean droplet running Ubuntu Server with the CouchDB 2.1.1 on it (and it previously ran version 1.6.1). It works well, but is only used as a test machine for a development project. The spec is one CPU, 512mb RAM and 20gb SSD disk.</p>


答:
first you can convert the list of list into a one list and than apply set to that list.

```<code>x = [['a', 'b', 'c', 2, 4], ['x', 1, 2, 3, 'z'], ['z', 'b', 'y', 'a' 'x']]
new_ls=[]
for ls in x:
    new_ls.extend(ls)
print(list(set(new_ls))
</code>```

output:

```<code>[1, 2, 3, 4, 'ax', 'b', 'y', 'x', 'c', 'z', 'a']
</code>```

Title: Python merge all child list into parent list and remove duplicates

Body:
first you can convert the list of list into a one list and than apply set to that list.

x = [['a', 'b', 'c', 2, 4], ['x', 1, 2, 3, 'z'], ['z', 'b', 'y', 'a' 'x']]
new_ls=[]
for ls in x:
    new_ls.extend(ls)
print(list(set(new_ls))

output:

[1, 2, 3, 4, 'ax', 'b', 'y', 'x', 'c', 'z', 'a']


问:
Merge two codes to pick up data
I'm trying to pull customer data from my store, I have a code that does exactly what I need, except that some attributes have the value as text, so it returns me 0. Even with a text value, magento assigns a numeric value to the attribute , I know where to get that number from this attribute, how would I get this attribute number per client?

In this code I get the numeric values of the attribute with text value

```<code>$config    = Mage::getModel('eav/config');

$attribute = $config->getAttribute('customer_address', 'esmart_address_type');
$values    = $attribute->getSource()->getAllOptions();
print_r($values);

//here is another method
$options = Mage::getResourceModel('eav/entity_attribute_option_collection');
$values  = $options->setAttributeFilter($attribute->getId())->toOptionArray();
print_r($values);
</code>```

Return

```<code>[1] => Array
    (
        [value] => 8993
        [label] => Residencial
    )

[2] => Array
    (
        [value] => 8994
        [label] => Comercial
    )
</code>```

From this other way it's how I get the customer's data, I make a repeat loop to pick up from all the customers, however as I explained the attributes with text values come as 0, I would need to bring the number value as in the code above, as would I implement the above code in this current to bring all the data together?

```<code>ini_set("display_errors", 1);
ini_set('memory_limit','1024M');
require_once('app/Mage.php');
Mage::app(0);

$users = Mage::getModel('customer/address')->getCollection();

$i = 1;
foreach ($users as $key => $user) {
    $id = $user->getId();

    $usuario_loaded = Mage::getModel('customer/address')->load($id);

    $tudo = array('id'=>addslashes($usuario_loaded->getId()), 'endereço_id'=>addslashes($usuario_loaded->getId()), 'smsmessagex'=>addslashes($usuario_loaded->getEsmartFlSmsMessage()), 'smsmessagexx'=>addslashes($usuario_loaded->getEsmartFlSmsConfirmation()), 'prefixo'=>addslashes($usuario_loaded->getPrefix()), 'nome'=>addslashes($usuario_loaded->getFirstname()), 'relaçao'=>addslashes($usuario_loaded->getEsmartRelationship()), 'ocasiao'=>addslashes($usuario_loaded->getEsmartOccasion()), 'tipoend'=>addslashes($usuario_loaded->getEsmartAddressType()));

    var_dump($tudo);
}
</code>```

I can bring all fields with 'example'=>addslashes($user_loaded-> getExample()) but fields that have been created with text value bring me0 or ''

 What I Pull

```<code>'tipoend'=>addslashes($username_loaded->getEsmartAddressType())

array (1) {
  ["tipoend"] =>
  string (1) "0"
}
</code>```

 What I'd like to pull
Only with getEsmartAddressType I do not get this value I need, how would I get the value 8993 as I get in the first code? I need to get each customer (70 thousand).

```<code>'tipoend'=>addslashes($username_loaded->getEsmartAddressType())

array (1) {
  ["tipoend"] =>
  string (1) "8993"
}
</code>```

答:
```<code>$model->getResource()->getAttribute('attribute_code')->getFrontendLabel();
</code>```

or

```<code>$model->getAttributeText('attribute_code');
</code>```

your example

```<code>'tipoend'=>addslashes($username_loaded->getAttributeText('esmart_address_type'))
</code>```

UPDATE

also this line is wrong (you can't load addresses with user id)

```<code>$usuario_loaded = Mage::getModel('customer/address')->load($id);
</code>```

because address entities have their own ids

Title: Merge two codes to pick up data

Body:
I'm trying to pull customer data from my store, I have a code that does exactly what I need, except that some attributes have the value as text, so it returns me 0. Even with a text value, magento assigns a numeric value to the attribute , I know where to get that number from this attribute, how would I get this attribute number per client?

In this code I get the numeric values of the attribute with text value

$config    = Mage::getModel('eav/config');

$attribute = $config->getAttribute('customer_address', 'esmart_address_type');
$values    = $attribute->getSource()->getAllOptions();
print_r($values);

//here is another method
$options = Mage::getResourceModel('eav/entity_attribute_option_collection');
$values  = $options->setAttributeFilter($attribute->getId())->toOptionArray();
print_r($values);

Return

[1] => Array
    (
        [value] => 8993
        [label] => Residencial
    )

[2] => Array
    (
        [value] => 8994
        [label] => Comercial
    )

From this other way it's how I get the customer's data, I make a repeat loop to pick up from all the customers, however as I explained the attributes with text values come as 0, I would need to bring the number value as in the code above, as would I implement the above code in this current to bring all the data together?

ini_set("display_errors", 1);
ini_set('memory_limit','1024M');
require_once('app/Mage.php');
Mage::app(0);

$users = Mage::getModel('customer/address')->getCollection();

$i = 1;
foreach ($users as $key => $user) {
    $id = $user->getId();

    $usuario_loaded = Mage::getModel('customer/address')->load($id);

    $tudo = array('id'=>addslashes($usuario_loaded->getId()), 'endereço_id'=>addslashes($usuario_loaded->getId()), 'smsmessagex'=>addslashes($usuario_loaded->getEsmartFlSmsMessage()), 'smsmessagexx'=>addslashes($usuario_loaded->getEsmartFlSmsConfirmation()), 'prefixo'=>addslashes($usuario_loaded->getPrefix()), 'nome'=>addslashes($usuario_loaded->getFirstname()), 'relaçao'=>addslashes($usuario_loaded->getEsmartRelationship()), 'ocasiao'=>addslashes($usuario_loaded->getEsmartOccasion()), 'tipoend'=>addslashes($usuario_loaded->getEsmartAddressType()));

    var_dump($tudo);
}

I can bring all fields with 'example'=>addslashes($user_loaded-> getExample()) but fields that have been created with text value bring me0 or ''

 What I Pull

'tipoend'=>addslashes($username_loaded->getEsmartAddressType())

array (1) {
  ["tipoend"] =>
  string (1) "0"
}

 What I'd like to pull
Only with getEsmartAddressType I do not get this value I need, how would I get the value 8993 as I get in the first code? I need to get each customer (70 thousand).

'tipoend'=>addslashes($username_loaded->getEsmartAddressType())

array (1) {
  ["tipoend"] =>
  string (1) "8993"
}

Body:
$model->getResource()->getAttribute('attribute_code')->getFrontendLabel();

or

$model->getAttributeText('attribute_code');

your example

'tipoend'=>addslashes($username_loaded->getAttributeText('esmart_address_type'))

UPDATE

also this line is wrong (you can't load addresses with user id)

$usuario_loaded = Mage::getModel('customer/address')->load($id);

because address entities have their own ids


问:
Apache Kafka consumer implemented in Golang panics when deployed to Docker
here is my attempt in implementing a simple microservice that is supposed to read messages from a kafka server and send it via HTTP. It works fine when i run it from the terminal, but when deployed on to docker it panics with

```<code>panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x40 pc=0x7b6345]

goroutine 12 [running]:
main.kafkaRoutine.func1(0xc420174060, 0x0, 0x0)
    /go/src/github.com/deathcore666/ProperConsumerServiceYo/kafka.go:36 +0x95
created by main.kafkaRoutine
    /go/src/github.com/deathcore666/ProperConsumerServiceYo/kafka.go:32 +0x1ad
</code>```

kafka.go lines 32 and 36 are the ones where  go func(pc sarama.PartitionConsumer) function sits.
I am relatively new to programming, so any help would be appreciated. Thank you!

main.go:

```<code>func main() {
var (
    listen = flag.String("listen", ":8080", "HTTP listen address")
    proxy  = flag.String("proxy", "", "Optional comma-separated list of URLs to proxy uppercase requests")
)
flag.Parse()

logger := log.NewLogfmtLogger(os.Stderr)

var svc KafkaService
svc = kafkaService{}
svc = proxyingMiddleware(context.Background(), *proxy, logger)(svc)
svc = loggingMiddleware(logger)(svc)

consumehandler := httptransport.NewServer(
    makeConsumeEndpoint(svc),
    decodeConsumeRequest,
    encodeResponse,
)

http.Handle("/consume", consumehandler)

logger.Log("msg", "HTTP", "addr", *listen)
logger.Log("err", http.ListenAndServe(*listen, nil))}
</code>```

service.go:

```<code>    package main

import (
    "context"
    "errors"
    "time"
)

//KafkaService yolo
type KafkaService interface {
    Consume(context.Context, string) (string, error)
}

//ErrEmpty yolo
var ErrEmpty = errors.New("No topic provided")

type kafkaService struct{}

//Consumer logic implemented here
func (kafkaService) Consume(_ context.Context, topic string) (string, error) {
    if topic == "" {
        return "", ErrEmpty
    }

    var inChan = make(chan string)
    var readyChan = make(chan struct{})
    var result string
    var brokers = []string{"192.168.88.208:9092"}
    //var brokersLocal = []string{"localhost:9092"}
    go kafkaRoutine(inChan, topic, brokers)
    go func() {
        for {
            select {
            case msg := <-inChan:
                result = result + msg + "\n"
            case <-time.After(time.Second * 1):
                readyChan <- struct{}{}
            }

        }
    }()

    <-readyChan
    close(inChan)
    return result, nil
}

//ServiceMiddleware is a chainable thing for the service
type ServiceMiddleware func(KafkaService) KafkaService
</code>```

kafka.go:

```<code>package main

import (
    "fmt"
    "time"

    "github.com/Shopify/sarama"
)

func kafkaRoutine(inChan chan string, topic string, brokers []string) {
    config := sarama.NewConfig()
    config.Consumer.Return.Errors = true
    consumer, err := sarama.NewConsumer(brokers, config)
    if err != nil {
        panic(err)
    }

    topics, _ := consumer.Topics()
    if !(containsTopic(topics, topic)) {
        inChan <- "There is no such a topic"
        fmt.Println("kafkaroutine exited")
        return
    }

    partitionList, err := consumer.Partitions(topic)
    for _, partition := range partitionList {
        pc, _ := consumer.ConsumePartition(topic, partition, sarama.OffsetOldest)
        go func(pc sarama.PartitionConsumer) {
        loop:
            for {
                select {
                case msg := <-pc.Messages():
                    inChan <- string(msg.Value)
                case <-time.After(time.Second * 1):
                    break loop
                }
            }
        }(pc)
    }
    fmt.Println("Kafka GoRoutine exited")
}

func containsTopic(topics []string, topic string) bool {
    for _, v := range topics {
        if topic == v {
            return true
        }
    }
    return false
}
</code>```

答: On line 27 of kafka.go, you are ignoring the error returned from ConsumePartition(). It's likely that it's returning an error and not a valid partition consumer, but since you're ignoring it when you attempt to use the partition consumer it's crashing.

Body:
here is my attempt in implementing a simple microservice that is supposed to read messages from a kafka server and send it via HTTP. It works fine when i run it from the terminal, but when deployed on to docker it panics with

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x40 pc=0x7b6345]

goroutine 12 [running]:
main.kafkaRoutine.func1(0xc420174060, 0x0, 0x0)
    /go/src/github.com/deathcore666/ProperConsumerServiceYo/kafka.go:36 +0x95
created by main.kafkaRoutine
    /go/src/github.com/deathcore666/ProperConsumerServiceYo/kafka.go:32 +0x1ad

kafka.go lines 32 and 36 are the ones where  go func(pc sarama.PartitionConsumer) function sits.
I am relatively new to programming, so any help would be appreciated. Thank you!

main.go:

func main() {
var (
    listen = flag.String("listen", ":8080", "HTTP listen address")
    proxy  = flag.String("proxy", "", "Optional comma-separated list of URLs to proxy uppercase requests")
)
flag.Parse()

logger := log.NewLogfmtLogger(os.Stderr)

var svc KafkaService
svc = kafkaService{}
svc = proxyingMiddleware(context.Background(), *proxy, logger)(svc)
svc = loggingMiddleware(logger)(svc)

consumehandler := httptransport.NewServer(
    makeConsumeEndpoint(svc),
    decodeConsumeRequest,
    encodeResponse,
)

http.Handle("/consume", consumehandler)

logger.Log("msg", "HTTP", "addr", *listen)
logger.Log("err", http.ListenAndServe(*listen, nil))}

service.go:

    package main

import (
    "context"
    "errors"
    "time"
)

//KafkaService yolo
type KafkaService interface {
    Consume(context.Context, string) (string, error)
}

//ErrEmpty yolo
var ErrEmpty = errors.New("No topic provided")

type kafkaService struct{}

//Consumer logic implemented here
func (kafkaService) Consume(_ context.Context, topic string) (string, error) {
    if topic == "" {
        return "", ErrEmpty
    }

    var inChan = make(chan string)
    var readyChan = make(chan struct{})
    var result string
    var brokers = []string{"192.168.88.208:9092"}
    //var brokersLocal = []string{"localhost:9092"}
    go kafkaRoutine(inChan, topic, brokers)
    go func() {
        for {
            select {
            case msg := <-inChan:
                result = result + msg + "\n"
            case <-time.After(time.Second * 1):
                readyChan <- struct{}{}
            }

        }
    }()

    <-readyChan
    close(inChan)
    return result, nil
}

//ServiceMiddleware is a chainable thing for the service
type ServiceMiddleware func(KafkaService) KafkaService

kafka.go:

package main

import (
    "fmt"
    "time"

    "github.com/Shopify/sarama"
)

func kafkaRoutine(inChan chan string, topic string, brokers []string) {
    config := sarama.NewConfig()
    config.Consumer.Return.Errors = true
    consumer, err := sarama.NewConsumer(brokers, config)
    if err != nil {
        panic(err)
    }

    topics, _ := consumer.Topics()
    if !(containsTopic(topics, topic)) {
        inChan <- "There is no such a topic"
        fmt.Println("kafkaroutine exited")
        return
    }

    partitionList, err := consumer.Partitions(topic)
    for _, partition := range partitionList {
        pc, _ := consumer.ConsumePartition(topic, partition, sarama.OffsetOldest)
        go func(pc sarama.PartitionConsumer) {
        loop:
            for {
                select {
                case msg := <-pc.Messages():
                    inChan <- string(msg.Value)
                case <-time.After(time.Second * 1):
                    break loop
                }
            }
        }(pc)
    }
    fmt.Println("Kafka GoRoutine exited")
}

func containsTopic(topics []string, topic string) bool {
    for _, v := range topics {
        if topic == v {
            return true
        }
    }
    return false
}


问:
Using Brotli with Firebase hosting
Is there a way to use Brotli compression instead of gzip with Firebase hosting?  I know that Firebase will automatically compress it but so far it is only with gzip.</p>

答: Somehow I ended up at this question, even though it is dated I wanted to mention it should be possible to use Brotli compression now using Firebase Cloud Functions. I havent tested it yet, but since you can run your own node.js code via Cloud Functions I don't see any reason why this would not work. Afcourse using Cloud Functions could slow down your app, so be sure to test carefully going this approach. It might not give the loading boost you are hoping for.</p>

Title: Using Brotli with Firebase hosting


问:
Webservice Serialization
I'm currently setting up a generic webservice that takes in credentials, an environment and tries to log a person in. It also returns a collection with return values that matter to for the specific environments.

The problem I'm having is when I want to return part of an object graph in the returnvalues node.

Since return values is a Dictionairy<string, object> it has no clue how to serialize the object graph.

So I thought I'd serialize this into a MemoryStream, load this into an XmlDocument and then serialize this.

How ever that gives the foloowing:

```<code><returnvalues>
 <returnvalue>
  <key>defendant</key>
  <value xsi:type="xsd:string">
   <?xml version="1.0"?>
    <something xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    </something>
  </value>
 </returnvalue>
<returnvalues>
</code>```

What I'd like to get is the following:

```<code><returnvalues>
 <returnvalue>
  <key>defendant</key>
  <value>
    <something></something>
  </value>
  </returnvalue>
<returnvalues>
</code>```

Is this possible? and if so, how do I go about making my response dynamic in such a way? Should I use a different type for my returnvalues node?

I should note this is in .NET 2.0 so i don't have access to any fancy WCF bits :(

答:
You need to do special things when Xml-serializing a generic Dictionary.

This article shows you how to do it.

In your case, you'd need to make the return value of your WebMethod a SerializableDictionary<T1,T2>.

Title: Webservice Serialization

Body:
I'm currently setting up a generic webservice that takes in credentials, an environment and tries to log a person in. It also returns a collection with return values that matter to for the specific environments.

The problem I'm having is when I want to return part of an object graph in the returnvalues node.

Since return values is a Dictionairy<string, object> it has no clue how to serialize the object graph.

So I thought I'd serialize this into a MemoryStream, load this into an XmlDocument and then serialize this.

How ever that gives the foloowing:

<returnvalues>
 <returnvalue>
  <key>defendant</key>
  <value xsi:type="xsd:string">
   <?xml version="1.0"?>
    <something xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    </something>
  </value>
 </returnvalue>
<returnvalues>

What I'd like to get is the following:

<returnvalues>
 <returnvalue>
  <key>defendant</key>
  <value>
    <something></something>
  </value>
  </returnvalue>
<returnvalues>

Is this possible? and if so, how do I go about making my response dynamic in such a way? Should I use a different type for my returnvalues node?

I should note this is in .NET 2.0 so i don't have access to any fancy WCF bits :(


问:
junit spring boot profile properties not being read
I am trring to read a value from the properties file in my junit setup using spring boot.
I can not read the value. Below is my content:-

application-test.properties

```<code>my.user.name=Amar
</code>```

COnfig file to create beans:

```<code>@Configuration
@ActiveProfiles("test")
@Profile("test")
public class RdbmsTestConfig {

    @Value("${my.user.name}")
    private String name;

    @Bean
    public String myString(){
        return "Amar";
    }

    @Bean
    public PropsHolder propsHolder() {
        PropsHolder propsHolder = new PropsHolder();
        propsHolder.setUserName(name);
        return propsHolder;
    }
 }
</code>```

My test class:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = RdbmsTestConfig.class)
@ActiveProfiles("test")
public class TestRoomService {

    @Autowired
    @Qualifier("myString")
    private String myString;

    @Autowired
    private PropsHolder propsHolder;

    @Autowired
    private Environment env;

    @Test
    public void userTest() {
        Arrays.stream(env.getActiveProfiles()).forEach(System.out::println);
        System.out.println(propsHolder.getUserName());
        Assert.assertNotNull(myString);
        Assert.assertEquals("Amar",myString);
    }
}
</code>```

The value for propsHolder.getUserName comes out to be ${my.user.name}

答: First remove @ActiveProfiles("test") from your class RdbmsTestConfig. Then your test just defines the RdbmsTestConfig as spring context. As I can see you do not run a real spring boot test. The problem is you do not have any PropertyPlaceholderConfigurer configured in your spring config. So either configure one PropertyPlaceholderConfigurer or add @SpringBootTest to your test if you have any SpringBootApplication.

Body:
I am trring to read a value from the properties file in my junit setup using spring boot.
I can not read the value. Below is my content:-

application-test.properties

my.user.name=Amar

COnfig file to create beans:

@Configuration
@ActiveProfiles("test")
@Profile("test")
public class RdbmsTestConfig {

    @Value("${my.user.name}")
    private String name;

    @Bean
    public String myString(){
        return "Amar";
    }

    @Bean
    public PropsHolder propsHolder() {
        PropsHolder propsHolder = new PropsHolder();
        propsHolder.setUserName(name);
        return propsHolder;
    }
 }

My test class:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = RdbmsTestConfig.class)
@ActiveProfiles("test")
public class TestRoomService {

    @Autowired
    @Qualifier("myString")
    private String myString;

    @Autowired
    private PropsHolder propsHolder;

    @Autowired
    private Environment env;

    @Test
    public void userTest() {
        Arrays.stream(env.getActiveProfiles()).forEach(System.out::println);
        System.out.println(propsHolder.getUserName());
        Assert.assertNotNull(myString);
        Assert.assertEquals("Amar",myString);
    }
}

The value for propsHolder.getUserName comes out to be ${my.user.name}


问:
Issues with updating my app version in gradle file
So I was using API 25 which is Nougat version, and I wanted to update my app to Version ApI27 which is newly out these days. but whenever I update to 27.0.1, this Error:

```<code>"Error:Failed to resolve: com.android.support:appcompat-v7.27.0.1"
</code>```

keeps occurring. I don't know what I've done wrong and I'm struggling all day to find the resolution. Thank you very much for your time and assistance in this matter.

Oh, and I'm sure that I've downloaded SDK Versions and all the files that are needed already in SDK manager.

My Gradle File(Module App):

```<code>apply plugin: 'com.android.application'

android {
compileSdkVersion 27
buildToolsVersion '27.0.1'
defaultConfig {
    applicationId "org.poream.dejaview"
    minSdkVersion 15
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
    }
}
}

dependencies {

implementation 'com.google.firebase:firebase-storage:11.6.0'
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2',
{
    exclude group: 'com.android.support', module: 'support-annotations'
})

compile 'com.android.support:design:27.0.1'
compile 'com.google.android.gms:play-services-maps:11.6.0'
compile 'com.android.support:appcompat-v7.27.0.1'
compile 'com.android.support:design:27.0.1'
compile 'com.google.android.gms:play-services-maps:11.6.0'
compile 'com.android.support:cardview-v7:27.0.1'
compile 'com.google.android.gms:play-services-location:11.6.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.firebase:firebase-core:11.6.0'
compile 'com.google.firebase:firebase-database:11.6.0'
compile 'com.google.firebase:firebase-crash:11.6.0'
compile 'com.google.firebase:firebase-auth:11.6.0'
compile 'com.android.support:support-v4:27.0.1'
compile 'com.android.support:recyclerview-v7:27.0.1'
compile 'com.google.android.gms:play-services-auth:11.6.0'
testCompile 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'
</code>```

My Gradle File(Project):

```<code>// Top-level build file where you can add configuration options common to
all sub-projects/modules.

buildscript {
repositories {

    mavenCentral()
    jcenter()
    google()
}
dependencies {

    classpath 'com.android.tools.build:gradle:3.0.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
    classpath 'com.google.gms:google-services:3.1.0'
}
}

allprojects {
repositories {
    jcenter()
    google()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}
</code>```

答:
There is a typo (the . instead of :)

```<code>compile 'com.android.support:appcompat-v7.27.0.1'
</code>```

Use:

```<code>compile 'com.android.support:appcompat-v7:27.0.1'
</code>```

Body:
So I was using API 25 which is Nougat version, and I wanted to update my app to Version ApI27 which is newly out these days. but whenever I update to 27.0.1, this Error:

"Error:Failed to resolve: com.android.support:appcompat-v7.27.0.1"

keeps occurring. I don't know what I've done wrong and I'm struggling all day to find the resolution. Thank you very much for your time and assistance in this matter.

Oh, and I'm sure that I've downloaded SDK Versions and all the files that are needed already in SDK manager.

My Gradle File(Module App):

apply plugin: 'com.android.application'

android {
compileSdkVersion 27
buildToolsVersion '27.0.1'
defaultConfig {
    applicationId "org.poream.dejaview"
    minSdkVersion 15
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
    }
}
}

dependencies {

implementation 'com.google.firebase:firebase-storage:11.6.0'
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2',
{
    exclude group: 'com.android.support', module: 'support-annotations'
})

compile 'com.android.support:design:27.0.1'
compile 'com.google.android.gms:play-services-maps:11.6.0'
compile 'com.android.support:appcompat-v7.27.0.1'
compile 'com.android.support:design:27.0.1'
compile 'com.google.android.gms:play-services-maps:11.6.0'
compile 'com.android.support:cardview-v7:27.0.1'
compile 'com.google.android.gms:play-services-location:11.6.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.firebase:firebase-core:11.6.0'
compile 'com.google.firebase:firebase-database:11.6.0'
compile 'com.google.firebase:firebase-crash:11.6.0'
compile 'com.google.firebase:firebase-auth:11.6.0'
compile 'com.android.support:support-v4:27.0.1'
compile 'com.android.support:recyclerview-v7:27.0.1'
compile 'com.google.android.gms:play-services-auth:11.6.0'
testCompile 'junit:junit:4.12'
}

apply plugin: 'com.google.gms.google-services'

My Gradle File(Project):

// Top-level build file where you can add configuration options common to
all sub-projects/modules.

buildscript {
repositories {

    mavenCentral()
    jcenter()
    google()
}
dependencies {

    classpath 'com.android.tools.build:gradle:3.0.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
    classpath 'com.google.gms:google-services:3.1.0'
}
}

allprojects {
repositories {
    jcenter()
    google()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}

Body:
There is a typo (the . instead of :)

compile 'com.android.support:appcompat-v7.27.0.1'

Use:

compile 'com.android.support:appcompat-v7:27.0.1'


Body:
Use set

x = [['a', 'b', 'c', 2, 4], ['x', 1, 2, 3, 'z'], ['z', 'b', 'y', 'a' 'x']]
>>> list(set([item for sublist in x for item in sublist]))
[1, 2, 3, 4, 'z', 'ax', 'a', 'b', 'c', 'x', 'y']


问:
PHP Server-side rate limit on AJAX callbacks?
I'm using PHP in conjunction with AJAX for a lot of functions on my site. I've implemented a sort of rate limiting system on the client-side with Javascript. Basically, disabling a button for 1 sec after it's clicked.

Although this works fine for the more innocent cases, but I feel like I need something on the server-side of things to limit requests as well.

Basically, I want users to have a maximum amount of AJAX calls they can make per second. In fact, one per second seems reasonable.

One way would be somehow logging every request to my AJAX callback, and reading from that table before a new request is made. But this would immensely increase the work load on my server and database.

Are there any alternative methods of doing this?

PHP

```<code>function comment_upvote_callback() {

    // Some sort of rate limit??

    // $_POST data validation

    // Add upvote to database

    // Return success or error

}
add_action( 'wp_ajax_comment_upvote_callback', 'comment_upvote_callback' );
</code>```

jQuery

```<code>var is_clicked = false;

if ( is_clicked == false ) {
    $('#comments').on('click', '.comment-upvote', function(event) {
        event.preventDefault();

        // Button disabled as long as isClicked == true
        isClicked = true;

        // Data to be sent
        var data = {
            'action': 'comment_upvote_callback',
            'security': nonce,
            'comment_id': comment_id
        };

        // Send Data
        jQuery.post(ajaxurl, data, function(response) {

            // Callback

            // Client-side rate limit
            setTimeout( function() {
                is_clicked = false;
            }, 1000);
        });
    });
}
</code>```

答:
As already told above, you should be using rate limiting at server-side
I have written a code to implement the same. You can copy the code into a file and simply include in your server-side script at the top. It accepts maximum 3hits/5secs. You can change the rate according to your needs </p>

```<code>    session_start();
    const cap = 3;
    $stamp_init = date("Y-m-d H:i:s");
    if( !isset( $_SESSION['FIRST_REQUEST_TIME'] ) ){
            $_SESSION['FIRST_REQUEST_TIME'] = $stamp_init;
    }
    $first_request_time = $_SESSION['FIRST_REQUEST_TIME'];
    $stamp_expire = date( "Y-m-d H:i:s", strtotime( $first_request_time )+( 5 ) );
    if( !isset( $_SESSION['REQ_COUNT'] ) ){
            $_SESSION['REQ_COUNT'] = 0;
    }
    $req_count = $_SESSION['REQ_COUNT'];
    $req_count++;
    if( $stamp_init > $stamp_expire ){//Expired
            $req_count = 1;
            $first_request_time = $stamp_init;
    }
    $_SESSION['REQ_COUNT'] = $req_count;
    $_SESSION['FIRST_REQUEST_TIME'] = $first_request_time;
    header('X-RateLimit-Limit: '.cap);
    header('X-RateLimit-Remaining: ' . ( cap-$req_count ) );
    if( $req_count > cap){//Too many requests
            http_response_code( 429 );
            exit();
    }
</code>```

Body:
I'm using PHP in conjunction with AJAX for a lot of functions on my site. I've implemented a sort of rate limiting system on the client-side with Javascript. Basically, disabling a button for 1 sec after it's clicked.

Although this works fine for the more innocent cases, but I feel like I need something on the server-side of things to limit requests as well.

Basically, I want users to have a maximum amount of AJAX calls they can make per second. In fact, one per second seems reasonable.

One way would be somehow logging every request to my AJAX callback, and reading from that table before a new request is made. But this would immensely increase the work load on my server and database.

Are there any alternative methods of doing this?

PHP

function comment_upvote_callback() {

    // Some sort of rate limit??

    // $_POST data validation

    // Add upvote to database

    // Return success or error

}
add_action( 'wp_ajax_comment_upvote_callback', 'comment_upvote_callback' );

jQuery

var is_clicked = false;

if ( is_clicked == false ) {
    $('#comments').on('click', '.comment-upvote', function(event) {
        event.preventDefault();

        // Button disabled as long as isClicked == true
        isClicked = true;

        // Data to be sent
        var data = {
            'action': 'comment_upvote_callback',
            'security': nonce,
            'comment_id': comment_id
        };

        // Send Data
        jQuery.post(ajaxurl, data, function(response) {

            // Callback

            // Client-side rate limit
            setTimeout( function() {
                is_clicked = false;
            }, 1000);
        });
    });
}

Body:
As already told above, you should be using rate limiting at server-side
I have written a code to implement the same. You can copy the code into a file and simply include in your server-side script at the top. It accepts maximum 3hits/5secs. You can change the rate according to your needs

    session_start();
    const cap = 3;
    $stamp_init = date("Y-m-d H:i:s");
    if( !isset( $_SESSION['FIRST_REQUEST_TIME'] ) ){
            $_SESSION['FIRST_REQUEST_TIME'] = $stamp_init;
    }
    $first_request_time = $_SESSION['FIRST_REQUEST_TIME'];
    $stamp_expire = date( "Y-m-d H:i:s", strtotime( $first_request_time )+( 5 ) );
    if( !isset( $_SESSION['REQ_COUNT'] ) ){
            $_SESSION['REQ_COUNT'] = 0;
    }
    $req_count = $_SESSION['REQ_COUNT'];
    $req_count++;
    if( $stamp_init > $stamp_expire ){//Expired
            $req_count = 1;
            $first_request_time = $stamp_init;
    }
    $_SESSION['REQ_COUNT'] = $req_count;
    $_SESSION['FIRST_REQUEST_TIME'] = $first_request_time;
    header('X-RateLimit-Limit: '.cap);
    header('X-RateLimit-Remaining: ' . ( cap-$req_count ) );
    if( $req_count > cap){//Too many requests
            http_response_code( 429 );
            exit();
    }


问:
Using different proxy on each request
As far as it is my understanding, the only way I can set a proxy for a request is to assign it to a client and then use that for a request. However, I also understand I should reuse the clients for my requests. Is there any way to individually assign proxies for each request whilst using the same client? Or any way to efficiently do a collection of requests with a different proxy for each request? </p>

答:
Creating of http.Client is not so expensive - its just a struct allocation that can be done for each request.

You should create http.Client and transport objects yourself and set proxy directly there.

```<code>proxyUrl, err := url.Parse("http://127.0.0.1:123")
if err != nil {
    panic(err)
}
myClient := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(proxyUrl)}}
myClient.Get("http://www.google.com/")
</code>```

Tere is the other posibility to use always the same client with different proxies:

http.ProxyURL call from the first example is function:

```<code>// ProxyURL returns a proxy function (for use in a Transport)
// that always returns the same URL.
func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error) {
    return func(*Request) (*url.URL, error) {
        return fixedURL, nil
    }
}
</code>```

You can extend it and chose proxy based on the information from request or implement some other logic.

UPD: here is implementation how to use ProxyUrl with only one Client. But overehead of changing context is comparable with overhead on creating a client. I would use the first scenario.

// We must write our own Get (or some other) request and add somewere the info that this is a proxy request. You can do it via context of request.

```<code>func GetWithProxy(c *http.Client,proxyUrl *url.URL, url string) (resp *http.Response, err error) {
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        return nil, err
    }

    if proxyUrl != nil {
        req = req.WithContext(context.WithValue(context.Background(),"proxy",proxyUrl))
    }

    return c.Do(req)
}
</code>```

// Organize client that can use this information:

```<code>proxyUrl, err := url.Parse("http://127.0.0.1:123")
if err != nil {
    panic(err)
}

myClient := &http.Client{Transport: &http.Transport{Proxy: func(req *http.Request) (*url.URL, error) {
    currentProxy,_ := req.Context().Value("proxy").(*url.URL)
    return currentProxy, nil
}}}
</code>```

Use it:

```<code>GetWithProxy(myClient,nil,"http://www.google.com/")
GetWithProxy(myClient,proxyUrl,"http://www.google.com/")
</code>```

Title: Using different proxy on each request

Body:
Creating of http.Client is not so expensive - its just a struct allocation that can be done for each request.

You should create http.Client and transport objects yourself and set proxy directly there.

proxyUrl, err := url.Parse("http://127.0.0.1:123")
if err != nil {
    panic(err)
}
myClient := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(proxyUrl)}}
myClient.Get("http://www.google.com/")

Tere is the other posibility to use always the same client with different proxies:

http.ProxyURL call from the first example is function:

// ProxyURL returns a proxy function (for use in a Transport)
// that always returns the same URL.
func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error) {
    return func(*Request) (*url.URL, error) {
        return fixedURL, nil
    }
}

You can extend it and chose proxy based on the information from request or implement some other logic.

UPD: here is implementation how to use ProxyUrl with only one Client. But overehead of changing context is comparable with overhead on creating a client. I would use the first scenario.

// We must write our own Get (or some other) request and add somewere the info that this is a proxy request. You can do it via context of request.

func GetWithProxy(c *http.Client,proxyUrl *url.URL, url string) (resp *http.Response, err error) {
    req, err := http.NewRequest("GET", url, nil)
    if err != nil {
        return nil, err
    }

    if proxyUrl != nil {
        req = req.WithContext(context.WithValue(context.Background(),"proxy",proxyUrl))
    }

    return c.Do(req)
}

// Organize client that can use this information:

proxyUrl, err := url.Parse("http://127.0.0.1:123")
if err != nil {
    panic(err)
}

myClient := &http.Client{Transport: &http.Transport{Proxy: func(req *http.Request) (*url.URL, error) {
    currentProxy,_ := req.Context().Value("proxy").(*url.URL)
    return currentProxy, nil
}}}

Use it:

GetWithProxy(myClient,nil,"http://www.google.com/")
GetWithProxy(myClient,proxyUrl,"http://www.google.com/")


问:
How to convert image to integer array? (do not use any non-standard library)
How to convert image.png or image.bmp to integer array? (do not use any non-standard library)

Please ignore chunks that are not directly related to image data.(IHDR、IEND...etc.)

thank you very much.

SOLVED: I should use binary I/O function in stdio.h to read image file. thanks

答:
If you have to read images into arrays without any image processing libraries you need two things:

You need means to read files in general.

You need to know the internal structure of the file formats you want to read.

So for png refer to https://www.w3.org/TR/2003/REC-PNG-20031110/

This document will tell you where to find the image dimensions, pixel data and other features. It's basically a manual for software developers on how to use this standard format properly.

Some image formats will require additional work like decrompression.


问:
Magento Enterprise Licence - Does it include SQL Cluster?
Trying to Evaluate Magento for an E-commerce solution. I have a naive question regarding the licence (Interestingly Magento Sales North America is not able to get me an answer, since i haven't bought licence yet, i cant raise this question under technical support either). So the Question is

Does Enterprise Edition comes with a MYSQL Cluster licence also or should i procure that MySQL cluster licence separately. I know it supports MySQL cluster in Enterprise Version but does the Licence include cluster license too is the question.

Any help is appreciated.

答:
I have no idea about Magento and their licenses.
With MySQL there is a MySQL Cluster Carrier Grade Edition
that gives you access to MySQL Cluster.
The MySQL Enterprise Edition does not.</p>