问:
template class that derives from same template
I have an equivalent to following code:

```<code>struct Empty {
  static constexpr int id = 0;
};

template <typename Self, typename Base = Empty> struct Compound : public Base
{
  int get_id() const
  {
    return Self::id;
  }
};

struct A : Compound<A>
{
  static constexpr int id = 0xa;
};

struct B : Compound<B, A>
{
  static constexpr int id = 0xb;
};

template <typename T, typename Base> int get_id(const Compound<T, Base> &c)
{
  return c.get_id();
}

int test_a()
{
  A var;
  return get_id(var);
}

int test_b()
{
  B var;
  return get_id(var);
}
</code>```

test_b doesn't compile with following error:

```<code>error: no matching function for call to 'get_id(B&)'
   return get_id(var);
                    ^
note: candidate: template<class T, class Base> int get_id(const Compound<T, Base>&)
 template <typename T, typename Base> int get_id(const Compound<T, Base> &c)
                                          ^
note:   template argument deduction/substitution failed:
note:   'const Compound<T, Base>' is an ambiguous base class of 'B'
   return get_id(var);
</code>```

I understand why that is. B is derived and is convertible to both Compound and Compound

I'm wondering if it is possible to change (within context of C++14) Compound template and get_id() function such that it would return 0xa for A and 0xb for B and would work for arbitrarily long chains of inheritance.

I know that this can be easily solved with virtual function that is overridden in A and B, but I would like to avoid that if possible. Everywhere these types are used they are known and fixed at compile time so there shouldn't be a need to incur run-time overhead.

答:
It's not clear from your post why need to go the route of Compound in get_id. You can simply use:

```<code>template <typename T> int get_id(T const& c)
{
  return T::id;
}
</code>```

Body:
I have an equivalent to following code:

struct Empty {
  static constexpr int id = 0;
};

template <typename Self, typename Base = Empty> struct Compound : public Base
{
  int get_id() const
  {
    return Self::id;
  }
};

struct A : Compound
{
  static constexpr int id = 0xa;
};

struct B : Compound
{
  static constexpr int id = 0xb;
};

template <typename T, typename Base> int get_id(const Compound<T, Base> &c)
{
  return c.get_id();
}

int test_a()
{
  A var;
  return get_id(var);
}

int test_b()
{
  B var;
  return get_id(var);
}

test_b doesn't compile with following error:

error: no matching function for call to 'get_id(B&)'
   return get_id(var);
                    ^
note: candidate: template<class T, class Base> int get_id(const Compound<T, Base>&)
 template <typename T, typename Base> int get_id(const Compound<T, Base> &c)
                                          ^
note:   template argument deduction/substitution failed:
note:   'const Compound<T, Base>' is an ambiguous base class of 'B'
   return get_id(var);

I understand why that is. B is derived and is convertible to both Compound and Compound

I'm wondering if it is possible to change (within context of C++14) Compound template and get_id() function such that it would return 0xa for A and 0xb for B and would work for arbitrarily long chains of inheritance.

I know that this can be easily solved with virtual function that is overridden in A and B, but I would like to avoid that if possible. Everywhere these types are used they are known and fixed at compile time so there shouldn't be a need to incur run-time overhead.

Body:
It's not clear from your post why need to go the route of Compound in get_id. You can simply use:

template <typename T> int get_id(T const& c)
{
  return T::id;
}


来源: stackexchange

问:
Python RSA Encryption calculate valid length of plaintext
I'm developing a program that encrypts and decrypts using RSA (in python). I've read that using only RSA is not secure and it's recommended to use PCKS to do that. My main problem is how to efficiently calculate the length of the plain text i can encrypt and decrypt using a PCKS (taking in account I'm using 4096 bit key it should be less than 512 byte and I think I have to take some bytes that the PCKS uses in account).

To sum up: How do I efficiently get the length (or split) the plain text in order to encrypt/decrypt (and how do I manage to now how many bytes takes de PCSK)?

Bonus Question: Why is it insecure just to cipher a plaintext with RSA?

EDIT: As suggested in the comments, I will use an AES symmetric key to encrpyt/decrypt and share the key with RSA. According to that change, Will python calculate the encrpytion/decryption by itself of all the plaintext or do I have to split it (and how to do it efficiently if it can be done)?

Thanks for you help.

答:
Let me first say that it is very easy to implement cryptography wrong, so unless you have been spending many years studying it (you have not -- which is clear from how you wrote your question), you shouldn't be writing crypto code that is used in production.  For example, the errors you return can be used to break the crypto in a Bleichenbacher attack.  However, if you are only doing it for learning activities, then here is some guidance.

You have a choice between implementing the insecure PKCS #1 v1.5 padding or the more secure PKCS #1 v2.x OAEP padding.  Everything you need to know is in the standard: you should follow it to a T.

To answer your question, for the OAEP version you need message length ≤ modulus length – 2 * hash function output length – 2, where lengths are in bytes.

Example 2048-bit modulus using SHA256 hash.  2048-bits is 256 bytes.  Hash function has 256-bits output, which is 32 bytes.  So your message must be ≤ 256 - 2*32 - 2 = 256 - 64 - 2 = 190 bytes.

Since you understand that RSA should be used for encrypting a symmetric key such as AES, you know that such keys are no longer than 256-bits, which is 32 bytes.  It comfortably fits into the 190-byte limit.

Why is textbook RSA insecure?  Well, three decades of cryptography has transformed an interesting concept (RSA), that we want to be as difficult to break as factoring, into something that we can almost prove that breaking it is as difficult as factoring under some crazy random oracle assumption.  The only way we got to this more secure version (OAEP) was by ruling out the heuristic versions that constantly got broken.  If you want to read in depth about the history of broken designs, the best paper is Twenty Years of Attacks on the RSA Cryptosystem.

However, let me give you a little insight into the theory of what is wrong with textbook RSA.  A cryptosystem should be secure even if a single bit of information is encrypted.  Suppose Markov sends an encrypted message to Sanchez where the plaintext is a single bit.  If Zhang sees the ciphertext, can he determine what the plaintext is?  With textbook RSA, the answer is yes.  All he has to do is encrypt '1' and '0' with the same public key and see which one matches the ciphertext he captured.  Lesson: for security, you need that encrypting the same message twice does not result in the same ciphertext twice.  Hence, secure encryption requires randomness brought into the equation!

ContentLicense: CC BY-SA 3.0


问:
Calling service from Html
i want to call asp.net web service from java script and pass the parameters to it .is there any code sample or demostration  that will help me to acheive that??
thanks in advance</p>

答:
jQuery supports this behavior. you can use jQuery to do the ajax call as show below. this method has two call back functions for success and for failure.</p>

```<code>function loadData()
{
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: 'methodurl',
        success: methodSuccedded,
        error: methodFailure
    });
}

function methodSuccedded()
{
    //do your logic.
}

function methodFailure()
{
    //do your logic.
}
</code>```

OwnerDisplayName: Shoun

ContentLicense: CC BY-SA 2.5

Title: Calling service from Html

Body:
jQuery supports this behavior. you can use jQuery to do the ajax call as show below. this method has two call back functions for success and for failure.

function loadData()
{
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        url: 'methodurl',
        success: methodSuccedded,
        error: methodFailure
    });
}

function methodSuccedded()
{
    //do your logic.
}

function methodFailure()
{
    //do your logic.
}


答:
Just keep it simple:

```<code>template <class T>
auto get_id(T const& c) -> decltype(c.get_id())
{
    return c.get_id();
}
</code>```

You don't need c to be some Compound, you really just want it to have a get_id() member function.

Title: template class that derives from same template

Body:
Just keep it simple:

template <class T>
auto get_id(T const& c) -> decltype(c.get_id())
{
    return c.get_id();
}

You don't need c to be some Compound, you really just want it to have a get_id() member function.


问:
A prolog predicate checks if an element occurs at least twice in a list
```<code>twice(X,[X|Y]):-
   member(X,[Y]).
twice(X,[Y|Z]):-
   twice(X,[Z]),
   X\=Y.
</code>```

I can't find any syntax error,but the execution fails every time.

答:
I like your intent, but cannot reproduce what you claim: that this predicate fails all the time. In fact, it loops! And here is the fragment why failure-slice:

```
<s>twice(X,[X|Y]):- <b>false</b></s>,
   <s>member(X,[Y])</s>.
twice(X,[Y|Z]):-
   twice(X,[Z]), <b>false</b>,
   <s>X\=Y</s>

?- twice(a,[a,a]).
```

Because this fragment loops, also your original program loops. Lurker has already shown you what is wrong. Here are some alternate formulations:

```<code>twice(X, Xs) :-
   phrase( ( ..., [X], ..., [X], ... ), Xs).

... --> [] | [_], ... .
</code>```

Nevertheless, this program has a big flaw:

```<code>?- twice(a,[a,a,a]).
   true
;  true
;  true
;  false.
</code>```

Thrice the very same answer. One time is more than enough!

The ambiguity comes from the ...-non-terminal which means just any sequence. There are three ways how that matches the list [a,a,a]:

```<code>     [     a,      a,      a     ]

      ...,[X],...,[X],    ...
      ...,[X],    ...,    [X],...
          ...,    [X],...,[X],...
</code>```

To remove the ambiguity we need to replace the ... by something more specific. In stead of anything, the sequence should match anything but X. In this way only the first match remains.

```<code>twice(X, Xs) :-
       phrase( ( all(dif(X)), [X], all(dif(X)), [X], ... ), Xs).

all(_) --> [].
all(P_1) -->
   [E],
   {call(P_1,E)},
   all(P_1).

?- twice(a,[a,a,a]).
   true
;  false.
</code>```

That's much better. But is it the bestest? Here is a further improvement using library(reif) for SICStus|SWI.

```<code>:- use_module(library(reif)).

twice(C, [X|Xs]) :-
   if_(C = X, memberd(X, Xs), twice(C, Xs) ).

memberd(C, [X|Xs]) :-
   if_(C = X, true, memberd(C, Xs) ).

?- twice(a,[a,a,a]).
   true.
</code>```

Body:
twice(X,[X|Y]):-
   member(X,[Y]).
twice(X,[Y|Z]):-
   twice(X,[Z]),
   X\=Y.

I can't find any syntax error,but the execution fails every time.

Body:
I like your intent, but cannot reproduce what you claim: that this predicate fails all the time. In fact, it loops! And here is the fragment why failure-slice:

<s>twice(X,[X|Y]):- false</s>,
   <s>member(X,[Y])</s>.
