问:
unsigned char array from c++ in c#
I'm trying to call a C++ dll function in C#.
The function has a struct as a parameter and I have a problem with the variable aby_data[8]. I defined the unsigned char[] as a byte[], the program doesn't crash but I don't receive any data.

Struct C++

```<code>typedef struct st_canmsg
{
    long l_id;
    unsigned char by_len;
    unsigned char by_msg_lost;
    unsigned char by_extended;
    unsigned char by_remote;
    unsigned char aby_data[8];
    unsigned long ul_tstamp;
} CMSG;
</code>```

Conversion to C#

```<code>[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct CMSG
{
    public Int32 l_id;
    public byte by_len;
    public byte by_msg_lost;
    public byte by_extended;
    public byte by_remote;
    public byte aby_data[];
    public UInt32 ul_tstamp;
};

CMSG t_CANMsg[] = new CMSG[1];
t_CANMsg[0].aby_data = new byte[8];
t_CANMsg[0].aby_data[0] = 01;
t_CANMsg[0].aby_data[1] = 02;
t_CANMsg[0].aby_data[2] = 03;
t_CANMsg[0].aby_data[3] = 04;
t_CANMsg[0].aby_data[4] = 05;
t_CANMsg[0].aby_data[5] = 06;
t_CANMsg[0].aby_data[6] = 07;
t_CANMsg[0].aby_data[7] = 08;

l_retval = canSend(handle, out t_CANMsg[0], out len);
</code>```

答:
Based on the Frederik Carlier code I got this solution for use it as array:</p>

```<code>[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct CMSG
{
    public Int32 l_id;
    public byte by_len;
    public byte by_msg_lost;
    public byte by_extended;
    public byte by_remote;
    public byte aby_data_0;
    public byte aby_data_1;
    public byte aby_data_2;
    public byte aby_data_3;
    public byte aby_data_4;
    public byte aby_data_5;
    public byte aby_data_6;
    public byte aby_data_7;
    public UInt32 ul_tstamp;

    public byte[] aby_data(){
        byte[] aby_data_array = new byte[8];
        aby_data_array[0] = aby_data_0;
        aby_data_array[1] = aby_data_1;
        aby_data_array[2] = aby_data_2;
        aby_data_array[3] = aby_data_3;
        aby_data_array[4] = aby_data_4;
        aby_data_array[5] = aby_data_5;
        aby_data_array[6] = aby_data_6;
        aby_data_array[7] = aby_data_7;
        return aby_data_array;
    }
};

l_retval = canRead(handle, out t_CANMsg[0], out len);
byte data [] = t_CANMsg[0].aby_data();
</code>```

Title: unsigned char array from c++ in c#

Body:
I'm trying to call a C++ dll function in C#.
The function has a struct as a parameter and I have a problem with the variable aby_data[8]. I defined the unsigned char[] as a byte[], the program doesn't crash but I don't receive any data.

Struct C++

typedef struct st_canmsg
{
    long l_id;
    unsigned char by_len;
    unsigned char by_msg_lost;
    unsigned char by_extended;
    unsigned char by_remote;
    unsigned char aby_data[8];
    unsigned long ul_tstamp;
} CMSG;

Conversion to C#

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct CMSG
{
    public Int32 l_id;
    public byte by_len;
    public byte by_msg_lost;
    public byte by_extended;
    public byte by_remote;
    public byte aby_data[];
    public UInt32 ul_tstamp;
};

CMSG t_CANMsg[] = new CMSG[1];
t_CANMsg[0].aby_data = new byte[8];
t_CANMsg[0].aby_data[0] = 01;
t_CANMsg[0].aby_data[1] = 02;
t_CANMsg[0].aby_data[2] = 03;
t_CANMsg[0].aby_data[3] = 04;
t_CANMsg[0].aby_data[4] = 05;
t_CANMsg[0].aby_data[5] = 06;
t_CANMsg[0].aby_data[6] = 07;
t_CANMsg[0].aby_data[7] = 08;

l_retval = canSend(handle, out t_CANMsg[0], out len);

Body:
Based on the Frederik Carlier code I got this solution for use it as array:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct CMSG
{
    public Int32 l_id;
    public byte by_len;
    public byte by_msg_lost;
    public byte by_extended;
    public byte by_remote;
    public byte aby_data_0;
    public byte aby_data_1;
    public byte aby_data_2;
    public byte aby_data_3;
    public byte aby_data_4;
    public byte aby_data_5;
    public byte aby_data_6;
    public byte aby_data_7;
    public UInt32 ul_tstamp;

    public byte[] aby_data(){
        byte[] aby_data_array = new byte[8];
        aby_data_array[0] = aby_data_0;
        aby_data_array[1] = aby_data_1;
        aby_data_array[2] = aby_data_2;
        aby_data_array[3] = aby_data_3;
        aby_data_array[4] = aby_data_4;
        aby_data_array[5] = aby_data_5;
        aby_data_array[6] = aby_data_6;
        aby_data_array[7] = aby_data_7;
        return aby_data_array;
    }
};

l_retval = canRead(handle, out t_CANMsg[0], out len);
byte data [] = t_CANMsg[0].aby_data();


来源: stackexchange

问:
Guidance Needed For MATLAB MATRIX
I am working on a script which takes in array values and generates a matrix as shown in the code. What I want to do, based on below code, is that I want to search another matrix of given values and find the values corresponding to the cel and flr variables as defined in the program and make a new row to the matrix.

This is the current output:

```<code>C =

   63.6944   51.7205  -38.2795  -39.0000  -38.0000   B value correspond to -39
  107.5034   68.4665  -21.5335  -22.0000  -21.0000   B value correspond to -22
  155.1031   75.2618  -14.7382  -15.0000  -14.0000   B value correspond to -15
  203.8553   78.8393  -11.1607  -12.0000  -11.0000
  253.0948   81.0307   -8.9693   -9.0000   -8.0000
  302.5838   82.5070   -7.4930   -8.0000   -7.0000
  352.2172   83.5677   -6.4323   -7.0000   -6.0000
  401.9415   84.3662   -5.6338   -6.0000   -5.0000
</code>```

to above I want to add another column which is searching corresponding values in given matrix say -39, -22, -15, 12, -9, -8, -7, -6 will be searched in a 2D matrix say B which is below. Now I want another column in below matrix which shows corresponding values of the matrix B in A.

```<code>B = [-39   14
     -38   12
     -15   10
     -12   17
     -9    45
     -8    16]

a = 1;
for X = [50 100 150 200 250 300 350 400]

   R = hypot(41.4586-2, X);
   theta = atand(X/(41.4586-2));

   dep = theta-90;
   flr = floor(dep);
   Y(row1:col1) = find(Y==flr);
   dB1 = Y(row1:2);

   cel = ceil(dep);
   Y(row2,col2) = find(Y==cel);
   dB2= Y(row2:2);

   A(1,a) = R;
   A(2,a) = theta;
   A(3,a) = dep;
   A(4,a) = flr;
   A(5,a) = cel;
   A(6,a) = dB1;

   a = a+1;

end

C = transpose(A);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Guidance Needed For MATLAB MATRIX

Body:
I am working on a script which takes in array values and generates a matrix as shown in the code. What I want to do, based on below code, is that I want to search another matrix of given values and find the values corresponding to the cel and flr variables as defined in the program and make a new row to the matrix.

This is the current output:

C =

   63.6944   51.7205  -38.2795  -39.0000  -38.0000   B value correspond to -39
  107.5034   68.4665  -21.5335  -22.0000  -21.0000   B value correspond to -22
  155.1031   75.2618  -14.7382  -15.0000  -14.0000   B value correspond to -15
  203.8553   78.8393  -11.1607  -12.0000  -11.0000
  253.0948   81.0307   -8.9693   -9.0000   -8.0000
  302.5838   82.5070   -7.4930   -8.0000   -7.0000
  352.2172   83.5677   -6.4323   -7.0000   -6.0000
  401.9415   84.3662   -5.6338   -6.0000   -5.0000

to above I want to add another column which is searching corresponding values in given matrix say -39, -22, -15, 12, -9, -8, -7, -6 will be searched in a 2D matrix say B which is below. Now I want another column in below matrix which shows corresponding values of the matrix B in A.

B = [-39   14
     -38   12
     -15   10
     -12   17
     -9    45
     -8    16]

a = 1;
for X = [50 100 150 200 250 300 350 400]

   R = hypot(41.4586-2, X);
   theta = atand(X/(41.4586-2));

   dep = theta-90;
   flr = floor(dep);
   Y(row1:col1) = find(Y==flr);
   dB1 = Y(row1:2);

   cel = ceil(dep);
   Y(row2,col2) = find(Y==cel);
   dB2= Y(row2:2);

   A(1,a) = R;
   A(2,a) = theta;
   A(3,a) = dep;
   A(4,a) = flr;
   A(5,a) = cel;
   A(6,a) = dB1;

   a = a+1;

end

C = transpose(A);

Body:
C =

   63.6944   51.7205  -38.2795  -39.0000  -38.0000   14-> value of B in col 2
  107.5034   68.4665  -21.5335  -22.0000  -21.0000   12
  155.1031   75.2618  -14.7382  -15.0000  -14.0000   10
  203.8553   78.8393  -11.1607  -12.0000  -11.0000   17
  253.0948   81.0307   -8.9693   -9.0000   -8.0000   45
  302.5838   82.5070   -7.4930   -8.0000   -7.0000   16

this should be the output


问:
How to use Angular 4 with SASS
I'm starting my first project using Angular4 and sass and I'm trying to figure it out how to work with sass the proper way. I'm using angular-cli and already set the default style to use scss syntax. I also already defined the compilation, etc.

However I saw that we have an option styleUrls on the component, where in some cases we define styles used only in that component.

The problem is, when I set a scss file in that component it's not generating it's own .css file neither being included in the main .css file, generated from the root project.

So basically I have a project structure like this:

```<code>app
    app.module.ts
    app.routing.ts
    home
        home.component.ts
        home.html
        _home.scss
    client
        client.component.ts
        client.html
        _client.scss
scss
    _imports.scss
    colors
        _colors.scss
    ui
        _button.scss
        _table.scss
    //.. more folder and files
styles.scss
index.html
</code>```

And I'd like to be able to set the main css style within the styles.scss file, which will be inserted into the index.html file later, on the build process. But also be able to generate a single css file for each component I have, e.g. home and client, and only use those css styles within their own component.

Is it possible to do it? I've tried to do it and I didn't find any other resource about this!

答:
i had the same issue, i have a leftnav component and its scss seemed  to be never compiled , i tried all the above but didnt work , and i tried to creat new app using ng  new ....  but after that i got it fixed by changing my thoughts :D

seems like we cant use same component selector inside its relative .scss file
but instead we should use a wrapping div with suitable className , and use that .className as a root wrapping of .scss file content.

let me demonstrate, this is my app:

```<code>app/component/leftnav
  |leftnav.scss
  |leftnav.html ==> simply `left nav works!`
  |leftnav.ts ==> selector leftnav
app/
  |app.html
  |app.scss
