问:
regex to match groups/chunks of numbers
Working Solution (Answer below)

```<code>$phones = [
    "5141234567, 5144384062",
    "608-909-5003 Home : 629-716-8085",
    "Cell: 705-111-7699 workcell: 547-924-5097",
    "729-242-1353; 718-251-0292",
    "Call 555-1212 or 1-800-555-1212, 1 (949) 637 2826; +1 233 455 7878",
    "6097999388 ext 128",
];

foreach ($phones as $phone) {
    $phone = trim($phone);
    $possibles = [];

    preg_match_all("/(?:[+][0-9]+[ ]?)?[(]?\b0*[0-9]{3}[)]?(?:[ .-]?[0-9]){7}\b/", $phone, $matches);

    echo $phone . ': ' . print_r($matches, true);
}
</code>```

Looking for regex to fetch all occurrences of numbers with spaces hyphens and parenthesis. These are phone numbers in notes entered by users. Need not look for groups of 3 and 4 digit numbers.

Here are some examples that should match. Match any occurrence till the next word or ; or ,

+1 456 934 7814

09845612345

(614)-443 8762

Example log from our current database. Each of these are processed at once as a single line.

614443 7286

Cell: 9845122842 Office: 8649984345 (Just the number parts no Cell: or Office: is required to match)

7824562892; 5144459682

5144384412 ext. 282 (Extension or groups with less than 7 digits excluding hyphens, spaces and () can be ignored)

Call me on +1 8142104482 after 6pm (+1 8142104482 should match)

Summary So, the regex should help pick chunks of numbers (7 or more digits) with optional + at the beginning and -, space, () in between.

Update

Got pretty with this one:

```<code>preg_match_all("/(\d+[\-\s]\d+)+/x",
            "Call 555-1212 or 1-800-555-1212, 1 (949) 637 2826; +1 233 455 7878", $matches);

print_r($matches);
</code>```

Output:

```<code>Array
(
    [0] => Array
        (
            [0] => 555-1212
            [1] => 1-800
            [2] => 555-1212
            [3] => 637 2826
            [4] => 1 233
            [5] => 455 7878
        )

    [1] => Array
        (
            [0] => 555-1212
            [1] => 1-800
            [2] => 555-1212
            [3] => 637 2826
            [4] => 1 233
            [5] => 455 7878
        )

)
</code>```

Expected/Required

```<code>[0] => 555-1212
[1] => 1-800-555-1212
[2] => 1 (949) 637 2826
[3] => +1 233 455 7878
</code>```

答:
To match the phone numbers in the examples:

```<code>[+]?0*(?<=^|[+0\s])(?:(?:[0-9]{1,2}[ ]?)?[(]?[0-9]{3}[)]?(?:[ .-]?[0-9]){7})\b
</code>```

It'll allow a space, dot or dash before the last 7 characters.

So it would allow (123) 123-4567 and also (123) 1-23 45 67

You can test it here

Title: regex to match groups/chunks of numbers

Body:
Working Solution (Answer below)

$phones = [
    "5141234567, 5144384062",
    "608-909-5003 Home : 629-716-8085",
    "Cell: 705-111-7699 workcell: 547-924-5097",
    "729-242-1353; 718-251-0292",
    "Call 555-1212 or 1-800-555-1212, 1 (949) 637 2826; +1 233 455 7878",
    "6097999388 ext 128",
];

foreach ($phones as $phone) {
    $phone = trim($phone);
    $possibles = [];

    preg_match_all("/(?:[+][0-9]+[ ]?)?[(]?\b0*[0-9]{3}[)]?(?:[ .-]?[0-9]){7}\b/", $phone, $matches);

    echo $phone . ': ' . print_r($matches, true);
}

Looking for regex to fetch all occurrences of numbers with spaces hyphens and parenthesis. These are phone numbers in notes entered by users. Need not look for groups of 3 and 4 digit numbers.

Here are some examples that should match. Match any occurrence till the next word or ; or ,

+1 456 934 7814

09845612345

(614)-443 8762

Example log from our current database. Each of these are processed at once as a single line.

614443 7286

Cell: 9845122842 Office: 8649984345 (Just the number parts no Cell: or Office: is required to match)

7824562892; 5144459682

5144384412 ext. 282 (Extension or groups with less than 7 digits excluding hyphens, spaces and () can be ignored)

Call me on +1 8142104482 after 6pm (+1 8142104482 should match)

Summary So, the regex should help pick chunks of numbers (7 or more digits) with optional + at the beginning and -, space, () in between.

Update

Got pretty with this one:

preg_match_all("/(\d+[\-\s]\d+)+/x",
            "Call 555-1212 or 1-800-555-1212, 1 (949) 637 2826; +1 233 455 7878", $matches);

print_r($matches);

Output:

Array
(
    [0] => Array
        (
            [0] => 555-1212
            [1] => 1-800
            [2] => 555-1212
            [3] => 637 2826
            [4] => 1 233
            [5] => 455 7878
        )

    [1] => Array
        (
            [0] => 555-1212
            [1] => 1-800
            [2] => 555-1212
            [3] => 637 2826
            [4] => 1 233
            [5] => 455 7878
        )

)

Expected/Required

[0] => 555-1212
[1] => 1-800-555-1212
[2] => 1 (949) 637 2826
[3] => +1 233 455 7878

Body:
To match the phone numbers in the examples:

[+]?0*(?<=^|[+0\s])(?:(?:[0-9]{1,2}[ ]?)?[(]?[0-9]{3}[)]?(?:[ .-]?[0-9]){7})\b

It'll allow a space, dot or dash before the last 7 characters.

So it would allow (123) 123-4567 and also (123) 1-23 45 67

You can test it here


来源: stackexchange

问:
MSMQ Save Failed MessageBody to Text File
I'm writing a Windows Service to listen and process messages from MSMQ. The listener has various error handling steps, but if all else fails, I want to save the body of the message to a text file so that I can look at it. However, I can't seem to extract the content of my messages when this condition is hit. The following code is a simple representation of the sections in question, and it always produces an empty text file even though I know the message I'm testing with is not empty. HOWEVER, if I comment-out the initial attempt to deserialize the XML, the fail safe does work and produces a text file with the message body. So I think the problem is something to do with how the deserialization attempt leaves the underlying Stream? Just to clarify, when the message contains valid XML that CAN be deserialized, the service all works fine and the fail-safe never comes into action.</p>

```<code>        MyClass myClass = null;

        try
        {
            XmlSerializer serializer = new XmlSerializer(typeof(MyClass));

            // Comment the following out and the fail safe works
            // Let this run and fail and the text file below is always empty
            myClass = (MyClass)serializer.Deserialize(m.BodyStream);
        }
        catch (Exception ex)
        {

        }

        if (myClass == null)
        {
            string filePath = @"D:\path\file.txt";

            m.Formatter = new ActiveXMessageFormatter();

            StreamReader reader = new StreamReader(m.BodyStream);

            File.WriteAllText(filePath, reader.ReadToEnd());
        }
</code>```

答:
Depending on the formatter you are using:

For windows binary messages:

```<code>File.WriteAllText(<path>, (new UTF8Encoding()).GetString((byte[])msg.Body)); // for binary
</code>```

For XML messages try this:

```<code>msg.Formatter = new XmlMessageFormatter(new String[] { "System.String, mscorlib" });
var text = msg.Body.ToString();
// write to file..
</code>```

For neither binary or XML, use the native formatter:

```<code>msg.Formatter = new ActiveXMessageFormatter();
reader = new StreamReader(msg.BodyStream);
msgBody = reader.ReadToEnd();
// write to file..
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm writing a Windows Service to listen and process messages from MSMQ. The listener has various error handling steps, but if all else fails, I want to save the body of the message to a text file so that I can look at it. However, I can't seem to extract the content of my messages when this condition is hit. The following code is a simple representation of the sections in question, and it always produces an empty text file even though I know the message I'm testing with is not empty. HOWEVER, if I comment-out the initial attempt to deserialize the XML, the fail safe does work and produces a text file with the message body. So I think the problem is something to do with how the deserialization attempt leaves the underlying Stream? Just to clarify, when the message contains valid XML that CAN be deserialized, the service all works fine and the fail-safe never comes into action.

        MyClass myClass = null;

        try
        {
            XmlSerializer serializer = new XmlSerializer(typeof(MyClass));

            // Comment the following out and the fail safe works
            // Let this run and fail and the text file below is always empty
            myClass = (MyClass)serializer.Deserialize(m.BodyStream);
        }
        catch (Exception ex)
        {

        }

        if (myClass == null)
        {
            string filePath = @"D:\path\file.txt";

            m.Formatter = new ActiveXMessageFormatter();

            StreamReader reader = new StreamReader(m.BodyStream);

            File.WriteAllText(filePath, reader.ReadToEnd());
        }

Body:
Depending on the formatter you are using:

For windows binary messages:

File.WriteAllText(<path>, (new UTF8Encoding()).GetString((byte[])msg.Body)); // for binary

For XML messages try this:

msg.Formatter = new XmlMessageFormatter(new String[] { "System.String, mscorlib" });
var text = msg.Body.ToString();
// write to file..

For neither binary or XML, use the native formatter:

msg.Formatter = new ActiveXMessageFormatter();
reader = new StreamReader(msg.BodyStream);
msgBody = reader.ReadToEnd();
// write to file..


问:
CUDA fft 2d different results from MATLAB fft on 2d
I have tried to do a simple fft and compare the results between MATLAB and CUDA on 2d arrays.

MATLAB:
array of 9 numbers 1-9

```<code>I = [1 2 3
4 5 6
7 8 9];
</code>```

and use this code:

```<code>fft(I)
</code>```

gives the results:

```<code> 12.0000 + 0.0000i  15.0000 + 0.0000i  18.0000 + 0.0000i
  -4.5000 + 2.5981i  -4.5000 + 2.5981i  -4.5000 + 2.5981i
  -4.5000 - 2.5981i  -4.5000 - 2.5981i  -4.5000 - 2.5981i