twice(X,[Y|Z]):-
   twice(X,[Z]), false,
   <s>X\=Y</s>

?- twice(a,[a,a]).

Because this fragment loops, also your original program loops. Lurker has already shown you what is wrong. Here are some alternate formulations:

twice(X, Xs) :-
   phrase( ( ..., [X], ..., [X], ... ), Xs).

... --> [] | [_], ... .

Nevertheless, this program has a big flaw:

?- twice(a,[a,a,a]).
   true
;  true
;  true
;  false.

Thrice the very same answer. One time is more than enough!

The ambiguity comes from the ...-non-terminal which means just any sequence. There are three ways how that matches the list [a,a,a]:

     [     a,      a,      a     ]

      ...,[X],...,[X],    ...
      ...,[X],    ...,    [X],...
          ...,    [X],...,[X],...

To remove the ambiguity we need to replace the ... by something more specific. In stead of anything, the sequence should match anything but X. In this way only the first match remains.

twice(X, Xs) :-
       phrase( ( all(dif(X)), [X], all(dif(X)), [X], ... ), Xs).

all(_) --> [].
all(P_1) -->
   [E],
   {call(P_1,E)},
   all(P_1).

?- twice(a,[a,a,a]).
   true
;  false.

That's much better. But is it the bestest? Here is a further improvement using library(reif) for SICStus|SWI.

:- use_module(library(reif)).

twice(C, [X|Xs]) :-
   if_(C = X, memberd(X, Xs), twice(C, Xs) ).

memberd(C, [X|Xs]) :-
   if_(C = X, true, memberd(C, Xs) ).

?- twice(a,[a,a,a]).
   true.


问:
getchar() stopping after printing one value
Function of the code: The function of my code is pretty simple. It converts a phone number with numbers into a phone number.

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

main(){

  char num;

  printf("Please enter a phone number with letters to be converted into a phone number: \n");

  while ((num = getchar()) != '\n') {
    switch(num){
      case 'A': case 'B': case 'C': printf("2"); break;
      case 'D': case 'E': case 'F': printf("3"); break;
      case 'G': case 'H': case 'I': printf("4"); break;
      case 'J': case 'K': case 'L': printf("5"); break;
      case 'M': case 'N': case 'O': printf("6"); break;
      case 'P': case 'R': case 'S': printf("7"); break;
      case 'T': case 'U': case 'V': printf("8"); break;
      case 'W': case 'X': case 'Y': printf("9"); break;
      default: putchar(num);
    }

    return 0;

  }

}
</code>```

The problem is that the getchar() is taking one value and changing that number/letter only when I want it to change the whole thing.

Things I have done: I found someone else code who did this already, copied it, changed it a bit (removed toupper function), stacked the cases side by side and it didn't work for some reason. Is it because of the placement of the switch statement? But I don't think it is because of that because it ends after printing one value.

What I want it to do:

```<code>Enter phone number: 1-800-COL-LECT
1-800-265-5328
</code>```

What it does:

```<code>Enter phone number: 1-800-COL-LECT
1
Enter phone number: 5-469-COL-LECT
5
</code>```

答:
The problem in the code is that return 0; is inside of your while loop. What you need to do is move the return 0; outside of the loop and it will fix it.

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

main(){

  char num;

  printf("Please enter a phone number with letters to be converted into a phone number: \n");

  while ((num = getchar()) != '\n') {
    switch(num){
      case 'A': case 'B': case 'C': printf("2"); break;
      case 'D': case 'E': case 'F': printf("3"); break;
      case 'G': case 'H': case 'I': printf("4"); break;
      case 'J': case 'K': case 'L': printf("5"); break;
      case 'M': case 'N': case 'O': printf("6"); break;
      case 'P': case 'R': case 'S': printf("7"); break;
      case 'T': case 'U': case 'V': printf("8"); break;
      case 'W': case 'X': case 'Y': printf("9"); break;
      default: putchar(num);
    }
  }
  return 0;
}
</code>```

Originally founded by @kaylum

Body:
Function of the code: The function of my code is pretty simple. It converts a phone number with numbers into a phone number.

#include <stdio.h>

main(){

  char num;

  printf("Please enter a phone number with letters to be converted into a phone number: \n");

  while ((num = getchar()) != '\n') {
    switch(num){
      case 'A': case 'B': case 'C': printf("2"); break;
      case 'D': case 'E': case 'F': printf("3"); break;
      case 'G': case 'H': case 'I': printf("4"); break;
      case 'J': case 'K': case 'L': printf("5"); break;
      case 'M': case 'N': case 'O': printf("6"); break;
      case 'P': case 'R': case 'S': printf("7"); break;
      case 'T': case 'U': case 'V': printf("8"); break;
      case 'W': case 'X': case 'Y': printf("9"); break;
      default: putchar(num);
    }

    return 0;

  }

}

The problem is that the getchar() is taking one value and changing that number/letter only when I want it to change the whole thing.

Things I have done: I found someone else code who did this already, copied it, changed it a bit (removed toupper function), stacked the cases side by side and it didn't work for some reason. Is it because of the placement of the switch statement? But I don't think it is because of that because it ends after printing one value.

What I want it to do:

Enter phone number: 1-800-COL-LECT
1-800-265-5328

What it does:

Enter phone number: 1-800-COL-LECT
1
Enter phone number: 5-469-COL-LECT
5

Body:
The problem in the code is that return 0; is inside of your while loop. What you need to do is move the return 0; outside of the loop and it will fix it.

#include <stdio.h>

main(){

  char num;

  printf("Please enter a phone number with letters to be converted into a phone number: \n");

  while ((num = getchar()) != '\n') {
    switch(num){
      case 'A': case 'B': case 'C': printf("2"); break;
      case 'D': case 'E': case 'F': printf("3"); break;
      case 'G': case 'H': case 'I': printf("4"); break;
      case 'J': case 'K': case 'L': printf("5"); break;
      case 'M': case 'N': case 'O': printf("6"); break;
      case 'P': case 'R': case 'S': printf("7"); break;
      case 'T': case 'U': case 'V': printf("8"); break;
      case 'W': case 'X': case 'Y': printf("9"); break;
      default: putchar(num);
    }
  }
  return 0;
}

Originally founded by @kaylum


问:
Custom Django Wagtailmenus Flatmenu Template
I am using https://github.com/rkhleics/wagtailmenus for my Django Wagtail menus, but can't seem to figure out how to use a custom template for my flat_menu.  I followed the guides but I think I may be doing something wrong.

My flat_menu template is in a directory menus/top_sub_menu.html, where top_sub_menu is the handle of the menu I created.

top_sub_menu.html

```<code>{% load menu_tags %}
{% if menu_items %}
  <ul class="c-links c-theme-ul">
    {% for item in menu_items %}
      <li>
        <a href="{{ item.href }}">{{ item.text }}</a> {% if item.has_children_in_menu %}{% sub_menu item %}{% endif %}
      </li>
    {% endfor %}
  </ul>
{% endif %}
</code>```

header.html

```<code>{% load menu_tags %}
...
{% flat_menu 'top_sub_menu' %}
...
</code>```

I have a custom main_menu.html and a sub_menu.html in the same directory and they work, so I know my menu directory is in correct location. Thank you.