</code>```

and inside the old leftnav.scss

```<code>leftnav{
    background:red;
}
</code>```

and inside app.html

```<code><leftnav></leftnav>
</code>```

and how i got it fixed ! as i said by adding a wrapping div with classname .leftnav inside leftnav.html and use its as root wrapping of my leftnav.scss instead of component selector

so my new

```<code>.leftnav{
    background:red;
}
</code>```

and it works !

ContentLicense: CC BY-SA 4.0

Title: How to use Angular 4 with SASS

Body:
I'm starting my first project using Angular4 and sass and I'm trying to figure it out how to work with sass the proper way. I'm using angular-cli and already set the default style to use scss syntax. I also already defined the compilation, etc.

However I saw that we have an option styleUrls on the component, where in some cases we define styles used only in that component.

The problem is, when I set a scss file in that component it's not generating it's own .css file neither being included in the main .css file, generated from the root project.

So basically I have a project structure like this:

app
    app.module.ts
    app.routing.ts
    home
        home.component.ts
        home.html
        _home.scss
    client
        client.component.ts
        client.html
        _client.scss
scss
    _imports.scss
    colors
        _colors.scss
    ui
        _button.scss
        _table.scss
    //.. more folder and files
styles.scss
index.html

And I'd like to be able to set the main css style within the styles.scss file, which will be inserted into the index.html file later, on the build process. But also be able to generate a single css file for each component I have, e.g. home and client, and only use those css styles within their own component.

Is it possible to do it? I've tried to do it and I didn't find any other resource about this!

Body:
i had the same issue, i have a leftnav component and its scss seemed  to be never compiled , i tried all the above but didnt work , and i tried to creat new app using ng  new ....  but after that i got it fixed by changing my thoughts :D

seems like we cant use same component selector inside its relative .scss file
but instead we should use a wrapping div with suitable className , and use that .className as a root wrapping of .scss file content.

let me demonstrate, this is my app:

app/component/leftnav
  |leftnav.scss
  |leftnav.html ==> simply `left nav works!`
  |leftnav.ts ==> selector leftnav
app/
  |app.html
  |app.scss

and inside the old leftnav.scss

leftnav{
    background:red;
}

and inside app.html

<leftnav></leftnav>

and how i got it fixed ! as i said by adding a wrapping div with classname .leftnav inside leftnav.html and use its as root wrapping of my leftnav.scss instead of component selector

so my new

.leftnav{
    background:red;
}

and it works !


问:
Set default time zone to use for an android application
I'm developing an application for android that has to list activities with its date and time. I would like to ignore the time zone of the device and show always the time in timezone +02:00.

The application is for Spain, but If someone from UK that is in another time zone use the application I want that the time for activities appear in local spanish time.

The date is in UTC format, using Calendar.getTime().toLocaleString(), the time appers in local time zone of device.

I would like to know if the is a way to set a default time zone that has to use my application, and when I invoke Calendar.getTime().toLocaleString() method get the time always in local time zone +2 despite of the device timezone

答:
```<code>TimeZone.setDefault(TimeZone.getTimeZone("GMT+3"));
</code>```

This sets the default timezone. Subsequent calls to Calendar.getInstance() always return as if the device was in that timezone.

Body:
TimeZone.setDefault(TimeZone.getTimeZone("GMT+3"));

This sets the default timezone. Subsequent calls to Calendar.getInstance() always return as if the device was in that timezone.


问:
Error Retrieving Array Value
I have an array with the following values,

```<code>Array(
[new_count] => 1
[updated_count] => 0
[error_count] => 0
[error_indices] => Array
    (
    )

[unmodified_indices] => Array
    (
    )

[persisted_recipients] => Array
    (
        [0] => ZEBhcy5jb20=
    )

[errors] => Array
    (
    )

)
</code>```

and I'm trying to pass to a variable only this value,

```<code>[persisted_recipients] => Array
    (
        [0] => ZEBhcy5jb20=
    )

$recipient_id = $array_retorno['persisted_recipients'][0];
</code>```

but I'm getting the following error

Undefined offset: 0 [APP\Controller\PostsController.php, line 129]

what is wrong?

答:
try to get_file_contents() function to fetch output data. or try

json_decode(json_encode($array), true).

Title: Error Retrieving Array Value

Body:
I have an array with the following values,

Array(
[new_count] => 1
[updated_count] => 0
[error_count] => 0
[error_indices] => Array
    (
    )

[unmodified_indices] => Array
    (
    )

[persisted_recipients] => Array
    (
        [0] => ZEBhcy5jb20=
    )

[errors] => Array
    (
    )

)

and I'm trying to pass to a variable only this value,

[persisted_recipients] => Array
    (
        [0] => ZEBhcy5jb20=
    )

$recipient_id = $array_retorno['persisted_recipients'][0];

but I'm getting the following error

Undefined offset: 0 [APP\Controller\PostsController.php, line 129]

what is wrong?


问:
Why are C pointers recommended to be the type of the data they're pointing to, if they're 8 bytes large regardless?
So I'm learning about C pointers, and I'm a little confused. Pointers just point to specific memory address.

sizeof(char*), sizeof(int*), sizeof(double*) all output 8. So they all take 8 bytes to store a memory address.

However, if I try to compile something like this:

```<code>int main(void)
{
    char letter = 'A';
    int *a = &letter;
    printf("letter: %c\n", *a);
}
</code>```

I get a warning from the compiler (gcc):

```<code> warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]
     int *a = &letter;
</code>```

However, char *a = &letter;, doesn't result in a warning.

Why does the type of the pointer matter, if it's 8 bytes long anyway? Why does declaring a pointer with a type different than the type of data it's pointing to yield in a warning?

答: It's not about bytes length but about the type of what you're pointing to. Char and int are completly different. Moreover, sizeof(char) equal 1 and sizeof(int *) equal 8.

Body:
So I'm learning about C pointers, and I'm a little confused. Pointers just point to specific memory address.

sizeof(char*), sizeof(int*), sizeof(double*) all output 8. So they all take 8 bytes to store a memory address.

However, if I try to compile something like this:

int main(void)
{
    char letter = 'A';
    int *a = &letter;
    printf("letter: %c\n", *a);
}

I get a warning from the compiler (gcc):

 warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]
     int *a = &letter;

However, char *a = &letter;, doesn't result in a warning.

Why does the type of the pointer matter, if it's 8 bytes long anyway? Why does declaring a pointer with a type different than the type of data it's pointing to yield in a warning?


问:
How to check if an Array of strings is sorted in alphabetical order or not using Kotlin?
I am given a list of strings and I need to see if they are in alphabetical order.

I know I need to use a for loop and check the first character of each string but I don't know how to progress from there.

```<code>for (item in array)
     println(item[0])
</code>```

For example ["adam", "ben", "chloe"] should return true.

And likewise for ["ben", "adam", "chloe"] should return false.

答:
A very simple and easy way to accomplish it is by sorting and comparing the original list with the sorted one (two lists are equal when they have the exact same elements in the same order). Since you mentioned you are dealing with an array, you first need to convert it to a list. This solution is not the best in terms of performance (it's O(n log n) and converts the array twice to a list) but it's very readable:

```<code>val test = array.asList() == array.asList().sorted()
</code>```

The full code for your question could be:

```<code>println(if (array.asList() == array.asList().sorted()) "Strings are in alphabetical order." else "Strings are not in alphabetical order.")
</code>```

Body:
I am given a list of strings and I need to see if they are in alphabetical order.

I know I need to use a for loop and check the first character of each string but I don't know how to progress from there.

for (item in array)
     println(item[0])

For example ["adam", "ben", "chloe"] should return true.

And likewise for ["ben", "adam", "chloe"] should return false.

Body:
A very simple and easy way to accomplish it is by sorting and comparing the original list with the sorted one (two lists are equal when they have the exact same elements in the same order). Since you mentioned you are dealing with an array, you first need to convert it to a list. This solution is not the best in terms of performance (it's O(n log n) and converts the array twice to a list) but it's very readable:

val test = array.asList() == array.asList().sorted()

The full code for your question could be:

println(if (array.asList() == array.asList().sorted()) "Strings are in alphabetical order." else "Strings are not in alphabetical order.")


问:
Onelogin Simple SAML toolkit for PHP
I need configure OneLogin SAML toolkit for PHP.

I followed the step for the configuration of SAML toolkit for PHP in this link.

I add application SAML Test Connector (IdP w/ attr).

I add the content of repository Github to my hosting to run PHP code.

I defined the variable in demo1/settings.php

```<code>'idp' => array (
    'entityId' => 'https://app.onelogin.com/saml/metadata/123456',
    'singleSignOnService' => array (
        'url' => 'https://app.onelogin.com/trust/saml2/http-post/sso/123456',
    ),
    'singleLogoutService' => array (
        'url' => 'https://app.onelogin.com/trust/saml2/http-redirect/slo/123456',
    ),
    'x509cert' => 'XXXXxXXX1xXxXXXxXXXXXXxXXxxXx...',
)
</code>```

I copy the configuration from guide to my app in onelogin replaced myapp for my URL hosting

Now, i going to myhosting/php-saml-master/demo1 and click on Login

6.- The URL myhosting/php-saml-master/demo1 redirect a page mypage.onelogin.com and i write the user and password that i associated the demo1 app but receive this error message

Please Help! i followed all step in the guide of configuration the Onelogin Simple SAML toolkit for PHP but this not working for me.
any of you can configurate any app in onelogin?

Regards!

答:
Consumer URL should point to your website (ex. http://localhost/saml_requests) and make sure in you point 3 you use the values from the SSO tab including their certificate.

You can also for starters, initiate the auth from their app, for that make the app available and have the user assigned to it.

Title: Onelogin Simple SAML toolkit for PHP

Body:
I need configure OneLogin SAML toolkit for PHP.

I followed the step for the configuration of SAML toolkit for PHP in this link.

I add application SAML Test Connector (IdP w/ attr).

I add the content of repository Github to my hosting to run PHP code.

I defined the variable in demo1/settings.php

'idp' => array (
    'entityId' => 'https://app.onelogin.com/saml/metadata/123456',
    'singleSignOnService' => array (
        'url' => 'https://app.onelogin.com/trust/saml2/http-post/sso/123456',
    ),
    'singleLogoutService' => array (
        'url' => 'https://app.onelogin.com/trust/saml2/http-redirect/slo/123456',
    ),
    'x509cert' => 'XXXXxXXX1xXxXXXxXXXXXXxXXxxXx...',
)

I copy the configuration from guide to my app in onelogin replaced myapp for my URL hosting

Now, i going to myhosting/php-saml-master/demo1 and click on Login

6.- The URL myhosting/php-saml-master/demo1 redirect a page mypage.onelogin.com and i write the user and password that i associated the demo1 app but receive this error message

Please Help! i followed all step in the guide of configuration the Onelogin Simple SAML toolkit for PHP but this not working for me.
any of you can configurate any app in onelogin?

Regards!


问:
Instantiate structure at assigned address (allocation assignment)
For a class I'm taking, we need to develop allocation utilities.

Safety aside, I will be using far pointers to receive and assign addresses to some structures. I am also not allowed to use "memalloc" in this assignment.

I referred to: Linked Lists in C without malloc
to learn how to make a linked structure without using memalloc. However, I need to know how I can assign a new instantiation to a particular address. For example, if I have a starting pointer to address 0x5000, I would like to create my list so that I can use an incremental offset (let's say 256 for example) to start my next structure 256 bytes ahead (in terms of address) of my starting point.

This assignment is based on becoming familiar with segmentation and the x86 architecture.

Any help is appreciated!

答:
I just received an e-mail from my professor, and I'm not allowed to use the "new" operator. Just to double check with what you've told me, I may ask again with this example:

```<code>struct example{
    int a;
    struct example *next;
};

