问:
How do you compute the mean of integers entered by the user that are evenly divisible by a number?
So far.. I have coded this:

```<code>While True:
    div_5 = []
    x = float(input("Please input an integer(negative if you want to stop: "))
    x = int(x)
    length = len(div_5)
    total_sum = sum(div_5)
    average = total_sum/length
    if x % 5:
        div_5.append(x)
    if x < 0:
        break
print(average)
</code>```

When I run the code, It says that line 7 has a ZeroDivisionError. What am I doing wrong? I am adding x if it is divisible by 5 to the list, why is saying this?
Any tips will be helpful for I am new to python.

This is what I need to do

I have been working on this for a week, hours at a time. I can't seem to get it correct.

答:
```<code>nums = []
while True:
    x = int(input("Please input an integer(negative if you want to stop: "))

    if x < 0:
        div_5 = [x for x in nums if x % 5 == 0]
        try:
            print(sum(div_5)/float(len(div_5)))
        except ZeroDivisionError:
            print("No number divisible by 5")
        break

    nums.append(x)
</code>```

In fact, you don't need to keep numbers that aren't divisible by 5.  Here is a way with a running average that ignores zeros.

```<code>count = 0.
average = 0.
while True:
    x = int(input("Please input a positive integer(negative if you want to stop: "))

    if x < 0:
        print(average)
        break
    if x % 5 == 0 and x != 0:
        count += 1
        average = average * (count - 1)/count + (1./count) * x
</code>```

Body:
So far.. I have coded this:

While True:
    div_5 = []
    x = float(input("Please input an integer(negative if you want to stop: "))
    x = int(x)
    length = len(div_5)
    total_sum = sum(div_5)
    average = total_sum/length
    if x % 5:
        div_5.append(x)
    if x < 0:
        break
print(average)

When I run the code, It says that line 7 has a ZeroDivisionError. What am I doing wrong? I am adding x if it is divisible by 5 to the list, why is saying this?
Any tips will be helpful for I am new to python.

This is what I need to do

I have been working on this for a week, hours at a time. I can't seem to get it correct.

Body:
nums = []
while True:
    x = int(input("Please input an integer(negative if you want to stop: "))

    if x < 0:
        div_5 = [x for x in nums if x % 5 == 0]
        try:
            print(sum(div_5)/float(len(div_5)))
        except ZeroDivisionError:
            print("No number divisible by 5")
        break

    nums.append(x)

In fact, you don't need to keep numbers that aren't divisible by 5.  Here is a way with a running average that ignores zeros.

count = 0.
average = 0.
while True:
    x = int(input("Please input a positive integer(negative if you want to stop: "))

    if x < 0:
        print(average)
        break
    if x % 5 == 0 and x != 0:
        count += 1
        average = average * (count - 1)/count + (1./count) * x


来源: stackexchange

问:
Multiple enums with the same values
I have a set of constants for which I use an enum in my C# project. In some situations I need just a single value in other situations I need multiple values. I started out with using IEnumerable or a simple array of my enum type to handle multiple values. However I have recently come to need multiple values in an attribute constructor for multiple attributes which I would like to put in a const field of the class.

A simple example:

```<code>public enum Browsers {
  Firefox, Chrome, IE, Opera, Safari
}

public class SomeClass {
  [Attr(new Browsers[] { Browsers.Firefox, Browsers.Chrome })]
  public void SomeMethod() { }

  [Attr(new Browsers[] { Browsers.Firefox, Browsers.Chrome })]
  public void SomeOtherMethod() { }
}
</code>```

I would like to refactor the array of browsers out into a field in the class, however for a field to be used in an attribute constructor it must be a const field and a field with an array initialization cannot be const.

I then tried to use the FlagsAttribute on my enum so that the enum can hold multiple values. I can then make a field private const Browsers = Browsers.Firefox | Browsers.Chrome and I'm good. In this situation.

Applying the FlagsAttribute thus allowing for multiple values is not so good in a situation where I need only a single value. In those situations I will always have to first check that the enum has only a single value (I do that by checking if it is a power of 2). I find that a bit annoying. Trading maintainability in one situation for less maintainability in other situations - not ideal.

So my question is is there some smart way to get around this? I thought of making two separate enums one with FlagsAttribute and one without however I will then have to maintain all the values of the enums in two places instead of one. Again not ideal.

Have I missed something that can solve this in a way that does not trade off maintainability anywhere?

UPDATE:
What I wanted my code to look like is something like this:

```<code>public class SomeClass {
  private const Browsers[] browsers = new Browsers[] { Browsers.Firefox, Browsers.Chrome };

  [Attr(browsers)]
  public void SomeMethod() { }

  [Attr(browsers)]
  public void SomeOtherMethod() { }
}
</code>```

However that results in a compile error.

An example of a place where I use the enum with a single value only:

```<code>public void SomeMethod(Browsers browser) {
  /* When using Flags I need to verify that browser contains only a single value */
  switch(browser)
  {
    case Browsers.Firefox:
      /* do something */
      break;
    case Browsers.Chrome:
      /* do something */
      break;
    /* cases for the rest of the values */
  }

}
</code>```

My question is: can I somehow create two enums with the same values, one of which has the Flags attribute and the other not having it?

Bonus question: is there a smarter way around this that I am just not seeing?

答:
Multiple enum members may share the same associated value. The example

```<code>enum Color
{
   Red,
   Green,
   Blue,
   Max = Blue
}
</code>```

shows an enum in which two enum members—Blue and Max—have the same associated value.

ContentLicense: CC BY-SA 3.0

Title: Multiple enums with the same values

Body:
I have a set of constants for which I use an enum in my C# project. In some situations I need just a single value in other situations I need multiple values. I started out with using IEnumerable or a simple array of my enum type to handle multiple values. However I have recently come to need multiple values in an attribute constructor for multiple attributes which I would like to put in a const field of the class.

A simple example:

public enum Browsers {
  Firefox, Chrome, IE, Opera, Safari
}

public class SomeClass {
  [Attr(new Browsers[] { Browsers.Firefox, Browsers.Chrome })]
  public void SomeMethod() { }

  [Attr(new Browsers[] { Browsers.Firefox, Browsers.Chrome })]
  public void SomeOtherMethod() { }
}

I would like to refactor the array of browsers out into a field in the class, however for a field to be used in an attribute constructor it must be a const field and a field with an array initialization cannot be const.

I then tried to use the FlagsAttribute on my enum so that the enum can hold multiple values. I can then make a field private const Browsers = Browsers.Firefox | Browsers.Chrome and I'm good. In this situation.

Applying the FlagsAttribute thus allowing for multiple values is not so good in a situation where I need only a single value. In those situations I will always have to first check that the enum has only a single value (I do that by checking if it is a power of 2). I find that a bit annoying. Trading maintainability in one situation for less maintainability in other situations - not ideal.

So my question is is there some smart way to get around this? I thought of making two separate enums one with FlagsAttribute and one without however I will then have to maintain all the values of the enums in two places instead of one. Again not ideal.

Have I missed something that can solve this in a way that does not trade off maintainability anywhere?

UPDATE:
What I wanted my code to look like is something like this:

public class SomeClass {
  private const Browsers[] browsers = new Browsers[] { Browsers.Firefox, Browsers.Chrome };

  [Attr(browsers)]
  public void SomeMethod() { }

  [Attr(browsers)]
  public void SomeOtherMethod() { }
}

However that results in a compile error.

An example of a place where I use the enum with a single value only:

public void SomeMethod(Browsers browser) {
  /* When using Flags I need to verify that browser contains only a single value */
  switch(browser)
  {
    case Browsers.Firefox:
      /* do something */
      break;
    case Browsers.Chrome:
      /* do something */
      break;
    /* cases for the rest of the values */
  }

}

My question is: can I somehow create two enums with the same values, one of which has the Flags attribute and the other not having it?

Bonus question: is there a smarter way around this that I am just not seeing?

Body:
Multiple enum members may share the same associated value. The example

enum Color
{
   Red,
   Green,
   Blue,
   Max = Blue
}

shows an enum in which two enum members—Blue and Max—have the same associated value.


问:
User input upperCase and lowerCase - Java
I am attempting to take an input of A or B in either Uppercase or LowerCase to follow on through the if statement. I can't figure out how to do this. At the moment, it's only taking in UpperCase A or B. Looked around the forum and the class notes, came up with nothing. Any help would be appriciated!
I tried using toUpperCase() but don't think i am putting it in the right place. It keeps giving me an error</p>

```<code>import java.util.Scanner;

public class printNumber{
    public static void main (String[] args){
        Scanner input = new Scanner(System.in);
        System.out.println("Please select an option between A or B: ");
        char user = input.next().charAt(0);

        System.out.println("You have selected " +user+ " : ");
        if (user == 'A'){
            for(int n=1; n<=100; n++){
                if((n%2)==0)
                    System.out.println(n);
            }
        }
        else if (user =='B'){
            for (int x =1; x<=100; x=x+2){
                System.out.println(x);
            }
        }
        else
            System.out.println("Error, please try again!");
    }
}
</code>```

答:
You are calling next() method of Scanner class, which returns String, so rather than converting it into a character you can use equalsIgnoreCase() method on the input String for validation. But always check the length of the input string and show error message if the length of the string entered by user is greater than 1.

"a".equalsIgnoreCase("A") and "a".equalsIgnoreCase("a") will be always true.

Body:
I am attempting to take an input of A or B in either Uppercase or LowerCase to follow on through the if statement. I can't figure out how to do this. At the moment, it's only taking in UpperCase A or B. Looked around the forum and the class notes, came up with nothing. Any help would be appriciated!
I tried using toUpperCase() but don't think i am putting it in the right place. It keeps giving me an error

import java.util.Scanner;

public class printNumber{
    public static void main (String[] args){
        Scanner input = new Scanner(System.in);
        System.out.println("Please select an option between A or B: ");
        char user = input.next().charAt(0);

        System.out.println("You have selected " +user+ " : ");
        if (user == 'A'){
            for(int n=1; n<=100; n++){
                if((n%2)==0)
                    System.out.println(n);
            }
        }
        else if (user =='B'){
            for (int x =1; x<=100; x=x+2){
                System.out.println(x);
            }
        }
        else
            System.out.println("Error, please try again!");
    }
}


问:
Creating a textarea with auto-resize
There was another thread about this, which I've tried. But there is one problem: the textarea doesn't shrink if you delete the content. I can't find any way to shrink it to the correct size - the clientHeight value comes back as the full size of the textarea, not its contents.

The code from that page is below:

```<code>function FitToContent(id, maxHeight)
{
   var text = id && id.style ? id : document.getElementById(id);
   if ( !text )
      return;

   var adjustedHeight = text.clientHeight;
   if ( !maxHeight || maxHeight > adjustedHeight )
   {
      adjustedHeight = Math.max(text.scrollHeight, adjustedHeight);
      if ( maxHeight )
         adjustedHeight = Math.min(maxHeight, adjustedHeight);
      if ( adjustedHeight > text.clientHeight )
         text.style.height = adjustedHeight + "px";
   }
}

window.onload = function() {
    document.getElementById("ta").onkeyup = function() {
      FitToContent( this, 500 )
    };
}
</code>```