答:
The template location behaviour described in the README for the {% flat_menu %} tag (https://github.com/rkhleics/wagtailmenus#4-using-the--flat_menu--tag) was only introduced in version 2.2.0. You should be able to use your custom template by utilising the template argument, though. For example:

In header.html

```<code>{% load menu_tags %}
...
{% flat_menu 'top_sub_menu' template="menus/top_sub_menu.html" %}
...
</code>```

Body:
I am using https://github.com/rkhleics/wagtailmenus for my Django Wagtail menus, but can't seem to figure out how to use a custom template for my flat_menu.  I followed the guides but I think I may be doing something wrong.

My flat_menu template is in a directory menus/top_sub_menu.html, where top_sub_menu is the handle of the menu I created.

top_sub_menu.html

{% load menu_tags %}
{% if menu_items %}

    {% for item in menu_items %}

        {{ item.text }} {% if item.has_children_in_menu %}{% sub_menu item %}{% endif %}

    {% endfor %}

{% endif %}

header.html

{% load menu_tags %}
...
{% flat_menu 'top_sub_menu' %}
...

I have a custom main_menu.html and a sub_menu.html in the same directory and they work, so I know my menu directory is in correct location. Thank you.

Body:
The template location behaviour described in the README for the {% flat_menu %} tag (https://github.com/rkhleics/wagtailmenus#4-using-the--flat_menu--tag) was only introduced in version 2.2.0. You should be able to use your custom template by utilising the template argument, though. For example:

In header.html

{% load menu_tags %}
...
{% flat_menu 'top_sub_menu' template="menus/top_sub_menu.html" %}
...


问:
Gmail's new image caching is breaking image links in newsletter
I've got some automatic emails that are sent out upon signup completion for my site.

Until recently, they worked fine. Now Google's new system is rewriting the images and storing them in its cache (supposedly)

However, Google's new rewriting of my image links are completely breaking them, giving a 500 error and a broken link image.

Lets say my normal image url is:

```<code>http://www.example.com/images/pic1.jpg
</code>```

Google is rewriting this to:

```<code>https://ci5.googleusercontent.com/proxy/vI79kajdUGm6Wk-fjyicDLjZbCB1w9NfkoZ-zQFOB2OpJ1ILmSvfvHmE56r72us5mIuIXCFiO3V8rgkZOjfhghTH0R07BbcQy5g=s0-d-e1-ft#http://www.example.com/images/pic1.jpg
</code>```

However, there is nothing at that URL.

So, either there is something wrong with the links that are being created by Google or the images are just not being uploaded to the googleusercontent server, but I have no idea how to solve the issue.

Im using PHP, the phpmailer library and a Ubuntu server on Amazon EC2, but Im not sure that is related to the issue.

答:
I was having a similar issue, but it was caused by the length of the URL. Google generates the following URL when caching an image from gmail:

```<code>https://ci4.googleusercontent.com/proxy/[hash]#[url])
</code>```

The hash generated is based on the URL of the image, but the size will vary based on characters used. I ran several tests with different sized URLs, and found the cached image would fail to load consistently (400/Invalid Request) if the hash exceeds 2076 characters in length (close to 2048 bytes + meta? not sure).

Again, the image URL could generate a hash that exceeds this many characters at ~1000 special characters, or 1500+ simple characters. If the hash exceeds 2076 characters in length, the request fails.

I realize this is an old post, but hopefully this helps other devs scouring Google

ContentLicense: CC BY-SA 4.0

Body:
I've got some automatic emails that are sent out upon signup completion for my site.

Until recently, they worked fine. Now Google's new system is rewriting the images and storing them in its cache (supposedly)

However, Google's new rewriting of my image links are completely breaking them, giving a 500 error and a broken link image.

Lets say my normal image url is:

http://www.example.com/images/pic1.jpg

Google is rewriting this to:

https://ci5.googleusercontent.com/proxy/vI79kajdUGm6Wk-fjyicDLjZbCB1w9NfkoZ-zQFOB2OpJ1ILmSvfvHmE56r72us5mIuIXCFiO3V8rgkZOjfhghTH0R07BbcQy5g=s0-d-e1-ft#http://www.example.com/images/pic1.jpg

However, there is nothing at that URL.

So, either there is something wrong with the links that are being created by Google or the images are just not being uploaded to the googleusercontent server, but I have no idea how to solve the issue.

Im using PHP, the phpmailer library and a Ubuntu server on Amazon EC2, but Im not sure that is related to the issue.

Body:
I was having a similar issue, but it was caused by the length of the URL. Google generates the following URL when caching an image from gmail:

https://ci4.googleusercontent.com/proxy/[hash]#[url])

The hash generated is based on the URL of the image, but the size will vary based on characters used. I ran several tests with different sized URLs, and found the cached image would fail to load consistently (400/Invalid Request) if the hash exceeds 2076 characters in length (close to 2048 bytes + meta? not sure).

Again, the image URL could generate a hash that exceeds this many characters at ~1000 special characters, or 1500+ simple characters. If the hash exceeds 2076 characters in length, the request fails.

I realize this is an old post, but hopefully this helps other devs scouring Google


问:
When to use Class methods over Activities?
I'm getting introduced to Android programming and want to understand Activities a bit more (I'm coming in with basic-advanced java knowledge, basic knowledge in GUIs).

I currently assume that all methods will be contained in their respective activity, or in some helper class--whose methods wouldn't be shown to the user, (unless an activity used it), but whose methods could perhaps be used in multiple activities.

Are these assumptions correct?

When are helper classes even required?

Any good online resources regarding (specifically) classes vs activity use cases?

Any examples of a fairly simple, complete APK where I could look through and dissect the code, including XML?  Hopefully something I could just import into Android Studio.

Thanks!

答:
Yes, the methods are either in the activity or in other classes, but since there is no other places for java code to be, could you clarify this question better?

To reduce the complexity of Activitys. If you have very little logic, it is perfectly fine, to have all the code in the activity. But as soon as the count of lines rise, you may run into problems like readability, testability and things like that.
But you should at least put code, that you use in different Activitys, into separate classes.

A good example would be something like M(odel)V(iew)P(resenter), where the goal is, to separate the View (Setup Buttons, Textview etc.), the presenter (Connection the loginbutton to the loginservice while showing a loginview) and the model (The actual implementation of the loginservice).

Google itself offers some examples for a clean architecture and a simple example for MVP.


问:
Keyboard shortcut to remove empty lines in a C# code file
Is there any keyboard shortcut to remove empty lines in C# code files (.cs)?

Similar to Ctrl + K , D which formats the whole .cs file.

Or is there a workaround?

答: I don't think there is any. You can use a separate refactoring add-in to automate this, such as ReSharper.</p>


问:
How can I add a field to existing mapping with values in other fields?
Current Mapping field is

```<code>      ...
      "latitude": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      },
      ...
</code>```

I wish to add a field 'location' using those data in latitude & longitude field. How can I implement?

```<code>    "location": {
      "type": "geo_point"
    }
  }
</code>```

答:
Currently, it is not possible to add and populate data for new fields in the existing index.

The only way you can achieve it by reindexing data into new index.

Let's say you have an index(source-index) test-geo-index with two fields(not restricted to two fields for easy understanding purpose I took only 2 fields) latitude and longitude as shown below:

```<code>PUT test-geo-index
{
  "mappings": {
    "test-geo-type": {
      "properties": {
        "longitute": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        },
        "latitude": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        }
      }
    }
  }
}
</code>```

Now you can create a new index(dest-index) test-geo-updated-index with the above mapping and  location field and populate data into it by using elasticsearch _reindex API.

```<code>PUT test-geo-updated-index
{
  "mappings": {
    "test-geo-type": {
      "properties": {
        "longitute": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        },
        "latitude": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        },
        "location": {
          "type": "geo_point"
        }
      }
    }
  }
}
</code>```

Elasticsearch ReIndex API:

```<code>POST _reindex
{
  "source": {
    "index": "test-geo-index"
  },
  "dest": {
    "index": "test-geo-updated-index"
  },
  "script": {
    "inline": "ctx._source.location=ctx._source.latitude + \",\" + ctx._source.longitude"
  }
}
</code>```

You can read more about Reindex API here

Body:
Current Mapping field is

      ...
      "latitude": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      },
      ...

I wish to add a field 'location' using those data in latitude & longitude field. How can I implement?

    "location": {
      "type": "geo_point"
    }
  }

Body:
Currently, it is not possible to add and populate data for new fields in the existing index.

The only way you can achieve it by reindexing data into new index.

Let's say you have an index(source-index) test-geo-index with two fields(not restricted to two fields for easy understanding purpose I took only 2 fields) latitude and longitude as shown below:

PUT test-geo-index
{
  "mappings": {
    "test-geo-type": {
      "properties": {
        "longitute": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        },
        "latitude": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        }
      }
    }
  }
}

Now you can create a new index(dest-index) test-geo-updated-index with the above mapping and  location field and populate data into it by using elasticsearch _reindex API.

PUT test-geo-updated-index
{
  "mappings": {
    "test-geo-type": {
      "properties": {
        "longitute": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        },
        "latitude": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword",
              "ignore_above": 256
            }
          }
        },
        "location": {
          "type": "geo_point"
        }
      }
    }
  }
}

Elasticsearch ReIndex API:

POST _reindex
{
  "source": {
    "index": "test-geo-index"
  },
  "dest": {
    "index": "test-geo-updated-index"
  },
  "script": {
    "inline": "ctx._source.location=ctx._source.latitude + \",\" + ctx._source.longitude"
  }
}

You can read more about Reindex API here


问:
Finish activity that is waiting for result
I'm developing the login system and currently the flow is as follows:

LoginActivity can call ExecuteLoginActivity to show a screen with a progressbar while it connects to the backend via an AsyncTask to authenticate the user and return the result to the LoginActivity, which can then call the MainActivity, or the LoginActivity can call the SignUpActivity that can then call the ExecuteSignUpActivity which does the same as the ExecuteLoginActivity but for signup, and then return the result to the SignUpActivity that in turn returns the result to the LoginActivity which can then call the MainActivity.

The problem with this approach is that the LoginScreen (and sometimes the SignUpActivity) ends up "flashing" to the user before it can call the MainActivity. I want the Execute activities to call the MainActivity themselves after a sucessfull login/signup and to return to the Login/Signup activities to show an error on a failed attempt.

I tought about using a broadcast to send a signal to finish the Login/Signup activities on a sucessfull login but I don't know if I can finish them while they are waiting for the result of the spawned Execute activities. So my question is, can I finish an activity that is waiting for the result of another activity?

答:
In Sign up and Login Activity do this:</p>

```<code>    Intent i = new Intent(this,MainActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(i);
    finish();
</code>```

Body:
In Sign up and Login Activity do this:

    Intent i = new Intent(this,MainActivity.class);
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(i);
    finish();


问:
.hasClass() seem to always return true when used inside a .click() function, why?
```<code><ul id="list">
    <li>item 1</li>
    <li>item 2</li>
</ul>

$('#list li').click(function () {
    alert($(this).hasClass('active')); // supposed to be an if
    $(this).parent('ul').children('li').removeClass('active');
    $(this).addClass('active');
});
</code>```

Why does "$(this).hasClass('active')" always return true?

答:
```<code>$('#list li').click(function () {
    alert($(this).hasClass('active')); // supposed to be an if
    $(this).parent('ul').children('li').removeClass('active');
    $(this).addClass('active');
});
</code>```

$(this).hasClass('active') is used to fetch element with that class name.

if u want to check availability of class use this code

```<code><ul id="list">
    <li>item 1</li>
    <li>item 2</li>
</ul>

$('#list li').click(function () {
    alert($(this).isClass('active')); // alert returns true if element has that class
if($(this).is('.active'))
{
    $(this).parent('ul').children('li').removeClass('active');
    $(this).addClass('active');
}
});
</code>```

Body:
item 1

item 2

$('#list li').click(function () {
    alert($(this).hasClass('active')); // supposed to be an if
    $(this).parent('ul').children('li').removeClass('active');
    $(this).addClass('active');
});

Why does "$(this).hasClass('active')" always return true?

Body:
$('#list li').click(function () {
    alert($(this).hasClass('active')); // supposed to be an if
    $(this).parent('ul').children('li').removeClass('active');
    $(this).addClass('active');
});

$(this).hasClass('active') is used to fetch element with that class name.

if u want to check availability of class use this code

<ul id="list">
    <li>item 1</li>
    <li>item 2</li>
</ul>

$('#list li').click(function () {
    alert($(this).isClass('active')); // alert returns true if element has that class
if($(this).is('.active'))
{
    $(this).parent('ul').children('li').removeClass('active');
    $(this).addClass('active');
}
});


问:
Errors Migrating from Angular 2 to 4.0.0
(Edited question) After upgrading the packages and dependencies,

```<code>"typescript": "2.1.1"
"typings": "^0.8.1"
"zone.js": "^0.8.4"
"rxjs": "5.0.1"
</code>```

Using the upgrade command to upgrade angular packages to 4.0.0 did not help. I am doing the usual npm run clean , npm install and npm run build in the same order. Should I change the version of typings?

```<code>ERROR in [default] node_modules/@angular/core/src/change_detection/differs/iterable_differs.d.ts:15:47
Cannot find name 'Iterable'.

ERROR in [default] /typings/browser/ambient/node/index.d.ts:426:10
Interface 'NodeBuffer' incorrectly extends interface 'Uint8Array'.
  Types of property 'fill' are incompatible.
    Type '(value: any, offset?: number, end?: number) => Buffer' is not assignable to type '(value: number, start?: number, end?: number) => this'.
      Type 'Buffer' is not assignable to type 'this'.
</code>```

答:
Update your package as below: </p>