void *ptr;
ptr = 0x5000;
ptr = &((example)*ptr);
</code>```

Or something along the lines of that?

ContentLicense: CC BY-SA 2.5

Body:
I just received an e-mail from my professor, and I'm not allowed to use the "new" operator. Just to double check with what you've told me, I may ask again with this example:

struct example{
    int a;
    struct example *next;
};

void *ptr;
ptr = 0x5000;
ptr = &((example)*ptr);

Or something along the lines of that?


答:
The issue isn't about the size of the pointer - it's about the type of the pointee.

If you have a pointer to an int, the pointer takes up some number of bytes (seems like you have a 64-bit system, where that pointer takes up eight bytes). However, if you dereference that pointer to read or write what it points to, because the type of the pointer is int*, the read or write will try to manipulate sizeof(int) bytes at the target, and it will try to manipulate them as though they're an int.

If you have a single object of type char, which by definition has size 1, and you try to read or write it through a pointer of type int, which (on many systems) has size 4, then reading the pointer will pull back some garbage data along with the char and writing to the pointer will clobber random regions of memory around that char with unrelated values.

Additionally, C has a rule called the strict aliasing rule that says that you are not allowed to read or write through a pointer of a type that doesn't match the type of what's being pointed at (unless the pointer is of type char *, signed char*, or unsigned char*). Breaking strict aliasing can mess up all sorts of compiler optimizations and lead to code that doesn't behave as expected.

So in short, the size of the pointer really isn't the issue here. It's the semantics about what happens when you try to read or write what's being pointed at.

Title: Why are C pointers recommended to be the type of the data they're pointing to, if they're 8 bytes large regardless?


问:
select2, simple_form and acts_as_taggable_on
I am trying to add tags to a model. I need it to function with the following features:

Rendered as tags in the view using select2

User can create their own tags (ie. enter new tag then 'space' or ',')

User is prompted with existing tags to keep input consistant

i.e. the same way the "tags" box works on this site when posting a question!

I am 99% of the way there but each approach I take it seems that one part does not work.

Here are my software versions:

select2-rails (3.5.7)

simple_form (3.0.1)

acts-as-taggable-on (4.0.0)

Rails 4.03

Following Code: rendered correctly, but not able to add new tags before saving, prompt for existing tags works

```<code>@tags = ActsAsTaggableOn::Tag.all
<%= f.input :tag_list, input_html: { class: 'tags', multiple: true}, collection: @tags, value_method: :name %>

$('.tags').select2({

    tokenSeparators: [',', ' '],
    placeholder: "Add your tag here"
});
</code>```

Following Code: rendered as a multi line text box, not tags via select2

```<code>@tags = ActsAsTaggableOn::Tag.all
<%= f.input :tag_list, input_html: { class: 'tags', multiple: true}, collection: @tags, value_method: :name %>

$('.tags').select2({
    tags: true,
    tokenSeparators: [',', ' '],
    placeholder: "Add your tag here"
});
</code>```

Following Code: rendered correctly, and can add new tags, but not prompt to select existing tags

```<code>@tags = ActsAsTaggableOn::Tag.all
<%= f.input :tag_list, input_html: { class: 'tags', multiple: true } %>

$('.tags').select2({
    tags: true,
    tokenSeparators: [',', ' '],
    placeholder: "Add your tag here"
});
</code>```

答:
for anyone who finds this I ended up doing this to get it to work.

```<code>@tags = ActsAsTaggableOn::Tag.all.pluck(:name)
<%= f.input :tag_list, input_html: { class: 'tags', multiple: true, data: {options: @tags} } %>

$('.tags').select2({
    tags: $('.tags').data('options'),
    tokenSeparators: [' ', ',']
});
</code>```

Happy to hear if there is a cleaner method.

Body:
I am trying to add tags to a model. I need it to function with the following features:

Rendered as tags in the view using select2

User can create their own tags (ie. enter new tag then 'space' or ',')

User is prompted with existing tags to keep input consistant

i.e. the same way the "tags" box works on this site when posting a question!

I am 99% of the way there but each approach I take it seems that one part does not work.

Here are my software versions:

select2-rails (3.5.7)

simple_form (3.0.1)

acts-as-taggable-on (4.0.0)

Rails 4.03

Following Code: rendered correctly, but not able to add new tags before saving, prompt for existing tags works

@tags = ActsAsTaggableOn::Tag.all
<%= f.input :tag_list, input_html: { class: 'tags', multiple: true}, collection: @tags, value_method: :name %>

$('.tags').select2({

    tokenSeparators: [',', ' '],
    placeholder: "Add your tag here"
});

Following Code: rendered as a multi line text box, not tags via select2

@tags = ActsAsTaggableOn::Tag.all
<%= f.input :tag_list, input_html: { class: 'tags', multiple: true}, collection: @tags, value_method: :name %>

$('.tags').select2({
    tags: true,
    tokenSeparators: [',', ' '],
    placeholder: "Add your tag here"
});

Following Code: rendered correctly, and can add new tags, but not prompt to select existing tags

@tags = ActsAsTaggableOn::Tag.all
<%= f.input :tag_list, input_html: { class: 'tags', multiple: true } %>

$('.tags').select2({
    tags: true,
    tokenSeparators: [',', ' '],
    placeholder: "Add your tag here"
});

Body:
for anyone who finds this I ended up doing this to get it to work.

@tags = ActsAsTaggableOn::Tag.all.pluck(:name)
<%= f.input :tag_list, input_html: { class: 'tags', multiple: true, data: {options: @tags} } %>

$('.tags').select2({
    tags: $('.tags').data('options'),
    tokenSeparators: [' ', ',']
});

Happy to hear if there is a cleaner method.


问:
strncpy or strlcpy in my case
what should I use when I want to copy src_str to dst_arr and why?

```<code>char dst_arr[10];
char *src_str = "hello";
</code>```

PS: my head is spinning faster than the disk of my computer after reading a lot of things on how good or bad is strncpy and strlcpy.

Note: I know strlcpy is not available everywhere. That is not the concern here.

答:
You should always the standard function, which in this case is the C11 strcpy_s() function. Not strncpy(), as this is unsafe not guaranteeing zero termination. And not the OpenBSD-only strlcpy(), as it is also unsafe, and OpenBSD always comes up with it's own inventions, which usually don't make it into any standard.

See
http://en.cppreference.com/w/c/string/byte/strcpy

The function strcpy_s is similar to the BSD function strlcpy, except that
strlcpy truncates the source string to fit in the destination (which is a security risk)

strlcpy does not perform all the runtime checks that strcpy_s does

strlcpy does not make failures obvious by setting the destination to a null string or calling a handler if the call fails.

Although strcpy_s prohibits truncation due to potential security risks, it's possible to truncate a string using bounds-checked strncpy_s instead.

If your C library doesn't have strcpy_s, use the safec lib.
https://rurban.github.io/safeclib/doc/safec-3.1/df/d8e/strcpy__s_8c.html

Title: strncpy or strlcpy in my case

Body:
what should I use when I want to copy src_str to dst_arr and why?

char dst_arr[10];
char *src_str = "hello";

PS: my head is spinning faster than the disk of my computer after reading a lot of things on how good or bad is strncpy and strlcpy.

Note: I know strlcpy is not available everywhere. That is not the concern here.


问:
Firebase load related data iOS
What's the best way to load "related" data in swift?

Common setup, if I have a list of users all stored under uid node and contains a list of follows which stores uids, something like:

"users" : {
    "abc123" : {
      "email" : "test@test.com",
      "follows" : {
        "xyz789" : true
      }
    },
    "xyz789" : { ... }
}

What's the most efficient way of loading in the data for all the users one user follows? Is it best to loop through each of the uid's with observeSingleEvent(of: .value)?

This is the solution I've come up with, but feels somewhat cumbersome:

```<code>func loadRelated(user: User, completion: @escaping (Bool, [UserObject]) -> ()) {

  let ref = Database.database().reference(withPath: "users/" + user.uid + "/follows")
  ref.observeSingleEvent(of: .value) { snapshot in

    var uids = [String]()
    for child in snapshot.children {
      let userData = child as! DataSnapshot
      uids.append(userData.key)
    }

    let userRef = Database.database().reference(withPath: "users")
    var users = [UserObject]()
    var count = 0
    uids.forEach { uid in
      userRef.child(uid).observeSingleEvent(of: .value) { snapshot in
        let user: UserObject(from: snapshot)
        users.append(user)
        count += 1
        if count == uids.count {
          completion(true, users)
        }
      }
    }
  }
}
</code>```

I don't really want to go down the denormalization path and store each users data under the top level user.

答:
If you know that your node at /users will always contain few users, you could try to get all the users at once with a observeSingleEvent(of:) at path /users. Then filter the users with the ones who are in ../follows.
This may pull more data but it might be faster (not sure) and will need less code to handle.

In fact your initial implementation is quite performant already. Just make sure to handle correctly failing of observeSingleEvent(of:) or the condition count == uids.count will never be fulfilled.

By the way storing each user under ../follows will just duplicate your data and will be hard to maintain updated. So yes avoid it.

Title: Firebase load related data iOS

Body:
What's the best way to load "related" data in swift?

Common setup, if I have a list of users all stored under uid node and contains a list of follows which stores uids, something like:

"users" : {
    "abc123" : {
      "email" : "test@test.com",
      "follows" : {
        "xyz789" : true
      }
    },
    "xyz789" : { ... }
}

What's the most efficient way of loading in the data for all the users one user follows? Is it best to loop through each of the uid's with observeSingleEvent(of: .value)?

This is the solution I've come up with, but feels somewhat cumbersome:

func loadRelated(user: User, completion: @escaping (Bool, [UserObject]) -> ()) {

  let ref = Database.database().reference(withPath: "users/" + user.uid + "/follows")
  ref.observeSingleEvent(of: .value) { snapshot in

    var uids = [String]()
    for child in snapshot.children {
      let userData = child as! DataSnapshot
      uids.append(userData.key)
    }

    let userRef = Database.database().reference(withPath: "users")
    var users = [UserObject]()
    var count = 0
    uids.forEach { uid in
      userRef.child(uid).observeSingleEvent(of: .value) { snapshot in
        let user: UserObject(from: snapshot)
        users.append(user)
        count += 1
        if count == uids.count {
          completion(true, users)
        }
      }
    }
  }
}

I don't really want to go down the denormalization path and store each users data under the top level user.


问:
JavaScript Object Array: Removing objects with duplicate properties
I have an array of objects:

```<code>[
  { id: 1, name: "Bob" },
  { id: 1, name: "Donald" },
  { id: 2, name: "Daryl" }
]
</code>```

I'd like to strip out objects with duplicate Ids, leaving an array that would look like this:

```<code>[
  { id: 1, name: "Bob" },
  { id: 2, name: "Daryl" }
]
</code>```

I don't care which objects are left, as long as each ID is unique. Anything in Underscore, maybe, that would do this?

Edit: This is not the same as the duplicate listed below; I'm not trying to filter duplicate OBJECTS, but objects that contain identical IDs. I've done this using Underscore - I'll post the answer shortly.

答:
Can use es6 Map collection mix with reduce</p>

```<code>const items = [
    { id: 1, name: "Bob" },
    { id: 1, name: "Donald" },
    { id: 2, name: "Daryl" }
]

const uniqItems = [...items.reduce((itemsMap, item) =>
      itemsMap.has(item.id) ? itemsMap : itemsMap.set(item.id, item)
    , new Map()).values()]

console.log(uniqItems);
</code>```

Body:
I have an array of objects:

[
  { id: 1, name: "Bob" },
  { id: 1, name: "Donald" },
  { id: 2, name: "Daryl" }
]

I'd like to strip out objects with duplicate Ids, leaving an array that would look like this:

[
  { id: 1, name: "Bob" },
  { id: 2, name: "Daryl" }
]

I don't care which objects are left, as long as each ID is unique. Anything in Underscore, maybe, that would do this?

Edit: This is not the same as the duplicate listed below; I'm not trying to filter duplicate OBJECTS, but objects that contain identical IDs. I've done this using Underscore - I'll post the answer shortly.

Body:
Can use es6 Map collection mix with reduce

const items = [
    { id: 1, name: "Bob" },
    { id: 1, name: "Donald" },
    { id: 2, name: "Daryl" }
]

const uniqItems = [...items.reduce((itemsMap, item) =>
      itemsMap.has(item.id) ? itemsMap : itemsMap.set(item.id, item)
    , new Map()).values()]

console.log(uniqItems);


问:
tsql sql multiple temp tables with same name
I'm working on a Report using RDL files and stored procedures.
RDL file name is test.rdl and I have four(4) stored procedures connected to this test.rdl file. so this file will have four datasets.

report file name:

test.rdl

stored procedure names:

sp_test_1

sp_test_2

sp_test_3

sp_test_4

each of these stored procedures have temp tables with same name(#temp).

```<code>create table #temp(
ID int,
Name varchar(max),
Location varchar(max)
)