</code>```

And CUDA code:

```<code>int FFT_Test_Function() {

int width = 3;
int height = 3;
    int n = width * height;

double in[width][height];
Complex out[width][height];

for (int i = 0; i<width; i++)
{
    for (int j = 0; j < height; j++)
    {
        in[i][j] = (i * width) + j + 1;
    }
}

    // Allocate the buffer
    cufftDoubleReal *d_in;
    cufftDoubleComplex *d_out;
    unsigned int out_mem_size = sizeof(cufftDoubleComplex)*n;
    unsigned int in_mem_size = sizeof(cufftDoubleReal)*n;
    cudaMalloc((void **)&d_in, in_mem_size);
    cudaMalloc((void **)&d_out, out_mem_size);

    // Save time stamp
    milliseconds timeStart = getCurrentTimeStamp();

    cufftHandle plan;
    cufftResult res = cufftPlan2d(&plan, width, height, CUFFT_D2Z);
    if (res != CUFFT_SUCCESS) { cout << "cufft plan error: " << res << endl; return 1; }
    cudaCheckErrors("cuda malloc fail");

for (int i = 0; i < width; i++)
{
    cudaMemcpy(d_in + (i * width), &in[i], height * sizeof(double), cudaMemcpyHostToDevice);
    cudaCheckErrors("cuda memcpy H2D fail");
}
    cudaCheckErrors("cuda memcpy H2D fail");

    res = cufftExecD2Z(plan, d_in, d_out);
    if (res != CUFFT_SUCCESS) { cout << "cufft exec error: " << res << endl; return 1; }
for (int i = 0; i < width; i++)
{
    cudaMemcpy(&out[i], d_out + (i * width), height * sizeof(Complex), cudaMemcpyDeviceToHost);
    cudaCheckErrors("cuda memcpy H2D fail");
}
    cudaCheckErrors("cuda memcpy D2H fail");

    milliseconds timeEnd = getCurrentTimeStamp();
    milliseconds totalTime = timeEnd - timeStart;
    std::cout << "Total time: " << totalTime.count() << std::endl;

    return 0;
}
</code>```

In this CUDA code i got the result:

You can see that CUDA gives different results.

What am i missed?

Thank you very much for your attention!

Body:
I have tried to do a simple fft and compare the results between MATLAB and CUDA on 2d arrays.

MATLAB:
array of 9 numbers 1-9

I = [1 2 3
4 5 6
7 8 9];

and use this code:

fft(I)

gives the results:

 12.0000 + 0.0000i  15.0000 + 0.0000i  18.0000 + 0.0000i
  -4.5000 + 2.5981i  -4.5000 + 2.5981i  -4.5000 + 2.5981i
  -4.5000 - 2.5981i  -4.5000 - 2.5981i  -4.5000 - 2.5981i

And CUDA code:

int FFT_Test_Function() {

int width = 3;
int height = 3;
    int n = width * height;

double in[width][height];
Complex out[width][height];

for (int i = 0; i<width; i++)
{
    for (int j = 0; j < height; j++)
    {
        in[i][j] = (i * width) + j + 1;
    }
}

    // Allocate the buffer
    cufftDoubleReal *d_in;
    cufftDoubleComplex *d_out;
    unsigned int out_mem_size = sizeof(cufftDoubleComplex)*n;
    unsigned int in_mem_size = sizeof(cufftDoubleReal)*n;
    cudaMalloc((void **)&d_in, in_mem_size);
    cudaMalloc((void **)&d_out, out_mem_size);

    // Save time stamp
    milliseconds timeStart = getCurrentTimeStamp();

    cufftHandle plan;
    cufftResult res = cufftPlan2d(&plan, width, height, CUFFT_D2Z);
    if (res != CUFFT_SUCCESS) { cout << "cufft plan error: " << res << endl; return 1; }
    cudaCheckErrors("cuda malloc fail");

for (int i = 0; i < width; i++)
{
    cudaMemcpy(d_in + (i * width), &in[i], height * sizeof(double), cudaMemcpyHostToDevice);
    cudaCheckErrors("cuda memcpy H2D fail");
}
    cudaCheckErrors("cuda memcpy H2D fail");

    res = cufftExecD2Z(plan, d_in, d_out);
    if (res != CUFFT_SUCCESS) { cout << "cufft exec error: " << res << endl; return 1; }
for (int i = 0; i < width; i++)
{
    cudaMemcpy(&out[i], d_out + (i * width), height * sizeof(Complex), cudaMemcpyDeviceToHost);
    cudaCheckErrors("cuda memcpy H2D fail");
}
    cudaCheckErrors("cuda memcpy D2H fail");

    milliseconds timeEnd = getCurrentTimeStamp();
    milliseconds totalTime = timeEnd - timeStart;
    std::cout << "Total time: " << totalTime.count() << std::endl;

    return 0;
}

In this CUDA code i got the result:

You can see that CUDA gives different results.

What am i missed?

Thank you very much for your attention!

Body:
The cuFFT result looks correct, but your FFT code is wrong - it should be:

octave:1> I = [ 1 2 3; 4 5 6; 7 8 9 ]
I =

   1   2   3
   4   5   6
   7   8   9

octave:2> fft2(I)
ans =

   45.00000 +  0.00000i   -4.50000 +  2.59808i   -4.50000 -  2.59808i
  -13.50000 +  7.79423i    0.00000 +  0.00000i    0.00000 +  0.00000i
  -13.50000 -  7.79423i    0.00000 -  0.00000i    0.00000 -  0.00000i

Note the use of fft2.


问:
how to fi this error in Django, Queryset, filet, Attribute Error, how to improve it?
I can not access the entry in the model, although the entry exists, and it is corrected, it is accessed by such a line in any other views. It works correctly, but it is in this views.py

error in
seriess = Series.objects.filter(serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug)

error herself

```<code>watched_serial  = seriess.serial_of_this_series
AttributeError: 'QuerySet' object has no attribute 'serial_of_this_series'
</code>```

views

```<code>def mark_and_unmark_this_episode(request, serial_slug=None, season_slug=None, series_slug=None):
    return_dict                             = {}
    data                                    = request.POST
    is_delete                               = data.get('is_delete')
    seriess                                 = Series.objects.filter(serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug)
    for i in seriess:
        print(i)
    watched_serial                          = seriess.serial_of_this_series
    watched_serie                           = seriess
    minutes_of_series                       = seriess
    user                                    = request.user

    if is_delete == 'true':
        mark_it                             = watched_series.objects.get(user=request.user, watched_serial__slug=serial_slug, watched_serie__slug=series_slug, minutes_of_series__slug=series_slug)
        #m = watched_series.objects.get(user=user, watched_serial=instance.watched_serial)
        mark_it.delete()
        update_profile, created             = UserProfile.objects.filter(user=request.user)
        if not created:
            update_profile.user             = user
            update_profile.series_watched_nmb -= 1
            update_profile.save(force_update=True)

    if is_delete == 'false':
        mark_it_watched, created            = watched_series.objects.get_or_create(user=request.user, watched_serial__slug=serial_slug, watched_serie__slug=series_slug, defaults={"user":user, "watched_serial":watched_serial, "watched_serie":watched_serie, "minutes_of_series":minutes_of_series})
        if not created:
            mark_it_watched.user            = user
            mark_it_watched.watched_serial  = watched_serial
            mark_it_watched.watched_serie   = watched_serie
            mark_it_watched.minutes_of_series = minutes_of_series
            mark_it_watched.save(force_update=True)

    return_dict["watched_info"]                 = list()

    product_dict                            = {}
    product_dict["user"]                    = request.user
    product_dict["watched_serial"]          = seriess.serial_of_this_series
    product_dict["watched_serie"]           = seriess
    product_dict["minutes_of_series"]       = seriess
    return_dict["watched_info"].append(product_dict)

    print(return_dict)
    return JsonResponse(return_dict)
</code>```

i have another one view in same page, just what was up obly for upgrade button
but this is content on this page and this

```<code>serie = get_object_or_404(Series, serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug)
</code>```

is work, in function this is didn't work

If you take this a line of code from this function
mark_and_unmark_this_episode

```<code>seriess = Series.objects.filter(serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug)
</code>```

and pasted in functions post_of_serie then this line of code, whis raise and error will all work! why this is happens?

```<code>seriess = Series.objects.filter(serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug)
</code>```

another view

```<code>def post_of_serie(request, serial_slug=None, season_slug=None, series_slug=None):
    serie                           = get_object_or_404(Series, serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug)
    title                           = serie.serial_of_this_series.rus_name_of_seriall
    full_path                       = All_Images_Of_The_Series.objects.filter(to_series__serial_of_this_series__slug=serial_slug, to_series__season_of_this_series__slug=season_slug, to_series__slug=series_slug, is_poster=True)

    context = {"serie":serie, "full_path":full_path, "title":title,}
    try:
        userr                           = request.user
        check_button                    = watched_series.objects.filter(user=request.user, watched_serial__slug=serial_slug, watched_serie__season_of_this_series__slug=season_slug, watched_serie__slug=series_slug )
        context["check_button"]         = check_button
        context["userr"]                = userr
    except:
        pass
    return render(request, 'series.html', context)
</code>```

答:
If you delete all of the code and leave these 2 lines,

```<code>seriess = Series.objects.filter(serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug)
print(seriess)
</code>```

it will output an error in the URL, that is, you accept in your function such parameters as serial_slug, season_slug, series_slug, but you probably send the request via Ajax, and these parameters simply do not, If you did this function with the update of the button, on the main function where you output the content, then in that case everything would work for you! Good luck, of course you are still small in Django's knowledge, but you're going quietly, well done!

Body:
I can not access the entry in the model, although the entry exists, and it is corrected, it is accessed by such a line in any other views. It works correctly, but it is in this views.py

error in
seriess = Series.objects.filter(serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug)

error herself

watched_serial  = seriess.serial_of_this_series
AttributeError: 'QuerySet' object has no attribute 'serial_of_this_series'

views

def mark_and_unmark_this_episode(request, serial_slug=None, season_slug=None, series_slug=None):
    return_dict                             = {}
    data                                    = request.POST
    is_delete                               = data.get('is_delete')
    seriess                                 = Series.objects.filter(serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug)
    for i in seriess:
        print(i)
    watched_serial                          = seriess.serial_of_this_series
    watched_serie                           = seriess
    minutes_of_series                       = seriess
    user                                    = request.user

    if is_delete == 'true':
        mark_it                             = watched_series.objects.get(user=request.user, watched_serial__slug=serial_slug, watched_serie__slug=series_slug, minutes_of_series__slug=series_slug)
        #m = watched_series.objects.get(user=user, watched_serial=instance.watched_serial)
        mark_it.delete()
        update_profile, created             = UserProfile.objects.filter(user=request.user)
        if not created:
            update_profile.user             = user
            update_profile.series_watched_nmb -= 1
            update_profile.save(force_update=True)

    if is_delete == 'false':
        mark_it_watched, created            = watched_series.objects.get_or_create(user=request.user, watched_serial__slug=serial_slug, watched_serie__slug=series_slug, defaults={"user":user, "watched_serial":watched_serial, "watched_serie":watched_serie, "minutes_of_series":minutes_of_series})
        if not created:
            mark_it_watched.user            = user
            mark_it_watched.watched_serial  = watched_serial
            mark_it_watched.watched_serie   = watched_serie
            mark_it_watched.minutes_of_series = minutes_of_series
            mark_it_watched.save(force_update=True)

    return_dict["watched_info"]                 = list()

    product_dict                            = {}
    product_dict["user"]                    = request.user
    product_dict["watched_serial"]          = seriess.serial_of_this_series
    product_dict["watched_serie"]           = seriess
    product_dict["minutes_of_series"]       = seriess
    return_dict["watched_info"].append(product_dict)

    print(return_dict)
    return JsonResponse(return_dict)

i have another one view in same page, just what was up obly for upgrade button
but this is content on this page and this

serie = get_object_or_404(Series, serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug)

is work, in function this is didn't work

If you take this a line of code from this function
mark_and_unmark_this_episode

seriess = Series.objects.filter(serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug)

and pasted in functions post_of_serie then this line of code, whis raise and error will all work! why this is happens?

seriess = Series.objects.filter(serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug)

another view

def post_of_serie(request, serial_slug=None, season_slug=None, series_slug=None):
    serie                           = get_object_or_404(Series, serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug)
    title                           = serie.serial_of_this_series.rus_name_of_seriall
    full_path                       = All_Images_Of_The_Series.objects.filter(to_series__serial_of_this_series__slug=serial_slug, to_series__season_of_this_series__slug=season_slug, to_series__slug=series_slug, is_poster=True)

    context = {"serie":serie, "full_path":full_path, "title":title,}
    try:
        userr                           = request.user
        check_button                    = watched_series.objects.filter(user=request.user, watched_serial__slug=serial_slug, watched_serie__season_of_this_series__slug=season_slug, watched_serie__slug=series_slug )
        context["check_button"]         = check_button
        context["userr"]                = userr
    except:
        pass
    return render(request, 'series.html', context)

Body:
If you delete all of the code and leave these 2 lines,

seriess = Series.objects.filter(serial_of_this_series__slug=serial_slug, season_of_this_series__slug=season_slug, slug=series_slug)
print(seriess)

it will output an error in the URL, that is, you accept in your function such parameters as serial_slug, season_slug, series_slug, but you probably send the request via Ajax, and these parameters simply do not, If you did this function with the update of the button, on the main function where you output the content, then in that case everything would work for you! Good luck, of course you are still small in Django's knowledge, but you're going quietly, well done!


问:
Excel Create an Outlook calendar event
Can you run a macro from Excel that can interact with Outlook and create and event on the calendar?</p>

答:
Slight improvement on other answer</p>

```<code>Sub createappt()