```<code>"dependencies": {
    "@angular/animations": "^4.0.0",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "core-js": "^2.4.1",
    "rxjs": "^5.1.0",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@types/node": "~6.0.60",
    "ts-node": "~2.0.0",
    "typescript": "~2.2.0"
  }
</code>```

Body:
(Edited question) After upgrading the packages and dependencies,

"typescript": "2.1.1"
"typings": "^0.8.1"
"zone.js": "^0.8.4"
"rxjs": "5.0.1"

Using the upgrade command to upgrade angular packages to 4.0.0 did not help. I am doing the usual npm run clean , npm install and npm run build in the same order. Should I change the version of typings?

ERROR in [default] node_modules/@angular/core/src/change_detection/differs/iterable_differs.d.ts:15:47
Cannot find name 'Iterable'.

ERROR in [default] /typings/browser/ambient/node/index.d.ts:426:10
Interface 'NodeBuffer' incorrectly extends interface 'Uint8Array'.
  Types of property 'fill' are incompatible.
    Type '(value: any, offset?: number, end?: number) => Buffer' is not assignable to type '(value: number, start?: number, end?: number) => this'.
      Type 'Buffer' is not assignable to type 'this'.

Body:
Update your package as below:

"dependencies": {
    "@angular/animations": "^4.0.0",
    "@angular/common": "^4.0.0",
    "@angular/compiler": "^4.0.0",
    "@angular/core": "^4.0.0",
    "@angular/forms": "^4.0.0",
    "@angular/http": "^4.0.0",
    "@angular/platform-browser": "^4.0.0",
    "@angular/platform-browser-dynamic": "^4.0.0",
    "@angular/router": "^4.0.0",
    "core-js": "^2.4.1",
    "rxjs": "^5.1.0",
    "zone.js": "^0.8.4"
  },
  "devDependencies": {
    "@types/node": "~6.0.60",
    "ts-node": "~2.0.0",
    "typescript": "~2.2.0"
  }


问:
debugging in Vue. Quick and dirty way to console.dir() a reactive variable?
I have this malfunctioning code within a Vue component that's caused by _errors being undefined in my data, at least when the page is loading.

```<code>  data: function () {
     var temp = {
        show_debug : false
        ,password_changed_flag : false
        ,_errors : this.$store.state.form01._errors  || {}
     }

    var data = Object.assign({}, this.$store.state.form01.data, temp);

    //this is the part I am struggling with:
    console.log("data:");
    console.dir(data);

    return data;
  },
</code>```

This isn't however about what I am doing wrong, it's about how to easily console.dir(data) Vue's reactive objects.

I.e. how can I print out a simple nested object, minus the getters and setters?  And take a snapshot in time of that object.

i.e. _errors seems to be present now, but I'd like to only display the state of the object at the completion of the data function, not track subsequent changes.

What I am currently getting in Firefox and Chrome is instead the following:

答:
```<code>console.log(JSON.parse(JSON.stringify(thing)))
</code>```

Won't work on the Vue itself, but for data properties should be fine.

Body:
I have this malfunctioning code within a Vue component that's caused by _errors being undefined in my data, at least when the page is loading.

  data: function () {
     var temp = {
        show_debug : false
        ,password_changed_flag : false
        ,_errors : this.$store.state.form01._errors  || {}
     }

    var data = Object.assign({}, this.$store.state.form01.data, temp);

    //this is the part I am struggling with:
    console.log("data:");
    console.dir(data);

    return data;
  },

This isn't however about what I am doing wrong, it's about how to easily console.dir(data) Vue's reactive objects.

I.e. how can I print out a simple nested object, minus the getters and setters?  And take a snapshot in time of that object.

i.e. _errors seems to be present now, but I'd like to only display the state of the object at the completion of the data function, not track subsequent changes.

What I am currently getting in Firefox and Chrome is instead the following:

Body:
console.log(JSON.parse(JSON.stringify(thing)))

Won't work on the Vue itself, but for data properties should be fine.


问:
AmazonS3Builder produces valid AmazonS3 object but a null is ultimately returned
I'm using the AWS Java SDK v1 and I'm trying to create an AmazonS3 instance using the builder. I'm following the guide in the AWS documentation here and passing explicit credentials using a BasicAWSCredentials object. When the builder builds, I get a null client back to s3Client which is where I'm storing the instance, and I'm not sure why. There are no errors thrown or caught by the try-catch blocks. Here is how I am making the connection:

```<code>    BasicAWSCredentials awsCreds = null;
    try {
        awsCreds = new BasicAWSCredentials(settings.getAccessKey(), settings.getSecretKey());
    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.getMessage());
    }

    try {
        AmazonS3 s3Client = AmazonS3Client.builder()
                .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
                .withRegion(Regions.US_EAST_1)
                .build();
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println(s3Client);
</code>```

I have stepped through it with the Eclipse debugger and it looks like the build() call is actually returning a valid AmazonS3Client instance, but then before this reference is returned back to the s3Client variable, there's a step in which checkPackageAccess() is called, and this return value is what is being returned back for some reason. On further inspection I found that checkPackageAccess() is a method in the java.lang.ClassLoader that's being called by the JVM, and it has a void return type. In my application, it looks like there's no default SecurityManager set, so there's no other function called inside the ClassLoader's checkPackageAccess() method.

I'm a bit confused by this behavior. My JRE is 1.8. So far as I understand, the ClassLoader is always called when looking for a class definition, but why would it be called after a class has already been instantiated, and why is the original return value of the build() function not coming back to the caller context? In this case, the debugger shows a valid AmazonS3Client object exists and is returned by the call to build() even before the checkPackageAccess call.

I've made an AmazonRedshift instance with almost identical code in the same project previously, and that worked without a hitch, so I'm quite positive the problem is with the AmazonS3 class or the builder, but I'm not sure where and I'm not seeing any errors or strange prints.

Code used for making a similar connection to Amazon Redshift:

```<code>        BasicAWSCredentials awsCreds = null;
    try {
        awsCreds = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);
    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.getMessage());
    }
    try {
        client = AmazonRedshiftClientBuilder.standard()
                                .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
                                .withRegion(Regions.US_EAST_1)
                                .build();
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println(client);
</code>```

Has anyone debugged this kind of issue before? What can I do to resolve this and get back a valid instance?

答:
Are you open to constructing your builder from its own class rather than from the S3Client method builder()?  The following code, which parallels your Redshift case, is working okay for me.

```<code>    static final String BUCKET_NAME = "hello-world";

    /** Creates bucket
    @param args Command line arguments*/
    public static void main(final String[] args) {

            AmazonS3 s3 = AmazonS3ClientBuilder.standard().build();

            CreateBucketRequest request = new
                    CreateBucketRequest(BUCKET_NAME);

            Bucket bucket = s3.createBucket(request);

    System.out.println("S3 Hello World completed.");
</code>```

For what it's worth, my compiler cannot find the static builder() method, although it is indeed in the API.