insert into #temp

select * from anothertable where date between '20171001' and '20171031'
</code>```

some more extra queries to get the desired result and then finally drop the temp table.

select . . . . . . . . . .

```<code>drop table #temp
</code>```

so all of the four stored procedures have temp table using one name(#temp).

so my question is, will this work fine when the RDL test file is ran and when all of the four(4) stored procedures are called at once?
my concern is with the #temp table, all four stored procedures have drop table #temp at the end of the run. will this affect the filling of the temp tables during runtime as one of the stored procedures may finish with drop table while the other one was running hence resulting in cancelling of query or finishing with incomplete results?

can some please explain. I hope this is a valid question.

答:
Broadly speaking....
Local temp tables (using a single #) are only available to the instance of the procedure that called them or procedures that were called from the same procedure as the one that created the temp table.

If you call a procedure 10 times simultaneously, each has it's own "copy" of the temp table.

From your description it sounds like you just have 4 datasets, each running a Stored Procedure and each of these SP's creates a temp table called #temp. You don't have an SP that calls the other SP's...

Assuming that's correct then it will work fine, in fact you don't even have to drop the temp table at the end of the proc as this done automatically.

The fact that the temp tables are all referenced using the same name doesn't matter, the actual name of the physical temp table stored in the database will not be #temp but something more like tempdb.dbo.#temp_______________000000000123, the point is that they are in fact all unique tables in the database but SQL Server handles the translation to/from the name you created it under automatically.

Body:
I'm working on a Report using RDL files and stored procedures.
RDL file name is test.rdl and I have four(4) stored procedures connected to this test.rdl file. so this file will have four datasets.

report file name:

test.rdl

stored procedure names:

sp_test_1

sp_test_2

sp_test_3

sp_test_4

each of these stored procedures have temp tables with same name(#temp).

create table #temp(
ID int,
Name varchar(max),
Location varchar(max)
)

insert into #temp

select * from anothertable where date between '20171001' and '20171031'

some more extra queries to get the desired result and then finally drop the temp table.

select . . . . . . . . . .

drop table #temp

so all of the four stored procedures have temp table using one name(#temp).

so my question is, will this work fine when the RDL test file is ran and when all of the four(4) stored procedures are called at once?
my concern is with the #temp table, all four stored procedures have drop table #temp at the end of the run. will this affect the filling of the temp tables during runtime as one of the stored procedures may finish with drop table while the other one was running hence resulting in cancelling of query or finishing with incomplete results?

can some please explain. I hope this is a valid question.


问:
Count New Lines in Text File
I would like to count the number of shift+enters in a text file using PHP.

Please help me with this.

Thanks

答:
Assuming you just mean "\r\n" (carriage-return + line feed) by this, the function substr_count in conjunction with file_get_contents should do the trick.

For example:

```<code>$count = substr_count(file_get_contents($filename), "\r\n");
</code>```

Title: Count New Lines in Text File

Body:
Assuming you just mean "\r\n" (carriage-return + line feed) by this, the function substr_count in conjunction with file_get_contents should do the trick.

For example:

$count = substr_count(file_get_contents($filename), "\r\n");


问:
How to output tensor flow prediction results in .csv?
I am training a model using CNN.

Here is my prediction part in the model.

```<code>predictions = {
    "classes": tf.argmax(input=logit2, axis=1),
    "probabilities": tf.nn.softmax(logit2, name="softmax_tensor")
}
</code>```

Here is the code in main that do the evaluation.

```<code>eval_input_fn = tf.estimator.inputs.numpy_input_fn(
    x={"x": images_test},
    y=test_labels,
    num_epochs=1,
    shuffle=False)
eval_results = model.evaluate(input_fn=eval_input_fn)
</code>```

I have trained my models, now I have a list of test image names (in the first column of a csv file), and I want to make the predictions and output the corresponding results to the second column (with probability between 0 and 1), how to achieve this, and where to add the code?

Thanks in advance.

答:
The Estimator class has a predict function that returns the predictions as an iterable object (for an example, scroll to the very bottom of this page).

so you could do:

predictions = model.predict(input_fn=predict_input_fn)
for p in predictions:
  # write p['classes'] to the csv
```

As for writing to the second column of the csv, take a look at the csv python module.

Body:
I am training a model using CNN.

Here is my prediction part in the model.

predictions = {
    "classes": tf.argmax(input=logit2, axis=1),
    "probabilities": tf.nn.softmax(logit2, name="softmax_tensor")
}

Here is the code in main that do the evaluation.

eval_input_fn = tf.estimator.inputs.numpy_input_fn(
    x={"x": images_test},
    y=test_labels,
    num_epochs=1,
    shuffle=False)
eval_results = model.evaluate(input_fn=eval_input_fn)

I have trained my models, now I have a list of test image names (in the first column of a csv file), and I want to make the predictions and output the corresponding results to the second column (with probability between 0 and 1), how to achieve this, and where to add the code?

Thanks in advance.

Body:
The Estimator class has a predict function that returns the predictions as an iterable object (for an example, scroll to the very bottom of this page).

so you could do:

predictions = model.predict(input_fn=predict_input_fn)
for p in predictions:
  # write p['classes'] to the csv

As for writing to the second column of the csv, take a look at the csv python module.


问:
Generate random numbers from exponential distribution and model using python
My goal is to create a dataset of random points whose histogram looks like an exponential decay function and then plot an exponential decay function through those points.

First I tried to create a series of random numbers (but did not do so successfully since these should be points, not numbers) from an exponential distribution.

```<code>from pylab import *
from scipy.optimize import curve_fit
import random
import numpy as np
import pandas as pd

testx = pd.DataFrame(range(10)).astype(float)
testx = testx[0]

for i in range(1,11):
   x = random.expovariate(15) # rate = 15 arrivals per second
   data[i] = [x]

testy = pd.DataFrame(data).T.astype(float)
testy = testy[0]; testy

plot(testx, testy, 'ko')
</code>```

The result could look something like this.

And then I define a function to draw a line through my points:

```<code>def func(x, a, e):
return a*np.exp(-a*x)+e

popt, pcov = curve_fit(f=func, xdata=testx, ydata=testy, p0 = None, sigma = None)

print popt # parameters
print pcov # covariance

plot(testx, testy, 'ko')

xx = np.linspace(0, 15, 1000)
plot(xx, func(xx,*popt))

plt.show()
</code>```

What I'm looking for is: (1) a more elegant way to create an array of random numbers from an exponential (decay) distribution and (2) how to test that my function is indeed going through the data points.

答:
I would guess that the following is close to what you want. You can generate some random numbers drawn from an exponential distribution with numpy,

```<code>data = numpy.random.exponential(5, size=1000)
</code>```

You can then create a histogram of them using numpy.hist and draw the histogram values into a plot. You may decide to take the middle of the bins as position for the point (this assumption is of course wrong, but gets the more valid the more bins you use).

Fitting works as in the code from the question. You will then find out that our fit roughly finds the parameter used for the data generation (in this case below ~5).

```<code>import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

data = np.random.exponential(5, size=1000)

hist,edges = np.histogram(data,bins="auto",density=True )

x = edges[:-1]+np.diff(edges)/2.
plt.scatter(x,hist)

func = lambda x,beta: 1./beta*np.exp(-x/beta)

popt, pcov = curve_fit(f=func, xdata=x, ydata=hist)

print(popt)

xx = np.linspace(0, x.max(), 101)
plt.plot(xx, func(xx,*popt), ls="--", color="k",
         label="fit, $beta = ${}".format(popt))
plt.legend()
plt.show()
</code>```

Body:
My goal is to create a dataset of random points whose histogram looks like an exponential decay function and then plot an exponential decay function through those points.

First I tried to create a series of random numbers (but did not do so successfully since these should be points, not numbers) from an exponential distribution.

from pylab import *
from scipy.optimize import curve_fit
import random
import numpy as np
import pandas as pd

testx = pd.DataFrame(range(10)).astype(float)
testx = testx[0]

for i in range(1,11):
   x = random.expovariate(15) # rate = 15 arrivals per second
   data[i] = [x]

testy = pd.DataFrame(data).T.astype(float)
testy = testy[0]; testy

plot(testx, testy, 'ko')

The result could look something like this.

And then I define a function to draw a line through my points:

def func(x, a, e):
return a*np.exp(-a*x)+e

popt, pcov = curve_fit(f=func, xdata=testx, ydata=testy, p0 = None, sigma = None)

print popt # parameters
print pcov # covariance

plot(testx, testy, 'ko')

xx = np.linspace(0, 15, 1000)
plot(xx, func(xx,*popt))

plt.show()

What I'm looking for is: (1) a more elegant way to create an array of random numbers from an exponential (decay) distribution and (2) how to test that my function is indeed going through the data points.

Body:
I would guess that the following is close to what you want. You can generate some random numbers drawn from an exponential distribution with numpy,

data = numpy.random.exponential(5, size=1000)

You can then create a histogram of them using numpy.hist and draw the histogram values into a plot. You may decide to take the middle of the bins as position for the point (this assumption is of course wrong, but gets the more valid the more bins you use).

Fitting works as in the code from the question. You will then find out that our fit roughly finds the parameter used for the data generation (in this case below ~5).

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

data = np.random.exponential(5, size=1000)

hist,edges = np.histogram(data,bins="auto",density=True )

x = edges[:-1]+np.diff(edges)/2.
plt.scatter(x,hist)

func = lambda x,beta: 1./beta*np.exp(-x/beta)

popt, pcov = curve_fit(f=func, xdata=x, ydata=hist)

print(popt)

xx = np.linspace(0, x.max(), 101)
plt.plot(xx, func(xx,*popt), ls="--", color="k",
         label="fit, $beta = ${}".format(popt))
plt.legend()
plt.show()


问:
Need Help: Python agent does not send any data to proxy and controller

Pyagent, Guniccorn and Python (Sanic) app are all installed in a Virtual Environment.

Vitual Env: Python 3.6.1 in macOs 10.12.4

I am using supervisor to manage gunicorn process.

[program:Test app]
command = /env/bin/pyagent run -c /etc/appdynamics.cfg -- /env/bin/gunicorn app:app --bind 0.0.0.0:8000 --worker-class sanic.worker.GunicornWorker
directory = /projects/app_dir/
autorestart=true

Appdynamics versions; pip freeze

```<code>appdynamics==4.3.8.0
appdynamics-bindeps-osx-x64==6.0
appdynamics-proxysupport-osx-x64==1.8.0.51.1
</code>```

Appdynamics.cfg

```<code>MacBook-Pro:appd$ cat /etc/appdynamics.cfg
[agent]
app = Test app
tier = api
node = node dev

[controller]
host = elephant2017072405043015.saas.appdynamics.com
port = 443
ssl = (on)
account = XXXXXXXXX
accesskey = XXXXXXXX

[log]
level = debug
debugging = on
</code>```

When i start the procees, i can see that agent is loaded properly and proxy is started as well.