答:
Native Javascript solution without flickering in Firefox and faster than method withclientHeight...

1) Add div.textarea selector to all your selectors containing textarea. Do not forget to add box-sizing: border-box;

2) Include this script:

```<code>function resizeAll()
{
   var textarea=document.querySelectorAll('textarea');
   for(var i=textarea.length-1; i>=0; i--)
      resize(textarea[i]);
}

function resize(textarea)
{
   var div = document.createElement("div");
   div.setAttribute("class","textarea");
   div.innerText=textarea.value+"\r\n";
   div.setAttribute("style","width:"+textarea.offsetWidth+'px;display:block;height:auto;left:0px;top:0px;position:fixed;z-index:-200;visibility:hidden;word-wrap:break-word;overflow:hidden;');
   textarea.form.appendChild(div);
   var h=div.offsetHeight;
   div.parentNode.removeChild(div);
   textarea.style.height=h+'px';
}

function resizeOnInput(e)
{
   var textarea=document.querySelectorAll('textarea');
   for(var i=textarea.length-1; i>=0; i--)
      textarea[i].addEventListener("input",function(e){resize(e.target); return false;},false);
}

window.addEventListener("resize",function(){resizeAll();}, false);
window.addEventListener("load",function(){resizeAll();}, false);
resizeOnInput();
</code>```

Tested on IE11, Firefox and Chrome.

This solution creates div similar to your textarea including internal text and measures height.

OwnerDisplayName: DisgruntledGoat

Title: Creating a textarea with auto-resize

Body:
There was another thread about this, which I've tried. But there is one problem: the textarea doesn't shrink if you delete the content. I can't find any way to shrink it to the correct size - the clientHeight value comes back as the full size of the textarea, not its contents.

The code from that page is below:

function FitToContent(id, maxHeight)
{
   var text = id && id.style ? id : document.getElementById(id);
   if ( !text )
      return;

   var adjustedHeight = text.clientHeight;
   if ( !maxHeight || maxHeight > adjustedHeight )
   {
      adjustedHeight = Math.max(text.scrollHeight, adjustedHeight);
      if ( maxHeight )
         adjustedHeight = Math.min(maxHeight, adjustedHeight);
      if ( adjustedHeight > text.clientHeight )
         text.style.height = adjustedHeight + "px";
   }
}

window.onload = function() {
    document.getElementById("ta").onkeyup = function() {
      FitToContent( this, 500 )
    };
}

Body:
Native Javascript solution without flickering in Firefox and faster than method withclientHeight...

1) Add div.textarea selector to all your selectors containing textarea. Do not forget to add box-sizing: border-box;

2) Include this script:

function resizeAll()
{
   var textarea=document.querySelectorAll('textarea');
   for(var i=textarea.length-1; i>=0; i--)
      resize(textarea[i]);
}

function resize(textarea)
{
   var div = document.createElement("div");
   div.setAttribute("class","textarea");
   div.innerText=textarea.value+"\r\n";
   div.setAttribute("style","width:"+textarea.offsetWidth+'px;display:block;height:auto;left:0px;top:0px;position:fixed;z-index:-200;visibility:hidden;word-wrap:break-word;overflow:hidden;');
   textarea.form.appendChild(div);
   var h=div.offsetHeight;
   div.parentNode.removeChild(div);
   textarea.style.height=h+'px';
}

function resizeOnInput(e)
{
   var textarea=document.querySelectorAll('textarea');
   for(var i=textarea.length-1; i>=0; i--)
      textarea[i].addEventListener("input",function(e){resize(e.target); return false;},false);
}

window.addEventListener("resize",function(){resizeAll();}, false);
window.addEventListener("load",function(){resizeAll();}, false);
resizeOnInput();

Tested on IE11, Firefox and Chrome.

This solution creates div similar to your textarea including internal text and measures height.


问:
How to properly perform operations on two templates of the same type?
I am getting the following error from the compiler: error: no match for 'operator+' (operand types are 'Expected<double>' and 'Expected<double>') Expected is either a type, or an exception.

```<code>template<typename T>
class Expected
{
    template<typename U>
    Expected<U> apply(std::function<U(T)> f)
    {
        if(!valid) return std::get<std::exception_ptr>(state);
        try
        {
            return f(std::get<T>(state));
        }
        catch(...)
        {
            return std::current_exception();
        }
    }
};

#define MixedMode(op)\
template<typename T, typename U, typename V>\
Expected<U> op(Expected<T> t, Expected<V> v)\
{\
    return t.apply([&](T myT){return op(v,myT);});\
}\
template<typename T, typename U, typename V>\
Expected<U> op(Expected<T> t, V v)\
{\
    return t.apply([&](T myT){return op(myT,v);});\
}\
\
template<typename T, typename U, typename V>\
Expected<U> op(V v, Expected<T> t)\
{\
    return t.apply([&](T myT){return op(v,myT);});\
}\

MixedMode(operator+)

int main()
{
    Expected<double> a;
    Expected<double> b;

    a + b;
}
</code>```

I believe in my header file I have done enough to get them to overload and  add them together. In the first I am expecting two templates to add together. In my main file, I simply call:

```<code>Expected<double> a;
Expected<double> b;
std::cout << a + b << std::endl;
</code>```

And then the error is thrown. Before I added Expected op(Expected<T> t, Expected<V> v)\ portion of the code, I was able to compile and run if I had a function called operator T() { return value(); } which would implicitly cast the Expected<T> to whatever type was being passed in. However, I realized that my apply function was never being used. Not only that, when I check the Type of a+b I was returned a double instead of an Expected<double> so I eliminated the operator T() function and the compiler informed me that it doesn't know how to add two Expected<T> together.

How do I go about fixing this error? I have been beating my head against this all day.

答:
The bodies of template functions are never used to deduce template parameters.  U cannot be deduced from the arguments, so your + overloads are ignored.

```<code>#define MixedMode(op)\
template<typename T, typename V>\
auto op(Expected<T> t, Expected<V> v)\
{\
  return t.apply([&](T myT){return op(v,myT);});\
}\
template<typename T, typename V>\
auto op(Expected<T> t, V v)\
{\
  return t.apply([&](T myT){return op(myT,v);});\
}\
template<typename T, typename V>\
auto op(V v, Expected<T> t)\
{\
  return t.apply([&](T myT){return op(v,myT);});\
}
</code>```

This will fail to compile, but that is because you wrote apply wrong.

A std::function is not a lambda, and a lambda is not a std::function.  If you are deducing the type of a std::function 999/1000 times you are screwing up, brcause std::function is about type erasure and deduction is about type deduction, and those are opposite concepts.

More importantly, you are composing them backwards, and they don't compose that way.

```<code>template<class F>
Expected<std::invoke_result_t<F&,T&>> apply(F f){
</code>```

or something similar.

Body:
I am getting the following error from the compiler: error: no match for 'operator+' (operand types are 'Expected<double>' and 'Expected<double>') Expected is either a type, or an exception.

template<typename T>
class Expected
{
    template<typename U>
    Expected apply(std::function f)
    {
        if(!valid) return std::get<std::exception_ptr>(state);
        try
        {
            return f(std::get<T>(state));
        }
        catch(...)
        {
            return std::current_exception();
        }
    }
};

#define MixedMode(op)\
template<typename T, typename U, typename V>\
Expected op(Expected<T> t, Expected<V> v)\
{\
    return t.apply([&](T myT){return op(v,myT);});\
}\
template<typename T, typename U, typename V>\
Expected op(Expected<T> t, V v)\
{\
    return t.apply([&](T myT){return op(myT,v);});\
}\
\
template<typename T, typename U, typename V>\
Expected op(V v, Expected<T> t)\
{\
    return t.apply([&](T myT){return op(v,myT);});\
}\

MixedMode(operator+)

int main()
{
    Expected<double> a;
    Expected<double> b;

    a + b;
}

I believe in my header file I have done enough to get them to overload and  add them together. In the first I am expecting two templates to add together. In my main file, I simply call:

Expected<double> a;
Expected<double> b;
std::cout << a + b << std::endl;

And then the error is thrown. Before I added Expected op(Expected<T> t, Expected<V> v)\ portion of the code, I was able to compile and run if I had a function called operator T() { return value(); } which would implicitly cast the Expected<T> to whatever type was being passed in. However, I realized that my apply function was never being used. Not only that, when I check the Type of a+b I was returned a double instead of an Expected<double> so I eliminated the operator T() function and the compiler informed me that it doesn't know how to add two Expected<T> together.

How do I go about fixing this error? I have been beating my head against this all day.

Body:
The bodies of template functions are never used to deduce template parameters.  U cannot be deduced from the arguments, so your + overloads are ignored.

#define MixedMode(op)\
template<typename T, typename V>\
auto op(Expected<T> t, Expected<V> v)\
{\
  return t.apply([&](T myT){return op(v,myT);});\
}\
template<typename T, typename V>\
auto op(Expected<T> t, V v)\
{\
  return t.apply([&](T myT){return op(myT,v);});\
}\
template<typename T, typename V>\
auto op(V v, Expected<T> t)\
{\
  return t.apply([&](T myT){return op(v,myT);});\
}

This will fail to compile, but that is because you wrote apply wrong.

A std::function is not a lambda, and a lambda is not a std::function.  If you are deducing the type of a std::function 999/1000 times you are screwing up, brcause std::function is about type erasure and deduction is about type deduction, and those are opposite concepts.

More importantly, you are composing them backwards, and they don't compose that way.