Body:
I'm using the AWS Java SDK v1 and I'm trying to create an AmazonS3 instance using the builder. I'm following the guide in the AWS documentation here and passing explicit credentials using a BasicAWSCredentials object. When the builder builds, I get a null client back to s3Client which is where I'm storing the instance, and I'm not sure why. There are no errors thrown or caught by the try-catch blocks. Here is how I am making the connection:

    BasicAWSCredentials awsCreds = null;
    try {
        awsCreds = new BasicAWSCredentials(settings.getAccessKey(), settings.getSecretKey());
    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.getMessage());
    }

    try {
        AmazonS3 s3Client = AmazonS3Client.builder()
                .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
                .withRegion(Regions.US_EAST_1)
                .build();
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println(s3Client);

I have stepped through it with the Eclipse debugger and it looks like the build() call is actually returning a valid AmazonS3Client instance, but then before this reference is returned back to the s3Client variable, there's a step in which checkPackageAccess() is called, and this return value is what is being returned back for some reason. On further inspection I found that checkPackageAccess() is a method in the java.lang.ClassLoader that's being called by the JVM, and it has a void return type. In my application, it looks like there's no default SecurityManager set, so there's no other function called inside the ClassLoader's checkPackageAccess() method.

I'm a bit confused by this behavior. My JRE is 1.8. So far as I understand, the ClassLoader is always called when looking for a class definition, but why would it be called after a class has already been instantiated, and why is the original return value of the build() function not coming back to the caller context? In this case, the debugger shows a valid AmazonS3Client object exists and is returned by the call to build() even before the checkPackageAccess call.

I've made an AmazonRedshift instance with almost identical code in the same project previously, and that worked without a hitch, so I'm quite positive the problem is with the AmazonS3 class or the builder, but I'm not sure where and I'm not seeing any errors or strange prints.

Code used for making a similar connection to Amazon Redshift:

        BasicAWSCredentials awsCreds = null;
    try {
        awsCreds = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);
    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.getMessage());
    }
    try {
        client = AmazonRedshiftClientBuilder.standard()
                                .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
                                .withRegion(Regions.US_EAST_1)
                                .build();
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println(client);

Has anyone debugged this kind of issue before? What can I do to resolve this and get back a valid instance?

Body:
Are you open to constructing your builder from its own class rather than from the S3Client method builder()?  The following code, which parallels your Redshift case, is working okay for me.

    static final String BUCKET_NAME = "hello-world";

    /** Creates bucket
    @param args Command line arguments*/
    public static void main(final String[] args) {

            AmazonS3 s3 = AmazonS3ClientBuilder.standard().build();

            CreateBucketRequest request = new
                    CreateBucketRequest(BUCKET_NAME);

            Bucket bucket = s3.createBucket(request);

    System.out.println("S3 Hello World completed.");

For what it's worth, my compiler cannot find the static builder() method, although it is indeed in the API.


问:
Need to reset fields in PHP edit form somehow
I have a DB-based AMCharts form/page that graphs figures that are entered in a separate edit form accessed from that main page. This latter php edit form is set up to always bring up the present set of entries in every field. This edit form serves two purposes: one is to be able to correct earlier mistakes, and the other is to enter a whole set of new ones. The new figures are entered in this edit page and then submitted. A series of four sets of previous generations are saved in identical tables, which are also graphed on the same main page. A JS div slider script allows the user to compare among 5 generations of separate graphs in the same space. A trigger built into MySql allows each new set to be passed on to older sets, 5 gen deep. Without getting into too many details, the trigger is written so that it is activated if two specific fields in the form are different from the previous. Thus allowing mistakes to be corrected without activating the trigger. With me so far? My question does not concern the structure of the thing, it works fine, but just one problem that does not seem to be available on SO or any other google search result. Specifically, in the case that the edit form is used to enter a brand new set of numbers, how could you use a reset button that activates  a script that clears all the old figures from the inputs? I've found numerous answers on SO that use either pure JS or JQuery, but they are not used on PHP forms, rather HMTL forms. Some posters point out that this is anyhow not possible, as edit forms contain DB values cannot be replaced unless the SUBMIT button is used. This simple device is to make entry of new figures easier when they are empty, but I haven't found any scripts so far that succeed in clearing them. The simple reset code that works in HTML forms but in my php one:

```<code>   <script>function resetform() {
   document.getElementById("myform").reset();}</script>

   <form action="" method="post" id="myform">

   <input value="RESET" onclick="resetform()">
</code>```

答:
Like j08691 said, you might wish to brush up on your information on what PHP is and what it does.

It creates a HTML page and once it's created, it doesn't "touch" it anymore. It's done, finito. The only way for PHP to "modify" the page is to create (reload) it again.

If you wish to interact with a ready, loaded HTML page - such as a form with values inputed in the fields, you will have to use another technology like Javascript.

Now, if your problem is the "echo $var" -part - you could avoid populating the form fields with values by either emptying the $var (in which case the value would be '' like in your empty form) or having some kind of "toggle" which sniffs if you wish to print old values or have empty ones like:

```<code>$echo ($want_empty_form ? '' : $var);
</code>```

... in which case you somehow, with a GET or POST parameter perhaps, tell the form at load time you want a empty form, leading to...

```<code>$want_empty_form = true;
</code>```

... and thus the form fields to being empty.

Body:
I have a DB-based AMCharts form/page that graphs figures that are entered in a separate edit form accessed from that main page. This latter php edit form is set up to always bring up the present set of entries in every field. This edit form serves two purposes: one is to be able to correct earlier mistakes, and the other is to enter a whole set of new ones. The new figures are entered in this edit page and then submitted. A series of four sets of previous generations are saved in identical tables, which are also graphed on the same main page. A JS div slider script allows the user to compare among 5 generations of separate graphs in the same space. A trigger built into MySql allows each new set to be passed on to older sets, 5 gen deep. Without getting into too many details, the trigger is written so that it is activated if two specific fields in the form are different from the previous. Thus allowing mistakes to be corrected without activating the trigger. With me so far? My question does not concern the structure of the thing, it works fine, but just one problem that does not seem to be available on SO or any other google search result. Specifically, in the case that the edit form is used to enter a brand new set of numbers, how could you use a reset button that activates  a script that clears all the old figures from the inputs? I've found numerous answers on SO that use either pure JS or JQuery, but they are not used on PHP forms, rather HMTL forms. Some posters point out that this is anyhow not possible, as edit forms contain DB values cannot be replaced unless the SUBMIT button is used. This simple device is to make entry of new figures easier when they are empty, but I haven't found any scripts so far that succeed in clearing them. The simple reset code that works in HTML forms but in my php one:

   <form action="" method="post" id="myform">

   <input value="RESET" onclick="resetform()">

Body:
Like j08691 said, you might wish to brush up on your information on what PHP is and what it does.

It creates a HTML page and once it's created, it doesn't "touch" it anymore. It's done, finito. The only way for PHP to "modify" the page is to create (reload) it again.

If you wish to interact with a ready, loaded HTML page - such as a form with values inputed in the fields, you will have to use another technology like Javascript.

Now, if your problem is the "echo $var" -part - you could avoid populating the form fields with values by either emptying the $var (in which case the value would be '' like in your empty form) or having some kind of "toggle" which sniffs if you wish to print old values or have empty ones like:

$echo ($want_empty_form ? '' : $var);

... in which case you somehow, with a GET or POST parameter perhaps, tell the form at load time you want a empty form, leading to...

$want_empty_form = true;

... and thus the form fields to being empty.


问:
Animate div from center of it
I have a div that pops up when a certain action appears. Instead of just popping up, I animated it so it appears to grow in size when the event happens. This is nice and all, but I would like it to instead of animating from the top left corner of the div, I want it to animate from either the center of the div, or the center-top of the div. How would I achieve this by using just Javascript and jQuery?

Below is what I have as of now.

var newsPopup = $('#news-container');
slideIntoHub(newsPopup);

// Slides any HTML object into the hub by animations
function slideIntoHub(object) {
    removeHubContents();
    object.css({'height' : '0', 'width' : '0'});
    object.appendTo('#hub');
    object.animate({width: '500', height: '200'}, 1000);
}
// Removes everything from #hub
function removeHubContents() {
    var hub = $('#hub');
    hub.children().each(function() {
        $(this).detach();
    });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#news-container {
    background-color: white;
    border: 15px gray outset;
    border-radius: 50px;
    padding: 10px;
}
.news-firstRow {
    width: 100%;
    display: inline-block;
}
.news-icon {
    display: inline-block;
    margin: 0 auto;
    padding-right: 50px;
    vertical-align: middle;
}
.news-title {
    display: inline-block;
    margin: 0 auto;
    vertical-align: middle;
}
.news-secondRow {
    width: 100%;
    display: inline-block;
}
.news-thirdRow {
    width: 100%;
    display: inline-block;
}
.news-publishedDate {
    float: right;
    padding-bottom: 10px;
    font-size: 7px;
}</code>```

Sales booming

The team is coming up with more products everyday

Published on: 3-29-2017

```

答:
you could try this. heres the fiddle http://jsfiddle.net/FQwYJ/260/ . This makes the animation start at the top center.

```<code>object.css({'height' : '0', 'width' : '0', 'margin-left':'250px'});
object.appendTo('#hub');
object.animate({width: '500', height: '200','margin-left':'0'},
</code>```

the following animates from center of the div itself. http://jsfiddle.net/FQwYJ/261/

```<code>object.css({'height' : '0', 'width' : '0', 'margin-
left':'250px','margin-top':'100px'});
object.appendTo('#hub');
object.animate({width: '500', height: '200','margin-left':'0','margin-
top':'0'}, 1000);
</code>```

you could take your pick of which one to use.

Title: Animate div from center of it

Body:
I have a div that pops up when a certain action appears. Instead of just popping up, I animated it so it appears to grow in size when the event happens. This is nice and all, but I would like it to instead of animating from the top left corner of the div, I want it to animate from either the center of the div, or the center-top of the div. How would I achieve this by using just Javascript and jQuery?

Below is what I have as of now.

var newsPopup = $('#news-container');
slideIntoHub(newsPopup);

// Slides any HTML object into the hub by animations
function slideIntoHub(object) {
    removeHubContents();
    object.css({'height' : '0', 'width' : '0'});
    object.appendTo('#hub');
    object.animate({width: '500', height: '200'}, 1000);
}
// Removes everything from #hub
function removeHubContents() {
    var hub = $('#hub');
    hub.children().each(function() {
        $(this).detach();
    });
}

#news-container {
    background-color: white;
    border: 15px gray outset;
    border-radius: 50px;
    padding: 10px;
}
.news-firstRow {
    width: 100%;
    display: inline-block;
}
.news-icon {
    display: inline-block;
    margin: 0 auto;
    padding-right: 50px;
    vertical-align: middle;
}
.news-title {
    display: inline-block;
    margin: 0 auto;
    vertical-align: middle;
}
.news-secondRow {
    width: 100%;
    display: inline-block;
}
.news-thirdRow {
    width: 100%;
    display: inline-block;
}
.news-publishedDate {
    float: right;
    padding-bottom: 10px;
    font-size: 7px;
}

Sales booming

The team is coming up with more products everyday

Published on: 3-29-2017

Body:
you could try this. heres the fiddle http://jsfiddle.net/FQwYJ/260/ . This makes the animation start at the top center.

object.css({'height' : '0', 'width' : '0', 'margin-left':'250px'});
object.appendTo('#hub');
object.animate({width: '500', height: '200','margin-left':'0'},

the following animates from center of the div itself. http://jsfiddle.net/FQwYJ/261/

object.css({'height' : '0', 'width' : '0', 'margin-
left':'250px','margin-top':'100px'});
object.appendTo('#hub');
object.animate({width: '500', height: '200','margin-left':'0','margin-
top':'0'}, 1000);

you could take your pick of which one to use.


问:
C# Replace all characters in string with value of character key in dictionary
hi i have this dictionary

```<code>Dictionary<char, string> keys = new Dictionary<char, string>();
keys.Add("a", "23");
keys.Add("A", "95");
keys.Add("d", "12");
keys.Add("D", "69");
</code>```

and for example this string

```<code>string text = "Dad";
</code>```

i want to encrypt the string with dictionary keys and values!

the final encrypted string will be:

692312

anyone can  help?!

答:
If your plaintext is quite large, you might also find it more performant to use a StringBuilder, instead of plain string concatenation.</p>

```<code>StringBuilder cyphertext = new StringBuilder();

foreach(char letter in text)
{
    cyphertext.Append(keys[letter]);
}
</code>```

Body:
hi i have this dictionary

Dictionary<char, string> keys = new Dictionary<char, string>();
keys.Add("a", "23");
keys.Add("A", "95");
keys.Add("d", "12");
keys.Add("D", "69");

and for example this string

string text = "Dad";

i want to encrypt the string with dictionary keys and values!

the final encrypted string will be:

692312

anyone can  help?!

Body:
If your plaintext is quite large, you might also find it more performant to use a StringBuilder, instead of plain string concatenation.

StringBuilder cyphertext = new StringBuilder();

foreach(char letter in text)
{
    cyphertext.Append(keys[letter]);
}


问:
how to send data rapidly between a service and an activty
how can i send data from a service to an activity if that activity is running without restarting service or activity. actually i have a Asynctask class inside my service that downloads a file and i wanna show the percentage of downloading on a Progress-bar inside an activity . can any one tell me how should i do that?
i tried interface in asynctask but it make a new request and my progress bar is null.

```<code>public class Downloader extends AsyncTask<Combine,String,Combine> {
Responcer1 responder;
HttpURLConnection connection;
int id;
int position;

public Downloader(int position){
    this.position=position;
}
@Override
protected void onPreExecute() {
    super.onPreExecute();

    responder=new SavedLinks();
    responder.start(position);
}

@Override
protected Combine doInBackground(Combine... param) {

    try {
        int position=param[0].position;
        Log.i("downloader",param[0].caption+param[0].link+param[0].url+param[0].user);
        id=param[0].id;

        connection = null;
        URL url;
        url = new URL(param[0].link);
        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(45000);
        connection.setReadTimeout(5000);
        InputStream in = connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");}
        in.close();
        connection.disconnect();
        return saperate(sb.toString(),param[0]);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }}
</code>```

}

答:
Well you don't need to actually send it all that frequently.  Every couple of seconds is good enough for a progress bar.  But ignoring that, there's a couple of good solutions:

1)Broadcast the status from the Service and use a BroadcastReceiver in the Activity

2)Bind to the service and pass in a status callback to the Service to call back to your activity

3)Use an EventBus for message passing of status

2 and 3 require the service to be in the same process, but since that's the default they're probably ok.

Body:
how can i send data from a service to an activity if that activity is running without restarting service or activity. actually i have a Asynctask class inside my service that downloads a file and i wanna show the percentage of downloading on a Progress-bar inside an activity . can any one tell me how should i do that?
i tried interface in asynctask but it make a new request and my progress bar is null.

public class Downloader extends AsyncTask<Combine,String,Combine> {
Responcer1 responder;
HttpURLConnection connection;
int id;
int position;

public Downloader(int position){
    this.position=position;
}
@Override
protected void onPreExecute() {
    super.onPreExecute();

    responder=new SavedLinks();
    responder.start(position);
}

@Override
protected Combine doInBackground(Combine... param) {

    try {
        int position=param[0].position;
        Log.i("downloader",param[0].caption+param[0].link+param[0].url+param[0].user);
        id=param[0].id;

        connection = null;
        URL url;
        url = new URL(param[0].link);
        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(45000);
        connection.setReadTimeout(5000);
        InputStream in = connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");}
        in.close();
        connection.disconnect();
        return saperate(sb.toString(),param[0]);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }}

}


问:
Are IceCandidate and SDP static?
Are IceCandidate and SDP fixed values? Is this a good idea to store them in a server database instead of retrieving on every connection? If updating these data is unavoidable, when should I do it?</p>

答: No they are not. Ice candidates contain end point's IP and port combination which can change. Even if you have a static IP address a new port number is generated every time. </p>

Title: Are IceCandidate and SDP static?


问:
Set JSON values dynamically?
Can I do something like this:

```<code>var number = 0;
var values = ["my_component_state_0", "my_component_state_1"];

      this.setState({
          values[number]: evt.target.value
      });
</code>```

instead of writing out:

```<code>      this.setState({
        my_component_state_0: evt.target.value
      });
</code>```

?

I need to iterate through some things and something like this would be useful. But it seems too hacky, and it also doesn't seem to work - or does it? (or something like this)

答:
You can create the object dynamically:

```<code>var obj    = {},
    number = 0,
    values = ["my_component_state_0", "my_component_state_1"];

 obj[ values[number] ] = evt.target.value;   // dynamic key creation
</code>```

With this principle, you can loop over any array to dynamically create any number of the keys, but make sure you want to assign evt.target.value to all.

Demo

function example(evt) {
  // for demo:
  this.setState = function(obj) { console.log(obj); };

  // object setup
  var state_obj = {},
      number    = 0,
      values    = ["my_component_state_0", "my_component_state_1"];

  // assign the value for a dynamic key
  state_obj[ values[number] ] = evt.target.value;

  // set the state
  this.setState( state_obj );
}

example({
  target: {
    value: 'foo'
  }
});```

Title: Set JSON values dynamically?

Body:
Can I do something like this:

var number = 0;
var values = ["my_component_state_0", "my_component_state_1"];

      this.setState({
          values[number]: evt.target.value
      });

instead of writing out:

      this.setState({
        my_component_state_0: evt.target.value
      });

?

I need to iterate through some things and something like this would be useful. But it seems too hacky, and it also doesn't seem to work - or does it? (or something like this)

Body:
You can create the object dynamically:

var obj    = {},
    number = 0,
    values = ["my_component_state_0", "my_component_state_1"];

 obj[ values[number] ] = evt.target.value;   // dynamic key creation

With this principle, you can loop over any array to dynamically create any number of the keys, but make sure you want to assign evt.target.value to all.

Demo

function example(evt) {
  // for demo:
  this.setState = function(obj) { console.log(obj); };

  // object setup
  var state_obj = {},
      number    = 0,
      values    = ["my_component_state_0", "my_component_state_1"];

  // assign the value for a dynamic key
  state_obj[ values[number] ] = evt.target.value;

  // set the state
  this.setState( state_obj );
}

example({
  target: {
    value: 'foo'
  }
});


问:
Adding comma separators to numbers, asp.net
I'm trying to add comma separators to a number. I've tried the advice here: add commas using String.Format for number and and here: .NET String.Format() to add commas in thousands place for a number but I can't get it to work - they just return the number without commas. The code I'm using is here:

 public static string addCommas(string cash) {
 return string.Format("{0:n0}", cash).ToString();

 }

Where am I going wrong?

Thanks.

Update: Hi all, thanks for your help, but all of those methods are returning the same error: "error CS1502: The best overloaded method match for 'BishopFlemingFunctions.addCommas(int)' has some invalid arguments" (or variations therof depending on what number type I'm using.) Any ideas?

答: In order to apply number formatting you have to pass cash as a number type (int, double, float etc)


问:
Extracting numbers and slashes from a string
I have the following string

```<code>Policy 023203232/02/05 saved successfully
</code>```

And I need to extract 023203232/02/05 from the above string and I have written the following code

```<code>puts a[/\d+\/\d+\/\d+/]
</code>```

And it works fine. But If the number increases with the slashes like, 023203232/02/05/06 I have to include one more \d+ but I don't know how many slashes and number would repeat this way, So any one can suggest me to write some generic solution

If string is

```<code>Policy 023203232/02/05 saved successfully
</code>```

Then

```<code>023203232/02/05
</code>```

If string is

```<code>Policy 023203232/02/05/06 saved successfully
</code>```

Then

```<code>023203232/02/05/06
</code>```

If string is

```<code>Policy 023203232/02/05/06/08 saved successfully
</code>```

Then

```<code>023203232/02/05/06/08
</code>```

How to write such a generic regular expression?

Body:
I have the following string

Policy 023203232/02/05 saved successfully

And I need to extract 023203232/02/05 from the above string and I have written the following code

puts a[/\d+\/\d+\/\d+/]

And it works fine. But If the number increases with the slashes like, 023203232/02/05/06 I have to include one more \d+ but I don't know how many slashes and number would repeat this way, So any one can suggest me to write some generic solution

If string is

Policy 023203232/02/05 saved successfully

Then

023203232/02/05

If string is

Policy 023203232/02/05/06 saved successfully

Then

023203232/02/05/06

If string is

Policy 023203232/02/05/06/08 saved successfully

Then

023203232/02/05/06/08

How to write such a generic regular expression?

Body:
This regex should be what you're looking for :

/(\d+\/?)+/

It means :

At least one pattern of :

at least one digit

possibly followed by a /

It should be a bit more robust than the other answers :

"Policy 023203232/02/05/06/08 saved successfully"[/(\d+\/?)+/]
# => "023203232/02/05/06/08"
"Policy 023203232/02/05/07/3434343/56 saved successfully 09/56/32"[/(\d+\/?)+/]
# => "023203232/02/05/07/3434343/56"
"Policy // // 023203232/02/05/07/3434343/56 saved successfully 09/56/32"[/(\d+\/?)+/]
# => "023203232/02/05/07/3434343/56"

If you want to make sure that the number is right after 'Policy ' but don't want to have 'Policy ' inside your match, you can use a positive look-behind :

/(?<=Policy )(\d+\/?)+/

Here in action :

"2017/03/31 Policy 023203232/02/05/07/3434343/56 saved successfully"[/(?<=Policy )(\d+\/?)+/]
# => "023203232/02/05/07/3434343/56"


问:
How to remove file with invalid name (Ubuntu)?
By mistake I have createad file with name:

```<code>0);          if (count($keys->toArray())  0) {              $this->obj->api(messages.send, [                 access_token > $this->group->getAccessToken(),                 user_id > $this->userId,                 message > Я
</code>```

I'm not able to remove it via ssh or sftp.

Is there any way?

答:
If you have an SSH connection, you should just be able to delete this using bash auto-complete; tested and working.

```<code>rm -- 0<tab>
</code>```

Evaluates to the escape sequence:

```<code>rm -- 0\)\;\ \ \ \ \ \ \ \ \ \ if\ \(count\(-\>toArray\(\)\)\ \ 0\)\ \{\ \ \ \ \ \ \ \ \ \ \ \ \ \ -\>obj-\>api\(messages.send\,\ \[\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ access_token\ \>\ -\>group-\>getAccessToken\(\)\,\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ user_id\ \>\ -\>userId\,\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ message\ \>\ Я
</code>```

Body:
By mistake I have createad file with name:

0);          if (count($keys->toArray())  0) {              $this->obj->api(messages.send, [                 access_token > $this->group->getAccessToken(),                 user_id > $this->userId,                 message > Я

I'm not able to remove it via ssh or sftp.

Is there any way?

Body:
If you have an SSH connection, you should just be able to delete this using bash auto-complete; tested and working.

rm -- 0<tab>

Evaluates to the escape sequence:

rm -- 0\)\;\ \ \ \ \ \ \ \ \ \ if\ \(count\(-\>toArray\(\)\)\ \ 0\)\ \{\ \ \ \ \ \ \ \ \ \ \ \ \ \ -\>obj-\>api\(messages.send\,\ \[\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ access_token\ \>\ -\>group-\>getAccessToken\(\)\,\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ user_id\ \>\ -\>userId\,\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ message\ \>\ Я


答: I suggest you to use EventBus, a library written just to simplify interaction between activity, service and so on. It's quite simple to use, you can start reading quick start guide.</p>

Title: how to send data rapidly between a service and an activty


答:
Note the cash parameter is of type double and the .## at the end of the formatted string for cents.

EDIT

Here is the code in its entirety:

```<code>static class Program {
    static void Main() {
        double d = 123456789.7845;
        string s = addCommas(d);
        System.Console.WriteLine(s);
    }

    public static string addCommas(double cash) {
        return string.Format("${0:#,###0.##}", cash);
    }
}
</code>```

This prints "$123,456,789.78" to console. If you're getting

error CS1502: The best overloaded
  method match for 'addCommas(double)'
  has some invalid arguments

check to make sure that you're calling the function properly and that you're actually passing in the correct data type. I encourage you to copy/paste the code I have above and run it - BY ITSELF.

Title: Adding comma separators to numbers, asp.net

Body:
I'm trying to add comma separators to a number. I've tried the advice here: add commas using String.Format for number and and here: .NET String.Format() to add commas in thousands place for a number but I can't get it to work - they just return the number without commas. The code I'm using is here:

 public static string addCommas(string cash) {
 return string.Format("{0:n0}", cash).ToString();

 }

Where am I going wrong?

Thanks.

Update: Hi all, thanks for your help, but all of those methods are returning the same error: "error CS1502: The best overloaded method match for 'BishopFlemingFunctions.addCommas(int)' has some invalid arguments" (or variations therof depending on what number type I'm using.) Any ideas?

Body:
Note the cash parameter is of type double and the .## at the end of the formatted string for cents.

EDIT

Here is the code in its entirety:

static class Program {
    static void Main() {
        double d = 123456789.7845;
        string s = addCommas(d);
        System.Console.WriteLine(s);
    }

    public static string addCommas(double cash) {
        return string.Format("${0:#,###0.##}", cash);
    }
}

This prints "$123,456,789.78" to console. If you're getting

error CS1502: The best overloaded
  method match for 'addCommas(double)'
  has some invalid arguments

check to make sure that you're calling the function properly and that you're actually passing in the correct data type. I encourage you to copy/paste the code I have above and run it - BY ITSELF.


问:
Clarify the use of bind in this context?
Can someone help explain what is the use of bind in this context is?

```<code><button onClick={this.add.bind(null, 'Bacon tuna')} className="button-info-create">Add New</button>
</code>```

https://youtu.be/OKRu7i49X54?list=PL6gx4Cwl9DGBuKtLgPR_zWYnrwv-JllpA&t=3m3s

From what I understand, when null passed to bind, this refers to the global scope. Yet somehow it is seems to be referring to the Board instance.

答:
React.createClass() will automatically bind this values correctly for us, but changes when using ES6 classes affect this, source

This is the reason why on the video, bind(null, 'something') could be used even if add() method is using this.setState(). If you try to use bind(null, ...) with extends React.Component instead of React.createClass, it will not work.

If you open the source link, you can read very detailed and longer explanation by Todd Motto.

Body:
Can someone help explain what is the use of bind in this context is?

<button onClick={this.add.bind(null, 'Bacon tuna')} className="button-info-create">Add New</button>

https://youtu.be/OKRu7i49X54?list=PL6gx4Cwl9DGBuKtLgPR_zWYnrwv-JllpA&t=3m3s

From what I understand, when null passed to bind, this refers to the global scope. Yet somehow it is seems to be referring to the Board instance.


问:
Issue activating a generic type with generic array in constructor parameters
I have a very strange issue with the following code:

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

namespace ConsoleApp1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var testTuples1 = GimeStringTuples("foo", "bar");
            var testTuples2 = GimeTuples("foo", "bar");
            Console.ReadKey();
        }

        public static object GimeStringTuples(params string[] values)
        {
            Type genericType = Type.GetType("System.Tuple`" + values.Length);
            Type[] typeArgs = values.Select(_ => typeof(string)).ToArray();
            Type specificType = genericType.MakeGenericType(typeArgs);
            return Activator.CreateInstance(specificType, values);
        }

        public static object GimeTuples<T>(params T[] values)
        {
            Type genericType = Type.GetType("System.Tuple`" + values.Length);
            Type[] typeArgs = values.Select(_ => typeof(T)).ToArray();
            Type specificType = genericType.MakeGenericType(typeArgs);

            dynamic result;
            string[] testArgs = { "foo", "bar" };
            result = Activator.CreateInstance(specificType, testArgs);
            result = Activator.CreateInstance(specificType, values);
            return result;
        }
    }
}
</code>```

It's failing on the second to last line:

```<code>result = Activator.CreateInstance(specificType, values);
</code>```

This is weird since it's basically identical to the line that executes just before it:

```<code>result = Activator.CreateInstance(specificType, testArgs);
</code>```

In both cases, the same argument is being passed as the specificType parameter and a string[2] is being passed as the second parameter.

And the GimeStringTuples method works just fine... although there are no generics involved there - which is maybe the hint.

Can anyone explain this unusual behaviour?

答:
OK so the solution (thanks to @thehennyy):

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

namespace ConsoleApp1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var testTuple = GimeTuples("foo", "bar");
            Console.WriteLine(testTuple);
            Console.ReadKey();
        }

        public static object GimeTuples<T>(params T[] values)
        {
            Type genericType = Type.GetType("System.Tuple`" + values.Length);
            Type[] typeArgs = values.Select(_ => typeof(T)).ToArray();
            Type specificType = genericType.MakeGenericType(typeArgs);
            object[] constructorArguments = values.Cast<object>().ToArray();
            return Activator.CreateInstance(specificType, constructorArguments);
        }
    }
}
</code>```

This forces the compiler to pass the generic array elements as params rather than passing the whole array as a single param.

Body:
I have a very strange issue with the following code:

using System;
using System.Linq;

namespace ConsoleApp1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var testTuples1 = GimeStringTuples("foo", "bar");
            var testTuples2 = GimeTuples("foo", "bar");
            Console.ReadKey();
        }

        public static object GimeStringTuples(params string[] values)
        {
            Type genericType = Type.GetType("System.Tuple`" + values.Length);
            Type[] typeArgs = values.Select(_ => typeof(string)).ToArray();
            Type specificType = genericType.MakeGenericType(typeArgs);
            return Activator.CreateInstance(specificType, values);
        }

        public static object GimeTuples<T>(params T[] values)
        {
            Type genericType = Type.GetType("System.Tuple`" + values.Length);
            Type[] typeArgs = values.Select(_ => typeof(T)).ToArray();
            Type specificType = genericType.MakeGenericType(typeArgs);

            dynamic result;
            string[] testArgs = { "foo", "bar" };
            result = Activator.CreateInstance(specificType, testArgs);
            result = Activator.CreateInstance(specificType, values);
            return result;
        }
    }
}