```<code>2017-08-12 12:43:51,029 [WARNING] appdynamics.proxy.watchdog <83867>: Defunct proxy pid (83627) found; starting over
2017-08-12 12:43:51,093 [INFO] appdynamics.proxy.watchdog <83867>: Started watchdog with pid=83867
2017-08-12 12:43:51,198 [WARNING] appdynamics.proxy.watchdog <83867>: Found defunct proxy pid file with pid=83628
2017-08-12 12:43:51,218 [INFO] appdynamics.proxy.watchdog <83867>: Starting proxy: /Volumes/Personal/Django/versions/3.6.1/envs/events/lib/python3.6/site-packages/appdynamics_bindeps/proxy/runProxy -j /Volumes/Personal/Django/versions/3.6.1/envs/events/lib/python3.6/site-packages/appdynamics_proxysupport -d /Volumes/Personal/Django/versions/3.6.1/envs/events/lib/python3.6/site-packages/appdynamics_bindeps/proxy -r /tmp/appd/run /tmp/appd/run/comm /tmp/appd/logs
2017-08-12 12:43:51,723 [INFO] appdynamics.proxy.watchdog <83867>: Started proxy with pid=83868
Install Directory resolved to[/Volumes/Personal/Django/versions/3.6.1/envs/events/lib/python3.6/site-packages/appdynamics_bindeps/proxy]
Agent Logging Directory [/private/tmp/appd/logs]
Logs Directory resolved to[/tmp/appd/logs]
12:44:01,271  INFO [main] ProxyControlEntryPoint - ProxyControl - init
12:44:01,272  INFO [main] ProxyControlEntryPoint - comm dir set to: /tmp/appd/run/comm
12:44:01,423  INFO [main] ZeroMQControlServer - ipcNodeBaseDir dir set to: /tmp/appd/run/comm/proxy-6272190574628013158
12:44:01,423  INFO [main] ZeroMQControlServer - ZeroMQControlServer - init
12:44:01,722  INFO [main] ZeroMQControlServer - ControlReqRouterSocket started at:ipc:///tmp/appd/run/comm/0
12:44:02,330  INFO [main] ProxyControlEntryPoint - ProxyControl - init completed
12:44:02,330  INFO [main] ProxyControlEntryPoint - Should register node at startup:false
</code>```

But the problem is i dont see any data reported to controller when i generate load to my app. (using wrk to generate load)

Agent and proxy  Logs does not have any info about app data/metrics.

```<code>MacBook-Pro:appd $ cat /tmp/appd/logs/Test app-node_dev.log
2017-08-12 12:29:33,602 [DEBUG] appdynamics.agent <82799>: Running http.client hook <function intercept_httplib at 0x10fbfa730>
2017-08-12 12:29:33,603 [DEBUG] appdynamics.agent <82799>: Running logging hook <function intercept_logging at 0x10fb36c80>
2017-08-12 12:35:50,887 [DEBUG] appdynamics.agent <83569>: Running http.client hook <function intercept_httplib at 0x108151730>
2017-08-12 12:35:50,904 [DEBUG] appdynamics.agent <83569>: Running logging hook <function intercept_logging at 0x10808dc80>
2017-08-12 12:40:33,493 [DEBUG] appdynamics.agent <83625>: Running http.client hook <function intercept_httplib at 0x109b04730>
2017-08-12 12:40:33,517 [DEBUG] appdynamics.agent <83625>: Running logging hook <function intercept_logging at 0x109a40c80>
2017-08-12 12:43:54,092 [DEBUG] appdynamics.agent <83862>: Running http.client hook <function intercept_httplib at 0x108116730>
2017-08-12 12:43:54,115 [DEBUG] appdynamics.agent <83862>: Running logging hook <function intercept_logging at 0x108051c80>

MacBook-Pro:appd$ cat /tmp/appd/logs/proxyCore.2017_08_12__12_40_33.0.log
[main] 12 Aug 2017 12:40:33,704  INFO com.singularity.proxyControl.ProxyControlEntryPoint - ProxyControl - init
[main] 12 Aug 2017 12:40:33,705  INFO com.singularity.proxyControl.ProxyControlEntryPoint - comm dir set to: /tmp/appd/run/comm
[main] 12 Aug 2017 12:40:33,724  INFO com.singularity.proxyControl.ZeroMQControlServer - ipcNodeBaseDir dir set to: /tmp/appd/run/comm/proxy-2817425872527039173
[main] 12 Aug 2017 12:40:33,725  INFO com.singularity.proxyControl.ZeroMQControlServer - ZeroMQControlServer - init
[main] 12 Aug 2017 12:40:33,757  INFO com.singularity.proxyControl.ZeroMQControlServer - ControlReqRouterSocket started at:ipc:///tmp/appd/run/comm/0
[main] 12 Aug 2017 12:40:33,903  INFO com.singularity.proxyControl.ProxyControlEntryPoint - ProxyControl - init completed
[main] 12 Aug 2017 12:40:33,904  INFO com.singularity.proxyControl.ProxyControlEntryPoint - Should register node at startup:false
</code>```

Would really appreciate if someone can help me find out  the issue?

Thanks,
Manivasagan

答:
in your appdynamics.cfg, change

```<code>ssl = (on)
</code>```

to

```<code>ssl = on
</code>```

Body:
Pyagent, Guniccorn and Python (Sanic) app are all installed in a Virtual Environment.

Vitual Env: Python 3.6.1 in macOs 10.12.4

I am using supervisor to manage gunicorn process.

[program:Test app]
command = /env/bin/pyagent run -c /etc/appdynamics.cfg -- /env/bin/gunicorn app:app --bind 0.0.0.0:8000 --worker-class sanic.worker.GunicornWorker
directory = /projects/app_dir/
autorestart=true

Appdynamics versions; pip freeze

appdynamics==4.3.8.0
appdynamics-bindeps-osx-x64==6.0
appdynamics-proxysupport-osx-x64==1.8.0.51.1

Appdynamics.cfg

MacBook-Pro:appd$ cat /etc/appdynamics.cfg
[agent]
app = Test app
tier = api
node = node dev

[controller]
host = elephant2017072405043015.saas.appdynamics.com
port = 443
ssl = (on)
account = XXXXXXXXX
accesskey = XXXXXXXX

[log]
level = debug
debugging = on

When i start the procees, i can see that agent is loaded properly and proxy is started as well.

2017-08-12 12:43:51,029 [WARNING] appdynamics.proxy.watchdog <83867>: Defunct proxy pid (83627) found; starting over
2017-08-12 12:43:51,093 [INFO] appdynamics.proxy.watchdog <83867>: Started watchdog with pid=83867
2017-08-12 12:43:51,198 [WARNING] appdynamics.proxy.watchdog <83867>: Found defunct proxy pid file with pid=83628
2017-08-12 12:43:51,218 [INFO] appdynamics.proxy.watchdog <83867>: Starting proxy: /Volumes/Personal/Django/versions/3.6.1/envs/events/lib/python3.6/site-packages/appdynamics_bindeps/proxy/runProxy -j /Volumes/Personal/Django/versions/3.6.1/envs/events/lib/python3.6/site-packages/appdynamics_proxysupport -d /Volumes/Personal/Django/versions/3.6.1/envs/events/lib/python3.6/site-packages/appdynamics_bindeps/proxy -r /tmp/appd/run /tmp/appd/run/comm /tmp/appd/logs
2017-08-12 12:43:51,723 [INFO] appdynamics.proxy.watchdog <83867>: Started proxy with pid=83868
Install Directory resolved to[/Volumes/Personal/Django/versions/3.6.1/envs/events/lib/python3.6/site-packages/appdynamics_bindeps/proxy]
Agent Logging Directory [/private/tmp/appd/logs]
Logs Directory resolved to[/tmp/appd/logs]
12:44:01,271  INFO [main] ProxyControlEntryPoint - ProxyControl - init
12:44:01,272  INFO [main] ProxyControlEntryPoint - comm dir set to: /tmp/appd/run/comm
12:44:01,423  INFO [main] ZeroMQControlServer - ipcNodeBaseDir dir set to: /tmp/appd/run/comm/proxy-6272190574628013158
12:44:01,423  INFO [main] ZeroMQControlServer - ZeroMQControlServer - init
12:44:01,722  INFO [main] ZeroMQControlServer - ControlReqRouterSocket started at:ipc:///tmp/appd/run/comm/0
12:44:02,330  INFO [main] ProxyControlEntryPoint - ProxyControl - init completed
12:44:02,330  INFO [main] ProxyControlEntryPoint - Should register node at startup:false

But the problem is i dont see any data reported to controller when i generate load to my app. (using wrk to generate load)

Agent and proxy  Logs does not have any info about app data/metrics.

MacBook-Pro:appd $ cat /tmp/appd/logs/Test app-node_dev.log
2017-08-12 12:29:33,602 [DEBUG] appdynamics.agent <82799>: Running http.client hook <function intercept_httplib at 0x10fbfa730>
2017-08-12 12:29:33,603 [DEBUG] appdynamics.agent <82799>: Running logging hook <function intercept_logging at 0x10fb36c80>
2017-08-12 12:35:50,887 [DEBUG] appdynamics.agent <83569>: Running http.client hook <function intercept_httplib at 0x108151730>
2017-08-12 12:35:50,904 [DEBUG] appdynamics.agent <83569>: Running logging hook <function intercept_logging at 0x10808dc80>
2017-08-12 12:40:33,493 [DEBUG] appdynamics.agent <83625>: Running http.client hook <function intercept_httplib at 0x109b04730>
2017-08-12 12:40:33,517 [DEBUG] appdynamics.agent <83625>: Running logging hook <function intercept_logging at 0x109a40c80>
2017-08-12 12:43:54,092 [DEBUG] appdynamics.agent <83862>: Running http.client hook <function intercept_httplib at 0x108116730>
2017-08-12 12:43:54,115 [DEBUG] appdynamics.agent <83862>: Running logging hook <function intercept_logging at 0x108051c80>

MacBook-Pro:appd$ cat /tmp/appd/logs/proxyCore.2017_08_12__12_40_33.0.log
[main] 12 Aug 2017 12:40:33,704  INFO com.singularity.proxyControl.ProxyControlEntryPoint - ProxyControl - init
[main] 12 Aug 2017 12:40:33,705  INFO com.singularity.proxyControl.ProxyControlEntryPoint - comm dir set to: /tmp/appd/run/comm
[main] 12 Aug 2017 12:40:33,724  INFO com.singularity.proxyControl.ZeroMQControlServer - ipcNodeBaseDir dir set to: /tmp/appd/run/comm/proxy-2817425872527039173
[main] 12 Aug 2017 12:40:33,725  INFO com.singularity.proxyControl.ZeroMQControlServer - ZeroMQControlServer - init
[main] 12 Aug 2017 12:40:33,757  INFO com.singularity.proxyControl.ZeroMQControlServer - ControlReqRouterSocket started at:ipc:///tmp/appd/run/comm/0
[main] 12 Aug 2017 12:40:33,903  INFO com.singularity.proxyControl.ProxyControlEntryPoint - ProxyControl - init completed
[main] 12 Aug 2017 12:40:33,904  INFO com.singularity.proxyControl.ProxyControlEntryPoint - Should register node at startup:false

Would really appreciate if someone can help me find out  the issue?

Thanks,
Manivasagan

Body:
in your appdynamics.cfg, change

ssl = (on)

to

ssl = on


问:
How to toggle a button to an active state using vanilla JS?
I have a list of 20 buttons on a page. When I click on a button I want it to switch to an "active" state. In this active state it will be a different color. I would like to do this using only vanilla javascript and css.

I have the following code to create the buttons:

```<code>var button;
createButtons();

function createButtons() {
  for (i = 0; i < 20; i++) {
    //creates a new button
    button = document.createElement('Button');

    //sets correct button number and button text
    var index = i + 1;
    var text = document.createTextNode('Button ' + index);
    button.appendChild(text);
    button.className += "button";
    button.className += " default-button";
    document.body.appendChild(button);
  }
}
</code>```