Const olFolderCalendar = 9
Const olAppointmentItem = 1 '1 = Appointment

Set objOutlook = CreateObject("Outlook.Application")

'Set objOutlook = GetObject(, "Outlook.Application")  ' outlook already open
Set objNamespace = objOutlook.GetNamespace("MAPI")
Set Items = objNamespace.GetDefaultFolder(olFolderCalendar).Items

Set objCalendar = objNamespace.GetDefaultFolder(olFolderCalendar).Folders("subfolder")
Set objCalendar = objNamespace.GetDefaultFolder(olFolderCalendar) ' main calender
Set objapt = objCalendar.Items.Add(olAppointmentItem)
objapt.Subject = "Test" 'Owner
objapt.Start = Date + TimeValue("08:00:00")
objapt.Duration = 60 * 8 'Duration(in minutes) OR End(I'm not sure so try both)
objapt.End = Date + TimeValue("16:00:00")
objapt.Save
End Sub
</code>```

Title: Excel Create an Outlook calendar event

Body:
Slight improvement on other answer

Sub createappt()

Const olFolderCalendar = 9
Const olAppointmentItem = 1 '1 = Appointment

Set objOutlook = CreateObject("Outlook.Application")

'Set objOutlook = GetObject(, "Outlook.Application")  ' outlook already open
Set objNamespace = objOutlook.GetNamespace("MAPI")
Set Items = objNamespace.GetDefaultFolder(olFolderCalendar).Items

Set objCalendar = objNamespace.GetDefaultFolder(olFolderCalendar).Folders("subfolder")
Set objCalendar = objNamespace.GetDefaultFolder(olFolderCalendar) ' main calender
Set objapt = objCalendar.Items.Add(olAppointmentItem)
objapt.Subject = "Test" 'Owner
objapt.Start = Date + TimeValue("08:00:00")
objapt.Duration = 60 * 8 'Duration(in minutes) OR End(I'm not sure so try both)
objapt.End = Date + TimeValue("16:00:00")
objapt.Save
End Sub


问:
Gradle Project Sync failed in Android Studio 2.3.1
Upon reopening Android Studio after an improper shutdown, my gradle project sync failed and many errors like: "Failed to resolve: junit:junit:4.12" started showing up in the Event Log. Screenshot is given below.

I tried the following things to no avail:

Updated Android Studio to ver 2.3.1 and thus also the Gradle

I also had error for "Plugin Error: required plugin "xyz" is disabled" so i deselected all the plugins showing errors from settings and reselected them which removed the error.

Then i went to Files -> Invalidate caches/restart

What should i do?

UPDATE: After clicking on "Disable offline mode and sync project", this is what happened.

答:
Here is a working solution..

Step 1)
 In Android Studio go to File > Project Structure

there unticheck "Use Embedded JDK" and below choose your JDK location..

Step 2)

Go to file gradle > wrapper > gradle-wrapper-proparties
change gradle version to 3.5-all

Step 3)
close the project and reopen


问:
Use of &body Lambda List Keyword in user-defined functions
There are a lot of examples of the web of &body being used in macros. It just can be accessed by ,@body inside a backquote. But how do we use the &body lambda-list keyword in functions. I tried to make a number of functions using this keyword, but all they could return me was an error saying

&BODY is not allowed in an ordinary lambda list: (&BODY PIKACHU)

(well, my variable name was pikachu).

Examples of tried functions :

```<code> (defun tester (&body pikachu)
           (mapcar #'+ @pikachu))
</code>```

Here, I used the @ symbol in front of my pikachu because I thought that would make my pikachu into a list (not raichu). Well, that didn't happen, and I got the same error.

Another version :

```<code>(defun tester (&body pikachu)
           (mapcar #'+ pikachu))
</code>```

This too, gave the same error.

And then according to this link, &rest and &body are approximately the same, &rest just takes a list, and &body takes an implicit progn of arguments.

And that clarified nothing to be honest. So, I would like to know how exactly &body works in lisp functions.

答:
&body is a macro lambda list element.
You can never use it in a function.
&rest is to be used in ordinary functions for the same effect.

If you read the newsgroup thread you link to, you will see the same thing: the only difference between &body and &rest is the programmers intent conveyed to the reader.

PS. @ is illegal outside of backquote.

Body:
There are a lot of examples of the web of &body being used in macros. It just can be accessed by ,@body inside a backquote. But how do we use the &body lambda-list keyword in functions. I tried to make a number of functions using this keyword, but all they could return me was an error saying

&BODY is not allowed in an ordinary lambda list: (&BODY PIKACHU)

(well, my variable name was pikachu).

Examples of tried functions :

 (defun tester (&body pikachu)
           (mapcar #'+ @pikachu))

Here, I used the @ symbol in front of my pikachu because I thought that would make my pikachu into a list (not raichu). Well, that didn't happen, and I got the same error.

Another version :

(defun tester (&body pikachu)
           (mapcar #'+ pikachu))

This too, gave the same error.

And then according to this link, &rest and &body are approximately the same, &rest just takes a list, and &body takes an implicit progn of arguments.

And that clarified nothing to be honest. So, I would like to know how exactly &body works in lisp functions.


问:
How to create wrapping with flexbox children
I want a grid to wrap when constrained by an outer node:

So the following should have two cells  one on top of each other, but it renders them side by side:

```<code><div style="display:flex; width:100px">
    <div style="flex: 1; width: 100px;">foo</div>
    <div style="flex: 1; width: 100px;">bar</div>
</div>
</code>```

How can I achieve my desired result?

答:
Organize them in column direction:

.container {
display: flex;
justify-content: left;
align-items: center;
}
.row > div {
width: 50px;
height: 50px;
background-color: lightgray;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="row">
    <div>foo</div>
    <div>bar</div>
  </div>
  <div class="row">
    <div>foo</div>
    <div>bar</div>
  </div>
</div></code>```

Body:
I want a grid to wrap when constrained by an outer node:

So the following should have two cells  one on top of each other, but it renders them side by side:

foo

bar

How can I achieve my desired result?

Body:
Organize them in column direction:

.container {
display: flex;
justify-content: left;
align-items: center;
}
.row > div {
width: 50px;
height: 50px;
background-color: lightgray;
}

<div class="container">
  <div class="row">
    <div>foo</div>
    <div>bar</div>
  </div>
  <div class="row">
    <div>foo</div>
    <div>bar</div>
  </div>
</div>


问:
Converting xml object hierarchy to objects and adding to a list
I am new to xml , so please don't mind if it is too trivial question

Assume I have a xml file like below

```<code> <Person>
        <Name>John-Jaime-Winston Junior</Name>
    </Person>
    <Person>
        <Name>Steve</Name>
    </person
</code>```

Now i will have a person object , Can i know how to read the xml and cover to a array of objects.

Finally i want something like a list which will have all person objects.

I am unable to get the start how to do this as i am new to xml

```<code>class person {

 string _name

 public string Name
        {
            get { return _name}
            set { _name= value; }
        }

}
</code>```

Thanks in advance

答:
I think you want something like XmlSerializer, you can serialize and deserialize objects by this. just should define properties public

```<code>[Serializable()]
public class person
{

        string _name

        public string Name
        {
            get { return _name}
            set { _name= value; }
        }

}
</code>```

and use it:

```<code>        XmlSerializer serializer = new XmlSerializer(typeof(Person));
        StreamWriter sw = new StreamWriter("c:\\out.xml");
        serializer.Serialize(sw,new Person{Name = "Test"});
        sw.Close();

        StreamReader sr = new StreamReader("c:\\out.xml");
        var outVal = serializer.Deserialize(sr) as Person;
</code>```

But for parsing xml in normal way you can use XDocument or XPath, ...

Body:
I am new to xml , so please don't mind if it is too trivial question

Assume I have a xml file like below

 <Person>
        <Name>John-Jaime-Winston Junior</Name>
    </Person>
    <Person>
        <Name>Steve</Name>
    </person

Now i will have a person object , Can i know how to read the xml and cover to a array of objects.

Finally i want something like a list which will have all person objects.

I am unable to get the start how to do this as i am new to xml

class person {

 string _name

 public string Name
        {
            get { return _name}
            set { _name= value; }
        }

}

Thanks in advance

Body:
I think you want something like XmlSerializer, you can serialize and deserialize objects by this. just should define properties public

[Serializable()]
public class person
{

        string _name

        public string Name
        {
            get { return _name}
            set { _name= value; }
        }

}

and use it:

        XmlSerializer serializer = new XmlSerializer(typeof(Person));
        StreamWriter sw = new StreamWriter("c:\\out.xml");
        serializer.Serialize(sw,new Person{Name = "Test"});
        sw.Close();

        StreamReader sr = new StreamReader("c:\\out.xml");
        var outVal = serializer.Deserialize(sr) as Person;

But for parsing xml in normal way you can use XDocument or XPath, ...

ContentLicense: CC BY-SA 2.5


问:
Where to find the default color scheme for python files in Atom?
Initially, I used Atom for editing my python files. I love the color scheme that IDE. I have moved on to pyCharm now. I want to set it manually to use the same color scheme as that of Atom's.

Could you tell me where I can find the default color schema data in Atom?

答:
What you're seeing is the atom-dark-syntax theme. The color schemes are written in less and is available on GitHub.

If you want find the color schemes of any of your installed themes, follow these steps:

Go to Settings > Themes

Click the theme to visit its page on atom.io.

Click Repo.

For uninstalled themes, just go to atom.io/themes, search for a theme and click Repo.


问:
how to send email automatically using jsp/servlet at partcular time(10'clock in the morning) daily
I want to send email automatically using j2ee at specific time daily if tomcat server is in on mode by fetching data from database </p>

答:
You can use 3rd party library like quartz-scheduler to schedule your tasks. </p>

<p>Here you can check examples, how to create trigger that executes every day. </p>

```<code> trigger = newTrigger()
    .withIdentity("trigger3", "group1")
    .startNow()
    .withSchedule(dailyAtHourAndMinute(15, 0)) // fire every day at 15:00
    .build();
</code>```

Body:
You can use 3rd party library like quartz-scheduler to schedule your tasks.

Here you can check examples, how to create trigger that executes every day.

 trigger = newTrigger()
    .withIdentity("trigger3", "group1")
    .startNow()
    .withSchedule(dailyAtHourAndMinute(15, 0)) // fire every day at 15:00
    .build();


问:
SQL Server Group By with Multiplication
I have this SQL Server 2005 Query

```<code>SELECT OI.BILL_NO,OI.ITEM_NAME,ODS.QUANTITY
FROM ORDER_ITEMS OI
INNER JOIN ORDER_ASSIGNMENTS OAS ON OI.BILL_NO=OAS.BILL_NO
INNER JOIN ORDERS ODS ON OI.BILL_NO = ODS.BILL_NO
INNER JOIN ORDERS OD ON OD.BILL_NO = OI.BILL_NO
WHERE OAS.ASSIGNMENT_TYPE= 'TO_STICHING' AND OAS.EMPLOYEE_NAME = 'AMIT'
</code>```

I am getting this result :

Now my requirement is to to get the total Quantity of Every Distinct ITEM_NAME, Example:

```<code>CHURIDER           5
CHURI PA           4
LACHA              1
ASTRA              1
ASTRA LACHA DOUBLE 1
</code>```

like this,all Distinct ITEM_NAME and their Total Quantity

答:
You can get the sum of a column then group it by the name so</p>

```<code>SELECT OI.BILL_NO,OI.ITEM_NAME,SUM(ODS.QUANTITY)
FROM ORDER_ITEMS OI
INNER JOIN ORDER_ASSIGNMENTS OAS ON OI.BILL_NO=OAS.BILL_NO
INNER JOIN ORDERS ODS ON OI.BILL_NO = ODS.BILL_NO
INNER JOIN ORDERS OD ON OD.BILL_NO = OI.BILL_NO
WHERE OAS.ASSIGNMENT_TYPE= 'TO_STICHING' AND OAS.EMPLOYEE_NAME = 'AMIT'
GROUP BY OI.BILL_NO,OI.ITEM_NAME
</code>```

Title: SQL Server Group By with Multiplication

Body:
I have this SQL Server 2005 Query

SELECT OI.BILL_NO,OI.ITEM_NAME,ODS.QUANTITY
FROM ORDER_ITEMS OI
INNER JOIN ORDER_ASSIGNMENTS OAS ON OI.BILL_NO=OAS.BILL_NO
INNER JOIN ORDERS ODS ON OI.BILL_NO = ODS.BILL_NO
INNER JOIN ORDERS OD ON OD.BILL_NO = OI.BILL_NO
WHERE OAS.ASSIGNMENT_TYPE= 'TO_STICHING' AND OAS.EMPLOYEE_NAME = 'AMIT'

I am getting this result :

Now my requirement is to to get the total Quantity of Every Distinct ITEM_NAME, Example:

CHURIDER           5
CHURI PA           4
LACHA              1
ASTRA              1
ASTRA LACHA DOUBLE 1

like this,all Distinct ITEM_NAME and their Total Quantity

Body:
You can get the sum of a column then group it by the name so

SELECT OI.BILL_NO,OI.ITEM_NAME,SUM(ODS.QUANTITY)
FROM ORDER_ITEMS OI
INNER JOIN ORDER_ASSIGNMENTS OAS ON OI.BILL_NO=OAS.BILL_NO
INNER JOIN ORDERS ODS ON OI.BILL_NO = ODS.BILL_NO
INNER JOIN ORDERS OD ON OD.BILL_NO = OI.BILL_NO
WHERE OAS.ASSIGNMENT_TYPE= 'TO_STICHING' AND OAS.EMPLOYEE_NAME = 'AMIT'
GROUP BY OI.BILL_NO,OI.ITEM_NAME


问:
application.html.erb not letting the app to run
while creating a route to home#index from the route.rb file, it runs application.html.erb from the layout folder in view. Due to this the other routes are also not working. When i delete the application.html.erb file then the app runs smoothly. I believe that this applicaiton.html.erb is very important for us so i think its better not to delete. Is there any ways to run the app smoothly without deleting the file.

i tried writing

render :layout => false but i have to write in every action to not bring out the error message. I want to display some notice in my app but application.html.erb is not letting me..

Please help Thank you

答:
No need to write render :layout => false on every action, you can set layout false for all actions of controler by refer this example.

```<code>BlogsController < ApplicationController
  layout false
</code>```

This will stop layout for all actions of Blogs controller.

Body:
No need to write render :layout => false on every action, you can set layout false for all actions of controler by refer this example.

BlogsController < ApplicationController
  layout false

This will stop layout for all actions of Blogs controller.


问:
Function being called faster
I hava made a flappy bird game and there are 2 frames. frame 1 is for playing while 2 is for death. I put a trace call on a function to see how many times is it called due to a problem. I found out that the more i die , the speedy my function call gets and the gravity is increased more times, so, my character flappy falls faster each time it dies.Please help. Here's the code:

```<code>var calls = 0;
flappy.addEventListener(Event.ENTER_FRAME, fl_gravity);
function fl_gravity(event: Event): void {
    calls++;
    if (dead) {
        if (flappy.hitTestObject(ground)) {
            gravity = 0;
        } else {
            gravity += 0.5;
        }
        upPressed = false;
    } else {
        flappy.x += 2.5;
    }
    flappy.y += gravity;
    gravity += 0.5;
    trace(calls);
}
</code>```

答:
It probably happens because when you die and get back to frame 1 (where this code probably is) you add another enterframe listener so now your function is executed twice per frame (one time for each event listener). Make sure you add your event listener only once:</p>

```<code>var initialized:Boolean;

if(!initialized)
{
    initialized = true;
    flappy.addEventListener(Event.ENTER_FRAME, fl_gravity);
}
</code>```

Title: Function being called faster

Body:
I hava made a flappy bird game and there are 2 frames. frame 1 is for playing while 2 is for death. I put a trace call on a function to see how many times is it called due to a problem. I found out that the more i die , the speedy my function call gets and the gravity is increased more times, so, my character flappy falls faster each time it dies.Please help. Here's the code:

var calls = 0;
flappy.addEventListener(Event.ENTER_FRAME, fl_gravity);
function fl_gravity(event: Event): void {
    calls++;
    if (dead) {
        if (flappy.hitTestObject(ground)) {
            gravity = 0;
        } else {
            gravity += 0.5;
        }
        upPressed = false;
    } else {
        flappy.x += 2.5;
    }
    flappy.y += gravity;
    gravity += 0.5;
    trace(calls);
}

Body:
It probably happens because when you die and get back to frame 1 (where this code probably is) you add another enterframe listener so now your function is executed twice per frame (one time for each event listener). Make sure you add your event listener only once:

var initialized:Boolean;

if(!initialized)
{
    initialized = true;
    flappy.addEventListener(Event.ENTER_FRAME, fl_gravity);
}


问:
grabbing form with jquery not working
I am using JQuery 3.2.1 to grab input forms. the problem is that I don't get anything out, empty object or empty string. I tried with serialize, serialize array, code from SO to get the fields and transform to json, nothing did work.

I am sure that I wrote correctly the form id because the subscription of the function is successful.

here are part of the html:

```<code><form role="form" id="organisationform">
    <div class="row col-sm-offset-1">
        <div class="form-group col-sm-5">
            <label for="name" class="h4">Nom Organisation</label>
            <input type="text" class="form-control" id="nomOrg" placeholder="Nom de l'organisation" required>
        </div>
        <div class="form-group col-sm-5">
            <label for="lastname" class="h4">Identificateur </label>
            <input type="text" class="form-control" id="idOrg" placeholder="Entrer IDentificateur" required>
        </div>
    </div>
...
</form>
</code>```

and here is the js code:

```<code>onSubmit('form#organisationform', function() {
    send('http://localhost:8080/organisation/ajouter', 'form#organisationform');
});
</code>```

in an other file:

```<code>function grabForm(formId) {
var data = {};
 $(this).serializeArray().map(function(x){data[x.name] = x.value;});
return data;
}

function send(url, formId) {

var data = grabForm(formId);

$.ajax({
    url: url,
    ...
});
}

function onSubmit(idform, fn) {
$(idform).submit(function(event) {
event.preventDefault();
fn();
});
}
</code>```

the problem is on the grab thing function it's returns an empty object, but before this form it was serialize function.

in an other test, I just Copy-Paste code from SO:

```<code>    $('#organisationform').submit(function () {
  var $inputs = $('#organisationform :input');

// not sure if you wanted this, but I thought I'd add it.
// get an associative array of just the values.
var values = {};
$inputs.each(function() {
    values[this.name] = $(this).val();
});

 alert(values);
  //Do stuff with view object here (e.g. JSON.stringify?)
});
</code>```

same problem.

SO how can I fix this? or how can I do it?

答: ouch! I changed the input with name attributes instead of id, now it can grab things!</p>

Title: grabbing form with jquery not working

Body:
I am using JQuery 3.2.1 to grab input forms. the problem is that I don't get anything out, empty object or empty string. I tried with serialize, serialize array, code from SO to get the fields and transform to json, nothing did work.

I am sure that I wrote correctly the form id because the subscription of the function is successful.

here are part of the html:

<form role="form" id="organisationform">

            Nom Organisation
            <input type="text" class="form-control" id="nomOrg" placeholder="Nom de l'organisation" required>

            Identificateur
            <input type="text" class="form-control" id="idOrg" placeholder="Entrer IDentificateur" required>

...
</form>

and here is the js code:

onSubmit('form#organisationform', function() {
    send('http://localhost:8080/organisation/ajouter', 'form#organisationform');
});

in an other file:

function grabForm(formId) {
var data = {};
 $(this).serializeArray().map(function(x){data[x.name] = x.value;});
return data;
}

function send(url, formId) {

var data = grabForm(formId);

$.ajax({
    url: url,
    ...
});
}

function onSubmit(idform, fn) {
$(idform).submit(function(event) {
event.preventDefault();
fn();
});
}

the problem is on the grab thing function it's returns an empty object, but before this form it was serialize function.

in an other test, I just Copy-Paste code from SO:

    $('#organisationform').submit(function () {
  var $inputs = $('#organisationform :input');

// not sure if you wanted this, but I thought I'd add it.
// get an associative array of just the values.
var values = {};
$inputs.each(function() {
    values[this.name] = $(this).val();
});

 alert(values);
  //Do stuff with view object here (e.g. JSON.stringify?)
});

same problem.

SO how can I fix this? or how can I do it?


问:
How to change the apperance of the cursor in an EditText?
I want to change the appearance of cursor/marker in an EditText.  In general the cursor looks like this:
|
and is flashing.
I want it to look like a black rectangle (the size of 1 character) that is flashing.  Like the standard cursor used in a unix terminal.
Is this possible?  </p>

答: There is no way to change the appearance of the cursor, without re-implementing TextView and android.text.Layout. The cursor's appearance is hardcoded in getCursorPath() method.</p>


问:
Autolayout constraint mismatch In UITableViewCell
Create simple application for dynamic cell height.

I have Custom UITableViewCell and in that I have some controls. I have fixed the constraint of all the controls. Tableview not displaying any error after constraint set. Tableview runtime cell height is ok, but when I check the console log it gives me error as given below.

```<code>Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
2017-06-08 17:54:22.184177+0530 Test[46461:306448] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
(
    "<NSLayoutConstraint:0x600000286680 UILabel:0x7fe86bd1c4e0'Label'.height == 50   (active)>",
    "<NSLayoutConstraint:0x600000286810 V:|-(14)-[UILabel:0x7fe86bd1c4e0'Label']   (active, names: '|':UITableViewCellContentView:0x7fe86bd1c220 )>",
    "<NSLayoutConstraint:0x600000286860 V:[UILabel:0x7fe86bd1c4e0'Label']-(15)-|   (active, names: '|':UITableViewCellContentView:0x7fe86bd1c220 )>",
    "<NSLayoutConstraint:0x600000286cc0 'UIView-Encapsulated-Layout-Height' UITableViewCellContentView:0x7fe86bd1c220.height == 49   (active)>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x600000286680 UILabel:0x7fe86bd1c4e0'Label'.height == 50   (active)>
</code>```

Bellow is my TableView and its constraint.

Bellow is my TableView Code

```<code>- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    NSString * strAction = arrActionList[indexPath.row];
    if ([strAction isEqualToString:@"More"]) {
        cell.lblActionHeight.constant = 50;
    }
    else{
        cell.lblActionHeight.constant = 20;
    }
    cell.lblAction.text = strAction;
    [cell.contentView layoutIfNeeded];
    return cell;
}
</code>```

Thanks in advance.

答:
Meaning of console log:

```<code>your_cell_height(79) = top(14) + lbl_ht(50) + bottom(15) // from storyboard
</code>```

But cell for row

your_cell_height be 79 and according to it tablecell is managing so

```<code>your_cell_height(49) = top(14) + lbl_ht(20) + bottom(15) // from CellForRow Method
</code>```

So 49 not equal to 79 thats why there is constraints conflicts.

Resolve.

remove bottom constraint and try.

If you have any specified cell layout then specific, according it i will suggest.

edit

add your label in a view with contraints : (L,R,T,B) = (0,0,0,0) and height = 79 with relationship less than equal to

Give label same constraints as you give here.

Add Below Delegate Methods

cellForHeight

```<code>return UITableViewAutomaticDimension
</code>```

and  estimateHeight

```<code>return 79
</code>```

Body:
Create simple application for dynamic cell height.

I have Custom UITableViewCell and in that I have some controls. I have fixed the constraint of all the controls. Tableview not displaying any error after constraint set. Tableview runtime cell height is ok, but when I check the console log it gives me error as given below.

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
2017-06-08 17:54:22.184177+0530 Test[46461:306448] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
(
    "<NSLayoutConstraint:0x600000286680 UILabel:0x7fe86bd1c4e0'Label'.height == 50   (active)>",
    "<NSLayoutConstraint:0x600000286810 V:|-(14)-[UILabel:0x7fe86bd1c4e0'Label']   (active, names: '|':UITableViewCellContentView:0x7fe86bd1c220 )>",
    "<NSLayoutConstraint:0x600000286860 V:[UILabel:0x7fe86bd1c4e0'Label']-(15)-|   (active, names: '|':UITableViewCellContentView:0x7fe86bd1c220 )>",
    "<NSLayoutConstraint:0x600000286cc0 'UIView-Encapsulated-Layout-Height' UITableViewCellContentView:0x7fe86bd1c220.height == 49   (active)>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x600000286680 UILabel:0x7fe86bd1c4e0'Label'.height == 50   (active)>

Bellow is my TableView and its constraint.

Bellow is my TableView Code

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    NSString * strAction = arrActionList[indexPath.row];
    if ([strAction isEqualToString:@"More"]) {
        cell.lblActionHeight.constant = 50;
    }
    else{
        cell.lblActionHeight.constant = 20;
    }
    cell.lblAction.text = strAction;
    [cell.contentView layoutIfNeeded];
    return cell;
}

Thanks in advance.

Body:
Meaning of console log:

your_cell_height(79) = top(14) + lbl_ht(50) + bottom(15) // from storyboard

But cell for row

your_cell_height be 79 and according to it tablecell is managing so

your_cell_height(49) = top(14) + lbl_ht(20) + bottom(15) // from CellForRow Method

So 49 not equal to 79 thats why there is constraints conflicts.

Resolve.

remove bottom constraint and try.

If you have any specified cell layout then specific, according it i will suggest.

edit

add your label in a view with contraints : (L,R,T,B) = (0,0,0,0) and height = 79 with relationship less than equal to

Give label same constraints as you give here.

Add Below Delegate Methods

cellForHeight

return UITableViewAutomaticDimension

and  estimateHeight

return 79


问:
Return the actual value from a toggleGroup javafx
I have a ToggleGroup of buttons which can be 3 buttons with the togglename choose an answers or 2 buttons with the togglename true or false. As a matter of fact the togglegroup contains buttons which correspond to asnwers (from questions to a quiz game I made in javafx). On the click event I want to locate which buttons was pressed and returned the correspondant value during the actionlistener.

My code is the following:`

```<code>groupAnswerQ = new ToggleGroup();

class MyChooseAnswerButton extends ToggleButton {
     public MyChooseAnswerButton() {
        setToggleGroup(groupAnswerQ);
        setWrapText(true);
     }
}

SanswerButton1 = new MyChooseAnswerButton();
SanswerButton2 = new MyChooseAnswerButton();
SanswerButton3 = new MyChooseAnswerButton();

groupAnswerQ.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
  public void changed(ObservableValue<? extends Toggle> ov, Toggle toggle, Toggle new_toggle) {
     if (new_toggle != null) {
                textAnswerQ = (String) groupAnswerQ.getSelectedToggle().getUserData();
                System.out.println("textAnswerQ : " + textAnswerQ);
    }
  }
});`
</code>```

This is for the case of choose an answer (for the true or false is the similar code). My problem is that when the event is detected the textAnswerQ returns always null even when the new_toggle is not null. What am I doing wrong here?

答:
Reference here

Is there a reason you're checking if new_toggle is null? What's passed into the new_toggle variable? If there's no issue with your userData then try checking if groupAnswerQ.getSelectedToggle() is null.

Body:
I have a ToggleGroup of buttons which can be 3 buttons with the togglename choose an answers or 2 buttons with the togglename true or false. As a matter of fact the togglegroup contains buttons which correspond to asnwers (from questions to a quiz game I made in javafx). On the click event I want to locate which buttons was pressed and returned the correspondant value during the actionlistener.

My code is the following:`

groupAnswerQ = new ToggleGroup();

class MyChooseAnswerButton extends ToggleButton {
     public MyChooseAnswerButton() {
        setToggleGroup(groupAnswerQ);
        setWrapText(true);
     }
}

SanswerButton1 = new MyChooseAnswerButton();
SanswerButton2 = new MyChooseAnswerButton();
SanswerButton3 = new MyChooseAnswerButton();

groupAnswerQ.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
  public void changed(ObservableValue<? extends Toggle> ov, Toggle toggle, Toggle new_toggle) {
     if (new_toggle != null) {
                textAnswerQ = (String) groupAnswerQ.getSelectedToggle().getUserData();
                System.out.println("textAnswerQ : " + textAnswerQ);
    }
  }
});`

This is for the case of choose an answer (for the true or false is the similar code). My problem is that when the event is detected the textAnswerQ returns always null even when the new_toggle is not null. What am I doing wrong here?


问:
Padding zeros in a string
I'm writing a bash script to get some podcasts.  The problem is that some of the podcast numbers are one digits while others are two/three digits, therefore I need to pad them to make them all 3 digits.

I tried the following:

```<code>n=1

n = printf %03d $n

wget http://aolradio.podcast.aol.com/sn/SN-$n.mp3
</code>```

but the variable 'n' doesn't stay padded permanently.  How can I make it permanent?

OwnerDisplayName: baxter

Title: Padding zeros in a string

Body:
I'm writing a bash script to get some podcasts.  The problem is that some of the podcast numbers are one digits while others are two/three digits, therefore I need to pad them to make them all 3 digits.

I tried the following:

n=1

n = printf %03d $n

wget http://aolradio.podcast.aol.com/sn/SN-$n.mp3

but the variable 'n' doesn't stay padded permanently.  How can I make it permanent?

Body:
to avoid context switching:

a="123"
b="00000${a}"
c="${b: -5}"


问:
C++ error: expected ',' or ';' before '{' token when their is
I am trying to create a function that will return the alphabet position of a letter that is passed into the function
for example

```<code>cout<<getPosition('l')
</code>```

would return the integer 12. I am fairly certain I have got the logic correct however I am having some trouble with the syntax. I found many similar questions however I still was not able to solve the problem.
Any help appreciated

```<code>#include <iostream>
using namespace std;

int getPosition(letter)
{
    int pos = 0;
    const char alphabet[26]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
    for (int counter=0; counter!=26; counter++)
    {
        if (alphabet[counter] == letter)
        {
            pos = counter;
            break;
        }
    }
    return pos;
}

int main()
{
    string letter = 'r';
    cout << posInAlpha(letter);
    return 0;
}
</code>```

答:
```<code>#include <iostream>

int getPosition( char c )
{
  c |= 0x20; // to lower
  return ( c < 'a' || c > 'z' )
    ? -1
    : c - 'a';
}

int main()
{
  std::cout << getPosition( 'R' );
  return 0;
}
</code>```

Demo

Body:
I am trying to create a function that will return the alphabet position of a letter that is passed into the function
for example

cout<<getPosition('l')

would return the integer 12. I am fairly certain I have got the logic correct however I am having some trouble with the syntax. I found many similar questions however I still was not able to solve the problem.
Any help appreciated

#include <iostream>
using namespace std;

int getPosition(letter)
{
    int pos = 0;
    const char alphabet[26]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
    for (int counter=0; counter!=26; counter++)
    {
        if (alphabet[counter] == letter)
        {
            pos = counter;
            break;
        }
    }
    return pos;
}

int main()
{
    string letter = 'r';
    cout << posInAlpha(letter);
    return 0;
}

Body:
#include <iostream>

int getPosition( char c )
{
  c |= 0x20; // to lower
  return ( c < 'a' || c > 'z' )
    ? -1
    : c - 'a';
}

int main()
{
  std::cout << getPosition( 'R' );
  return 0;
}

Demo


问:
A TabBarViewController cannot be presented as a child. Consider using Root instead
On the start of my iOS application (that I am building with Xamarin and MvvmCross), I want to immediately change UIViewController to a UITabBarViewController. My code:

```<code>public class MainViewModel : BaseViewModel
{
    public void Initialization()
    {
        ShowViewModel<TabLayoutViewModel>(); // Breaks here
    }
}

public class MainViewController : BaseViewController<MainViewModel>
{
    public override void ViewDidLoad()
    {
        base.ViewDidLoad();

        this.ViewModel.Initialization();
    }
}

public class TabLayoutViewController : MvxTabBarViewController<TabLayoutViewModel>
{
}
</code>```

On the line ShowViewModel<TabLayoutViewModel>() it throws an exception:

A TabBarViewController cannot be presented as a child. Consider using
  Root instead

I just want to push this controller on top of the stack. I know this is legal in plain iOS so there should be a way to do it with MvvmCross?

答:
Update: Since MvvmCross 5.0.4 it is now possible to show a TabBarController as a child. Just mark your TabBarController with [MvxChildPresentation].

See this PR to the source code..

Original answer:

A TabBarController is not meant to be presented inside a UINavigationController. What you can do is to change the root ViewController of your Window. To do so, you can add the MvxRootPresentation attribute above the TabLayoutViewController class.

If you do need to show tabs inside a UINavigationController, you might find this question relevant.

Body:
On the start of my iOS application (that I am building with Xamarin and MvvmCross), I want to immediately change UIViewController to a UITabBarViewController. My code:

public class MainViewModel : BaseViewModel
{
    public void Initialization()
    {
        ShowViewModel<TabLayoutViewModel>(); // Breaks here
    }
}

public class MainViewController : BaseViewController<MainViewModel>
{
    public override void ViewDidLoad()
    {
        base.ViewDidLoad();

        this.ViewModel.Initialization();
    }
}

public class TabLayoutViewController : MvxTabBarViewController<TabLayoutViewModel>
{
}

On the line ShowViewModel<TabLayoutViewModel>() it throws an exception:

A TabBarViewController cannot be presented as a child. Consider using
  Root instead

I just want to push this controller on top of the stack. I know this is legal in plain iOS so there should be a way to do it with MvvmCross?


问:
GCDAsyncUDPSocket get source address from structure using swift
I am using CocoaAsyncSocket to send and receive UDP packets. My code is working but I'm not sure how to get the address of the sender. The following function receives the packet and has a variable address but it's passed as Data.

```<code>func udpSocket(_ sock: GCDAsyncUdpSocket, didReceive data: Data, fromAddress address: Data, withFilterContext filterContext: Any?)
{

}
</code>```

I found in this post that the data is in the following structure format.

```<code>struct sockaddr_in {
__uint8_t   sin_len;
sa_family_t sin_family;
in_port_t   sin_port;
struct  in_addr sin_addr;
char        sin_zero[8];
};
</code>```

In swift how would I go about changing the Data address to a structure and then getting the ip address from that?

Thanks!

答:
I've managed to get information from the address with the following code  taken from this other answer:

```<code>        var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
        do {
            try address.withUnsafeBytes { (pointer:UnsafePointer<sockaddr>) -> Void in
                guard getnameinfo(pointer, socklen_t(address.count), &hostname, socklen_t(hostname.count), nil, 0, NI_NUMERICHOST) == 0 else {
                    throw NSError(domain: "domain", code: 0, userInfo: ["error":"unable to get ip address"])
                }
            }
        } catch {
            print(error)
            return
        }
        let senderAddress = String(cString:hostname)
</code>```

Hope it will help you

Body:
I am using CocoaAsyncSocket to send and receive UDP packets. My code is working but I'm not sure how to get the address of the sender. The following function receives the packet and has a variable address but it's passed as Data.

func udpSocket(_ sock: GCDAsyncUdpSocket, didReceive data: Data, fromAddress address: Data, withFilterContext filterContext: Any?)
{

}

I found in this post that the data is in the following structure format.

struct sockaddr_in {
__uint8_t   sin_len;
sa_family_t sin_family;
in_port_t   sin_port;
struct  in_addr sin_addr;
char        sin_zero[8];
};

In swift how would I go about changing the Data address to a structure and then getting the ip address from that?

Thanks!

Body:
I've managed to get information from the address with the following code  taken from this other answer:

        var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
        do {
            try address.withUnsafeBytes { (pointer:UnsafePointer<sockaddr>) -> Void in
                guard getnameinfo(pointer, socklen_t(address.count), &hostname, socklen_t(hostname.count), nil, 0, NI_NUMERICHOST) == 0 else {
                    throw NSError(domain: "domain", code: 0, userInfo: ["error":"unable to get ip address"])
                }
            }
        } catch {
            print(error)
            return
        }
        let senderAddress = String(cString:hostname)

Hope it will help you


问:
Unwrap an variable number of wrapper types in a single operation
I have a generic wrapper type:

```<code>public class Wrap<T> {
    public T Contents { get; set; }
}
</code>```

I can wrap any object in a wrap or unwrap a wrapped object:

```<code>public static class WrapHelpers {
    public static Wrap<T> Wrap<T>(this T contents) {
        return new Wrap<T> { Contents = contents };
    }
    public static T Unwrap<T>(this Wrap<T> wrapped) {
        return wrapped.Contents;
    }
    //NOP
    public static T Unwrap<T>(this T contents) {
        return contents;
    }
}
</code>```

Here is how I can wrap and unwrap some string:

```<code>string s = "ssss";
var wrappedString = s.Wrap().Wrap().Wrap();
string unwrappedString = wrappedString.Unwrap().Unwrap().Unwrap().Unwrap().Unwrap().Unwrap();
</code>```

See how I need to unwrap multiple times to get to get to the string inside.

What I want is to write a strongly-typed generic operation that can do the unwrapping in a single step (or constant number of steps).
Some tools that might be useful are generic methods, lambdas, method overloads. I even thought about building type-based Y-combinatory from fixed-point combinators to use for unlimited recursion. Even recursion needs steps/cycles/iterations though.

I'm not sure this is solvable, but C#'s type inference can solve NP-hard problems (see https://blogs.msdn.microsoft.com/ericlippert/2007/03/28/lambda-expressions-vs-anonymous-methods-part-five/) so there is still a tiny chance I'm overlooking something.

答:
This may work, but you lose type safety and it certainly isn't in a constant number of steps :(</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;

namespace Test
{
    public class Wrap<T>
    {
        public T Contents { get; set; }

        public object DeepUnwrap()
        {
            var wrapped = this;
            var hello = wrapped.Unwrap();

            if (hello != null)
            {
                var type = hello.GetType();

                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Wrap<>))
                    return ((dynamic)hello).DeepUnwrap();
            }

            return hello;
        }

    }

    public static class WrapHelpers
    {
        public static Wrap<T> Wrap<T>(this T contents)
        {
            return new Wrap<T> { Contents = contents };
        }
        public static T Unwrap<T>(this Wrap<T> wrapped)
        {
            return wrapped.Contents;
        }

        public static object FullUnwrap<T>(this Wrap<T> wrapped)
        {
            var hello = wrapped.DeepUnwrap();

            return hello;
        }

        //NOP
        public static T Unwrap<T>(this T contents)
        {
            return contents;
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            string s = "ssss";
            var wrappedString = s.Wrap().Wrap().Wrap();
            Console.WriteLine(wrappedString.FullUnwrap());
            Console.ReadLine();
        }
    }
}
</code>```

Body:
I have a generic wrapper type:

public class Wrap<T> {
    public T Contents { get; set; }
}

I can wrap any object in a wrap or unwrap a wrapped object:

public static class WrapHelpers {
    public static Wrap<T> Wrap<T>(this T contents) {
        return new Wrap<T> { Contents = contents };
    }
    public static T Unwrap<T>(this Wrap<T> wrapped) {
        return wrapped.Contents;
    }
    //NOP
    public static T Unwrap<T>(this T contents) {
        return contents;
    }
}

Here is how I can wrap and unwrap some string:

string s = "ssss";
var wrappedString = s.Wrap().Wrap().Wrap();
string unwrappedString = wrappedString.Unwrap().Unwrap().Unwrap().Unwrap().Unwrap().Unwrap();

See how I need to unwrap multiple times to get to get to the string inside.

What I want is to write a strongly-typed generic operation that can do the unwrapping in a single step (or constant number of steps).
Some tools that might be useful are generic methods, lambdas, method overloads. I even thought about building type-based Y-combinatory from fixed-point combinators to use for unlimited recursion. Even recursion needs steps/cycles/iterations though.

I'm not sure this is solvable, but C#'s type inference can solve NP-hard problems (see https://blogs.msdn.microsoft.com/ericlippert/2007/03/28/lambda-expressions-vs-anonymous-methods-part-five/) so there is still a tiny chance I'm overlooking something.

Body:
This may work, but you lose type safety and it certainly isn't in a constant number of steps :(

using System;
using System.Collections.Generic;
using System.Linq;

namespace Test
{
    public class Wrap<T>
    {
        public T Contents { get; set; }

        public object DeepUnwrap()
        {
            var wrapped = this;
            var hello = wrapped.Unwrap();

            if (hello != null)
            {
                var type = hello.GetType();

                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Wrap<>))
                    return ((dynamic)hello).DeepUnwrap();
            }

            return hello;
        }

    }

    public static class WrapHelpers
    {
        public static Wrap<T> Wrap<T>(this T contents)
        {
            return new Wrap<T> { Contents = contents };
        }
        public static T Unwrap<T>(this Wrap<T> wrapped)
        {
            return wrapped.Contents;
        }

        public static object FullUnwrap<T>(this Wrap<T> wrapped)
        {
            var hello = wrapped.DeepUnwrap();

            return hello;
        }

        //NOP
        public static T Unwrap<T>(this T contents)
        {
            return contents;
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            string s = "ssss";
            var wrappedString = s.Wrap().Wrap().Wrap();
            Console.WriteLine(wrappedString.FullUnwrap());
            Console.ReadLine();
        }
    }
}


问:
ERROR: 'object' does not contain a definition for 'methodName'
I need to pass different objects instantiated from different classes which they have a function with same name, and I would like to call that function.

For example:

```<code>Class1 object1;
Class2 object2;
Class3 object3;

Object object = object1;
object1->functionname();

Object object = object2;
object2->functionname();

Object object = object3;
object3->functionname();
</code>```

this is not possible in c#...

In php it's pretty simple you can just do it with object like the sample above but in c# i get this error:  ERROR: 'object' does not contain a definition for 'methodName'

I though it's legal to call any method name on a object object! since it doesn't know what is really inside.

How can I do that?

答: c# is statically typed: it looks up method names when the code is compiled, not when it is run. object doesn't have that method name, so you can't expect to call that function.

Body:
I need to pass different objects instantiated from different classes which they have a function with same name, and I would like to call that function.

For example:

Class1 object1;
Class2 object2;
Class3 object3;

Object object = object1;
object1->functionname();

Object object = object2;
object2->functionname();

Object object = object3;
object3->functionname();

this is not possible in c#...

In php it's pretty simple you can just do it with object like the sample above but in c# i get this error:  ERROR: 'object' does not contain a definition for 'methodName'

I though it's legal to call any method name on a object object! since it doesn't know what is really inside.

How can I do that?


问:
Pass struct with c strings from vb6
this seems like a simple question but I can't seem to google up the answer. I have a dll that has an interface like this:

```<code>struct TestResults
{
    int StringLengths;
    Error Error;
    LPTSTR SerialNumber;
    LPTSTR Application;
    LPTSTR GSM;
};

extern "C" Error DLLNAME_ _stdcall GetResult(TestResults* testResults);
</code>```

The dll will fill in the several strings.
How can I use this interface from VB6?  How can I initialize the strings to use for example a 64 character long fixed length string?

答:
I assume Error is defined as a 32-bit integer, which means that in VB your Type should look like:

```<code>Type ResultsType
    StringLengths As Long
    ErrorValue As Long
    SerialNumber As Long
    Application As Long
    GSM As Long
End Type
</code>```

Dim testResults As ResultsType

Each of the strings should be a pre-sized variable-length string, like;

```<code>Dim strGSM as String
strGSM = String$(64, 0)
testResults.GSM = StrPtr(strGSM)
</code>```

The Declaration would be:

```<code>Declare Function GetResult Lib "DLLNAME" (ByVal testResults As ResultsType) As Long
</code>```

The return value would be the Error value described above. The Lib field assumes the DLL is in your path -- if not, you can qualify it further.

All that's air code, no guarantees since it isn't tested.

Title: Pass struct with c strings from vb6

Body:
this seems like a simple question but I can't seem to google up the answer. I have a dll that has an interface like this:

struct TestResults
{
    int StringLengths;
    Error Error;
    LPTSTR SerialNumber;
    LPTSTR Application;
    LPTSTR GSM;
};

extern "C" Error DLLNAME_ _stdcall GetResult(TestResults* testResults);

The dll will fill in the several strings.
How can I use this interface from VB6?  How can I initialize the strings to use for example a 64 character long fixed length string?

Body:
I assume Error is defined as a 32-bit integer, which means that in VB your Type should look like:

Type ResultsType
    StringLengths As Long
    ErrorValue As Long
    SerialNumber As Long
    Application As Long
    GSM As Long
End Type

Dim testResults As ResultsType

Each of the strings should be a pre-sized variable-length string, like;

Dim strGSM as String
strGSM = String$(64, 0)
testResults.GSM = StrPtr(strGSM)

The Declaration would be:

Declare Function GetResult Lib "DLLNAME" (ByVal testResults As ResultsType) As Long

The return value would be the Error value described above. The Lib field assumes the DLL is in your path -- if not, you can qualify it further.

All that's air code, no guarantees since it isn't tested.


问:
Compare large MySQL tables
I need to make a comparison between two (or more) tables with around 60.000 rows and about 60 columns.

In these tables there are two values on which I want to run a query. The purpose of the query is to count the rows which exists in TABLE_A but don't exist in TABLE_B based on two values in the row.

I've ran the following query:

```<code>SELECT id
FROM table_a ta
WHERE NOT EXISTS (
  SELECT id
  FROM table_b tb
  WHERE ta.value1=tb.value1 AND ta.value2=tb.value2
)
</code>```

As said, I've tried the code above and some variations on it. But to run this query it takes ages before it's finished. I hope to find a solution which runs in under 10 seconds.

Next query I tried, and of which I thought was working:

```<code>SELECT value1, value2
FROM (
    SELECT ta.value1, ta.value2
    FROM table_a ta
    UNION ALL
    SELECT tb.value1, tb.value2
    FROM table_b tb
) result
GROUP BY value1, value2
HAVING COUNT(*) = 1
ORDER BY value1
</code>```

The code shows me all differences between the two tables. So if valueX exists in TABLE_A but not in TABLE_B it's shown and vice versa.

So in short, I want to get all rows from TABLE_A which are not present in TABLE_B based on two values in the row.

Hope someone can help, thanks!

答:
After some trial and error I have improved the second block of code. I noticed an additional field in my table which I could use to further filter the results.

```<code>SELECT date, value1, value2
FROM (
    SELECT date, value1, value2
    FROM (
        SELECT ta.date, ta.value1, ta.value2
        FROM table_1 ta
        UNION ALL
        SELECT tb.date, tb.value1, tb.value2
        FROM table_2 tb
    ) filter
    GROUP BY value1, value2
    HAVING COUNT(*) = 1
) result
WHERE date='YYYY-MM-DD'
</code>```

This code filters the results in under 4 seconds.

Anyway, thanks everyone for the trouble.

Title: Compare large MySQL tables

Body:
I need to make a comparison between two (or more) tables with around 60.000 rows and about 60 columns.

In these tables there are two values on which I want to run a query. The purpose of the query is to count the rows which exists in TABLE_A but don't exist in TABLE_B based on two values in the row.

I've ran the following query:

SELECT id
FROM table_a ta
WHERE NOT EXISTS (
  SELECT id
  FROM table_b tb
  WHERE ta.value1=tb.value1 AND ta.value2=tb.value2
)

As said, I've tried the code above and some variations on it. But to run this query it takes ages before it's finished. I hope to find a solution which runs in under 10 seconds.

Next query I tried, and of which I thought was working:

SELECT value1, value2
FROM (
    SELECT ta.value1, ta.value2
    FROM table_a ta
    UNION ALL
    SELECT tb.value1, tb.value2
    FROM table_b tb
) result
GROUP BY value1, value2
HAVING COUNT(*) = 1
ORDER BY value1

The code shows me all differences between the two tables. So if valueX exists in TABLE_A but not in TABLE_B it's shown and vice versa.

So in short, I want to get all rows from TABLE_A which are not present in TABLE_B based on two values in the row.

Hope someone can help, thanks!

Body:
After some trial and error I have improved the second block of code. I noticed an additional field in my table which I could use to further filter the results.

SELECT date, value1, value2
FROM (
    SELECT date, value1, value2
    FROM (
        SELECT ta.date, ta.value1, ta.value2
        FROM table_1 ta
        UNION ALL
        SELECT tb.date, tb.value1, tb.value2
        FROM table_2 tb
    ) filter
    GROUP BY value1, value2
    HAVING COUNT(*) = 1
) result
WHERE date='YYYY-MM-DD'

This code filters the results in under 4 seconds.

Anyway, thanks everyone for the trouble.


问:
Object constructor points to the original constructor not prototype.constructor after redefining prototype of constructor function
For example:

```<code>function F() {};
F.prototype = {
    test: function() { console.log('test'); }
};

console.log(F.prototype.constructor); // [Function: Object]

F.prototype = 'string';

var o = new F();
console.log(F.prototype.constructor); // [Function: String]
console.log(F.prototype);             // string
console.log(o.constructor);           // [Function: Object]

o.test();  // Can't work
</code>```

In the code above, the initial constructor is F(), the F.prototype.constructor. But then I reset the F.prototype to 'string'. And there are my questions:

After reset F.prototype to 'string', why F.prototype.constructor becomes [Function: String]. In other words, which determine the value of
F.prototype.constructor?

I have known that the new object will inherit the properties of prototype object, so is constructor property. But why the constructor of object p was the original constructor [Function: Object], not [Function: String]?

Thanks in advance.

答:
The constructor field is nothing special, it's like any other field.

Answer for #1:

```<code>F.prototype = "string";
console.log(F.prototype.constructor); // function String
</code>```

logs function String because it's the same as

```<code>console.log("string".constructor); // function String
</code>```

Answer for #2:

Every objects internal __proto__ field must be typeof x === "object". At the end of the prototype chain there always is a null value (usually it's the Object.prototype.__proto__ one), and there are no cycles allowed. You assigned a primitive string to the constructors prototype field (typeof F.prototype === "string"), which cannot be used as __proto__, so the new operator just falls back to construct the object with a default prototype, which is Object.prototype.

Body:
For example:

function F() {};
F.prototype = {
    test: function() { console.log('test'); }
};

console.log(F.prototype.constructor); // [Function: Object]

F.prototype = 'string';

var o = new F();
console.log(F.prototype.constructor); // [Function: String]
console.log(F.prototype);             // string
console.log(o.constructor);           // [Function: Object]

o.test();  // Can't work

In the code above, the initial constructor is F(), the F.prototype.constructor. But then I reset the F.prototype to 'string'. And there are my questions:

After reset F.prototype to 'string', why F.prototype.constructor becomes [Function: String]. In other words, which determine the value of
F.prototype.constructor?

I have known that the new object will inherit the properties of prototype object, so is constructor property. But why the constructor of object p was the original constructor [Function: Object], not [Function: String]?

Thanks in advance.

Body:
The constructor field is nothing special, it's like any other field.

Answer for #1:

F.prototype = "string";
console.log(F.prototype.constructor); // function String

logs function String because it's the same as

console.log("string".constructor); // function String

Answer for #2:

Every objects internal __proto__ field must be typeof x === "object". At the end of the prototype chain there always is a null value (usually it's the Object.prototype.__proto__ one), and there are no cycles allowed. You assigned a primitive string to the constructors prototype field (typeof F.prototype === "string"), which cannot be used as __proto__, so the new operator just falls back to construct the object with a default prototype, which is Object.prototype.


问:
PHP Insert session name into path
Sorry for my english. I use form to send a file then I want to use $_SESSION to create user's dir where will be stocked that file. Create dir works but doesn't send into the "user's session" dir. File is send to the root of my "uploads" dir (instead of uploads/$_SESSION['myusername']/. I think it's because "/" is missing but I tried different things and got syntax errors. Any help would be appreciated. My actual code is :</p>

```<code><?php
session_start();

$target_dir = 'uploads/'.$_SESSION['myusername'];
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (!file_exists($target_dir)) {
    mkdir($target_dir, 0777, true);
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 20000000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>
</code>```

答:
You have to add slash at last of your path so path will complete to move file:</p>

```<code>$target_dir = 'uploads/'.$_SESSION['myusername'].'/';
</code>```

Title: PHP Insert session name into path

Body:
Sorry for my english. I use form to send a file then I want to use $_SESSION to create user's dir where will be stocked that file. Create dir works but doesn't send into the "user's session" dir. File is send to the root of my "uploads" dir (instead of uploads/$_SESSION['myusername']/. I think it's because "/" is missing but I tried different things and got syntax errors. Any help would be appreciated. My actual code is :

<?php
session_start();

$target_dir = 'uploads/'.$_SESSION['myusername'];
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (!file_exists($target_dir)) {
    mkdir($target_dir, 0777, true);
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 20000000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

Body:
You have to add slash at last of your path so path will complete to move file:

$target_dir = 'uploads/'.$_SESSION['myusername'].'/';


问:
How to store a list in a db column
I would like to store an object FOO in a database.
Lets say FOO contains three integers and a list of "Fruits".

The list can have any length, the only thing I know is that the all the fruits allowed are stored in another table.

Can I store the fruit list in a column?

答:
```<code>INSERT FOOFruits (FooID, FruitID)
SELECT 5, ID
FROM   Fruits
WHERE  name IN ('Apple', 'Orange');
</code>```

OwnerDisplayName: Stumproot

Title: How to store a list in a db column

OwnerDisplayName: MarcosJVC


问:
What the various ways of calling a method at runtime?
I need to call a method on an object but I do not know the method name until runtime.

What are the techniques available?

(e.g. GetMethod().Invoke(), delegates, c# 4.0 dynamic)

Thanks!

答:
The C# 4.0 dynamic functionality is going to be the easiest way to do this.  In a very real sense, dynamic is "just a wrapper" around Reflection.  It's a very good wrapper, though, that is probably your best option.

Other ways, in approximately increasing level of difficult:

Using a third-party Reflection
library.  Not sure what's out there
these days.

Writing your own
Reflection code.

Use the CodeDOM to
create code that calls the method you
want to call.

Emit IL that does
pretty much the same thing as the
CodeDOM generated code.

Create C#
source code that you then compile
into an assembly that you can call,
which in turn calls the desired
method.

The last three are not for the faint of heart.  Your best bet is to use dynamic or write your own Reflection code.  If I had had dynamic three years ago when I was writing code for something similar, I would have used it.


问:
Why does a QPX query result differ from that in Google Flights?
I just started to try Google's QPX Express API, an airline ticket search API. However, so many query results differ from those I get in Google Flights.

I'm not sure what I'm missing, but at least it should return the same results since Google Flights use the API internally.

For example, here is what I tried in Python:

```<code>import json
import requests

url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=myAPIKey"
headers = {
    "content-type": "application/json"
}
with open("sample.json") as fp:
    data = json.load(fp)

r = requests.post(url, data=json.dumps(data), headers=headers)

print(r.json()["trip"]["tripOption"][0]["pricing"][0]["saleTotal"])
</code>```

This should return the cheapest flight ticket. However, this seems to be different from the one you can get from Google Flights on the Web. My JSON file, which should be poured into the body of the request, is the following:

```<code>    {
        "request": {
            "passengers": {
                "adultCount": 1,
                "childCount": 0,
                "infantInLapCount": 0,
                "infantInSeatCount": 0,
                "seniorCount": 0
            },
            "slice": [
                {
                    "origin": "PEK",
                    "destination": "MIL",
                    "date": "2017-01-14",
                    "maxStops": 1
                }
            ],
            "maxPrice": "USD500",
            "saleCountry": "US",
            "refundable": false,
            "solutions": 500
        }
    }
</code>```

I typed in the same input into Google Flights, but the result was different.

Why do they return the different results? What am I missing here?

As of now, the QPX returned the cheapest flight as 239USD while Google Flights returned 241USD.

答:
I noticed that the QPX API and Ita Software Matrix (by Google) gives the same results, not including a lot of companies like Ryanair. Google flights includes these results.

I asked Google Support about it.

The answer is:

"QPX Express API and Matrix only include fares that are filed with ATPCO. There are a number of small carriers and low cost carriers that do not file."

Asking Google if they consider to add these flights to their APIs the answer was:

"Airlines determine which distribution channel they want to participate in. If any of these airlines were to file with ATPCO, then we would certainly be interested."

Body:
I just started to try Google's QPX Express API, an airline ticket search API. However, so many query results differ from those I get in Google Flights.

I'm not sure what I'm missing, but at least it should return the same results since Google Flights use the API internally.

For example, here is what I tried in Python:

import json
import requests

url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=myAPIKey"
headers = {
    "content-type": "application/json"
}
with open("sample.json") as fp:
    data = json.load(fp)

r = requests.post(url, data=json.dumps(data), headers=headers)

print(r.json()["trip"]["tripOption"][0]["pricing"][0]["saleTotal"])

This should return the cheapest flight ticket. However, this seems to be different from the one you can get from Google Flights on the Web. My JSON file, which should be poured into the body of the request, is the following:

    {
        "request": {
            "passengers": {
                "adultCount": 1,
                "childCount": 0,
                "infantInLapCount": 0,
                "infantInSeatCount": 0,
                "seniorCount": 0
            },
            "slice": [
                {
                    "origin": "PEK",
                    "destination": "MIL",
                    "date": "2017-01-14",
                    "maxStops": 1
                }
            ],
            "maxPrice": "USD500",
            "saleCountry": "US",
            "refundable": false,
            "solutions": 500
        }
    }

I typed in the same input into Google Flights, but the result was different.

Why do they return the different results? What am I missing here?

As of now, the QPX returned the cheapest flight as 239USD while Google Flights returned 241USD.


问:
Alternative to enquote_literal for string containing single quote
I am bound to use dbms_assert.enquote_literal to enquote string. The string is schema name which is unknown to me as it is coming as a parameter to my function. The only thing I know is that a schema name may contain single quote. For such strings enquote_literal fails with ORA-06502: PL/SQL: numeric or value error. Is there any alternative that I can use in place of enquote_literal that gives the same output as enquote_literal.

答:
Try 'q' quotes Read here.

```<code>select q'['<you string>']' from dual;
</code>```

Demo

```<code>SQL> select q'['Hello'workddl']' Col from dual;

COL
--------------
'Hello'workddl'
</code>```

Body:
Try 'q' quotes Read here.

select q'['<you string>']' from dual;

Demo

SQL> select q'['Hello'workddl']' Col from dual;

COL
--------------
'Hello'workddl'


问:
how to send email automatically using jsp/servlet at partcular time(10'clock in the morning) daily
I want to send email automatically using j2ee at specific time daily if tomcat server is in on mode by fetching data from database </p>

答:
Use a ScheduledExecutorService or as mentioned below third party lib like Quartz</p>

```<code>private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
 scheduler.scheduleAtFixedRate(yourRunnable, 8, 8, TimeUnit.HOURS);
</code>```

Body:
Use a ScheduledExecutorService or as mentioned below third party lib like Quartz

private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
 scheduler.scheduleAtFixedRate(yourRunnable, 8, 8, TimeUnit.HOURS);


问:
I want to call Action Method of controller and return View on Kendo grid row click
Below is my kendo grid code

```<code>@(Html.Kendo().Grid<DataSource>()
    .Name("grid")
    .Columns(columns =>
    {
        columns.Bound(p => p.Quote_ID).Filterable(false);
        columns.Bound(p => p.Ticket_ID).Groupable(true);
        columns.Bound(p => p.Channel).Groupable(true);
        columns.Bound(p => p.Agent_Alias).Groupable(true).Hidden(true);
        columns.Bound(p => p.Shipping_Carrier).Groupable(true).Hidden(true);
        columns.Bound(p => p.Quote_ID).Title("View
        Details").Groupable(false)

        .Template(@<text>
            @Html.ActionLink("Show Product Details", "GridRowSummary",
        "GridOrderSummary")</text>);

    })
</code>```

From ActionLink I am trying to call Action Method of my controller.

```<code>Below My controller code

public ActionResult GridRowSummary()
    {
        return View();
    }
</code>```

答:
Using Template will work when using Ajax bound grids e.g:

```<code>columns.Template(c => @Html.ActionLink("GridRowSummary", "GridOrderSummary", new { id = c.Id, }));
</code>```

If not using Ajax bound grids use ClientTemplate attribute on the column, along with a method to display the associated data, if required e.g.:

```<code>columns.Bound(p => p.Quote_ID).Title("View Details").Groupable(false)
    .ClientTemplate(@Html.ActionLink("#=Quote_ID#", "GridRowSummary", new { ID = "#=ID#" }).ToHtmlString());
</code>```

There is a third method (a little messy) which allows you to add custom buttons/icons etc e.g:

```<code>columns.Bound(p => p.Quote_ID).ClientTemplate("<a href='" + @Url.Action("GridRowSummary", "GridOrderSummary", new { id = "#=Id#" }) + "' class='btn btn-primary'><i class='fa fa-eye'></i>  Link</a>" );
</code>```

EDIT

From looking through the FAQ section, found an even neater solution where you can pass controller name and your Quote_ID parameter (although this way does involve setting up a Javascript function):

```<code>columns.Bound(p => p.Quote_ID).ClientTemplate("#= getDetails(data) #");

<script>
function getDetails(data) {
    var action = '@Url.Action("NameOfMethod", "NameOfController")';

    var html = kendo.format("<a href='{0}/{1}'>Link</a>",
        action,
        data.Quote_ID
    );

    return html;
}
</script>
</code>```

Body:
Below is my kendo grid code

@(Html.Kendo().Grid<DataSource>()
    .Name("grid")
    .Columns(columns =>
    {
        columns.Bound(p => p.Quote_ID).Filterable(false);
        columns.Bound(p => p.Ticket_ID).Groupable(true);
        columns.Bound(p => p.Channel).Groupable(true);
        columns.Bound(p => p.Agent_Alias).Groupable(true).Hidden(true);
        columns.Bound(p => p.Shipping_Carrier).Groupable(true).Hidden(true);
        columns.Bound(p => p.Quote_ID).Title("View
        Details").Groupable(false)

        .Template(@<text>
            @Html.ActionLink("Show Product Details", "GridRowSummary",
        "GridOrderSummary")</text>);

    })

From ActionLink I am trying to call Action Method of my controller.

Below My controller code

public ActionResult GridRowSummary()
    {
        return View();
    }

Body:
Using Template will work when using Ajax bound grids e.g:

columns.Template(c => @Html.ActionLink("GridRowSummary", "GridOrderSummary", new { id = c.Id, }));

If not using Ajax bound grids use ClientTemplate attribute on the column, along with a method to display the associated data, if required e.g.:

columns.Bound(p => p.Quote_ID).Title("View Details").Groupable(false)
    .ClientTemplate(@Html.ActionLink("#=Quote_ID#", "GridRowSummary", new { ID = "#=ID#" }).ToHtmlString());

There is a third method (a little messy) which allows you to add custom buttons/icons etc e.g:

columns.Bound(p => p.Quote_ID).ClientTemplate("<a href='" + @Url.Action("GridRowSummary", "GridOrderSummary", new { id = "#=Id#" }) + "' class='btn btn-primary'><i class='fa fa-eye'></i>  Link</a>" );

EDIT

From looking through the FAQ section, found an even neater solution where you can pass controller name and your Quote_ID parameter (although this way does involve setting up a Javascript function):

columns.Bound(p => p.Quote_ID).ClientTemplate("#= getDetails(data) #");

<script>
function getDetails(data) {
    var action = '@Url.Action("NameOfMethod", "NameOfController")';

    var html = kendo.format("<a href='{0}/{1}'>Link</a>",
        action,
        data.Quote_ID
    );

    return html;
}
</script>


问:
Delete data from datatable via AJAX call
I have a view where I have AJAX call

Here is code of AJAX request, it's just hit method on back end:

```<code><script>
// deleting
$("#send").click(
    function sender() {
        $.ajax({
            contentType: 'application/json; charset=utf-8',
            type: 'Post',
            dataType: 'json',
            processData: false,
            url: '@Url.Action("DeleteAll", "Questions")',
            success: function(da) {
                if (da.Result === "Success") {

                    alert("Data deleted!");

                } else {

                    alert('Error' + da.Message);
                }
            },
            error: function(da) {
                alert('Error');
            }
        });
    });
</code>```

And method on back end

```<code>public ActionResult DeleteAll()
{
    ApplicationDbContext context =  new ApplicationDbContext();
    List<InvitationMail> query = context.InvitationMails.ToList();
    foreach (InvitationMail q in query)
    {
        context.DeleteObject(q);
    }
    context.SaveChanges();
    return Json(new {Result = "Success", Message = "Saved Successfully"});
}
</code>```

But I have this error

I need to delete all data from  InvitationMail table, how I can do this?

答:
Why not using TRUNCATE TABLE SQL command like this:

```<code>context.Database.ExecuteSqlCommand("TRUNCATE TABLE InvitationMail");
</code>```

Body:
Why not using TRUNCATE TABLE SQL command like this:

context.Database.ExecuteSqlCommand("TRUNCATE TABLE InvitationMail");