It's failing on the second to last line:

result = Activator.CreateInstance(specificType, values);

This is weird since it's basically identical to the line that executes just before it:

result = Activator.CreateInstance(specificType, testArgs);

In both cases, the same argument is being passed as the specificType parameter and a string[2] is being passed as the second parameter.

And the GimeStringTuples method works just fine... although there are no generics involved there - which is maybe the hint.

Can anyone explain this unusual behaviour?

Body:
OK so the solution (thanks to @thehennyy):

using System;
using System.Linq;

namespace ConsoleApp1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var testTuple = GimeTuples("foo", "bar");
            Console.WriteLine(testTuple);
            Console.ReadKey();
        }

        public static object GimeTuples<T>(params T[] values)
        {
            Type genericType = Type.GetType("System.Tuple`" + values.Length);
            Type[] typeArgs = values.Select(_ => typeof(T)).ToArray();
            Type specificType = genericType.MakeGenericType(typeArgs);
            object[] constructorArguments = values.Cast<object>().ToArray();
            return Activator.CreateInstance(specificType, constructorArguments);
        }
    }
}

This forces the compiler to pass the generic array elements as params rather than passing the whole array as a single param.


问:
How to Determine Which Dll Dependency is Failing to Load in Windows Store/Universal Apps?
When running a UWP project I'm working on I receive the following dialog.