答:
.focus(), but most browsers actually block button click type behavior for security purposes. What you can do is set the button elements disabled = true attribute then when you get whatever action you are looking for toggle that attribute to disabled = false.

Here's a snippet you could adapt:

```<code>// enables submit button iif inputs meet validation contraints
function attachKeyupListenerToInputElements(){
    var inputs = doc.querySelectorAll('input');
    for (var i = 0; i < inputs.length; i++) {
        inputs[i].addEventListener("keyup", keyupHandler);
    }

    function keyupHandler() {
        if(this.value === ''){
            this.setCustomValidity('Required Field');
        } else {
            this.setCustomValidity('');
        }
        //for dialog inputs
        if(doc.querySelector(".mdc-dialog").classList.contains("mdc-dialog--open")){
            //dialog is open
            var thisSection  = this.parentElement.parentElement;
            var theseInputs = thisSection.querySelectorAll("input");
            var inputsFull = true;
            for (var i = 0; i < theseInputs.length; i++) {
                if(!theseInputs[i].checkValidity()){
                    inputsFull = false;
                }
            }
            if(inputsFull){
                doc.getElementById("dialog-accept-button").disabled = false;
            }
        }
    }
}
</code>```

Body:
I have a list of 20 buttons on a page. When I click on a button I want it to switch to an "active" state. In this active state it will be a different color. I would like to do this using only vanilla javascript and css.

I have the following code to create the buttons:

var button;
createButtons();

function createButtons() {
  for (i = 0; i < 20; i++) {
    //creates a new button
    button = document.createElement('Button');

    //sets correct button number and button text
    var index = i + 1;
    var text = document.createTextNode('Button ' + index);
    button.appendChild(text);
    button.className += "button";
    button.className += " default-button";
    document.body.appendChild(button);
  }
}

Body:
.focus(), but most browsers actually block button click type behavior for security purposes. What you can do is set the button elements disabled = true attribute then when you get whatever action you are looking for toggle that attribute to disabled = false.

Here's a snippet you could adapt:

// enables submit button iif inputs meet validation contraints
function attachKeyupListenerToInputElements(){
    var inputs = doc.querySelectorAll('input');
    for (var i = 0; i < inputs.length; i++) {
        inputs[i].addEventListener("keyup", keyupHandler);
    }

    function keyupHandler() {
        if(this.value === ''){
            this.setCustomValidity('Required Field');
        } else {
            this.setCustomValidity('');
        }
        //for dialog inputs
        if(doc.querySelector(".mdc-dialog").classList.contains("mdc-dialog--open")){
            //dialog is open
            var thisSection  = this.parentElement.parentElement;
            var theseInputs = thisSection.querySelectorAll("input");
            var inputsFull = true;
            for (var i = 0; i < theseInputs.length; i++) {
                if(!theseInputs[i].checkValidity()){
                    inputsFull = false;
                }
            }
            if(inputsFull){
                doc.getElementById("dialog-accept-button").disabled = false;
            }
        }
    }
}


问:
Error 500 when preparing a MySQL query
My registration page shows a Internal server error when submitting the form. There are no errors in the logs but I pinpointed the problem down to this code:

```<code>    databaseConnectie('database');
    //still works
    $stmt_query = $db->prepare("
      SELECT *
      FROM table
    ");
    //error 500
    //execute would be here
</code>```

I use the same code in other functions which works fine. Privileges also look fine, same as other DBs.

If it helps, I'm running Wordpress with BuddyPress.

Does anyone have any idea how to fix this?

答:
We may not be able to help you out without any more information.
You're saying that you have nothing into the logs, please make sure that debugging is enabled in wp-config.php

Try adding this into the file

define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);

and check on your wp-content directory the file 'debug.log'. You should be able to know a bit more about what's happening.

Title: Error 500 when preparing a MySQL query

Body:
My registration page shows a Internal server error when submitting the form. There are no errors in the logs but I pinpointed the problem down to this code:

    databaseConnectie('database');
    //still works
    $stmt_query = $db->prepare("
      SELECT *
      FROM table
    ");
    //error 500
    //execute would be here

I use the same code in other functions which works fine. Privileges also look fine, same as other DBs.

If it helps, I'm running Wordpress with BuddyPress.

Does anyone have any idea how to fix this?


问:
Cast Int to enum in Java
What is the correct way to cast an Int to an enum in Java given the following enum?</p>

```<code>public enum MyEnum
{
    EnumValue1,
    EnumValue2
}

MyEnum enumValue = (MyEnum) x; //Doesn't work???
</code>```

答:
In case it helps others, the option I prefer, which is not listed here, uses Guava's Maps functionality:

```<code>public enum MyEnum {
    OPTION_1(-66),
    OPTION_2(32);

    private int value;
    private MyEnum(final int value) {
        this.value = value;
    }

    public int getValue() {
        return this.value;
    }

    private static ImmutableMap<Integer, MyEnum> reverseLookup =
            Maps.uniqueIndex(Arrays.asList(MyEnum.values())), MyEnum::getValue);

    public static MyEnum fromInt(final int id) {
        return reverseLookup.getOrDefault(id, OPTION_1);
    }
}
</code>```

With the default you can use null, you can throw IllegalArgumentException or your fromInt could return an Optional, whatever behavior you prefer.

Title: Cast Int to enum in Java

Body:
What is the correct way to cast an Int to an enum in Java given the following enum?

public enum MyEnum
{
    EnumValue1,
    EnumValue2
}

MyEnum enumValue = (MyEnum) x; //Doesn't work???

Body:
In case it helps others, the option I prefer, which is not listed here, uses Guava's Maps functionality:

public enum MyEnum {
    OPTION_1(-66),
    OPTION_2(32);

    private int value;
    private MyEnum(final int value) {
        this.value = value;
    }

    public int getValue() {
        return this.value;
    }

    private static ImmutableMap<Integer, MyEnum> reverseLookup =
            Maps.uniqueIndex(Arrays.asList(MyEnum.values())), MyEnum::getValue);

    public static MyEnum fromInt(final int id) {
        return reverseLookup.getOrDefault(id, OPTION_1);
    }
}

With the default you can use null, you can throw IllegalArgumentException or your fromInt could return an Optional, whatever behavior you prefer.


答:
Think about what you're going to do with the pointer.

```<code>int n = 42;
char *p = &n; // BAD
</code>```

If this compiles (a compiler can reject it outright rather than printing a non-fatal warning), you have a pointer that points to the memory occupied by the int object n. How are you going to get the value of that object? *p gives you a char result, most likely the first byte of n -- which may be the high-order byte or the low-order byte.

Pointer types depend on the type of object they point to so that you can access that object.

(Also, don't make assumptions based on the behavior of your particular implementation. 32-bit systems have 4-byte pointers, and the language doesn't guarantee that all pointers are the same size.)

Body:
So I'm learning about C pointers, and I'm a little confused. Pointers just point to specific memory address.

sizeof(char*), sizeof(int*), sizeof(double*) all output 8. So they all take 8 bytes to store a memory address.

However, if I try to compile something like this:

int main(void)
{
    char letter = 'A';
    int *a = &letter;
    printf("letter: %c\n", *a);
}

I get a warning from the compiler (gcc):

 warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]
     int *a = &letter;

However, char *a = &letter;, doesn't result in a warning.

Why does the type of the pointer matter, if it's 8 bytes long anyway? Why does declaring a pointer with a type different than the type of data it's pointing to yield in a warning?

Body:
Think about what you're going to do with the pointer.

int n = 42;
char *p = &n; // BAD

If this compiles (a compiler can reject it outright rather than printing a non-fatal warning), you have a pointer that points to the memory occupied by the int object n. How are you going to get the value of that object? *p gives you a char result, most likely the first byte of n -- which may be the high-order byte or the low-order byte.

Pointer types depend on the type of object they point to so that you can access that object.

(Also, don't make assumptions based on the behavior of your particular implementation. 32-bit systems have 4-byte pointers, and the language doesn't guarantee that all pointers are the same size.)


问:
Will `Object.keys(x)` ever throw?
How can I know for sure if

Object.keys(x) will ever throw an error?

where x is anything.

答:
I finally decided to add my own answer because people aren't giving you the simplest possible and most complete answer here:

Will Object.keys(x) ever throw?

Yes it can throw.  In ES5, it will throw if x is not an object.  You can verify this yourself in IE11 or any older browser.

In ES2015, it will throw if x is undefined or null.  Other non-object values such as a number, string or boolean will be coerced into an object and will then return an empty array (since the coerced object has no enumerable properties).

The ES2015 specification requires that x is coerced into an object (if possible).  This means that it will successfully coerce some things into an object such as a number, boolean, string, but not null or undefined so even in ES2015, both Object.keys(null) and Object.keys(undefined) will still throw as tested in Chrome v62.

So, if you really wanted to be safe, you would either put a try/catch around your code or you would test to see if x !== null && typeof x === "object" before calling Object.keys().

```<code>function safeKeys(val) {
    // test to see if we have a valid non-null object
    if (val && typeof val === "object") {
        return Object.keys(val);
    } else {
        return [];
    }
}
</code>```

Or, using try/catch:

```<code>function safeKeys(val) {
    try {
        return Object.keys(val);
    } catch(e) {
        return [];
    }
}
</code>```

The try/catch is probably ultimately safer in case an imperfect implementation throws in some situation you weren't expecting.

How can I know for sure if Object.keys(x) will ever throw an error?

You can read relevant specifications to find out what implementations are supposed to do.  And, you can test pertinent implementations to find out what they actually do.  If you want to really know for sure, you have to test specific implementations.  In an imperfect world, if you want to know something like this that is a little off-the-beaten-path with absolutely certainty, you have to test it yourself and see how they behave.

In this example, a simple test case takes about 2 minutes to code and run in a few relevant environments.  This case was slightly more complicated than usual because the specification and then implementation changed over time (different from ES5 to ES2015).

But, practically speaking, if you know you might get a non-object there, then it's probably way simpler to just code defensively and in this particular case since you had a moving target of a specification and implementation it's advisable to just code defensively regardless of this aspect of the implementation.  Then, you don't have to know for sure how the underlying platform behaves when given bad data.  Just filter out the bad data up front so it has the behavior you want it to have in that case.

Title: Will `Object.keys(x)` ever throw?

Body:
I finally decided to add my own answer because people aren't giving you the simplest possible and most complete answer here:

Will Object.keys(x) ever throw?

Yes it can throw.  In ES5, it will throw if x is not an object.  You can verify this yourself in IE11 or any older browser.

In ES2015, it will throw if x is undefined or null.  Other non-object values such as a number, string or boolean will be coerced into an object and will then return an empty array (since the coerced object has no enumerable properties).

The ES2015 specification requires that x is coerced into an object (if possible).  This means that it will successfully coerce some things into an object such as a number, boolean, string, but not null or undefined so even in ES2015, both Object.keys(null) and Object.keys(undefined) will still throw as tested in Chrome v62.

So, if you really wanted to be safe, you would either put a try/catch around your code or you would test to see if x !== null && typeof x === "object" before calling Object.keys().

function safeKeys(val) {
    // test to see if we have a valid non-null object
    if (val && typeof val === "object") {
        return Object.keys(val);
    } else {
        return [];
    }
}

Or, using try/catch:

function safeKeys(val) {
    try {
        return Object.keys(val);
    } catch(e) {
        return [];
    }
}

The try/catch is probably ultimately safer in case an imperfect implementation throws in some situation you weren't expecting.

How can I know for sure if Object.keys(x) will ever throw an error?