template<class F>
Expected<std::invoke_result_t<F&,T&>> apply(F f){

or something similar.


问:
How can I print a portion of a 2d array
Say for example I would want to print half a quarter or a certain section of a 2D array how would I change the code below. Just in general printing only certain sections like if there were ten rows and columns how would I print the last 2 rows and last 2 columns,</p>

```<code>for (int row = 0; row < example.length; row++) {
for (int column = 0; column < example[row].length; column++) {
    System.out.print(" "+example[row][column] + "\t|");
    }
  System.out.println();
  }
</code>```

答:
You could use a scanner to take custom row and col values. Of course, you would need to check if the values provided are in the lengths of each prior to printing so you don't get any IndexOutOfBounds errors (not pictured here).</p>

```<code>int[][] example = new int[10][10];

    int count = 0;

//populate array

    for (int row = 0; row < example.length; row++) {
        for (int column = 0; column < example[row].length; column++) {
            example[row][column] = count;
            count++;
        }
    }

    Scanner sc = new Scanner(System.in);
    System.out.println("Enter row start: ");
    int rowStart = sc.nextInt();

    System.out.println("Enter row end: ");
    int rowEnd = sc.nextInt();

    System.out.println("Enter col start: ");
    int colStart = sc.nextInt();

    System.out.println("Enter col end: ");
    int colEnd = sc.nextInt();

    for (int row = rowStart; row < rowEnd; row++) {
        for (int column = colStart; column < colEnd; column++) {
            System.out.print(" "+example[row][column] + "\t|");
        }
        System.out.println();
    }
    sc.close();
</code>```

Title: How can I print a portion of a 2d array

Body:
Say for example I would want to print half a quarter or a certain section of a 2D array how would I change the code below. Just in general printing only certain sections like if there were ten rows and columns how would I print the last 2 rows and last 2 columns,

for (int row = 0; row < example.length; row++) {
for (int column = 0; column < example[row].length; column++) {
    System.out.print(" "+example[row][column] + "\t|");
    }
  System.out.println();
  }

Body:
You could use a scanner to take custom row and col values. Of course, you would need to check if the values provided are in the lengths of each prior to printing so you don't get any IndexOutOfBounds errors (not pictured here).

int[][] example = new int[10][10];

    int count = 0;

//populate array

    for (int row = 0; row < example.length; row++) {
        for (int column = 0; column < example[row].length; column++) {
            example[row][column] = count;
            count++;
        }
    }

    Scanner sc = new Scanner(System.in);
    System.out.println("Enter row start: ");
    int rowStart = sc.nextInt();

    System.out.println("Enter row end: ");
    int rowEnd = sc.nextInt();

    System.out.println("Enter col start: ");
    int colStart = sc.nextInt();

    System.out.println("Enter col end: ");
    int colEnd = sc.nextInt();

    for (int row = rowStart; row < rowEnd; row++) {
        for (int column = colStart; column < colEnd; column++) {
            System.out.print(" "+example[row][column] + "\t|");
        }
        System.out.println();
    }
    sc.close();


问:
PHP: Cast variable to null
I just stumbled upon a thing in the PHP manual that is new to me...

Casting a variable to null will remove the variable and unset its value. (Source)

Now I wonder how this can be done... I tried (null) and (NULL) but it seems to be interpreted as the value null, not the type null.
I know this question must sound ridiculous, but does somebody know how to cast to null?

答:
This piece of code is meant, isset will return false.

```
$test = "a";
$test = null;
var_dump( isset( $test ));
```

Casting variables in PHP is done by assigning it specific value ( eg $foo = intval( $bar ) etc. ).
If you put NULL into variable it will be interpreted as NULL ( type NULL ), isset return false if variable is type NULL

Edit: if you want to completly unset variable use

```
unset( $test );
```

Title: PHP: Cast variable to null

Body:
This piece of code is meant, isset will return false.

$test = "a";
$test = null;
var_dump( isset( $test ));

Casting variables in PHP is done by assigning it specific value ( eg $foo = intval( $bar ) etc. ).
If you put NULL into variable it will be interpreted as NULL ( type NULL ), isset return false if variable is type NULL

Edit: if you want to completly unset variable use

unset( $test );

ContentLicense: CC BY-SA 2.5


问:
SQL Server database Mail Unusual behaviour
Hi i have configured two  profile account with different gmail account associated respectively.

attached is a screenshot comparison.

Profile SRV SQL Alert is working, but the other one is not working, they both have the same settings in SSL and smtp and port.

anything i missed here?
Imgage screenshot is here: https://ibb.co/j7q4oR

答:
The screenshot of the "not working" setup on the right lists the server as SMPT.gmail.com

This does not resolve to an IP address. Swap the P and the T around to make it smtp.gmail.com


问:
I am getting gradle error Execution failed for task
I am getting this error

```<code>Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/android/volley/AuthFailureError.class
</code>```

I attached my gradle please check and help me.

```<code>    android {
              useLibrary 'org.apache.http.legacy'
             }

       dependencies {

    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile files('libs/android-async-http-1.4.4.jar')
    compile files('libs/disklrucache-2.0.1.jar')
    compile files('libs/google-gson.jar')
    compile project(':linkedin-sdk')
    compile files('libs/PGSDK_V2.0.jar')
    compile 'com.android.support:support-v13:25.3.1'
    compile files('libs/okhttp-1.2.1-jar-with-dependencies.jar')
    compile files('libs/volley.jar')
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'uk.co.chrisjenx:calligraphy:2.2.0'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:support-v4:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.razorpay:checkout:1.4.1'
    compile 'com.google.android.gms:play-services-auth:9.2.1'

    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile 'com.jjoe64:graphview:4.2.0'

}
</code>```

答:
Remove Below jar file from gradle

```<code>compile files('libs/volley.jar')
compile files('libs/google-gson.jar')
</code>```

and compile below dependency

```<code>compile 'com.google.code.gson:gson:2.8.1'
compile 'com.android.volley:volley:1.0.0'
compile 'com.google.android.gms:play-services-auth:11.4.0'
</code>```

Body:
I am getting this error

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/android/volley/AuthFailureError.class

I attached my gradle please check and help me.

    android {
              useLibrary 'org.apache.http.legacy'
             }

       dependencies {

    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile files('libs/android-async-http-1.4.4.jar')
    compile files('libs/disklrucache-2.0.1.jar')
    compile files('libs/google-gson.jar')
    compile project(':linkedin-sdk')
    compile files('libs/PGSDK_V2.0.jar')
    compile 'com.android.support:support-v13:25.3.1'
    compile files('libs/okhttp-1.2.1-jar-with-dependencies.jar')
    compile files('libs/volley.jar')
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'uk.co.chrisjenx:calligraphy:2.2.0'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:support-v4:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.razorpay:checkout:1.4.1'
    compile 'com.google.android.gms:play-services-auth:9.2.1'

    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile 'com.jjoe64:graphview:4.2.0'

}

Body:
Remove Below jar file from gradle

compile files('libs/volley.jar')
compile files('libs/google-gson.jar')

and compile below dependency

compile 'com.google.code.gson:gson:2.8.1'
compile 'com.android.volley:volley:1.0.0'
compile 'com.google.android.gms:play-services-auth:11.4.0'


问:
Can't integrate INNER JOIN in my query
Hello I'm using the query below to select the latest message from each unique conversation. Everything works perfectly except when I try to integrate an INNER JOIN to try to link the user's user_id with their username in the users table.

I've tried pretty much every combination to integrate the INNER JOIN so I decided to separate it from the working query until I get help.

I made a Fiddle http://sqlfiddle.com/#!9/a9bbc/1   I just want user_id on the right to print the user's username

```<code>SELECT message_id,
       msg,
       user_id
FROM   messages
   JOIN (SELECT user_id,
                Max(dat) m
         FROM   ((SELECT message_id,
                         recipient_id user_id,
                         dat
                  FROM   messages
                  WHERE  owner_id = 1)
                 UNION
                 (SELECT message_id,
                         owner_id user_id,
                         dat
                  FROM   messages
                  WHERE  recipient_id = 1)) t1
         GROUP  BY user_id) t2
     ON ( ( owner_id = 1
            AND recipient_id = user_id )
           OR ( owner_id = user_id
                AND recipient_id = 1 ) )
        AND ( dat = m )
 ORDER  BY dat DESC
</code>```

.

```<code>users.username INNER JOIN users ON messages.user_id = users.user_id;
</code>```

答:
If messages.message_id is an AUTO_INCREMENT PRIMARY KEY column, this will probably be the fastest way to receive the desired result:

```<code>select m.message_id, m.msg, u.username,
  case sub.other_user_id
    when m.owner_id     then 'received from'
    when m.recipient_id then 'sent to'
  end as direction
from (
  select other_user_id, max(message_id) as message_id
  from (
    select recipient_id as other_user_id, max(message_id) as message_id
    from messages
    where owner_id = @uid
    group by recipient_id

    union all

    select owner_id as other_user_id, max(message_id) as message_id
    from messages
    where recipient_id = @uid
    group by owner_id
  ) sub
  group by other_user_id
) sub
join messages m on m.message_id = sub.message_id
join users u    on u.user_id    = sub.other_user_id
order by sub.message_id desc
</code>```

I've also added the column direction. This way you will know if the message has been sent or received. The result would be like:

```<code>| message_id |                                                              msg | username |     direction |
|------------|------------------------------------------------------------------|----------|---------------|
|          9 | You should also see this                                         |    User3 |       sent to |
|          8 | you should Now see this instead even with the owner_id flipped.. |    User2 | received from |
</code>```

http://sqlfiddle.com/#!9/a9bbc/34

Note that you can still add any column from the users and messages tables in the SELECT clause.

To get this query work fast you will need indexes on messages(owner_id, recipient_id) and messages(recipient_id, owner_id).

Title: Can't integrate INNER JOIN in my query

Body:
Hello I'm using the query below to select the latest message from each unique conversation. Everything works perfectly except when I try to integrate an INNER JOIN to try to link the user's user_id with their username in the users table.

I've tried pretty much every combination to integrate the INNER JOIN so I decided to separate it from the working query until I get help.

I made a Fiddle http://sqlfiddle.com/#!9/a9bbc/1   I just want user_id on the right to print the user's username

SELECT message_id,
       msg,
       user_id
FROM   messages
   JOIN (SELECT user_id,
                Max(dat) m
         FROM   ((SELECT message_id,
                         recipient_id user_id,
                         dat
                  FROM   messages
                  WHERE  owner_id = 1)
                 UNION
                 (SELECT message_id,
                         owner_id user_id,
                         dat
                  FROM   messages
                  WHERE  recipient_id = 1)) t1
         GROUP  BY user_id) t2
     ON ( ( owner_id = 1
            AND recipient_id = user_id )
           OR ( owner_id = user_id
                AND recipient_id = 1 ) )
        AND ( dat = m )
 ORDER  BY dat DESC

.

users.username INNER JOIN users ON messages.user_id = users.user_id;

Body:
If messages.message_id is an AUTO_INCREMENT PRIMARY KEY column, this will probably be the fastest way to receive the desired result:

select m.message_id, m.msg, u.username,
  case sub.other_user_id
    when m.owner_id     then 'received from'
    when m.recipient_id then 'sent to'
  end as direction
from (
  select other_user_id, max(message_id) as message_id
  from (
    select recipient_id as other_user_id, max(message_id) as message_id
    from messages
    where owner_id = @uid
    group by recipient_id

    union all

    select owner_id as other_user_id, max(message_id) as message_id
    from messages
    where recipient_id = @uid
    group by owner_id
  ) sub
  group by other_user_id
) sub
join messages m on m.message_id = sub.message_id
join users u    on u.user_id    = sub.other_user_id
order by sub.message_id desc

I've also added the column direction. This way you will know if the message has been sent or received. The result would be like:

| message_id |                                                              msg | username |     direction |
|------------|------------------------------------------------------------------|----------|---------------|
|          9 | You should also see this                                         |    User3 |       sent to |
|          8 | you should Now see this instead even with the owner_id flipped.. |    User2 | received from |

http://sqlfiddle.com/#!9/a9bbc/34

Note that you can still add any column from the users and messages tables in the SELECT clause.

To get this query work fast you will need indexes on messages(owner_id, recipient_id) and messages(recipient_id, owner_id).


答:
You can take hint from this code , but since this seems a school homework so i suggest you should try yourself if you want to improve your coding.

```<code>user_input=[]
while True:

    x = int(input("Please input an integer(negative if you want to stop: "))
    if x>0:
        user_input.append(x)
    else:
        break

div_5=[item for item in user_input if item%5==0]
print('The mean is {}'.format(sum(div_5)/len(div_5)))
</code>```

output:

```<code>Please input an integer(negative if you want to stop: 1
Please input an integer(negative if you want to stop: 2
Please input an integer(negative if you want to stop: 3
Please input an integer(negative if you want to stop: 4
Please input an integer(negative if you want to stop: 5
Please input an integer(negative if you want to stop: 6
Please input an integer(negative if you want to stop: 7
Please input an integer(negative if you want to stop: 8
Please input an integer(negative if you want to stop: 9
Please input an integer(negative if you want to stop: 15
Please input an integer(negative if you want to stop: -12
The mean is 10.0
</code>```

Title: How do you compute the mean of integers entered by the user that are evenly divisible by a number?

Body:
You can take hint from this code , but since this seems a school homework so i suggest you should try yourself if you want to improve your coding.

user_input=[]
while True:

    x = int(input("Please input an integer(negative if you want to stop: "))
    if x>0:
        user_input.append(x)
    else:
        break

div_5=[item for item in user_input if item%5==0]
print('The mean is {}'.format(sum(div_5)/len(div_5)))

output:

Please input an integer(negative if you want to stop: 1
Please input an integer(negative if you want to stop: 2
Please input an integer(negative if you want to stop: 3
Please input an integer(negative if you want to stop: 4
Please input an integer(negative if you want to stop: 5
Please input an integer(negative if you want to stop: 6
Please input an integer(negative if you want to stop: 7
Please input an integer(negative if you want to stop: 8
Please input an integer(negative if you want to stop: 9
Please input an integer(negative if you want to stop: 15
Please input an integer(negative if you want to stop: -12
The mean is 10.0


问:
Django Rest Framework Routing for embedded Angular Applications
I'm trying to bundle an Angular app and deploy it as static content in a Django Rest Framework DRF application.

I don't know Django or DRF at all however, I want to take control of the routing to express something like this:

For /admin/* - delegate to built-in Django admin.

For /api/* - delegate to Django Rest Framework

For / only, and /* - treat as static content loaded from "some specified project folder", so
 / maps to file ./static/index.html
 /assets/pic.jpg maps to ./static/assets/pic.jpg

I've not been able to achieve the above. All I have is this:

A template view for index.html living at ./templates/index.html - This is the from the Angular project and is not a Django template.

Other webpack bundled content copied manually to ./static such as vendor.|hash|.bundle.js

Another problem is what to do with Assets. In the angular project, HTML views refer to assets via /assets which is at the same level as index.html

I've gotten some control over paths using this command line:

```<code>ng build --deploy-url=/static --output-path=../backend/tutorial/static
</code>```

The deploy-url arg results in bundled assets references in index.html being prefixed by /static which means that Django can serve them (but not favicon.ico for some reason).

The output-path arg dumps all the assets somewhere other than the default "dist" folder.

```<code>urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^api/', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^', TemplateView.as_view(template_name="index.html")),
]
</code>```

Url patterns looks like the above.

```<code>STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static")
]

STATIC_URL = '/static/'
</code>```

These are the static settings. What I need is to be able to say "/static" and "/assets" are both static asset folders.

I'm not sure what TemplateView is (urlPatterns). Maybe there's a StaticFilesView or something that maps a URL to a path on disk?

答:
Blockquote
  These are the static settings. What I need is to be able to say "/static" and "/assets" are both static asset folders.
  Blockquote

You can achieve that with the following steps:

Add /assets static directory in NGINX site configuration file:

```<code>server {
    ....
    ....
    # your Django project's static files - required
    location /static {
        alias /path/to.../static;
    }
    # your Angular project's static files
    location /assets {
        alias /path/to.../assets;
    }
    ....
    ....
}
</code>```

In your Django urls.py add:

```<code>from django.views.static import serve as static_serve

urlpatterns = [
    ....
    url(r'^assets/(?P<path>.*)$', static_serve,
                  {'document_root':'/path/to.../assets'}),
    ....
    ....
]
</code>```

That's it. You don't have to touch the static configuration in Django settings.

```<code>    STATIC_URL = '/static/'
    MEDIA_URL = '/media/'
    MEDIA_ROOT = os.path.join(DATA_DIR, 'media')
    STATIC_ROOT = os.path.join(DATA_DIR, 'static')

    STATICFILES_DIRS = (
        os.path.join(BASE_DIR, 'reservation_exchange', 'static'),
    )
</code>```

Body:
I'm trying to bundle an Angular app and deploy it as static content in a Django Rest Framework DRF application.

I don't know Django or DRF at all however, I want to take control of the routing to express something like this:

For /admin/* - delegate to built-in Django admin.

For /api/* - delegate to Django Rest Framework

For / only, and /* - treat as static content loaded from "some specified project folder", so
 / maps to file ./static/index.html
 /assets/pic.jpg maps to ./static/assets/pic.jpg

I've not been able to achieve the above. All I have is this:

A template view for index.html living at ./templates/index.html - This is the from the Angular project and is not a Django template.

Other webpack bundled content copied manually to ./static such as vendor.|hash|.bundle.js

Another problem is what to do with Assets. In the angular project, HTML views refer to assets via /assets which is at the same level as index.html

I've gotten some control over paths using this command line:

ng build --deploy-url=/static --output-path=../backend/tutorial/static

The deploy-url arg results in bundled assets references in index.html being prefixed by /static which means that Django can serve them (but not favicon.ico for some reason).

The output-path arg dumps all the assets somewhere other than the default "dist" folder.

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^api/', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^', TemplateView.as_view(template_name="index.html")),
]

Url patterns looks like the above.

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static")
]

STATIC_URL = '/static/'

These are the static settings. What I need is to be able to say "/static" and "/assets" are both static asset folders.

I'm not sure what TemplateView is (urlPatterns). Maybe there's a StaticFilesView or something that maps a URL to a path on disk?

Body:
Blockquote
  These are the static settings. What I need is to be able to say "/static" and "/assets" are both static asset folders.
  Blockquote

You can achieve that with the following steps:

Add /assets static directory in NGINX site configuration file:

server {
    ....
    ....
    # your Django project's static files - required
    location /static {
        alias /path/to.../static;
    }
    # your Angular project's static files
    location /assets {
        alias /path/to.../assets;
    }
    ....
    ....
}

In your Django urls.py add:

from django.views.static import serve as static_serve

urlpatterns = [
    ....
    url(r'^assets/(?P<path>.*)$', static_serve,
                  {'document_root':'/path/to.../assets'}),
    ....
    ....
]

That's it. You don't have to touch the static configuration in Django settings.

    STATIC_URL = '/static/'
    MEDIA_URL = '/media/'
    MEDIA_ROOT = os.path.join(DATA_DIR, 'media')
    STATIC_ROOT = os.path.join(DATA_DIR, 'static')

    STATICFILES_DIRS = (
        os.path.join(BASE_DIR, 'reservation_exchange', 'static'),
    )


问:
C# Primitive types (double, int, etc) and Struct differences
I am confused with structs.

```<code>class A
{
  double a { get; set; }
  MyStruct b { get; set; }

  void Modify()
  {
     a = 1.0;    // This compiles.
     b.c = 2.0;  // Assuming c is a double. This gives the known error.
  }
}
</code>```

Now why I am able to set the value of the structure a, and not of the structure's field b ?
The answer I read is that I have a copy of b and not b's backing field. By the same logic I must have a copy of a, not a, so how it explains that the a property is changed after the permitted assignement

```<code>a = 1.0;
</code>```

? Thank you.

EDIT :

Also in order to still use b inside the A class, "filtered" by the set and get methods and not directly by using the backing field _b, something which could look like this:

```<code>MyStruct _b;
MyStruct b { get { return _b; } set { _b=value; } }
</code>```

and then use the field

```<code>_b
</code>```

, as correctly stated in the answers, I thinked of a silly method to "wrap" the property in an one dimensional array of size 1.

```<code>MyStruct[] b { get; set; }
</code>```

kind of wrapping the struct with a class. I dont know the computational cost of this, but I preferred it from using the field directly inside the A class.

ANSWERED : Ok, the confusion in this question comes, when you are used to interpret properties as fields in your mind. If you interpret properties the correct way -as the MsIL does-, all things settle down. All the answers and comments below, are relevant.
(Sorry for the bad English.)

答:
Your logic is a little off.

In your first example, you're replacing a double with a brand new double.

In the second example, you're not replacing the struct with another struct. Instead you're trying to modify some field of the struct.

To do similar things, you would have to do:

```<code>a = 10.1;
b = new MyStruct(10.1);

a = 11.1;
b = new MyStruct(11.1);
</code>```

Body:
I am confused with structs.

class A
{
  double a { get; set; }
  MyStruct b { get; set; }

  void Modify()
  {
     a = 1.0;    // This compiles.
     b.c = 2.0;  // Assuming c is a double. This gives the known error.
  }
}

Now why I am able to set the value of the structure a, and not of the structure's field b ?
The answer I read is that I have a copy of b and not b's backing field. By the same logic I must have a copy of a, not a, so how it explains that the a property is changed after the permitted assignement

a = 1.0;

? Thank you.

EDIT :

Also in order to still use b inside the A class, "filtered" by the set and get methods and not directly by using the backing field _b, something which could look like this:

MyStruct _b;
MyStruct b { get { return _b; } set { _b=value; } }

and then use the field

_b

, as correctly stated in the answers, I thinked of a silly method to "wrap" the property in an one dimensional array of size 1.

MyStruct[] b { get; set; }

kind of wrapping the struct with a class. I dont know the computational cost of this, but I preferred it from using the field directly inside the A class.

ANSWERED : Ok, the confusion in this question comes, when you are used to interpret properties as fields in your mind. If you interpret properties the correct way -as the MsIL does-, all things settle down. All the answers and comments below, are relevant.
(Sorry for the bad English.)

Body:
Your logic is a little off.

In your first example, you're replacing a double with a brand new double.

In the second example, you're not replacing the struct with another struct. Instead you're trying to modify some field of the struct.

To do similar things, you would have to do:

a = 10.1;
b = new MyStruct(10.1);

a = 11.1;
b = new MyStruct(11.1);


问:
Send Anonymous Type (List) to View in ASP.NET Core
I'm trying to send an anonymous type to my view.

The anonymous type is constructed in the following way:

```<code>    public async Task<IActionResult> Historial()
    {
        return View(await _context.HechosLiquidador
            .Select(c => new { Store = c.StoreID, LiqDate = c.FechaLFinLiq}).Distinct()
            .AsNoTracking().OrderBy(s => s.LiqDate).ToListAsync());
    }
</code>```

The particularity of this case is that the result of the query is a list of items. How can I pass this to the view?

Should I construct a ViewModel? If that is the case, how can I populate that view model with the result of this query?

答:
I have used a ViewModel as a solution to my problem.

ViewModel:

```<code>public class HistorialIndexData
{
    public string StoreName { get; set; }

    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime FechaLFinLiq { get; set; }
}
</code>```

In the controller we will, at first, get the items that we want to list. Next we iterate through the object that contains those items and then store them on the ViewModel to finally be used to create a new list.

```<code>public async Task<IActionResult> Historial()
{
   List<HistorialIndexData> newHistorial = new List<HistorialIndexData>();
   var items = await _context.HechosLiquidador.Include(s => s.Stores)
              .Select(c => new { Store = c.Stores.StoreName, LiqDate = c.FechaLFinLiq })
              .Distinct()
              .AsNoTracking().OrderBy(s => s.LiqDate)
              .ToListAsync();

   foreach(var itemtolist in items)
   {
     HistorialIndexData info = new HistorialIndexData
     {
       StoreName = itemtolist.Store,
       FechaLFinLiq = itemtolist.LiqDate
     };
     newHistorial.Add(info);
   }

   return View(newHistorial);
}
</code>```

Update the view to work with the ViewModel.

```<code>@model List<Application.Models.ApplicationviewModels.HistorialIndexData>
</code>```

Body:
I'm trying to send an anonymous type to my view.

The anonymous type is constructed in the following way:

    public async Task<IActionResult> Historial()
    {
        return View(await _context.HechosLiquidador
            .Select(c => new { Store = c.StoreID, LiqDate = c.FechaLFinLiq}).Distinct()
            .AsNoTracking().OrderBy(s => s.LiqDate).ToListAsync());
    }

The particularity of this case is that the result of the query is a list of items. How can I pass this to the view?

Should I construct a ViewModel? If that is the case, how can I populate that view model with the result of this query?

Body:
I have used a ViewModel as a solution to my problem.

ViewModel:

public class HistorialIndexData
{
    public string StoreName { get; set; }

    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime FechaLFinLiq { get; set; }
}

In the controller we will, at first, get the items that we want to list. Next we iterate through the object that contains those items and then store them on the ViewModel to finally be used to create a new list.

public async Task<IActionResult> Historial()
{
   List<HistorialIndexData> newHistorial = new List<HistorialIndexData>();
   var items = await _context.HechosLiquidador.Include(s => s.Stores)
              .Select(c => new { Store = c.Stores.StoreName, LiqDate = c.FechaLFinLiq })
              .Distinct()
              .AsNoTracking().OrderBy(s => s.LiqDate)
              .ToListAsync();

   foreach(var itemtolist in items)
   {
     HistorialIndexData info = new HistorialIndexData
     {
       StoreName = itemtolist.Store,
       FechaLFinLiq = itemtolist.LiqDate
     };
     newHistorial.Add(info);
   }

   return View(newHistorial);
}

Update the view to work with the ViewModel.

@model List<Application.Models.ApplicationviewModels.HistorialIndexData>

ContentLicense: CC BY-SA 4.0


问:
Change language for the whole application inside a fragment?
Let's say this is the call stack:

Fragment2 (current position)

Fragment1

HostingActivity

The user has just navigated to fragment2 (which is the settings screen). He chooses a second language, and then navigates back to Fragment1. I want the app to show content from the second language as soon as he enters fragment1.

I've read that the best approach would be to let all the fragments derive from a base-fragment which configures the locale inside the OnResume() method.

```<code>public class BaseFragment : Fragment
{
    public override void OnResume()
    {
        string langCode = prefs.GetString("settings_language", "en_US");

        Resources res = Application.Context.Resources;
        // Change locale settings in the app.
        DisplayMetrics dm = res.DisplayMetrics;
        Configuration conf = res.Configuration;
        conf.SetLocale(new Locale(langCode.ToLower()));

        res.UpdateConfiguration(conf, dm);
        OnConfigurationChanged(conf);

        base.OnResume();
    }
}
</code>```

I've attempted this, but without any luck. I didn't see any change whatsoever.
I'm open to hear any suggestions.

PS. To ensure that I didn't mess up any of the naming conventions required by Android in the values folder, I tried rebooting the emulator (with adb shell) using the language I wanted and it worked as expected.

答:
You can create a base class that sets the CurrentCulture like this and inherit from it:

```<code>internal class MyBaseActivity : Activity
{
    protected override void OnResume ()
    {
        base.OnResume ();

        // Get the language from wherever.
        var userSelectedCulture = new CultureInfo ("fr-FR");

        Thread.CurrentThread.CurrentCulture = userSelectedCulture;
    }
}
</code>```

And here is how to inherit and use it:

```<code>public class MainActivity : MyBaseActivity
{
    protected override void OnResume()
    {
        base.OnResume();  // Do not forget to call base.OnResume()
        // Rest of Your Code...
    }
}
</code>```

Body:
Let's say this is the call stack:

Fragment2 (current position)

Fragment1

HostingActivity

The user has just navigated to fragment2 (which is the settings screen). He chooses a second language, and then navigates back to Fragment1. I want the app to show content from the second language as soon as he enters fragment1.

I've read that the best approach would be to let all the fragments derive from a base-fragment which configures the locale inside the OnResume() method.

public class BaseFragment : Fragment
{
    public override void OnResume()
    {
        string langCode = prefs.GetString("settings_language", "en_US");

        Resources res = Application.Context.Resources;
        // Change locale settings in the app.
        DisplayMetrics dm = res.DisplayMetrics;
        Configuration conf = res.Configuration;
        conf.SetLocale(new Locale(langCode.ToLower()));

        res.UpdateConfiguration(conf, dm);
        OnConfigurationChanged(conf);

        base.OnResume();
    }
}

I've attempted this, but without any luck. I didn't see any change whatsoever.
I'm open to hear any suggestions.

PS. To ensure that I didn't mess up any of the naming conventions required by Android in the values folder, I tried rebooting the emulator (with adb shell) using the language I wanted and it worked as expected.

Body:
You can create a base class that sets the CurrentCulture like this and inherit from it:

internal class MyBaseActivity : Activity
{
    protected override void OnResume ()
    {
        base.OnResume ();

        // Get the language from wherever.
        var userSelectedCulture = new CultureInfo ("fr-FR");

        Thread.CurrentThread.CurrentCulture = userSelectedCulture;
    }
}

And here is how to inherit and use it:

public class MainActivity : MyBaseActivity
{
    protected override void OnResume()
    {
        base.OnResume();  // Do not forget to call base.OnResume()
        // Rest of Your Code...
    }
}


问:
How to read .csv file?
I have a CSV file. If I open it with a standard text editor such as notepad or excel, I can read the strings. But I can't read it with my PHP code (there is a symbols font error). How can I fix it?

My PHP code:

```<code><?php
    $file = fopen("data.csv","r");

    while(! feof($file))
      {
          print_r(fgetcsv($file));
      }

    fclose($file);
 ?>
</code>```

My CSV file

Thank all! I found the answer http://www.practicalweb.co.uk/blog/2008/05/18/reading-a-unicode-excel-file-in-php/

答:
The file encoding appears to be UCS-2 LE, from which UTF-16 developed1. (also see  this answer).

Save the file with UTF-8 encoding. Instead of notepad, try using a different text editor like Notepad++. It has a menu for choosing the encoding of the file. Then the PHP code can read the characters as desired. See demo here.

1https://web.archive.org/web/20060114213239/http://www.unicode.org/faq/basic_q.html#23

Title: How to read .csv file?

Body:
I have a CSV file. If I open it with a standard text editor such as notepad or excel, I can read the strings. But I can't read it with my PHP code (there is a symbols font error). How can I fix it?

My PHP code:

<?php
    $file = fopen("data.csv","r");

    while(! feof($file))
      {
          print_r(fgetcsv($file));
      }

    fclose($file);
 ?>

My CSV file

Thank all! I found the answer http://www.practicalweb.co.uk/blog/2008/05/18/reading-a-unicode-excel-file-in-php/


问:
Master/slave multicore processing in R
I would like to parallelize the while loop in the following code:

```<code>work <- function(n) {
  # Do some intensive work (e.g explore a graph starting at n).
  # After this, we don't need to execute work() on nodes in excluding.
  # (e.g exclude could be the nodes explored/reached from n)
  # n is just an example. exclude can be a potentially large set.
  Sys.sleep(2)
  exclude <- c(n, sample(nodes, rbinom(1, length(nodes), 0.5)))
  return(exclude)
}

nodes <- 1:1e3

#Order of execution doesn't matter
nodes <- sample(nodes)

#parallelize this loop
while(length(nodes) > 0) {
  n <- nodes[1]
  exclude <- work(n)
  nodes <- setdiff(nodes, exclude)
}
</code>```

It doesn't matter if work() is executed on an excluded node, but we would like to minimize such instances.  The objective of the while loop above is to run work() as few times as possible

This is not an embarrassingly parallel computation, so I don't know how to use parLapply directly. A master-slave framework could be used, but I don't know of any for multicore programming (on Windows).

As a concrete example, you can think of work(n) as graph_exploration(n) (the function the finds all nodes connected to n) and exclude as the nodes in the connected component of n. The final objective is to find one node from each connected component. You want to run graph_exploration(n) as few times as necessary because it is an expensive operation.

答:
Miheer,

Here is a proposed solution.

Pre-amble:

The core problem here (as I understand it) is to unblock the while loop whilst work() is number crunching. Essentially, you want the loop to be non-blocked so long as resources remain to initiate more work() calls and processing. Ok, how? Well, my recommendation is you use the future package.

The example below essentially creates a new process invocation of work() for each call. The invocation, however, will not block the while loop unless all the assigned worker processes are busy. You can see this as each work() invocation has a different process id as shown in the runtime output.

Thus, each work() runs independently, to finish we resolve all the futures and return the finals results.

Results:

Sequential runtime: 20.61 sec elapsed

Parallel runtime: 8.22 sec elapsed

I hope this points you in the right direction.

Caveat: You have to run through all nodes, but it does improve runtime.

Machine setup:

```<code>R version 3.4.1 (2017-06-30)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)
[Windows 10, 8 Core Xeon, 64Gb RAM]
</code>```

Parallel Code Example:

```<code># Check for, and install and load required packages.
requiredPackages <-
  c("tictoc", "listenv", "future")

ipak <- function(pkg) {
  new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
  if (length(new.pkg))
    install.packages(new.pkg, dependencies = TRUE)
  sapply(pkg, require, character.only = TRUE)
}

ipak(requiredPackages)

work <- function(n) {
  # Do some intensive work (e.g explore a graph starting at n).
  # After this, we don't need to execute work() on nodes in exclude.
  # (e.g exclude could be the nodes explored/reached from n)
  # n is just an example. exclude can be a potentially large set.
  Sys.sleep(2) # sample(.5:5))
  exclude <- n
  return(exclude)
}

plan(multiprocess, workers = 4L)
#plan(sequential)

nodesGraph  <- 1:10
nodesGraph  <- sample(nodesGraph)
nodesCount  <- length(nodesGraph)
resultsList <- listenv()

tic()
while ( nodesCount > 0 ) {
  n <- nodesGraph[[nodesCount]]
  ## This is evaluated in parallel and will only block
  ## if all workers are busy.
  resultsList[[nodesCount]] %<-% {
      list( exclude = work(n),
            iteration = length(nodesGraph),
            pid = Sys.getpid())
  }

  nodesGraph <- setdiff(nodesGraph, nodesGraph[[nodesCount]] )
  cat("nodesGraph",nodesGraph,"\n")
  cat("nodesCount",nodesCount,"\n")
  nodesCount = nodesCount - 1
}
toc()

## Resolve all futures (blocks if not already finished)
resultsList <- as.list(resultsList)
str(resultsList)
</code>```

Parallel Runtime Output:

```<code>> source('<hidden>/dev/stackoverflow/47230384/47230384v5.R')
nodesGraph 2 5 8 4 6 10 7 1 9
nodesCount 10
nodesGraph 2 5 8 4 6 10 7 1
nodesCount 9
nodesGraph 2 5 8 4 6 10 7
nodesCount 8
nodesGraph 2 5 8 4 6 10
nodesCount 7
nodesGraph 2 5 8 4 6
nodesCount 6
nodesGraph 2 5 8 4
nodesCount 5
nodesGraph 2 5 8
nodesCount 4
nodesGraph 2 5
nodesCount 3
nodesGraph 2
nodesCount 2
nodesGraph
nodesCount 1
8.22 sec elapsed
List of 10
 $ :List of 3
  ..$ exclude  : int 2
  ..$ iteration: int 1
  ..$ pid      : int 10692
 $ :List of 3
  ..$ exclude  : int 5
  ..$ iteration: int 2
  ..$ pid      : int 2032
 $ :List of 3
  ..$ exclude  : int 8
  ..$ iteration: int 3
  ..$ pid      : int 16356
 $ :List of 3
  ..$ exclude  : int 4
  ..$ iteration: int 4
  ..$ pid      : int 7756
 $ :List of 3
  ..$ exclude  : int 6
  ..$ iteration: int 5
  ..$ pid      : int 10692
 $ :List of 3
  ..$ exclude  : int 10
  ..$ iteration: int 6
  ..$ pid      : int 2032
 $ :List of 3
  ..$ exclude  : int 7
  ..$ iteration: int 7
  ..$ pid      : int 16356
 $ :List of 3
  ..$ exclude  : int 1
  ..$ iteration: int 8
  ..$ pid      : int 7756
 $ :List of 3
  ..$ exclude  : int 9
  ..$ iteration: int 9
  ..$ pid      : int 10692
 $ :List of 3
  ..$ exclude  : int 3
  ..$ iteration: int 10
  ..$ pid      : int 2032
</code>```

Sequential Runtime output

```<code>> source('<hidden>/dev/stackoverflow/47230384/47230384v5.R')
nodesGraph 6 2 1 9 4 8 10 7 3
nodesCount 10
nodesGraph 6 2 1 9 4 8 10 7
nodesCount 9
nodesGraph 6 2 1 9 4 8 10
nodesCount 8
nodesGraph 6 2 1 9 4 8
nodesCount 7
nodesGraph 6 2 1 9 4
nodesCount 6
nodesGraph 6 2 1 9
nodesCount 5
nodesGraph 6 2 1
nodesCount 4
nodesGraph 6 2
nodesCount 3
nodesGraph 6
nodesCount 2
nodesGraph
nodesCount 1
20.61 sec elapsed
List of 10
 $ :List of 3
  ..$ exclude  : int 6
  ..$ iteration: int 1
  ..$ pid      : int 12484
 $ :List of 3
  ..$ exclude  : int 2
  ..$ iteration: int 2
  ..$ pid      : int 12484
 $ :List of 3
  ..$ exclude  : int 1
  ..$ iteration: int 3
  ..$ pid      : int 12484
 $ :List of 3
  ..$ exclude  : int 9
  ..$ iteration: int 4
  ..$ pid      : int 12484
 $ :List of 3
  ..$ exclude  : int 4
  ..$ iteration: int 5
  ..$ pid      : int 12484
 $ :List of 3
  ..$ exclude  : int 8
  ..$ iteration: int 6
  ..$ pid      : int 12484
 $ :List of 3
  ..$ exclude  : int 10
  ..$ iteration: int 7
  ..$ pid      : int 12484
 $ :List of 3
  ..$ exclude  : int 7
  ..$ iteration: int 8
  ..$ pid      : int 12484
 $ :List of 3
  ..$ exclude  : int 3
  ..$ iteration: int 9
  ..$ pid      : int 12484
 $ :List of 3
  ..$ exclude  : int 5
  ..$ iteration: int 10
  ..$ pid      : int 12484
</code>```

Title: Master/slave multicore processing in R

Body:
I would like to parallelize the while loop in the following code:

work <- function(n) {
  # Do some intensive work (e.g explore a graph starting at n).
  # After this, we don't need to execute work() on nodes in excluding.
  # (e.g exclude could be the nodes explored/reached from n)
  # n is just an example. exclude can be a potentially large set.
  Sys.sleep(2)
  exclude <- c(n, sample(nodes, rbinom(1, length(nodes), 0.5)))
  return(exclude)
}

nodes <- 1:1e3

#Order of execution doesn't matter
nodes <- sample(nodes)

#parallelize this loop
while(length(nodes) > 0) {
  n <- nodes[1]
  exclude <- work(n)
  nodes <- setdiff(nodes, exclude)
}

It doesn't matter if work() is executed on an excluded node, but we would like to minimize such instances.  The objective of the while loop above is to run work() as few times as possible

This is not an embarrassingly parallel computation, so I don't know how to use parLapply directly. A master-slave framework could be used, but I don't know of any for multicore programming (on Windows).

As a concrete example, you can think of work(n) as graph_exploration(n) (the function the finds all nodes connected to n) and exclude as the nodes in the connected component of n. The final objective is to find one node from each connected component. You want to run graph_exploration(n) as few times as necessary because it is an expensive operation.

Body:
Miheer,

Here is a proposed solution.

Pre-amble:

The core problem here (as I understand it) is to unblock the while loop whilst work() is number crunching. Essentially, you want the loop to be non-blocked so long as resources remain to initiate more work() calls and processing. Ok, how? Well, my recommendation is you use the future package.

The example below essentially creates a new process invocation of work() for each call. The invocation, however, will not block the while loop unless all the assigned worker processes are busy. You can see this as each work() invocation has a different process id as shown in the runtime output.

Thus, each work() runs independently, to finish we resolve all the futures and return the finals results.

Results:

Sequential runtime: 20.61 sec elapsed

Parallel runtime: 8.22 sec elapsed

I hope this points you in the right direction.

Caveat: You have to run through all nodes, but it does improve runtime.

Machine setup:

R version 3.4.1 (2017-06-30)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)
[Windows 10, 8 Core Xeon, 64Gb RAM]

Parallel Code Example:

# Check for, and install and load required packages.
requiredPackages <-
  c("tictoc", "listenv", "future")

ipak <- function(pkg) {
  new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
  if (length(new.pkg))
    install.packages(new.pkg, dependencies = TRUE)
  sapply(pkg, require, character.only = TRUE)
}

ipak(requiredPackages)

work <- function(n) {
  # Do some intensive work (e.g explore a graph starting at n).
  # After this, we don't need to execute work() on nodes in exclude.
  # (e.g exclude could be the nodes explored/reached from n)
  # n is just an example. exclude can be a potentially large set.
  Sys.sleep(2) # sample(.5:5))
  exclude <- n
  return(exclude)
}

plan(multiprocess, workers = 4L)
#plan(sequential)

nodesGraph  <- 1:10
nodesGraph  <- sample(nodesGraph)
nodesCount  <- length(nodesGraph)
resultsList <- listenv()

tic()
while ( nodesCount > 0 ) {
  n <- nodesGraph[[nodesCount]]
  ## This is evaluated in parallel and will only block
  ## if all workers are busy.
  resultsList[[nodesCount]] %<-% {
      list( exclude = work(n),
            iteration = length(nodesGraph),
            pid = Sys.getpid())
  }

  nodesGraph <- setdiff(nodesGraph, nodesGraph[[nodesCount]] )
  cat("nodesGraph",nodesGraph,"\n")
  cat("nodesCount",nodesCount,"\n")
  nodesCount = nodesCount - 1
}
toc()

## Resolve all futures (blocks if not already finished)
resultsList <- as.list(resultsList)
str(resultsList)

Parallel Runtime Output:

> source('<hidden>/dev/stackoverflow/47230384/47230384v5.R')
nodesGraph 2 5 8 4 6 10 7 1 9
nodesCount 10
nodesGraph 2 5 8 4 6 10 7 1
nodesCount 9
nodesGraph 2 5 8 4 6 10 7
nodesCount 8
nodesGraph 2 5 8 4 6 10
nodesCount 7
nodesGraph 2 5 8 4 6
nodesCount 6
nodesGraph 2 5 8 4
nodesCount 5
nodesGraph 2 5 8
nodesCount 4
nodesGraph 2 5
nodesCount 3
nodesGraph 2
nodesCount 2
nodesGraph
nodesCount 1
8.22 sec elapsed
List of 10
 $ :List of 3
  ..$ exclude  : int 2
  ..$ iteration: int 1
  ..$ pid      : int 10692
 $ :List of 3
  ..$ exclude  : int 5
  ..$ iteration: int 2
  ..$ pid      : int 2032
 $ :List of 3
  ..$ exclude  : int 8
  ..$ iteration: int 3
  ..$ pid      : int 16356
 $ :List of 3
  ..$ exclude  : int 4
  ..$ iteration: int 4
  ..$ pid      : int 7756
 $ :List of 3
  ..$ exclude  : int 6
  ..$ iteration: int 5
  ..$ pid      : int 10692
 $ :List of 3
  ..$ exclude  : int 10
  ..$ iteration: int 6
  ..$ pid      : int 2032
 $ :List of 3
  ..$ exclude  : int 7
  ..$ iteration: int 7
  ..$ pid      : int 16356
 $ :List of 3
  ..$ exclude  : int 1
  ..$ iteration: int 8
  ..$ pid      : int 7756
 $ :List of 3
  ..$ exclude  : int 9
  ..$ iteration: int 9
  ..$ pid      : int 10692
 $ :List of 3
  ..$ exclude  : int 3
  ..$ iteration: int 10
  ..$ pid      : int 2032

Sequential Runtime output

> source('<hidden>/dev/stackoverflow/47230384/47230384v5.R')
nodesGraph 6 2 1 9 4 8 10 7 3
nodesCount 10
nodesGraph 6 2 1 9 4 8 10 7
nodesCount 9
nodesGraph 6 2 1 9 4 8 10
nodesCount 8
nodesGraph 6 2 1 9 4 8
nodesCount 7
nodesGraph 6 2 1 9 4
nodesCount 6
nodesGraph 6 2 1 9
nodesCount 5
nodesGraph 6 2 1
nodesCount 4
nodesGraph 6 2
nodesCount 3
nodesGraph 6
nodesCount 2
nodesGraph
nodesCount 1
20.61 sec elapsed
List of 10
 $ :List of 3
  ..$ exclude  : int 6
  ..$ iteration: int 1
  ..$ pid      : int 12484
 $ :List of 3
  ..$ exclude  : int 2
  ..$ iteration: int 2
  ..$ pid      : int 12484
 $ :List of 3
  ..$ exclude  : int 1
  ..$ iteration: int 3
  ..$ pid      : int 12484
 $ :List of 3
  ..$ exclude  : int 9
  ..$ iteration: int 4
  ..$ pid      : int 12484
 $ :List of 3
  ..$ exclude  : int 4
  ..$ iteration: int 5
  ..$ pid      : int 12484
 $ :List of 3
  ..$ exclude  : int 8
  ..$ iteration: int 6
  ..$ pid      : int 12484
 $ :List of 3
  ..$ exclude  : int 10
  ..$ iteration: int 7
  ..$ pid      : int 12484
 $ :List of 3
  ..$ exclude  : int 7
  ..$ iteration: int 8
  ..$ pid      : int 12484
 $ :List of 3
  ..$ exclude  : int 3
  ..$ iteration: int 9
  ..$ pid      : int 12484
 $ :List of 3
  ..$ exclude  : int 5
  ..$ iteration: int 10
  ..$ pid      : int 12484


答:
```<code>import java.util.Scanner;

public class printNumber{
  public static void main (String[] args){
        Scanner input = new Scanner(System.in);

        System.out.println("Please select an option between A or B: ");
    String opt=input.nextLine();

    System.out.println("You have selected " +user+ " : ");

    if (opt.equalsIgnoreCase("A")){

    for(int n=1; n<=100; n++){
      if((n%2)==0)
        System.out.println(n);
     }
    }
    else if (opt.equalsIgnoreCase("B")){
    for (int x =1; x<=100; x=x+2){
      System.out.println(x);
     }
    }
    else
      System.out.println("Error, please try again!");
  }
}
</code>```

or you can simply use

```<code>  import java.util.Scanner;

    public class printNumber{
      public static void main (String[] args){
            Scanner input = new Scanner(System.in);

            System.out.println("Please select an option between A or B: ");
        String opt=input.next();

        System.out.println("You have selected " +user+ " : ");

        if (opt == "A" || opt == "a"){

        for(int n=1; n<=100; n++){
          if((n%2)==0)
            System.out.println(n);
         }
        }
        else if (opt == "B" || opt == "b"){
        for (int x =1; x<=100; x=x+2){
          System.out.println(x);
         }
        }
        else
          System.out.println("Error, please try again!");
      }
    }
</code>```

Title: User input upperCase and lowerCase - Java

Body:
I am attempting to take an input of A or B in either Uppercase or LowerCase to follow on through the if statement. I can't figure out how to do this. At the moment, it's only taking in UpperCase A or B. Looked around the forum and the class notes, came up with nothing. Any help would be appriciated!
I tried using toUpperCase() but don't think i am putting it in the right place. It keeps giving me an error

import java.util.Scanner;

public class printNumber{
    public static void main (String[] args){
        Scanner input = new Scanner(System.in);
        System.out.println("Please select an option between A or B: ");
        char user = input.next().charAt(0);

        System.out.println("You have selected " +user+ " : ");
        if (user == 'A'){
            for(int n=1; n<=100; n++){
                if((n%2)==0)
                    System.out.println(n);
            }
        }
        else if (user =='B'){
            for (int x =1; x<=100; x=x+2){
                System.out.println(x);
            }
        }
        else
            System.out.println("Error, please try again!");
    }
}

Body:
import java.util.Scanner;

public class printNumber{
  public static void main (String[] args){
        Scanner input = new Scanner(System.in);

        System.out.println("Please select an option between A or B: ");
    String opt=input.nextLine();

    System.out.println("You have selected " +user+ " : ");

    if (opt.equalsIgnoreCase("A")){

    for(int n=1; n<=100; n++){
      if((n%2)==0)
        System.out.println(n);
     }
    }
    else if (opt.equalsIgnoreCase("B")){
    for (int x =1; x<=100; x=x+2){
      System.out.println(x);
     }
    }
    else
      System.out.println("Error, please try again!");
  }
}

or you can simply use

  import java.util.Scanner;

    public class printNumber{
      public static void main (String[] args){
            Scanner input = new Scanner(System.in);

            System.out.println("Please select an option between A or B: ");
        String opt=input.next();

        System.out.println("You have selected " +user+ " : ");

        if (opt == "A" || opt == "a"){

        for(int n=1; n<=100; n++){
          if((n%2)==0)
            System.out.println(n);
         }
        }
        else if (opt == "B" || opt == "b"){
        for (int x =1; x<=100; x=x+2){
          System.out.println(x);
         }
        }
        else
          System.out.println("Error, please try again!");
      }
    }


问:
Pre-serializing some fields of a proto message
Suppose I have a proto structure that looks like the following:

```<code>message TMessage {
    optional TDictionary dictionary = 1;
    optional int specificField1 = 2;
    optional TOtherMessage specificField2 = 3;
    ...
}
</code>```

Suppose I am using C++. This is the message stub that is used in the master process to send information to the bunch of the nodes using the network. In particular, the dictionary field is 1) pretty heavy 2) common for all the serialized messages, and all the following specific fields are filled with the relatively small information specific to the destination node.

Of course, dictionary is built only once, but it comes out that the major part of running time is spent while serializing the common dictionary part again and again for each new node.

Obvious optimization would be to pre-serialize dictionary into the byte string and put it into the TMessage as a bytes field, but this looks a bit nasty to me.

Am I right that there is no built-in way to pre-serialize a message field without ruining the message structure? It sounds like an idea for a good plugin for proto compiler.

答:
Marc's answer is perfect for your use case. Here is just another option:

The field must be a submessage, like your TDictionary is.

Have another variant of the outer message, with bytes in place of the submessage you want to preserialize:

```
    message TMessage_preserialized {
        optional bytes dictionary = 1;
        ...
    }
```

Now you can serialize the TDictionary separately and put the resulting data in the bytes field. In protobuf format, submessages and bytes field are written out the same way. This means you can serialize as TMessage_preserialized and still deserialize as normal TMessage.

Body:
Suppose I have a proto structure that looks like the following:

message TMessage {
    optional TDictionary dictionary = 1;
    optional int specificField1 = 2;
    optional TOtherMessage specificField2 = 3;
    ...
}

Suppose I am using C++. This is the message stub that is used in the master process to send information to the bunch of the nodes using the network. In particular, the dictionary field is 1) pretty heavy 2) common for all the serialized messages, and all the following specific fields are filled with the relatively small information specific to the destination node.

Of course, dictionary is built only once, but it comes out that the major part of running time is spent while serializing the common dictionary part again and again for each new node.

Obvious optimization would be to pre-serialize dictionary into the byte string and put it into the TMessage as a bytes field, but this looks a bit nasty to me.

Am I right that there is no built-in way to pre-serialize a message field without ruining the message structure? It sounds like an idea for a good plugin for proto compiler.

Body:
Marc's answer is perfect for your use case. Here is just another option:

The field must be a submessage, like your TDictionary is.

Have another variant of the outer message, with bytes in place of the submessage you want to preserialize:

    message TMessage_preserialized {
        optional bytes dictionary = 1;
        ...
    }

Now you can serialize the TDictionary separately and put the resulting data in the bytes field. In protobuf format, submessages and bytes field are written out the same way. This means you can serialize as TMessage_preserialized and still deserialize as normal TMessage.


问:
How can I tell if my Oracle system is set to support Unicode or multibyte characters?
I understand that Oracle supports multiple character sets, but how can determine if the current 11g system where I work has that functionality enabled? </p>

答:
Unicode is a character encoding system that defines every character in most of the spoken languages in the world, Support for Unicode in Oracle Database:

```<code>Character Set   Supported in RDBMS Release  Unicode Encoding
AL24UTFFSS      7.2 - 8i                    UTF-8
UTF8            8.0 - 11g                   UTF-8
UTFE            8.0 - 11g                   UTF-EBCDIC
AL32UTF8        9i - 11g                    UTF-8
AL16UTF16       9i - 11g                    UTF-16
</code>```

To Make sure your database is Unicode, please check the value of "NLS_CHARACTERSET" Parameter and it should be AL32UTF8 or AL16UTF16 from above list.

```<code>SQL>
SQL> SELECT * FROM v$nls_parameters WHERE parameter='NLS_CHARACTERSET';

PARAMETER                   VALUE               CON_ID
--------------------------- ------------------- ----------
NLS_CHARACTERSET            AL32UTF8            0
</code>```

To Change the value of Parameter, Please Take the Fullback up because  ALTER DATABASE statement cannot be rolled back and the Use following statements:

```<code>SHUTDOWN IMMEDIATE
STARTUP MOUNT;
ALTER SYSTEM ENABLE RESTRICTED SESSION;
ALTER SYSTEM SET JOB_QUEUE_PROCESSES=0;
ALTER SYSTEM SET AQ_TM_PROCESSES=0;
ALTER DATABASE OPEN;
ALTER DATABASE CHARACTER SET AL32UTF8;
SHUTDOWN IMMEDIATE;
STARTUP;
</code>```

Body:
Unicode is a character encoding system that defines every character in most of the spoken languages in the world, Support for Unicode in Oracle Database:

Character Set   Supported in RDBMS Release  Unicode Encoding
AL24UTFFSS      7.2 - 8i                    UTF-8
UTF8            8.0 - 11g                   UTF-8
UTFE            8.0 - 11g                   UTF-EBCDIC
AL32UTF8        9i - 11g                    UTF-8
AL16UTF16       9i - 11g                    UTF-16

To Make sure your database is Unicode, please check the value of "NLS_CHARACTERSET" Parameter and it should be AL32UTF8 or AL16UTF16 from above list.

SQL>
SQL> SELECT * FROM v$nls_parameters WHERE parameter='NLS_CHARACTERSET';

PARAMETER                   VALUE               CON_ID
--------------------------- ------------------- ----------
NLS_CHARACTERSET            AL32UTF8            0

To Change the value of Parameter, Please Take the Fullback up because  ALTER DATABASE statement cannot be rolled back and the Use following statements:

SHUTDOWN IMMEDIATE
STARTUP MOUNT;
ALTER SYSTEM ENABLE RESTRICTED SESSION;
ALTER SYSTEM SET JOB_QUEUE_PROCESSES=0;
ALTER SYSTEM SET AQ_TM_PROCESSES=0;
ALTER DATABASE OPEN;
ALTER DATABASE CHARACTER SET AL32UTF8;
SHUTDOWN IMMEDIATE;
STARTUP;


问:
Create new row in a dataframe using the value from different dataframe
I'm new in Python or coding per se. I need your help. So I have 2 dataframe here containing different columns for data learning process. The first data frame contains Intents and Responses with PID. The second data frame spntains Intent and Phrases. I want to use PID information in the first dataframe to create new column in second dataframe that contains team.

first dataframe (var 'finalchat')

```<code>intent              response                                 Pid
PizzaDelivery       What Pizza do you like?                  1.4.6
WeatherForecast     What do you want to know the weather?    2
Emergency Number    Dial 911                                 10.8.9
</code>```

second dataframe (var 'intentdatas')

```<code>intent              response
PizzaDelivery       I want to order a pizza
WeatherForecast     What's the weather in Manila
Emergency Number    What's the number to dial?
</code>```

I want to get the first value in of Pid in the first dataframe. Which are 1, 2, and 3 and compare it with hardcoded condition where if its both TRUE then it will create a column in second dataframe with is 'Team'.

Here's the code I'm trying out but when I run it. It doesn't show anything.

```<code>row_list = []
for index,row in intentdatas.iterrows():
    if ([re.search("1",index) is not None for index in
    finalchat['Pid'].astype(str).str[0]] == 'TRUE'):
    row_list.append({'intent': row['intent'], 'phrases': row['phrases'],
    'Team': 'Pizza'})
elif ([re.search("2",index) is not None for index in
     finalchat['Pid'].astype(str).str[0]] == 'TRUE'):
     row_list.append({'intent': row['intent'], 'phrases': row['phrases'],
     'Team': 'Weather'})
elif ([re.search("10",index) is not None for index in
     finalchat['Pid'].astype(str).str[1]] == 'TRUE'):
    row_list.append({'intent': row['intent'], 'phrases': row['phrases'],
    'Team': 'Emergency'})

intentdatas.head(10)
</code>```

Expected out put

```<code>Intent              Response                          Team
PizzaDelivery       I want to order a pizza           Pizza
WeatherForecast     What's the weather in Manila      Weather
Emergency Number    What's the number to dial?        Emergency
</code>```

Someone told that I can't compare a list to Singleton which is the TRUE statement. Maybe that's why there's nothing outputs whenever i print the intentdatas. Please help me. thanks!

答:
You can merge your data frames, then map teams from Pid values.

```<code>team_map = {"1":"Pizza", "2":"Weather", "10":"Emergency"}

df = intentdatas.merge(finalchat[["intent","Pid"]], on="intent")

df.assign(team=df.Pid.apply(lambda x: team_map[x.split(".")[0]])).drop("Pid", 1)

             intent                      response          team
0     PizzaDelivery       I want to order a pizza         Pizza
1   WeatherForecast  What's the weather in Manila       Weather
2  Emergency Number    What's the number to dial?     Emergency
</code>```

Body:
I'm new in Python or coding per se. I need your help. So I have 2 dataframe here containing different columns for data learning process. The first data frame contains Intents and Responses with PID. The second data frame spntains Intent and Phrases. I want to use PID information in the first dataframe to create new column in second dataframe that contains team.

first dataframe (var 'finalchat')

intent              response                                 Pid
PizzaDelivery       What Pizza do you like?                  1.4.6
WeatherForecast     What do you want to know the weather?    2
Emergency Number    Dial 911                                 10.8.9

second dataframe (var 'intentdatas')

intent              response
PizzaDelivery       I want to order a pizza
WeatherForecast     What's the weather in Manila
Emergency Number    What's the number to dial?

I want to get the first value in of Pid in the first dataframe. Which are 1, 2, and 3 and compare it with hardcoded condition where if its both TRUE then it will create a column in second dataframe with is 'Team'.

Here's the code I'm trying out but when I run it. It doesn't show anything.

row_list = []
for index,row in intentdatas.iterrows():
    if ([re.search("1",index) is not None for index in
    finalchat['Pid'].astype(str).str[0]] == 'TRUE'):
    row_list.append({'intent': row['intent'], 'phrases': row['phrases'],
    'Team': 'Pizza'})
elif ([re.search("2",index) is not None for index in
     finalchat['Pid'].astype(str).str[0]] == 'TRUE'):
     row_list.append({'intent': row['intent'], 'phrases': row['phrases'],
     'Team': 'Weather'})
elif ([re.search("10",index) is not None for index in
     finalchat['Pid'].astype(str).str[1]] == 'TRUE'):
    row_list.append({'intent': row['intent'], 'phrases': row['phrases'],
    'Team': 'Emergency'})

intentdatas.head(10)

Expected out put

Intent              Response                          Team
PizzaDelivery       I want to order a pizza           Pizza
WeatherForecast     What's the weather in Manila      Weather
Emergency Number    What's the number to dial?        Emergency

Someone told that I can't compare a list to Singleton which is the TRUE statement. Maybe that's why there's nothing outputs whenever i print the intentdatas. Please help me. thanks!

Body:
You can merge your data frames, then map teams from Pid values.

team_map = {"1":"Pizza", "2":"Weather", "10":"Emergency"}

df = intentdatas.merge(finalchat[["intent","Pid"]], on="intent")

df.assign(team=df.Pid.apply(lambda x: team_map[x.split(".")[0]])).drop("Pid", 1)

             intent                      response          team
0     PizzaDelivery       I want to order a pizza         Pizza
1   WeatherForecast  What's the weather in Manila       Weather
2  Emergency Number    What's the number to dial?     Emergency


问:
Extract Emoji in JSON and extract it out
I have a Json file and i need to extract the emoji. How can i do that?</p>

```<code>filename = raw_input("Enter the JSON filename: ")
        fp = open(filename)
        jobj = json.load(fp)
        break
      except:
        print("File is not valid. Try again.")
</code>```

答:
 i don't know what your json data looks like but give a try like this if possible share your json data

```<code>import json
filename = raw_input("Enter the JSON filename: ")
        fp = open(filename)
        jobj = json.loads(fp.read())
        emoji = jobj["emojitext"]
        break
      except:
        print("File is not valid. Try again.")
</code>```

Body:
I have a Json file and i need to extract the emoji. How can i do that?

filename = raw_input("Enter the JSON filename: ")
        fp = open(filename)
        jobj = json.load(fp)
        break
      except:
        print("File is not valid. Try again.")

Body:
 i don't know what your json data looks like but give a try like this if possible share your json data

import json
filename = raw_input("Enter the JSON filename: ")
        fp = open(filename)
        jobj = json.loads(fp.read())
        emoji = jobj["emojitext"]
        break
      except:
        print("File is not valid. Try again.")


问:
dompdf form submit didn't send data codeigniter
i am trying to create an PDF using Dompdf, in my program i have model query with a dynamic parameter based on the input in the form, but when i click on my button to send the value from the select button to the controller, the data not been send properly, any idea why? below are my code

```<code><form class="form" method="get" action="<?=site_url()?>/laporan/pdfdownload" id="myID" name="myName">
    <select id="sel1" class="form-control">
         <option disabled selected="selected">Pilih</option>
                  <?php foreach ($kerja as $rows){?>
                  <option value="<?php echo $rows->id_project?>"><?php echo $rows->id_project.' - '.$rows->nama_project ?></option>
                  <?php }?>
    </select>
    <select id="sel2" class="form-control">
         <option disabled selected="selected">Pilih</option>
                  <?php foreach ($item as $rows){?>
                  <option value="<?php echo $rows->id_project?>"><?php echo $rows->id_project.' - '.$rows->nama_project ?></option>
                  <?php }?>
    </select>
   <button id="filter_button" style="margin-top: 26px;margin-left: 28px;width: auto" name="filter_button" type="submit" class="form btn btn-danger"><i class="fa fa-search"></i>&nbspSearch</button>
</form>
</code>```

and here is my controller

```<code>public function pdfdownload(){
                                      //If i click submit then all of the post didnt get sended
    $one = $this->input->post('sel1');//no value at all, anyone know why?
    $two = $this->input->post('sel2');//no value at all, anyone know why?

    $data['real'] = $this->report_m($one,$two)->row();

    htmlcontent = $this->load->view('laporan/download/laporan3.php',$data,true);
    include(APPPATH."third_party/dompdf/autoload.inc.php");
    // require_once APPPATH . 'third_party/dompdf/autoload.inc.php';
    $dompdf = new Dompdf\Dompdf();
    $dompdf->load_html($htmlcontent);
    $dompdf->set_paper("f4");
    $dompdf->render();
    $dompdf->stream("cobadlu.pdf",array("Attachment" => false));
    exit(0);
}

enter code here
</code>```

答:
First of all there is a mistake in your form:

```<code><form class="form" method="get" action="<?=site_url()?>/laporan/pdfdownload" id="myID" name="myName">
</code>```

You given the method='get' here, please change it to 'post'.

Second you are not include the 'name' attribute to the input type so after submit no data will send. So add the name attribute like that:

```<code><select id="sel1" name="sel1" class="form-control">
<select id="sel2" name="sel2" class="form-control">
</code>```

Body:
i am trying to create an PDF using Dompdf, in my program i have model query with a dynamic parameter based on the input in the form, but when i click on my button to send the value from the select button to the controller, the data not been send properly, any idea why? below are my code

<form class="form" method="get" action="<?=site_url()?>/laporan/pdfdownload" id="myID" name="myName">
    <select id="sel1" class="form-control">
         <option disabled selected="selected">Pilih</option>
                  <?php foreach ($kerja as $rows){?>
                  <option value="<?php echo $rows->id_project?>"><?php echo $rows->id_project.' - '.$rows->nama_project ?></option>
                  <?php }?>
    </select>
    <select id="sel2" class="form-control">
         <option disabled selected="selected">Pilih</option>
                  <?php foreach ($item as $rows){?>
                  <option value="<?php echo $rows->id_project?>"><?php echo $rows->id_project.' - '.$rows->nama_project ?></option>
                  <?php }?>
    </select>
   <button id="filter_button" style="margin-top: 26px;margin-left: 28px;width: auto" name="filter_button" type="submit" class="form btn btn-danger">&nbspSearch</button>
</form>

and here is my controller

public function pdfdownload(){
                                      //If i click submit then all of the post didnt get sended
    $one = $this->input->post('sel1');//no value at all, anyone know why?
    $two = $this->input->post('sel2');//no value at all, anyone know why?

    $data['real'] = $this->report_m($one,$two)->row();

    htmlcontent = $this->load->view('laporan/download/laporan3.php',$data,true);
    include(APPPATH."third_party/dompdf/autoload.inc.php");
    // require_once APPPATH . 'third_party/dompdf/autoload.inc.php';
    $dompdf = new Dompdf\Dompdf();
    $dompdf->load_html($htmlcontent);
    $dompdf->set_paper("f4");
    $dompdf->render();
    $dompdf->stream("cobadlu.pdf",array("Attachment" => false));
    exit(0);
}

enter code here

Body:
First of all there is a mistake in your form:

<form class="form" method="get" action="<?=site_url()?>/laporan/pdfdownload" id="myID" name="myName">

You given the method='get' here, please change it to 'post'.

Second you are not include the 'name' attribute to the input type so after submit no data will send. So add the name attribute like that:

<select id="sel1" name="sel1" class="form-control">
<select id="sel2" name="sel2" class="form-control">