"Unable to activate Windows Store app 'MyAppsMangledName'. The 'MyExeName' process started, but the activation request failed with error 'The App didn't start'."

The Visual Studio output has the following.

The thread 0x3d4c has exited with code -1073741515 (0xc0000135).
The thread 0x3b50 has exited with code -1073741515 (0xc0000135).
The program 'MyExeName' has exited with code -1073741515 (0xc0000135) 'A dependent dll was not found'.

The Event Viewer has 3 events that basically restate the popup dialog in 3 different ways and nothing else.

Running Process Monitor during the startup shows me many dlls being successfully loaded but nothing indicating failure besides some NAMENOTFOUND events which unfortunately don't show what name wasn't found.

In Win32 a helpful dialog usually indicates which dll could not be loaded. And of course with .Net apps the fusion logs make tracing this very straight forward. But for Store/UWP apps I can't seem to find a good way to track down the offending dependency.

答:
This just hit me too on a project I'm working on. And after much digging, someone on my team was able to figure it out. So figured I'd share it for others struggling with the same issue.

We're doing UWP with C++ using VS2015. So with that in mind, there is a program called gflags located for me at C:\program Files (x86)\Windows Kits 10\Debuggers\x64\gflags.exe

So you'll want a cmd window with admin, and run the command gflags.exe -i your-program-name.exe +sls

Note: gflags wasn't in my path so either add the path or navigate to where it is before executing the command.

Just pass in the name of the exe without directories. What it does is sets a registry setting for VS that turns on sls (show loader snaps) for exe's matching that name. Then run your application in VS and and you'll get a large amount of dll loading information including names of the dlls that fail to load in your output window. In our case it was this:

5038:34f4 @ 789320468 - LdrpProcessWork - ERROR: Unable to load DLL: "vccorlib140d_app.DLL", Parent Module: "E:\projects---\Source\Builds\vs2015_Debug_UWP_x64\AppX---.exe", Status: 0xc0000135

Another quicker alternative way to test this (YMMV) was to compare the output with another build config that does work. In our case, we can run release builds just fine, but debug builds barf. And the release output showed vccorlib140_app.dll loaded while the debug had it missing.


问:
Calling service from Html
i want to call asp.net web service from java script and pass the parameters to it .is there any code sample or demostration  that will help me to acheive that??
thanks in advance</p>

答:
You can do so, using AJAX, and get the response from the server as an JSON object.

```<code>    var xmlHttp = new ActiveXObject("Microsoft.XmlHttp");
    var url = "Service1.svc/ajaxEndpoint/";
    url = url + "Sum2Integers";
    var body = '{"n1":';
    body = body + document.getElementById("num1").value + ',"n2":';
    body = body + document.getElementById("num2").value + '}';

    // Send the HTTP request
    xmlHttp.open("POST", url, true);
    xmlHttp.setRequestHeader("Content-type", "application/json");
    xmlHttp.send(body);

    // Create result handler
    xmlHttp.onreadystatechange= function X()
    {

         if(xmlHttp.readyState == 4)
         {
              result.innerText = xmlHttp.responseText;
         }
    }
</code>```

Getting the response as JSON would help you evualte it asn object and u can act on it through JavaScript.

See these links for reference:
http://blogs.msdn.com/b/alikl/archive/2008/02/18/how-to-consume-wcf-using-ajax-without-asp-net.aspx