You can read relevant specifications to find out what implementations are supposed to do.  And, you can test pertinent implementations to find out what they actually do.  If you want to really know for sure, you have to test specific implementations.  In an imperfect world, if you want to know something like this that is a little off-the-beaten-path with absolutely certainty, you have to test it yourself and see how they behave.

In this example, a simple test case takes about 2 minutes to code and run in a few relevant environments.  This case was slightly more complicated than usual because the specification and then implementation changed over time (different from ES5 to ES2015).

But, practically speaking, if you know you might get a non-object there, then it's probably way simpler to just code defensively and in this particular case since you had a moving target of a specification and implementation it's advisable to just code defensively regardless of this aspect of the implementation.  Then, you don't have to know for sure how the underlying platform behaves when given bad data.  Just filter out the bad data up front so it has the behavior you want it to have in that case.


问:
lua OOP - how to write Class as a table of tables of functions

Context

I'm trying to write a class system which will generate melodies by performing permutations on the notes and rhythms. I'm gonna use this in the tool "xStream" in the "Renoise" software. My example here is a really dumbed down and generic version from what I really have.

I'm also making this as a learning opportunity. My OOP skills are weak, and I still haven't completely wrapped my head around metatables. So a preemptive sorry if I'm totally missing something. I'm doing all my code from the style of the basic OOP examples in the 3rd edition of Programming in Lua.

My question

What I want to do is have class methods with similar functionality all grouped into 'nested' tables. Eg, a table of 'melody permutations', a table of 'rhythm permutations', a table of miscellaneous utility methods, etc.

In the code, I have a class SomeClass. It has two types of print functions: print1_notes is in the 'main table' (ie, a key of SomeClass). print2.notes is in a 'nested' table print2, which is a key of SomeClass (ie, notes is just a key of SomeClass.print2).

I can call print1_notes just fine. The issue is when I call the print2 methods with the colon operator.
If I don't use sugar (eg, obj.print2.notes(obj)), then no problem. But when I do (eg, obj.print2:notes()), I get errors about "attempt to (blah blah) a function value ...".

How come it works without the colon operator?

Do methods in SomeClass.print2 have access to the keys in SomeClass? Do they have access the same way that the non-nested table keys do?

I was thinking that print2 needs an __index key to tell its methods to look up the keys in SomeClass when it doesn't know what self.a_key is. But self (inside the print2 methods) isn't a key. It's really just an alias for SomeClass. Is it though? Seems like there's a discrepancy with the nested table.

Do I need to make SomeClass the metatable of print2? Is that even possible, since print2 isn't a separate table from SomeClass?

Should I try a different approach? Maybe multiple inheritance?

Thanks. Sorry if this needs to be moved or if someone has asked this before.

My code

```<code>SomeClass = {
    new = function (self, t)
        t = t or {}
        setmetatable(t, self)
        self.__index = function (_, key)
            return self[key]
        end

        --should I add a setmetatable here? perhaps:
        --setmetatable(self.print2, self)

        return t
    end,

    notes = {},
    set_notes = function (self, t)
        self.notes = t or {}
        self.N = #self.notes
    end,

    print1_notes = function (self)
        print("There are "..tostring(self.N).." notes :", table.unpack(self.notes))
    end,

    --table of different print functions
    print2 = {
        notes = function (self)
            --is self an alias for SomeClass?
            assert(self.notes, "Error: self.notes = nil")
            print("There are "..tostring(self.N).." notes :", table.unpack(self.notes))
        end,

        first_note = function (self)
            fn = self.notes[1]
            print("first note is: ", fn)
        end,
    },

}

obj = SomeClass:new()
obj:set_notes{ 10,14,5, 10,14,5, 17 }

print("\ncalling print1_notes without sugar:")
obj.print1_notes(obj)
print("\ncalling print1_notes with sugar:")
obj:print1_notes()
print("\ncalling print2.notes without sugar")
obj.print2.notes(obj)
print("\ncalling print2.notes with sugar")
obj.print2:notes()  --this gives an error: "attempt to get length of a function value"

obj.print2.first_note(obj)  --this works fine
obj.print2:first_note()     --this gives an error:
                            --  "attempt to index a function value (field 'notes')"
</code>```

EDIT to code: instances of tostring(N) needed to be replaced with tostring(self.N).