http://dotnetslackers.com/articles/ajax/JSON-EnabledWCFServicesInASPNET35.aspx

Title: Calling service from Html

Body:
You can do so, using AJAX, and get the response from the server as an JSON object.

    var xmlHttp = new ActiveXObject("Microsoft.XmlHttp");
    var url = "Service1.svc/ajaxEndpoint/";
    url = url + "Sum2Integers";
    var body = '{"n1":';
    body = body + document.getElementById("num1").value + ',"n2":';
    body = body + document.getElementById("num2").value + '}';

    // Send the HTTP request
    xmlHttp.open("POST", url, true);
    xmlHttp.setRequestHeader("Content-type", "application/json");
    xmlHttp.send(body);

    // Create result handler
    xmlHttp.onreadystatechange= function X()
    {

         if(xmlHttp.readyState == 4)
         {
              result.innerText = xmlHttp.responseText;
         }
    }

Getting the response as JSON would help you evualte it asn object and u can act on it through JavaScript.

See these links for reference:
http://blogs.msdn.com/b/alikl/archive/2008/02/18/how-to-consume-wcf-using-ajax-without-asp-net.aspx

http://dotnetslackers.com/articles/ajax/JSON-EnabledWCFServicesInASPNET35.aspx


问:
C - Passing an array between functions gets different values
So I'm trying to write a function that'll search a word in a 2D bulk.
The function returns an (int) array of size [3] with values as the answer.
Here is my main() function:

```<code>void main() {
    char bulk[L][L];
    for (int i = 0; i < L; i++) {
        for (int j = 0;j < L;j++)
            scanf_s(" %c", &bulk[i][j]);
    }
    int *arr = search(&bulk, L, "bc");
    printf("ARR: %d, %d, %d\n", arr[0], arr[1], arr[2]);
}
</code>```

And here's the search() function:

```<code>int *search(char(*bulk)[L], int size, char *word) {
    int arr[3] = { 0,0,0 };
    int flag = 9;
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            if (bulk[i][j] == *word) {
                if (checkRight(bulk, i, j, word)) flag=0;
            }
            if (flag != 9) {
                arr[0] = i;
                arr[1] = j;
                arr[2] = flag;
                printf("ARR: %d, %d, %d\n", arr[0], arr[1], arr[2]);
                return arr;
            }
        }
    }
    return arr;
}
</code>```

The checkRight() function works well, it returns 0/1 for if the word exists to the right. The problem is that the two printf's are printing different values.

Output for search(): "ARR: 0,1,0".

Output for main(): "ARR: -858993460, -858993460, 0".

I assume it's pointer-related but I'm struggling with finding the problem. Any ideas?

Thanks a bunch!

答:
```<code>return arr;
</code>```

In here you are returning the address of the first value in the array, this address points to a temporary value inside the stack frame of the function search.

try to pass arr as a parameter or using "static int arr[3]" in order to make the array not temporary.

Body:
So I'm trying to write a function that'll search a word in a 2D bulk.
The function returns an (int) array of size [3] with values as the answer.
Here is my main() function:

void main() {
    char bulk[L][L];
    for (int i = 0; i < L; i++) {
        for (int j = 0;j < L;j++)
            scanf_s(" %c", &bulk[i][j]);
    }
    int *arr = search(&bulk, L, "bc");
    printf("ARR: %d, %d, %d\n", arr[0], arr[1], arr[2]);
}

And here's the search() function:

int *search(char(*bulk)[L], int size, char *word) {
    int arr[3] = { 0,0,0 };
    int flag = 9;
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            if (bulk[i][j] == *word) {
                if (checkRight(bulk, i, j, word)) flag=0;
            }
            if (flag != 9) {
                arr[0] = i;
                arr[1] = j;
                arr[2] = flag;
                printf("ARR: %d, %d, %d\n", arr[0], arr[1], arr[2]);
                return arr;
            }
        }
    }
    return arr;
}

The checkRight() function works well, it returns 0/1 for if the word exists to the right. The problem is that the two printf's are printing different values.

Output for search(): "ARR: 0,1,0".

Output for main(): "ARR: -858993460, -858993460, 0".

I assume it's pointer-related but I'm struggling with finding the problem. Any ideas?

Thanks a bunch!

Body:
return arr;

In here you are returning the address of the first value in the array, this address points to a temporary value inside the stack frame of the function search.

try to pass arr as a parameter or using "static int arr[3]" in order to make the array not temporary.


问:
Configure specific in memory database for testing purpose in Spring
How do I configure my Spring Boot application so that when I run unit tests it will use in-memory database such as H2/HSQL but when I run Spring Boot application it will use production database PostgreSQL/MySQL ?

答:
Simplest solution:

1) in src/main/resources have application.properties (production config):

```<code>spring.datasource.url=jdbc:mysql://localhost:3306/somedb
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect
</code>```

and application-test.properties with HSQL config like:

```<code>spring.jpa.hibernate.ddl-auto = create-drop
spring.jpa.database = HSQL
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.HSQLDialect
spring.datasource.driverClassName = org.hsqldb.jdbcDriver
spring.datasource.url= jdbc:hsqldb:mem:scratchdb
spring.datasource.username = sa
spring.datasource.password =
</code>```

2) Add HSQL dependency in pom.xml if you don't have it already.

3) Annotate your test class with @ActiveProfiles("test").

Worked like charm in my case.

Body:
Simplest solution:

1) in src/main/resources have application.properties (production config):

spring.datasource.url=jdbc:mysql://localhost:3306/somedb
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect

and application-test.properties with HSQL config like:

spring.jpa.hibernate.ddl-auto = create-drop
spring.jpa.database = HSQL
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.HSQLDialect
spring.datasource.driverClassName = org.hsqldb.jdbcDriver
spring.datasource.url= jdbc:hsqldb:mem:scratchdb
spring.datasource.username = sa
spring.datasource.password =

2) Add HSQL dependency in pom.xml if you don't have it already.

3) Annotate your test class with @ActiveProfiles("test").

Worked like charm in my case.


问:
How to add a primary key to a MySQL table?
This is what I tried but it fails:

```<code>alter table goods add column `id` int(10) unsigned primary AUTO_INCREMENT;
</code>```

Does anyone have a tip?

答:
Not sure if this matters to anyone else, but I prefer the id for the table to be the first column in the database. The syntax for that is:

```<code>ALTER TABLE your_db.your_table ADD COLUMN `id` int(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT FIRST;
</code>```

Which is just a slight improvement over the first answer. If you wanted it to be in a different position, then

```<code>ALTER TABLE unique_address ADD COLUMN `id` int(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT AFTER some_other_column;
</code>```

HTH,
-ft

Body:
This is what I tried but it fails:

alter table goods add column `id` int(10) unsigned primary AUTO_INCREMENT;

Does anyone have a tip?

Body:
Not sure if this matters to anyone else, but I prefer the id for the table to be the first column in the database. The syntax for that is:

ALTER TABLE your_db.your_table ADD COLUMN `id` int(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT FIRST;

Which is just a slight improvement over the first answer. If you wanted it to be in a different position, then

ALTER TABLE unique_address ADD COLUMN `id` int(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT AFTER some_other_column;

HTH,
-ft


问:
GIT clone branch to older commit in another directory
I have 2 directories of the same project, let call them directories A and B.

These two folder were cloned from a master git repo in another location, so they both started out with the same git repo commit.

Now A stayed with the original code and fixed a few minor bugs, and commited the changes, so A git branch looks like this:

```<code>A: (original)-(bug fix 1) - (bug fix 2) - (bug fix 3)
</code>```

While B, I decided to change the look of the application but I havent commited yet. so B git branch looks like this:

```<code>B: (original)
</code>```

What I would like to do is merge these 2 git repos from the original clone so I can have the following:

```<code>A: (original)-(bug fix 1) - (bug fix 2) - (bug fix 3)--------(merge both)

           \                                                    /
branch B:   \ -----------------(New version look) -------------
</code>```

答:
Hello I have 2 directories of the same project, let call them directories A and B. These two folder were cloned from a master git repo in another location,

Instead of cloning the repositories use

git worktree

Git worktree was introduced in 2007 under the contrib folder in git repo and was called new-workdir. In git v2.5 is was renamed to worktree.

The most simple syntax is this:

```<code>git worktree add <second path>/<branch name>
</code>```

will create another folder on your computer which allow you to work on different branches simultaneously.

git worktree will create 2 separate working folders separated from each other while pointing to the same repository.

This will allow you do to any experimentals on the new worktree without having any effect on the repository itself. In the attached image you can see that there are 2 separate working folder but both of them are using a single repo and share the content.

Here is a sample on how to create new worktree and what is the result of it:

What I would like to do is merge these 2 git repos from the original clone so I can have the following...

Now since you are working on the same repository you can merge,cherry-pick without pulling or pushing to the remote since you dont need to use the remote.

its all local !!!

Body:
I have 2 directories of the same project, let call them directories A and B.

These two folder were cloned from a master git repo in another location, so they both started out with the same git repo commit.

Now A stayed with the original code and fixed a few minor bugs, and commited the changes, so A git branch looks like this:

A: (original)-(bug fix 1) - (bug fix 2) - (bug fix 3)

While B, I decided to change the look of the application but I havent commited yet. so B git branch looks like this:

B: (original)

What I would like to do is merge these 2 git repos from the original clone so I can have the following:

A: (original)-(bug fix 1) - (bug fix 2) - (bug fix 3)--------(merge both)

           \                                                    /
branch B:   \ -----------------(New version look) -------------

Body:
Hello I have 2 directories of the same project, let call them directories A and B. These two folder were cloned from a master git repo in another location,

Instead of cloning the repositories use

git worktree

Git worktree was introduced in 2007 under the contrib folder in git repo and was called new-workdir. In git v2.5 is was renamed to worktree.

The most simple syntax is this:

git worktree add <second path>/<branch name>

will create another folder on your computer which allow you to work on different branches simultaneously.

git worktree will create 2 separate working folders separated from each other while pointing to the same repository.

This will allow you do to any experimentals on the new worktree without having any effect on the repository itself. In the attached image you can see that there are 2 separate working folder but both of them are using a single repo and share the content.

Here is a sample on how to create new worktree and what is the result of it:

What I would like to do is merge these 2 git repos from the original clone so I can have the following...

Now since you are working on the same repository you can merge,cherry-pick without pulling or pushing to the remote since you dont need to use the remote.

its all local !!!