EDIT: weird errors has to do with the fact that SomeClass.print2.notes has a notes member like SomeClass.notes. SomeClass.print2.first_note avoids this complication. (I'll explain more when I answer)

EDIT: I came up with a solution. It's not pretty, but it works. I'll post my answer below.

答:
I came up with a solution of sorts. In short: any functions in print2 must start with self = getmetatable(self). This is to turn self (originally obj.print2) into obj.

Also, sorry if this answer is too long or violates any guidelines.

To reiterate, I'm wanting to have another table SomeClass.print2 which has all print related functions. If I wanted to print the notes, I would do

```<code>obj.print2:notes()
--sugar for
obj.print2.notes(obj.print2)
</code>```

Of course, when I do this, self.notes inside SomeClass.print2.notes would refer to obj.print2.notes (and not obj.notes). This is an issue even if I rename the function to  SomeClass.print2.the_notes.

New Code

So what I did is changed SomeClass:new into this:

```<code>SomeClass:new = function (self, t)
    t = t or {}                     --
    setmetatable(t, self)           --
    self.__index = function (_, k)  --
        return self[k]              --
    end                             -- same from before

    mt = {}
    mt.print2 = {}
    mt.print2.__index = SomeClass.print2  -- only fixes calls to obj.print2:foo()

    t.print2 = {}
    setmetatable( t.print2, mt.print2)
    setmetatable(mt.print2, t)
    t.__index = t  -- fixes references to self.key inside print2 functions

    return t
end
</code>```

And SomeClass.print2 should look like this now:

```<code>SomeClass.print2 = {
    notes = function (self)
        self = getmetatable(self)   -- self is now mt.print2
                                    -- self.notes will become obj.notes
        self = getmetatable(self)   -- self should just be obj now
                                    -- but this is unnecessary

        print("There are "..tostring(self.N).." notes :", table.unpack(self.notes))
    end,

    first_note = function (self)
        self = getmetatable(self)

        fn = self.notes[1]
        print("first note is: ", fn)
    end,
}
</code>```

So basically, any calls to obj.print2.foo should return SomeClass.print2.foo. (See mt.print2.__index).

Every function in SomeClass.print2 MUST have at least one 'self = getmetatable(self)' at the top of the function body**. Then, inside SomeClass.print2.foo(), self is mt.print2. So then, self.key should become:

obj.key if key is notes or N

if obj.key is nil, then become SomeClass.key instead

** A second self = getmetatable(self) is recommended, but optional.

Very detailed explanation

Step-by-step, what we have is

Create a new object with obj = SomeClass:new()

obj has an empty table at obj.print2

A new table mt is created, which is associated with obj

more specifically, mt.print2 is the metatable of obj.print2, and the metatable of mt.print2 is obj

Set notes (eg, obj:set_notes{10,20,30})

call obj.print2:notes(), ie, obj.print2.notes(obj.print2)

obj.print2.somekey is nil where 'somekey' is notes

So we look for the __index function in the metatable of obj.print2

mt.__index returns SomeClass.print2.somekey

So obj.print2.notes(obj.print2) is now SomeClass.print2.notes(obj.print2)

Inside the call (part 1)

self is obj.print2

we want to get obj.notes using self.notes

So we change self into its metatable once. We do self = getmetatable(self).

self is now mt.print2

Now, if we did self.notes, this will be mt.print2.notes

mt.print2.notes is nil

This will call obj.__index because obj is the metatable for mt.print2

So mt.print2.notes should become obj.notes

Therefore, self.notes becomes obj.notes

Inside the call (part 2)

self is mt.print2

We could do self = getmetatable(self) again

Then self would just become obj, since that's the metatable for mt.print2

Notes

This is a pretty ugly solution, I'll admit. But it works.

I hate having to put self = getmetatable(self) at the top of any function body in SomeClass.print2. This could be avoided if there was someway to transform self into obj inside of mt.print2.__index. I'm pretty sure that's impossible, since mt.print2.__index can only return an object (ie, the function SomeClass.print2.foo).

The reason I made mt a table with mt.print2 was so that I could add more of these 'namespaced' functions to SomeClass. If I wanted a namespace m_notes for functions that transform the notes, I would just add these statements to SomeClass:new():

```<code>mt.m_notes = {}
mt.m_notes.__index = SomeClass.m_notes

t.m_notes = {}
setmetatable( t.m_notes, mt.m_notes )
setmetatable(mt.m_notes, t)
</code>```

In fact, I could make a function that does this for any new namespace:

```<code>add_namespace = function( t, mt, key_string )
    mt[key_string] = {}
    mt[key_string].__index = SomeClass[key_string]
     t[key_string] = {}
    setmetatable( t[key_string], mt[key_string] )
    setmetatable(mt[key_string], t)
end
</code>```

Maybe it'd be better to make mt just be a member in t. So mt would just be t.mt and mt.print2 would be t.mt.print2, etc. Then it could be accessed later if needed (eg, for encapsulation purposes). There aren't any issues with having mt by itself; Calling SomeClass:new() will always create a new mt to be associated with the new object.

Please comment if you can think of any performace issues/enhancements with this trick. Or if I can make it more elegant looking. Definitely let me know if you can think of any way to remove the self = getmetatable(self) at the top of every print2 function definition.

Body:
Context

I'm trying to write a class system which will generate melodies by performing permutations on the notes and rhythms. I'm gonna use this in the tool "xStream" in the "Renoise" software. My example here is a really dumbed down and generic version from what I really have.

I'm also making this as a learning opportunity. My OOP skills are weak, and I still haven't completely wrapped my head around metatables. So a preemptive sorry if I'm totally missing something. I'm doing all my code from the style of the basic OOP examples in the 3rd edition of Programming in Lua.

My question

What I want to do is have class methods with similar functionality all grouped into 'nested' tables. Eg, a table of 'melody permutations', a table of 'rhythm permutations', a table of miscellaneous utility methods, etc.

In the code, I have a class SomeClass. It has two types of print functions: print1_notes is in the 'main table' (ie, a key of SomeClass). print2.notes is in a 'nested' table print2, which is a key of SomeClass (ie, notes is just a key of SomeClass.print2).

I can call print1_notes just fine. The issue is when I call the print2 methods with the colon operator.
If I don't use sugar (eg, obj.print2.notes(obj)), then no problem. But when I do (eg, obj.print2:notes()), I get errors about "attempt to (blah blah) a function value ...".

How come it works without the colon operator?

Do methods in SomeClass.print2 have access to the keys in SomeClass? Do they have access the same way that the non-nested table keys do?

I was thinking that print2 needs an __index key to tell its methods to look up the keys in SomeClass when it doesn't know what self.a_key is. But self (inside the print2 methods) isn't a key. It's really just an alias for SomeClass. Is it though? Seems like there's a discrepancy with the nested table.

Do I need to make SomeClass the metatable of print2? Is that even possible, since print2 isn't a separate table from SomeClass?

Should I try a different approach? Maybe multiple inheritance?

Thanks. Sorry if this needs to be moved or if someone has asked this before.

My code

SomeClass = {
    new = function (self, t)
        t = t or {}
        setmetatable(t, self)
        self.__index = function (_, key)
            return self[key]
        end

        --should I add a setmetatable here? perhaps:
        --setmetatable(self.print2, self)

        return t
    end,

    notes = {},
    set_notes = function (self, t)
        self.notes = t or {}
        self.N = #self.notes
    end,

    print1_notes = function (self)
        print("There are "..tostring(self.N).." notes :", table.unpack(self.notes))
    end,

    --table of different print functions
    print2 = {
        notes = function (self)
            --is self an alias for SomeClass?
            assert(self.notes, "Error: self.notes = nil")
            print("There are "..tostring(self.N).." notes :", table.unpack(self.notes))
        end,

        first_note = function (self)
            fn = self.notes[1]
            print("first note is: ", fn)
        end,
    },

}

obj = SomeClass:new()
obj:set_notes{ 10,14,5, 10,14,5, 17 }

print("\ncalling print1_notes without sugar:")
obj.print1_notes(obj)
print("\ncalling print1_notes with sugar:")
obj:print1_notes()
print("\ncalling print2.notes without sugar")
obj.print2.notes(obj)
print("\ncalling print2.notes with sugar")
obj.print2:notes()  --this gives an error: "attempt to get length of a function value"

obj.print2.first_note(obj)  --this works fine
obj.print2:first_note()     --this gives an error:
                            --  "attempt to index a function value (field 'notes')"

EDIT to code: instances of tostring(N) needed to be replaced with tostring(self.N).

EDIT: weird errors has to do with the fact that SomeClass.print2.notes has a notes member like SomeClass.notes. SomeClass.print2.first_note avoids this complication. (I'll explain more when I answer)

EDIT: I came up with a solution. It's not pretty, but it works. I'll post my answer below.

Body:
I came up with a solution of sorts. In short: any functions in print2 must start with self = getmetatable(self). This is to turn self (originally obj.print2) into obj.

Also, sorry if this answer is too long or violates any guidelines.

To reiterate, I'm wanting to have another table SomeClass.print2 which has all print related functions. If I wanted to print the notes, I would do

obj.print2:notes()
--sugar for
obj.print2.notes(obj.print2)

Of course, when I do this, self.notes inside SomeClass.print2.notes would refer to obj.print2.notes (and not obj.notes). This is an issue even if I rename the function to  SomeClass.print2.the_notes.

New Code

So what I did is changed SomeClass:new into this:

SomeClass:new = function (self, t)
    t = t or {}                     --
    setmetatable(t, self)           --
    self.__index = function (_, k)  --
        return self[k]              --
    end                             -- same from before

    mt = {}
    mt.print2 = {}
    mt.print2.__index = SomeClass.print2  -- only fixes calls to obj.print2:foo()

    t.print2 = {}
    setmetatable( t.print2, mt.print2)
    setmetatable(mt.print2, t)
    t.__index = t  -- fixes references to self.key inside print2 functions

    return t
end

And SomeClass.print2 should look like this now:

SomeClass.print2 = {
    notes = function (self)
        self = getmetatable(self)   -- self is now mt.print2
                                    -- self.notes will become obj.notes
        self = getmetatable(self)   -- self should just be obj now
                                    -- but this is unnecessary

        print("There are "..tostring(self.N).." notes :", table.unpack(self.notes))
    end,

    first_note = function (self)
        self = getmetatable(self)

        fn = self.notes[1]
        print("first note is: ", fn)
    end,
}

So basically, any calls to obj.print2.foo should return SomeClass.print2.foo. (See mt.print2.__index).

Every function in SomeClass.print2 MUST have at least one 'self = getmetatable(self)' at the top of the function body**. Then, inside SomeClass.print2.foo(), self is mt.print2. So then, self.key should become:

obj.key if key is notes or N

if obj.key is nil, then become SomeClass.key instead

** A second self = getmetatable(self) is recommended, but optional.

Very detailed explanation

Step-by-step, what we have is

Create a new object with obj = SomeClass:new()

obj has an empty table at obj.print2

A new table mt is created, which is associated with obj

more specifically, mt.print2 is the metatable of obj.print2, and the metatable of mt.print2 is obj

Set notes (eg, obj:set_notes{10,20,30})

call obj.print2:notes(), ie, obj.print2.notes(obj.print2)

obj.print2.somekey is nil where 'somekey' is notes

So we look for the __index function in the metatable of obj.print2

mt.__index returns SomeClass.print2.somekey

So obj.print2.notes(obj.print2) is now SomeClass.print2.notes(obj.print2)

Inside the call (part 1)

self is obj.print2

we want to get obj.notes using self.notes

So we change self into its metatable once. We do self = getmetatable(self).

self is now mt.print2

Now, if we did self.notes, this will be mt.print2.notes

mt.print2.notes is nil

This will call obj.__index because obj is the metatable for mt.print2

So mt.print2.notes should become obj.notes

Therefore, self.notes becomes obj.notes

Inside the call (part 2)

self is mt.print2

We could do self = getmetatable(self) again

Then self would just become obj, since that's the metatable for mt.print2

Notes

This is a pretty ugly solution, I'll admit. But it works.

I hate having to put self = getmetatable(self) at the top of any function body in SomeClass.print2. This could be avoided if there was someway to transform self into obj inside of mt.print2.__index. I'm pretty sure that's impossible, since mt.print2.__index can only return an object (ie, the function SomeClass.print2.foo).

The reason I made mt a table with mt.print2 was so that I could add more of these 'namespaced' functions to SomeClass. If I wanted a namespace m_notes for functions that transform the notes, I would just add these statements to SomeClass:new():

mt.m_notes = {}
mt.m_notes.__index = SomeClass.m_notes

t.m_notes = {}
setmetatable( t.m_notes, mt.m_notes )
setmetatable(mt.m_notes, t)

In fact, I could make a function that does this for any new namespace:

add_namespace = function( t, mt, key_string )
    mt[key_string] = {}
    mt[key_string].__index = SomeClass[key_string]
     t[key_string] = {}
    setmetatable( t[key_string], mt[key_string] )
    setmetatable(mt[key_string], t)
end

Maybe it'd be better to make mt just be a member in t. So mt would just be t.mt and mt.print2 would be t.mt.print2, etc. Then it could be accessed later if needed (eg, for encapsulation purposes). There aren't any issues with having mt by itself; Calling SomeClass:new() will always create a new mt to be associated with the new object.

Please comment if you can think of any performace issues/enhancements with this trick. Or if I can make it more elegant looking. Definitely let me know if you can think of any way to remove the self = getmetatable(self) at the top of every print2 function definition.


问:
SQL Server - import XML fields from multiple levels
I'm wanting to select the XML hierarchy value for Chart Name into the first column for all Filter values under that Chart.

I've used the method below but ChartName returns a NULL.  I suspect I will need to do a subquery

```<code>DECLARE @input XML =
'<Report>
    <DataSets>
    </DataSets>
    <ReportSections>
      <ReportSection>
        <ReportItems>
          <Chart Name="Hub1">
            <Filters>
                <Filter>
                  <Expression>Fields!Hub.Value</Expression>
                  <Operator>Like</Operator>
                  <Values>
                    <Value>Central</Value>
                  </Values>
                </Filter>
                <Filter>
                    <Expression>Fields!ADP_Hrs.Value</Expression>
                    <Operator>NotEqual</Operator>
                    <Values>
                      <Value DataType="Float">0</Value>
                    </Values>
                </Filter>
                <Filter>
                    <Expression>Fields!TL.Value</Expression>
                    <Operator>Equal</Operator>
                    <Values>
                      <Value DataType="Integer">1</Value>
                    </Values>
                </Filter>
            </Filters>
          </Chart>
        </ReportItems>
      </ReportSection>
    </ReportSections>
</Report>'

SELECT
    [Tbl].[Col].value('Chart [4]', 'varchar(50)') as ChartName,
    [Tbl].[Col].value('Expression [1]', 'varchar(50)') as Expression,
    [Tbl].[Col].value(' Operator [1]', 'varchar(50)') as 'Operator',
    [Tbl].[Col].value(' Values [1]', 'varchar(50)') as 'Value'
FROM
    @input.nodes('Report/ReportSections/ReportSection/ReportItems/Chart/Filters/Filter') as [Tbl]([Col])
</code>```

Expected output:

```<code>ChartName  Expression              Operator    Value
------------------------------------------------------
Hub1       Fields!Hub.Value        Like        Central
Hub1       Fields!ADP_Hrs.Value    NotEqual    0
Hub1       Fields!TL.Value         Equal       1
</code>```

答:
Chart is not within the Filter element, so it can't find it unless you walk backwards up the XML path, and then pull the @Name attribute of the Chart element:

```<code>SELECT
[Tbl].[Col].value('(../../@Name)[1]', 'varchar(50)') as ChartName,
[Tbl].[Col].value('Expression [1]', 'varchar(50)') as Expression,
[Tbl].[Col].value(' Operator [1]', 'varchar(50)') as 'Operator',
[Tbl].[Col].value(' Values [1]', 'varchar(50)') as 'Value'

FROM @input.nodes('Report/ReportSections/ReportSection/ReportItems/Chart/Filters/Filter') as [Tbl]([Col])
</code>```

Which returns:

```<code>ChartName      Expression              Operator     Value
-------------- ----------------------- ------------ -------------
Hub1           Fields!Hub.Value        Like         Central
Hub1           Fields!ADP_Hrs.Value    NotEqual     0
Hub1           Fields!TL.Value         Equal        1
</code>```

Body:
I'm wanting to select the XML hierarchy value for Chart Name into the first column for all Filter values under that Chart.

I've used the method below but ChartName returns a NULL.  I suspect I will need to do a subquery

DECLARE @input XML =
'<Report>
    <DataSets>
    </DataSets>
    <ReportSections>
      <ReportSection>
        <ReportItems>
          <Chart Name="Hub1">
            <Filters>
                <Filter>
                  <Expression>Fields!Hub.Value</Expression>
                  <Operator>Like</Operator>
                  <Values>
                    <Value>Central</Value>
                  </Values>
                </Filter>
                <Filter>
                    <Expression>Fields!ADP_Hrs.Value</Expression>
                    <Operator>NotEqual</Operator>
                    <Values>
                      <Value DataType="Float">0</Value>
                    </Values>
                </Filter>
                <Filter>
                    <Expression>Fields!TL.Value</Expression>
                    <Operator>Equal</Operator>
                    <Values>
                      <Value DataType="Integer">1</Value>
                    </Values>
                </Filter>
            </Filters>
          </Chart>
        </ReportItems>
      </ReportSection>
    </ReportSections>
</Report>'

SELECT
    [Tbl].[Col].value('Chart [4]', 'varchar(50)') as ChartName,
    [Tbl].[Col].value('Expression [1]', 'varchar(50)') as Expression,
    [Tbl].[Col].value(' Operator [1]', 'varchar(50)') as 'Operator',
    [Tbl].[Col].value(' Values [1]', 'varchar(50)') as 'Value'
FROM
    @input.nodes('Report/ReportSections/ReportSection/ReportItems/Chart/Filters/Filter') as [Tbl]([Col])

Expected output:

ChartName  Expression              Operator    Value
------------------------------------------------------
Hub1       Fields!Hub.Value        Like        Central
Hub1       Fields!ADP_Hrs.Value    NotEqual    0
Hub1       Fields!TL.Value         Equal       1

Body:
Chart is not within the Filter element, so it can't find it unless you walk backwards up the XML path, and then pull the @Name attribute of the Chart element:

SELECT
[Tbl].[Col].value('(../../@Name)[1]', 'varchar(50)') as ChartName,
[Tbl].[Col].value('Expression [1]', 'varchar(50)') as Expression,
[Tbl].[Col].value(' Operator [1]', 'varchar(50)') as 'Operator',
[Tbl].[Col].value(' Values [1]', 'varchar(50)') as 'Value'

FROM @input.nodes('Report/ReportSections/ReportSection/ReportItems/Chart/Filters/Filter') as [Tbl]([Col])

Which returns:

ChartName      Expression              Operator     Value
-------------- ----------------------- ------------ -------------
Hub1           Fields!Hub.Value        Like         Central
Hub1           Fields!ADP_Hrs.Value    NotEqual     0
Hub1           Fields!TL.Value         Equal        1