问:
Django request.path not working in inclusion tag template
I tried to use request.path in the inclusion tag template, but the url does not show up. The request.path does work properly when used in parent template, and the inclusion tag works properly in all other places.
I enabled 'takes_context' in the inclusion tag, but I don't know if and where I should specify any path-specific context in the views.py.
Currently I use render() method to output the logic from my views.py:

```<code>def DJ_LastDay(request):
    p = Post.objects.latest('Day')
    posts = Post.objects.filter(Day=p.Day)
    return render(request, 'blog/DJ_LastDay.html', {'DJ_LastDay_posts': posts})
</code>```

Snippet of my inclusion tag:

```<code>from django import template
register = template.Library()
@register.inclusion_tag('blog/index_table.html', takes_context=True)
def DJ_LastDay(context):
    return {'posts': context['DJ_LastDay_posts']}
</code>```

Snippet of my inclusion tag template (DJLD, DJLW, DJLM, DJLQ, and DJLY are all url shortcuts I enabled in the parent template, and they work fine outside the inclusion template):

```<code>    {% if request.path == DJLD %}
        Last Day
    {% elif request.path == DJLW %}
        Last Week
    {% elif request.path == DJLM %}
        Last Month
    {% elif request.path == DJLQ %}
        Last Quarter
    {% elif request.path == DJLY %}
        Last Year
    {% endif %}
</code>```

I just needed to detect the current path for a conditional check to display the proper string in my template.
Any help is appreciated

答:
You have to pass request to inclusion_tag template like you did 'posts' in return</p>

```<code>@register.inclusion_tag('blog/index_table.html', takes_context=True)
def DJ_LastDay(context):
    return {'posts': context['DJ_LastDay_posts'], 'request':context['request']}
</code>```

Body:
I tried to use request.path in the inclusion tag template, but the url does not show up. The request.path does work properly when used in parent template, and the inclusion tag works properly in all other places.
I enabled 'takes_context' in the inclusion tag, but I don't know if and where I should specify any path-specific context in the views.py.
Currently I use render() method to output the logic from my views.py:

def DJ_LastDay(request):
    p = Post.objects.latest('Day')
    posts = Post.objects.filter(Day=p.Day)
    return render(request, 'blog/DJ_LastDay.html', {'DJ_LastDay_posts': posts})

Snippet of my inclusion tag:

from django import template
register = template.Library()
@register.inclusion_tag('blog/index_table.html', takes_context=True)
def DJ_LastDay(context):
    return {'posts': context['DJ_LastDay_posts']}

Snippet of my inclusion tag template (DJLD, DJLW, DJLM, DJLQ, and DJLY are all url shortcuts I enabled in the parent template, and they work fine outside the inclusion template):

    {% if request.path == DJLD %}
        Last Day
    {% elif request.path == DJLW %}
        Last Week
    {% elif request.path == DJLM %}
        Last Month
    {% elif request.path == DJLQ %}
        Last Quarter
    {% elif request.path == DJLY %}
        Last Year
    {% endif %}

I just needed to detect the current path for a conditional check to display the proper string in my template.
Any help is appreciated

Body:
You have to pass request to inclusion_tag template like you did 'posts' in return

@register.inclusion_tag('blog/index_table.html', takes_context=True)
def DJ_LastDay(context):
    return {'posts': context['DJ_LastDay_posts'], 'request':context['request']}


来源: stackexchange

问:
LibGDX stage fading to black color
I have multiple screens with stages in my game and I have been implementing a simple fade transition between them.

It works now, but I want that the screen fades out to black. The clear color of the game is white, though, so only the stage is obviously faded out, and the background keeps white. I have tried adding Actions.color(Color.BLACK, Interpolation.fade) to the stage but nothing really happens at all.

How could I implement the fade transition correctly?

答:
Stage doesn't have drawable content only a group that contains all children.

So create full Screen black Image and add to stage as background. Then inside show() that make it white by action, as your required background.

```<code>@Override
public void show() {

    final Image image=new Image(new TextureRegion(GdxTest.getTexture()));
    image.setSize(stage.getWidth(),stage.getHeight());
    image.setOrigin(stage.getWidth()/2,stage.getHeight()/2);
    image.setColor(Color.BLACK);

    stage.addActor(image);
    stage.addListener(new ClickListener(){

        @Override
        public void clicked(InputEvent event, float x, float y) {

            image.addAction(Actions.sequence(Actions.color(Color.BLACK,2),Actions.run(new Runnable() {
                @Override
                public void run() {
                    ((GdxTest)Gdx.app.getApplicationListener()).setScreen(new SecondScreen());
                }
            })));

            super.clicked(event, x, y);
        }
    });

    image.addAction(Actions.color(Color.WHITE,2));
}
</code>```

getTexture() method

```<code>public static Texture getTexture(){

    Pixmap pixmap;
    try {
        pixmap = new Pixmap(1, 1, Pixmap.Format.RGBA8888);
    }catch (GdxRuntimeException e)
    {
        pixmap=new Pixmap(1,1, Pixmap.Format.RGB565);
    }
    pixmap.setColor(Color.WHITE);
    pixmap.drawRectangle(0,0,1,1);

    return new Texture(pixmap);
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: LibGDX stage fading to black color

Body:
Stage doesn't have drawable content only a group that contains all children.

So create full Screen black Image and add to stage as background. Then inside show() that make it white by action, as your required background.

@Override
public void show() {

    final Image image=new Image(new TextureRegion(GdxTest.getTexture()));
    image.setSize(stage.getWidth(),stage.getHeight());
    image.setOrigin(stage.getWidth()/2,stage.getHeight()/2);
    image.setColor(Color.BLACK);

    stage.addActor(image);
    stage.addListener(new ClickListener(){

        @Override
        public void clicked(InputEvent event, float x, float y) {

            image.addAction(Actions.sequence(Actions.color(Color.BLACK,2),Actions.run(new Runnable() {
                @Override
                public void run() {
                    ((GdxTest)Gdx.app.getApplicationListener()).setScreen(new SecondScreen());
                }
            })));

            super.clicked(event, x, y);
        }
    });

    image.addAction(Actions.color(Color.WHITE,2));
}

getTexture() method

public static Texture getTexture(){

    Pixmap pixmap;
    try {
        pixmap = new Pixmap(1, 1, Pixmap.Format.RGBA8888);
    }catch (GdxRuntimeException e)
    {
        pixmap=new Pixmap(1,1, Pixmap.Format.RGB565);
    }
    pixmap.setColor(Color.WHITE);
    pixmap.drawRectangle(0,0,1,1);

    return new Texture(pixmap);
}


问:
How do I display duration in milliseconds as a properly formatted string?
I'm using Ruby 2.4.  I want to convert milliseconds to a readable hours, minutes, and seconds format.  SO I have this method

```<code>  def time_as_str(time_in_ms)
    regex = /^(0*:?)*0*/
    Time.at(time_in_ms.to_f/1000).utc.strftime("%H:%M:%S.%1N").sub!(regex, '')
  end
</code>```

The problem is, if my value in milliseconds is a day or greater, this function doesn't display the correct values.  FOr instance, if I pass

```<code>2.4.0 :009 > TimeFormattingHelper.time_as_str(86400000)
 => ".0"
</code>```

86400000 is a day in milliseconds (unless I've miscalculated).  So I would expect the value to be "24:00:00".  How do I correct the above to display the time formatted properly?

Body:
I'm using Ruby 2.4.  I want to convert milliseconds to a readable hours, minutes, and seconds format.  SO I have this method

  def time_as_str(time_in_ms)
    regex = /^(0*:?)*0*/
    Time.at(time_in_ms.to_f/1000).utc.strftime("%H:%M:%S.%1N").sub!(regex, '')
  end

The problem is, if my value in milliseconds is a day or greater, this function doesn't display the correct values.  FOr instance, if I pass

2.4.0 :009 > TimeFormattingHelper.time_as_str(86400000)
 => ".0"

86400000 is a day in milliseconds (unless I've miscalculated).  So I would expect the value to be "24:00:00".  How do I correct the above to display the time formatted properly?

Body:
def time_as_str(ms)
  secs, ms    =   ms.divmod(1000)
  mins, secs  = secs.divmod(60)
  hours, mins = mins.divmod(60)
  s = "%d.%d.%d.%s" % [hours, mins, secs, ms.zero? ? "0" : ms.to_s.sub(/0*\z/,'')]
  if hours > 0
    s
  elsif mins > 0
    s[2..-1]
  else
    s[4..-1]
  end
end

time_as_str(86_400_000)    #=> "24.0.0.0"
time_as_str(0)             #=> "0.0"
time_as_str(499)           #=> "0.499"
time_as_str(60_280)        #=> "1.0.28"
time_as_str(360_000)       #=> "6.0.0"
time_as_str(1_000_000_200) #=> "277.46.40.2"

See Integer#divmod, an oft-overlooked method.

Suppose

ms = 2_045_670

then

secs, ms    =   ms.divmod(1000)
  #=> [2045, 670] (secs #=> 2045, ms #=> 670)
mins, secs  = secs.divmod(60)
  #=> [34, 5]
hours, mins = mins.divmod(60)
  #=> [0, 34]
ms = ms.zero? ? "0" : ms.to_s.sub(/0*\z/,'')
  #=> "67" (truncate)
s = "%d.%d.%d.%s" % [hours, mins, secs, ms]
  #=> "0.34.5.67"
if hours > 0   # false
  "0.34.5.67"
elsif mins > 0 # true
  "34.5.67"
else           # not evaluated
  "5.67"
end
  #=> "34.5.67"


问:
Regex string match for swift function call
What I need is to return whole line that contains the word 'func' and ends with '{'

I want to detect function declaration in a swift file and add a comment as first line of the function body.

For example:

```<code>NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^(-[^{]+\\{)" options:NSRegularExpressionAnchorsMatchLines error:&error];
</code>```

This returns me every objective C function declaration in any .m file. I just want the pattern that will replace ^(-[^{]+\{). So that I can apply for .swift file to detect swift function call.

The program is written in Objective-C so if anyone can give me Objective C pattern that returns line containing 'func' and ends with '{' - that will meet my requirement.

答:
I thnk this will search ur exact pattern u r looking.I've added to search one more word after func .So it will find a function declared like this

func add {

\b(w{4})\s(\w+\s[{])

Body:
What I need is to return whole line that contains the word 'func' and ends with '{'

I want to detect function declaration in a swift file and add a comment as first line of the function body.

For example:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^(-[^{]+\\{)" options:NSRegularExpressionAnchorsMatchLines error:&error];

This returns me every objective C function declaration in any .m file. I just want the pattern that will replace ^(-[^{]+\{). So that I can apply for .swift file to detect swift function call.

The program is written in Objective-C so if anyone can give me Objective C pattern that returns line containing 'func' and ends with '{' - that will meet my requirement.


问:
Clicking one button then activate another button
I want to click 1st button then activate 2nd button. After 2nd button is activated, 1st button will be disabled. I wrote the code below but it is not working. Where is the problem?</p>

```<code><!DOCTYPE html>
<html>
<head>
<title>Edit Page</title>
</head>
<body>
<input type="submit" name="submit" value="button1" id="bt1">
<input type="button" name="button" value="button2" id="bt2" disabled="disabled">
</body>
<script>
$(function(){
        $("#bt1").click(function(){
            $(this).attr("disabled", "disabled");
            $("#bt2").removeAttr("disabled");
        });

        $("#bt2").click(function(){
            $(this).attr("disabled", "disabled");
            $("#bt1").removeAttr("disabled");
        });
    });
</script>

</html>
</code>```

答:
Include jQuery library file at the top of head tag like this:</p>

```<code><html>
<head>
<title>Edit Page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>$(function(){
$("#bt1").click(function(){
$(this).attr("disabled", "disabled");
$("#bt2").removeAttr("disabled");
});

$("#bt2").click(function(){
$(this).attr("disabled", "disabled");
$("#bt1").removeAttr("disabled");
});
});
</script>
</head>
<body>
<input type="submit" name="submit" value="button1" id="bt1">
<input type="button" name="button" value="button2" id="bt2" disabled="disabled">
</body>
</html>
</code>```

Body:
I want to click 1st button then activate 2nd button. After 2nd button is activated, 1st button will be disabled. I wrote the code below but it is not working. Where is the problem?

<!DOCTYPE html>

<title>Edit Page</title>

<input type="submit" name="submit" value="button1" id="bt1">
<input type="button" name="button" value="button2" id="bt2" disabled="disabled">

Body:
Include jQuery library file at the top of head tag like this:

<html>
<head>
<title>Edit Page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>$(function(){
$("#bt1").click(function(){
$(this).attr("disabled", "disabled");
$("#bt2").removeAttr("disabled");
});

$("#bt2").click(function(){
$(this).attr("disabled", "disabled");
$("#bt1").removeAttr("disabled");
});
});
</script>
</head>
<body>
<input type="submit" name="submit" value="button1" id="bt1">
<input type="button" name="button" value="button2" id="bt2" disabled="disabled">
</body>
</html>


问:
How to add the floating numbers in a list in python?
How do I add the sum of the squares in the input file?

Input file is a txt file and is shown below:

```<code>10 9 8 7 1 2 3 4
3 -4 1 -2
0.743 -12.3 5.3333 3
-3.3
</code>```

Hence the output may look like this;

```<code>324.0
30.0
189.28613789000002
10.889999999999999
</code>```

I can't add the floating numbers using sum as it displays an error, so any help would be much appreciated.

Here is my code:

```<code>#Ask the user to input a file name
file_name=input("Enter the Filename: ")

#Opening the desired file to read the content
infile=open(file_name,'r')

#Importing the math library
import math

#Iterating for the number of lines in the file
for line in infile:

    #Converting the file to a list row by row
    line_str=line.split()

    for element in range(len(line_str)):
        line_str[element]=float(line_str[element])
        line_str[element]=math.pow(line_str[element],2)
        total=sum(line_str[0:len(element)])
        print(total)
</code>```

答:
```<code>for line in infile:
    numbers = map(float, line.split())
    squares = (i ** 2 for i in numbers)
    print(sum(squares))
</code>```

Body:
How do I add the sum of the squares in the input file?

Input file is a txt file and is shown below:

10 9 8 7 1 2 3 4
3 -4 1 -2
0.743 -12.3 5.3333 3
-3.3

Hence the output may look like this;

324.0
30.0
189.28613789000002
10.889999999999999

I can't add the floating numbers using sum as it displays an error, so any help would be much appreciated.

Here is my code:

#Ask the user to input a file name
file_name=input("Enter the Filename: ")

#Opening the desired file to read the content
infile=open(file_name,'r')

#Importing the math library
import math

#Iterating for the number of lines in the file
for line in infile:

    #Converting the file to a list row by row
    line_str=line.split()

    for element in range(len(line_str)):
        line_str[element]=float(line_str[element])
        line_str[element]=math.pow(line_str[element],2)
        total=sum(line_str[0:len(element)])
        print(total)


问:
How to store Session ID securely
I am a student learning about cryptography. After searching online, I am still unable to find an answer to my question. I am wondering how to store a session ID securely for an ecommerce website. If it is possible, how so? Please do explain it in Layman's term. Looking forward to your helpful answers.

Cheers

答:
Session IDs are usually just a random (opaque) identifier that is passed between the client and the server.  The server uses the identifier to look up state information (e.g. current cart content) in the database.

As a practical matter, you have to trust that the client will protect the session id, as once you send it to them, it becomes a static token -- no amount of cryptography can fix the fact that anyone can present a session id and then pretend to be the user.

There are some things that you can do to mitigate issues:

ensure you are using a "secure enough" random generator to build the
token

make sure the transmission of the token is as secure as possible against eavesdropping or client-side theft (e.g. use SSL, httponly and secure cookie flags)

Give the token a reasonable timeout, and require the user to request a new token periodically using e.g. a refresh token or re-login.

A lot of thought has gone in to how this can work practically - have a look at the OAuth2 / OpenID Connect protocols.

Title: How to store Session ID securely


答:
There are multiple problems with your code.

The error you got is because you do:

```<code>total=sum(line_str[0:len(element)])
</code>```

and element is an integer as it loops over the the values range() generates.

You have the totalisation and print in the for loops. You call print for every element, not for every line, so you cannot get the output that you need.

This: line_str[0:0] will get you an empty list, and your use of this:  line_str[0:element] will never include the last element

This is a version that works with minimal changes:

```<code>#Ask the user to input a file name
# file_name=input("Enter the Filename: ")  # temporary commented out for easier testing.
file_name = "input.txt"

#Opening the desired file to read the content
infile=open(file_name,'r')

#Importing the math library
import math

#Iterating for the number of lines in the file
for line in infile:

    #Converting the file to a list row by row
    line_str=line.split()

    for element in range(len(line_str)):
        line_str[element]=float(line_str[element])
        line_str[element]=math.pow(line_str[element],2)
    total=sum(line_str[0:element+1])
    print(total)
</code>```

This gives:

```<code>324.0
30.0
189.28613789000002
10.889999999999999
</code>```

but can be much improved upon:

use spaces around = in assignments

don't use for .... range(somelist): and then index somelist.  Instead use enumerate.

combine the conversion to float with splitting the line

use a space after '#' in comments

Something along these lines:

```<code># Ask the user to input a file name
# file_name=input("Enter the Filename: ")
file_name = "input.txt"

# Opening the desired file to read the content
infile=open(file_name,'r')

# Importing the math library
import math

# Iterating for the number of lines in the file
for line in infile:

    # Converting the file to a list row by row and convert to float
    line_str = [float(x) for x in line.split()]

    for idx, element in enumerate(line_str):
        line_str[idx] = math.pow(element,2)
    total = sum(line_str)
    print(total)
</code>```

Title: How to add the floating numbers in a list in python?

Body:
There are multiple problems with your code.

The error you got is because you do:

total=sum(line_str[0:len(element)])

and element is an integer as it loops over the the values range() generates.

You have the totalisation and print in the for loops. You call print for every element, not for every line, so you cannot get the output that you need.

This: line_str[0:0] will get you an empty list, and your use of this:  line_str[0:element] will never include the last element

This is a version that works with minimal changes:

#Ask the user to input a file name
# file_name=input("Enter the Filename: ")  # temporary commented out for easier testing.
file_name = "input.txt"

#Opening the desired file to read the content
infile=open(file_name,'r')

#Importing the math library
import math

#Iterating for the number of lines in the file
for line in infile:

    #Converting the file to a list row by row
    line_str=line.split()

    for element in range(len(line_str)):
        line_str[element]=float(line_str[element])
        line_str[element]=math.pow(line_str[element],2)
    total=sum(line_str[0:element+1])
    print(total)

This gives:

324.0
30.0
189.28613789000002
10.889999999999999

but can be much improved upon:

use spaces around = in assignments

don't use for .... range(somelist): and then index somelist.  Instead use enumerate.

combine the conversion to float with splitting the line

use a space after '#' in comments

Something along these lines:

# Ask the user to input a file name
# file_name=input("Enter the Filename: ")
file_name = "input.txt"

# Opening the desired file to read the content
infile=open(file_name,'r')

# Importing the math library
import math

# Iterating for the number of lines in the file
for line in infile:

    # Converting the file to a list row by row and convert to float
    line_str = [float(x) for x in line.split()]

    for idx, element in enumerate(line_str):
        line_str[idx] = math.pow(element,2)
    total = sum(line_str)
    print(total)


问:
finding the keys of all the largest values in python dictionary?
if I have a dictionary

```<code>x ={0: 0, 1: 4, 2: 0, 3: 2, 4: 2, 5: 4}
</code>```

how do i get the keys of all the largest values

In this case they would be 1 and 5 .

Not a duplicate question. looking to find all the keys and not just the one.

答:
There is a class in collections called Counter that does exactly what you want. It provides the exact functionality you require via it's most_common method:

```<code>from collections import counter
maxes = Counter(x).most_common(2)
print([x[0] for x in maxes])
</code>```

```<code>[1, 5]
</code>```

Now this is probably not exactly what you want because I hard coded in the number 2. You can get this by using another Counter on the values of your dictionary!

```<code>x = Counter(x) # This preserves x: just makes it a subclass of dict
max_count = Counter(x.values())[x.most_common(1)[0][1]]
maxes = x.most_common(max_count)
maxes = [x[0] for x in maxes]
</code>```

Here, I compute the number of times that the most common value occurs by counting all the different values, and then checking the maximum one using x.most_common(1)[0][1].

Please do not select this answer. @BrightOne has the right answer. This is just a thing I did to see if I could avoid using anything but Counters. It is not actually a good idea.

Body:
if I have a dictionary

x ={0: 0, 1: 4, 2: 0, 3: 2, 4: 2, 5: 4}

how do i get the keys of all the largest values

In this case they would be 1 and 5 .

Not a duplicate question. looking to find all the keys and not just the one.

Body:
There is a class in collections called Counter that does exactly what you want. It provides the exact functionality you require via it's most_common method:

from collections import counter
maxes = Counter(x).most_common(2)
print([x[0] for x in maxes])

[1, 5]

Now this is probably not exactly what you want because I hard coded in the number 2. You can get this by using another Counter on the values of your dictionary!

x = Counter(x) # This preserves x: just makes it a subclass of dict
max_count = Counter(x.values())[x.most_common(1)[0][1]]
maxes = x.most_common(max_count)
maxes = [x[0] for x in maxes]

Here, I compute the number of times that the most common value occurs by counting all the different values, and then checking the maximum one using x.most_common(1)[0][1].

Please do not select this answer. @BrightOne has the right answer. This is just a thing I did to see if I could avoid using anything but Counters. It is not actually a good idea.


问:
How can I show file sizes with commas when getting a directory listing with 'ls -l'?
You can do 'ls -l' to get a detailed directory listing like this:

```<code>-rw-rw-rw-  1 alice themonkeys 1159995999 2008-08-20 07:01 foo.log
-rw-rw-rw-  1 bob   bob         244251992 2008-08-20 05:30 bar.txt
</code>```

But notice how you have to slide your finger along the screen to figure out the order of magnitude of those file sizes.

What's a good way to add commas to the file sizes in the directory listing, like this:

```<code>-rw-rw-rw-  1 alice themonkeys 1,159,995,999 2008-08-20 07:01 foo.log
-rw-rw-rw-  1 bob   bob          244,251,992 2008-08-20 05:30 bar.txt
</code>```

答:
I don't think 'ls' has exactly that capability. If you are looking for readability, 'ls -lh' will give you file sizes that are easier for humans to parse.</p>

```<code>-rw-rw-rw-  1 alice themonkeys 1.2G 2008-08-20 07:01 foo.log
-rw-rw-rw-  1 bob   bob        244M 2008-08-20 05:30 bar.txt
</code>```

OwnerDisplayName: dreeves

ContentLicense: CC BY-SA 2.5

Body:
You can do 'ls -l' to get a detailed directory listing like this:

-rw-rw-rw-  1 alice themonkeys 1159995999 2008-08-20 07:01 foo.log
-rw-rw-rw-  1 bob   bob         244251992 2008-08-20 05:30 bar.txt

But notice how you have to slide your finger along the screen to figure out the order of magnitude of those file sizes.

What's a good way to add commas to the file sizes in the directory listing, like this:

-rw-rw-rw-  1 alice themonkeys 1,159,995,999 2008-08-20 07:01 foo.log
-rw-rw-rw-  1 bob   bob          244,251,992 2008-08-20 05:30 bar.txt

Body:
I don't think 'ls' has exactly that capability. If you are looking for readability, 'ls -lh' will give you file sizes that are easier for humans to parse.

-rw-rw-rw-  1 alice themonkeys 1.2G 2008-08-20 07:01 foo.log
-rw-rw-rw-  1 bob   bob        244M 2008-08-20 05:30 bar.txt


问:
WCF low level communication hacking
I've just read about how WCF can send reliable messages and I wanted to check something.

If the WCF service is set to use Reliable Messaging and a client requested some data from a service.  If the client had been hacked to keep saying this data not received would the WCF service keep resending the data indefinitely? Could this be used to affect the stability of the server and is it a risk?

Are there security measures which should be put in place if the WCF service is public?

I suppose it's not much worse than clients clicking refresh on a webpage. But is there anything else which should be considered?

答:
There is a MaxRetryCount property:

This value, which defaults to 8
  (minimum 1, maximum 20), specifies how
  many times the infrastructure shall
  retry to resend a message in case of a
  transmission failure. Once a message
  has been unsuccessfully resent for the
  configured number of retries, the
  failure is considered to be
  unrecoverable and causes the channel
  to fault.

Title: WCF low level communication hacking


问:
Change view by changing segmented control
I have a view UIViewController which contains two containers, one container embed to UIViewController and second to UITableViewController. UIViewController has a SegmentedControl with 3 segments. I would like to change the UITableViewController contents according to each segment. Which way is better to implement that?

Example of one of the table views: (I have two more for songs and artists)

```<code>class AlbumsSegmentView: UITableViewController{

    let qryAlbums = MPMediaQuery.albums()
    var allAlbums : [MPMediaItem] = []
    var contentView = UIViewController()

    var myMP = MPMusicPlayerController.systemMusicPlayer()

    override func viewDidLoad() {

        /* Background */
        tableView.backgroundColor = UIColor.clear
        tableView.separatorColor = UIColor.clear

        /*  Grouping list  */
        qryAlbums.groupingType = MPMediaGrouping.album
        allAlbums += MPMediaQuery.albums().items!

        self.clearsSelectionOnViewWillAppear = false
        self.view.isHidden=true
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell: CustomTableViewCellAlbum = CustomTableViewCellAlbum(style: UITableViewCellStyle.subtitle, reuseIdentifier: "cell")
        cell.imageView!.clipsToBounds = true

        /*  For Album list  */
         let currLoc = qryAlbums.collectionSections![indexPath.section].range.location
         let rowItem = qryAlbums.collections![indexPath.row + currLoc]

        //Main text is Album name
        cell.textLabel!.text = rowItem.items[0].albumTitle
        cell.textLabel!.font = UIFont(name: "HelveticaNeue-Thin", size: 22)
        cell.textLabel!.textColor = UIColor.white

        // Detail text is Album artist
        cell.detailTextLabel!.text = rowItem.items[0].albumArtist!
        cell.detailTextLabel!.font = UIFont(name: "HelveticaNeue-Thin", size:18)
        cell.detailTextLabel!.textColor = UIColor.white

        cell.backgroundColor = UIColor.clear

        let seperatorImageView = UIImageView.init(image: UIImage.init(named: "Separator.png"))
        seperatorImageView.frame = CGRect(x: 10, y: cell.contentView.frame.size.height+26, width: cell.contentView.frame.size.width, height: 3)
        cell.contentView.addSubview(seperatorImageView)

        // Or number of songs from the current album if you prefer
        //cell.detailTextLabel!.text = String(rowItem.items.count) + " songs"

        // Add the album artwork
        let artWork = rowItem.representativeItem?.artwork
        let tableImageSize = CGSize(width: 10, height: 10) //doesn't matter - gets resized below
        let cellImg: UIImageView = UIImageView(frame: CGRect(x:12,y:6,width:60,height:60))
        cellImg.image = artWork?.image(at: tableImageSize)
        cell.addSubview(cellImg)

        return cell
    }

    /*  For Songs list  */

    func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
        let sectionIndexTitles = qryAlbums.itemSections!.map { $0.title }
        return sectionIndexTitles
    }
    func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
        return index
    }
    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return (qryAlbums.itemSections![section].title)
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return allAlbums.count
        //return (qryAlbums.collections?.count)!;
        //return qryAlbums.collectionSections![section].range.length
    }
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let currLoc = qryAlbums.collectionSections![indexPath.section].range.location
        myMP.setQueue(with: qryAlbums.collections![indexPath.row + currLoc])
        myMP.play()
    }

}

class CustomTableViewCellAlbum: UITableViewCell {

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }

    // Here you can customize the appearance of your cell
    override func layoutSubviews() {
        super.layoutSubviews()
        // Customize imageView like you need
        self.imageView?.frame = CGRect(x:12,y:6,width:60,height:60)
        self.imageView?.contentMode = UIViewContentMode.scaleAspectFit

        self.textLabel?.frame = CGRect(x:78, y:5, width:200, height:30)
        self.detailTextLabel?.frame = CGRect(x:78, y:35, width:200, height:30)

    }
}
</code>```

Example of container:

```<code>class MyParentViewController: UIViewController {

    var buttonPanelViewController: PanelViewController!
    var tableViewController: TableViewController2!

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if let tableViewController = segue.destination as? TableViewController {
            self.tableViewController = tableViewController
        }
        else if let buttonPanelViewController = segue.destination as? PanelViewController {
            self.buttonPanelViewController = buttonPanelViewController
        }
    }
}

class TableViewController: UITableViewController {}

class PanelViewController: UIViewController {}
</code>```

Example of Storyboard view
Picture example

UPD: The last thing I tried was to create 3 different UIViews above each other in MyParentViewController and attach them to different classes (Song, Artist, Album) and trying to hide one by one after switching the segments, but it didn't work. Maybe there is another and better way to implement this?

```<code>class MyParentViewController: UIViewController {

    var buttonPanelViewController: PanelViewController!

      override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if let artistViewController = segue.destination as? ArtistViewController {
            self.artistViewController = artistViewController
        }
        else if let buttonPanelViewController = segue.destination as? PanelViewController {
            self.buttonPanelViewController = buttonPanelViewController
        }
        else if let songViewController = segue.destination as? SongViewController { self.songViewController = songViewController
        }
        else let albumViewController = segue.destination as? AlbumViewController { self.albumViewController = albumViewController
         }
        }
    }

}

class TableViewController: UITableViewController {}

class PanelViewController: UIViewController {

    @IBOutlet public weak var segmentTest: UISegmentedControl!

    @IBAction func testAction(_ sender: UISegmentedControl) {

        if (segmentTest.selectedSegmentIndex == 0){
            BackTableVC().view.isHidden=false
            SongsSegmentView().view.isHidden = true
            AlbumsSegmentView().view.isHidden = true
            print("Hi")

        }else if (segmentTest.selectedSegmentIndex == 1){
            BackTableVC().view.isHidden = true
            SongsSegmentView().view.isHidden = false
            AlbumsSegmentView().view.isHidden = true
            print("Thank")
        }else{
            BackTableVC().view.isHidden = true
            SongsSegmentView().view.isHidden = true
            AlbumsSegmentView().view.isHidden = false
            print("You")
        }

    }

     }

class ArtistViewController: UIView{

} class SongViewController: UIView{

} class AlbumViewController: UIView{

}
</code>```

答:
The best way to solve this problem is to not change the table view for each segmented control, but to change the cell on each segmented control. register 3 cells for the table view controller, and once the segmented control value changes, call a delegate function to change which cell is dequeued and then update the table view with the new contents.

From the BackPanelVC, create an action from your segmented control to its class on value changed. In that action, call a delegate function with which control it has been switched to.

```<code>protocol SegmentControlChangeDelegate {
    func segmentedControlChangedValue(_ value: Int)
}

class PanelViewController: UIViewController {

@IBOutlet public weak var segmentTest: UISegmentedControl!
var delegate: SegmentControlChangeDelegate?

@IBAction func testAction(_ sender: UISegmentedControl) {
    delegate.segmentedControlChangedValue(value: sender.selectedSegmentIndex)
    self.performSegue(with: "identifier")
}

}
</code>```

And in the tableviewcontroller conform to the delegate like so:

```<code>class AlbumsSegmentView: UITableViewController, SegmentControlChangeDelegate {
     func segmentedControlChangedValue(_ value: Int){
     // Change which cell is being displayed with some type of boolean or switch statement that will be recalled in cell.dequeue
     }
}
</code>```

And make sure that you set the delegate to self in the tableviewcontroller

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destinationVC = segue.destination as? PanelViewController {
        destinationVC.delegate = self
    }
}
</code>```

Body:
I have a view UIViewController which contains two containers, one container embed to UIViewController and second to UITableViewController. UIViewController has a SegmentedControl with 3 segments. I would like to change the UITableViewController contents according to each segment. Which way is better to implement that?

Example of one of the table views: (I have two more for songs and artists)

class AlbumsSegmentView: UITableViewController{

    let qryAlbums = MPMediaQuery.albums()
    var allAlbums : [MPMediaItem] = []
    var contentView = UIViewController()

    var myMP = MPMusicPlayerController.systemMusicPlayer()

    override func viewDidLoad() {

        /* Background */
        tableView.backgroundColor = UIColor.clear
        tableView.separatorColor = UIColor.clear

        /*  Grouping list  */
        qryAlbums.groupingType = MPMediaGrouping.album
        allAlbums += MPMediaQuery.albums().items!

        self.clearsSelectionOnViewWillAppear = false
        self.view.isHidden=true
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell: CustomTableViewCellAlbum = CustomTableViewCellAlbum(style: UITableViewCellStyle.subtitle, reuseIdentifier: "cell")
        cell.imageView!.clipsToBounds = true

        /*  For Album list  */
         let currLoc = qryAlbums.collectionSections![indexPath.section].range.location
         let rowItem = qryAlbums.collections![indexPath.row + currLoc]

        //Main text is Album name
        cell.textLabel!.text = rowItem.items[0].albumTitle
        cell.textLabel!.font = UIFont(name: "HelveticaNeue-Thin", size: 22)
        cell.textLabel!.textColor = UIColor.white

        // Detail text is Album artist
        cell.detailTextLabel!.text = rowItem.items[0].albumArtist!
        cell.detailTextLabel!.font = UIFont(name: "HelveticaNeue-Thin", size:18)
        cell.detailTextLabel!.textColor = UIColor.white

        cell.backgroundColor = UIColor.clear

        let seperatorImageView = UIImageView.init(image: UIImage.init(named: "Separator.png"))
        seperatorImageView.frame = CGRect(x: 10, y: cell.contentView.frame.size.height+26, width: cell.contentView.frame.size.width, height: 3)
        cell.contentView.addSubview(seperatorImageView)

        // Or number of songs from the current album if you prefer
        //cell.detailTextLabel!.text = String(rowItem.items.count) + " songs"

        // Add the album artwork
        let artWork = rowItem.representativeItem?.artwork
        let tableImageSize = CGSize(width: 10, height: 10) //doesn't matter - gets resized below
        let cellImg: UIImageView = UIImageView(frame: CGRect(x:12,y:6,width:60,height:60))
        cellImg.image = artWork?.image(at: tableImageSize)
        cell.addSubview(cellImg)

        return cell
    }

    /*  For Songs list  */

    func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
        let sectionIndexTitles = qryAlbums.itemSections!.map { $0.title }
        return sectionIndexTitles
    }
    func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
        return index
    }
    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return (qryAlbums.itemSections![section].title)
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return allAlbums.count
        //return (qryAlbums.collections?.count)!;
        //return qryAlbums.collectionSections![section].range.length
    }
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let currLoc = qryAlbums.collectionSections![indexPath.section].range.location
        myMP.setQueue(with: qryAlbums.collections![indexPath.row + currLoc])
        myMP.play()
    }

}

class CustomTableViewCellAlbum: UITableViewCell {

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }

    // Here you can customize the appearance of your cell
    override func layoutSubviews() {
        super.layoutSubviews()
        // Customize imageView like you need
        self.imageView?.frame = CGRect(x:12,y:6,width:60,height:60)
        self.imageView?.contentMode = UIViewContentMode.scaleAspectFit

        self.textLabel?.frame = CGRect(x:78, y:5, width:200, height:30)
        self.detailTextLabel?.frame = CGRect(x:78, y:35, width:200, height:30)

    }
}

Example of container:

class MyParentViewController: UIViewController {

    var buttonPanelViewController: PanelViewController!
    var tableViewController: TableViewController2!

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if let tableViewController = segue.destination as? TableViewController {
            self.tableViewController = tableViewController
        }
        else if let buttonPanelViewController = segue.destination as? PanelViewController {
            self.buttonPanelViewController = buttonPanelViewController
        }
    }
}

class TableViewController: UITableViewController {}

class PanelViewController: UIViewController {}

Example of Storyboard view
Picture example

UPD: The last thing I tried was to create 3 different UIViews above each other in MyParentViewController and attach them to different classes (Song, Artist, Album) and trying to hide one by one after switching the segments, but it didn't work. Maybe there is another and better way to implement this?

class MyParentViewController: UIViewController {

    var buttonPanelViewController: PanelViewController!

      override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if let artistViewController = segue.destination as? ArtistViewController {
            self.artistViewController = artistViewController
        }
        else if let buttonPanelViewController = segue.destination as? PanelViewController {
            self.buttonPanelViewController = buttonPanelViewController
        }
        else if let songViewController = segue.destination as? SongViewController { self.songViewController = songViewController
        }
        else let albumViewController = segue.destination as? AlbumViewController { self.albumViewController = albumViewController
         }
        }
    }

}

class TableViewController: UITableViewController {}

class PanelViewController: UIViewController {

    @IBOutlet public weak var segmentTest: UISegmentedControl!

    @IBAction func testAction(_ sender: UISegmentedControl) {

        if (segmentTest.selectedSegmentIndex == 0){
            BackTableVC().view.isHidden=false
            SongsSegmentView().view.isHidden = true
            AlbumsSegmentView().view.isHidden = true
            print("Hi")

        }else if (segmentTest.selectedSegmentIndex == 1){
            BackTableVC().view.isHidden = true
            SongsSegmentView().view.isHidden = false
            AlbumsSegmentView().view.isHidden = true
            print("Thank")
        }else{
            BackTableVC().view.isHidden = true
            SongsSegmentView().view.isHidden = true
            AlbumsSegmentView().view.isHidden = false
            print("You")
        }

    }

     }

class ArtistViewController: UIView{

} class SongViewController: UIView{

} class AlbumViewController: UIView{

}

Body:
The best way to solve this problem is to not change the table view for each segmented control, but to change the cell on each segmented control. register 3 cells for the table view controller, and once the segmented control value changes, call a delegate function to change which cell is dequeued and then update the table view with the new contents.

From the BackPanelVC, create an action from your segmented control to its class on value changed. In that action, call a delegate function with which control it has been switched to.

protocol SegmentControlChangeDelegate {
    func segmentedControlChangedValue(_ value: Int)
}

class PanelViewController: UIViewController {

@IBOutlet public weak var segmentTest: UISegmentedControl!
var delegate: SegmentControlChangeDelegate?

@IBAction func testAction(_ sender: UISegmentedControl) {
    delegate.segmentedControlChangedValue(value: sender.selectedSegmentIndex)
    self.performSegue(with: "identifier")
}

}

And in the tableviewcontroller conform to the delegate like so:

class AlbumsSegmentView: UITableViewController, SegmentControlChangeDelegate {
     func segmentedControlChangedValue(_ value: Int){
     // Change which cell is being displayed with some type of boolean or switch statement that will be recalled in cell.dequeue
     }
}

And make sure that you set the delegate to self in the tableviewcontroller

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destinationVC = segue.destination as? PanelViewController {
        destinationVC.delegate = self
    }
}


问:
Xamarin.Forms & MVVM In C#: PropertyChanged Event Handler Is Always Null When OnPropertyChanged Called
I've written a simple application using Xamarin.Forms in C# with Visual Studio 2017, and have a problem with data binding working to update the contents of a Label child control to display the selected date value from a DatePicker child control in the same ContentPage.  Although all of the project elements compile, build and deploy without any errors, and the OnPropertyChanged method in the ViewModel is called each and every time when I change the date selected in the DatePicker, the PropertyChanged event handler is always a null object reference when the OnPropertyChanged method is called, and in turn, does not update the contents of the Label's Text property as expected with the new selected date value.

The following are my MainPage implementation in addition to the backing ViewModel class, SelectedDateViewModel.cs.

C# [MainPage.xaml.cs]

```<code>using System;
using Xamarin.Forms;

namespace DataBoundDatePicker
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();

            BindingContext = new SelectedDateViewModel();
        }
    }
}
</code>```

XAML [MainPage.xaml]

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:DataBoundDatePicker"
             x:Class="DataBoundDatePicker.MainPage">
    <StackLayout Padding="20" VerticalOptions="Center" HorizontalOptions="Center">
        <Label Text="Data Bound DatePicker" FontAttributes="Bold" HorizontalOptions="Center" />
        <Label Text="Select a Date:" />
        <DatePicker x:Name="SelectedDatePicker" Date="{Binding SelectedDate}"/>
        <StackLayout Orientation="Horizontal">
            <Label Text="Formatted Date:" />
            <Label x:Name="FormattedDateLabel" Text="{Binding SelectedDate, StringFormat='{0:dddd, MMMM d, yyyy}'}" />
        </StackLayout>
    </StackLayout>
</ContentPage>
</code>```

C# [SelectedDateViewModel.cs]

```<code>using System;
using System.ComponentModel;
using System.Diagnostics;

namespace DataBoundDatePicker
{
    public class SelectedDateViewModel
    {
        private readonly string FullDateFormat = "dddd, MMMM d, yyyy";

        private DateTime selectedDate;

        public event PropertyChangedEventHandler PropertyChanged;

        public SelectedDateViewModel()
        {
            Debug.WriteLine("Entering SelectedDateViewModel.SelectedDateViewModel() - Constructor");

            SelectedDate = DateTime.Now;

            Debug.WriteLine("Leaving SelectedDateViewModel.SelectedDateViewModel() - Constructor");
        }

        public DateTime SelectedDate
        {
            get
            {
                return selectedDate;
            }

            set
            {
                if (selectedDate != value)
                {
                    selectedDate = value;
                    OnPropertyChanged("SelectedDate");
                }
            }
        }

        protected virtual void OnPropertyChanged(string propertyName)
        {
            Debug.WriteLine("Inside SelectedDateViewModel.OnPropertyChanged()");

            Debug.WriteLine($"SelectedDate = {selectedDate.ToString(FullDateFormat)}");

            var trace =
            $"PropertyChanged Is Null: {(PropertyChanged == null ? "Yes" : "No")}";
            Debug.WriteLine(trace);

            var propertyChangedCallback = PropertyChanged;
            propertyChangedCallback?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
</code>```

The current implementation does the following:

On startup, the FormattedDateLabel displays the correct formatted
date string based on the SelectedDate DateTime property in the
SelectedDateViewModel. However, any subsequent changes to the Date
property in the SelectedDatePicker control.

Without fail, each and every time the Date value is changed in the
SelectedDatePicker control, the
SelectedDateViewModel.OnPropertyChanged() method is always called,
even on startup through the instantiation of MainPage and
SelectedDateViewModel object instances (e.g., constructor calls).

Although the SelectedDateViewModel.OnPropertyChanged() is called any
time when the Date value is changed in the DatePicker,
SelectedDateViewModel's PropertyChanged event reference is always
null, even on startup (again, when instantiated through constructor
calls).  This is shown with the following Debug trace statements
emitted as the program is running in Debug mode through Visual
Studio:

'DataBoundDatePicker.UWP.exe' (CoreCLR: CoreCLR_UWP_Domain): Loaded
  'c:\work\Xamarin\DataBoundDatePicker\DataBoundDatePicker\DataBoundDatePicker.UWP\bin\x86\Debug\AppX\Xamarin.Forms.Xaml.dll'.
  Skipped loading symbols. Module is optimized and the debugger option
  'Just My Code' is enabled.
      Entering MainPage.MainPage() - Constructor
      Entering SelectedDateViewModel.SelectedDateViewModel() - Constructor
      Inside SelectedDateViewModel.OnPropertyChanged()
      SelectedDate = Tuesday, July 4, 2017
      PropertyChanged Is Null: Yes
      Leaving SelectedDateViewModel.SelectedDateViewModel() - Constructor
      Leaving MainPage.MainPage() - Constructor
      The thread 0x1630 has exited with code 0 (0x0).
      Inside SelectedDateViewModel.OnPropertyChanged()
      SelectedDate = Sunday, March 4, 2012
      PropertyChanged Is Null: Yes

The code exhibits the same behavior, regardless of deploying and debugging
the UWP or Android version of the application.

Any help or insights and explanations you can share on how I can get the  Text property to have its Text property bound to the
 Date property using the ViewModel where the PropertyChanged event is not a null reference would be greatly appreciated.

Thank you in advance for your time and help.

答:
Use INotifyPropertyChanged Interface. like this.</p>

```<code>public class SelectedDateViewModel : INotifyPropertyChanged
    {
        private readonly string FullDateFormat = "dddd, MMMM d, yyyy";

        private DateTime selectedDate;

        public event PropertyChangedEventHandler PropertyChanged;

        public SelectedDateViewModel()
        {
            Debug.WriteLine("Entering SelectedDateViewModel.SelectedDateViewModel() - Constructor");

            SelectedDate = DateTime.Now;

            Debug.WriteLine("Leaving SelectedDateViewModel.SelectedDateViewModel() - Constructor");
        }

        public DateTime SelectedDate
        {
            get
            {
                return selectedDate;
            }

            set
            {
                if (selectedDate != value)
                {
                    selectedDate = value;
                    OnPropertyChanged("SelectedDate");
                }
            }
        }

        protected virtual void OnPropertyChanged(string propertyName)
        {
             if (PropertyChanged != null)
             {
                  PropertyChanged(this,
                         new PropertyChangedEventArgs(propertyName));
             }
        }
    }
</code>```

Body:
I've written a simple application using Xamarin.Forms in C# with Visual Studio 2017, and have a problem with data binding working to update the contents of a Label child control to display the selected date value from a DatePicker child control in the same ContentPage.  Although all of the project elements compile, build and deploy without any errors, and the OnPropertyChanged method in the ViewModel is called each and every time when I change the date selected in the DatePicker, the PropertyChanged event handler is always a null object reference when the OnPropertyChanged method is called, and in turn, does not update the contents of the Label's Text property as expected with the new selected date value.

The following are my MainPage implementation in addition to the backing ViewModel class, SelectedDateViewModel.cs.

C# [MainPage.xaml.cs]

using System;
using Xamarin.Forms;

namespace DataBoundDatePicker
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();

            BindingContext = new SelectedDateViewModel();
        }
    }
}

XAML [MainPage.xaml]

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:DataBoundDatePicker"
             x:Class="DataBoundDatePicker.MainPage">
    <StackLayout Padding="20" VerticalOptions="Center" HorizontalOptions="Center">

        <DatePicker x:Name="SelectedDatePicker" Date="{Binding SelectedDate}"/>
        <StackLayout Orientation="Horizontal">

        </StackLayout>
    </StackLayout>
</ContentPage>

C# [SelectedDateViewModel.cs]

using System;
using System.ComponentModel;
using System.Diagnostics;

namespace DataBoundDatePicker
{
    public class SelectedDateViewModel
    {
        private readonly string FullDateFormat = "dddd, MMMM d, yyyy";

        private DateTime selectedDate;

        public event PropertyChangedEventHandler PropertyChanged;

        public SelectedDateViewModel()
        {
            Debug.WriteLine("Entering SelectedDateViewModel.SelectedDateViewModel() - Constructor");

            SelectedDate = DateTime.Now;

            Debug.WriteLine("Leaving SelectedDateViewModel.SelectedDateViewModel() - Constructor");
        }

        public DateTime SelectedDate
        {
            get
            {
                return selectedDate;
            }

            set
            {
                if (selectedDate != value)
                {
                    selectedDate = value;
                    OnPropertyChanged("SelectedDate");
                }
            }
        }

        protected virtual void OnPropertyChanged(string propertyName)
        {
            Debug.WriteLine("Inside SelectedDateViewModel.OnPropertyChanged()");

            Debug.WriteLine($"SelectedDate = {selectedDate.ToString(FullDateFormat)}");

            var trace =
            $"PropertyChanged Is Null: {(PropertyChanged == null ? "Yes" : "No")}";
            Debug.WriteLine(trace);

            var propertyChangedCallback = PropertyChanged;
            propertyChangedCallback?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

The current implementation does the following:

On startup, the FormattedDateLabel displays the correct formatted
date string based on the SelectedDate DateTime property in the
SelectedDateViewModel. However, any subsequent changes to the Date
property in the SelectedDatePicker control.

Without fail, each and every time the Date value is changed in the
SelectedDatePicker control, the
SelectedDateViewModel.OnPropertyChanged() method is always called,
even on startup through the instantiation of MainPage and
SelectedDateViewModel object instances (e.g., constructor calls).

Although the SelectedDateViewModel.OnPropertyChanged() is called any
time when the Date value is changed in the DatePicker,
SelectedDateViewModel's PropertyChanged event reference is always
null, even on startup (again, when instantiated through constructor
calls).  This is shown with the following Debug trace statements
emitted as the program is running in Debug mode through Visual
Studio:

'DataBoundDatePicker.UWP.exe' (CoreCLR: CoreCLR_UWP_Domain): Loaded
  'c:\work\Xamarin\DataBoundDatePicker\DataBoundDatePicker\DataBoundDatePicker.UWP\bin\x86\Debug\AppX\Xamarin.Forms.Xaml.dll'.
  Skipped loading symbols. Module is optimized and the debugger option
  'Just My Code' is enabled.
      Entering MainPage.MainPage() - Constructor
      Entering SelectedDateViewModel.SelectedDateViewModel() - Constructor
      Inside SelectedDateViewModel.OnPropertyChanged()
      SelectedDate = Tuesday, July 4, 2017
      PropertyChanged Is Null: Yes
      Leaving SelectedDateViewModel.SelectedDateViewModel() - Constructor
      Leaving MainPage.MainPage() - Constructor
      The thread 0x1630 has exited with code 0 (0x0).
      Inside SelectedDateViewModel.OnPropertyChanged()
      SelectedDate = Sunday, March 4, 2012
      PropertyChanged Is Null: Yes

The code exhibits the same behavior, regardless of deploying and debugging
the UWP or Android version of the application.

Any help or insights and explanations you can share on how I can get the  Text property to have its Text property bound to the
 Date property using the ViewModel where the PropertyChanged event is not a null reference would be greatly appreciated.

Thank you in advance for your time and help.

Body:
Use INotifyPropertyChanged Interface. like this.

public class SelectedDateViewModel : INotifyPropertyChanged
    {
        private readonly string FullDateFormat = "dddd, MMMM d, yyyy";

        private DateTime selectedDate;

        public event PropertyChangedEventHandler PropertyChanged;

        public SelectedDateViewModel()
        {
            Debug.WriteLine("Entering SelectedDateViewModel.SelectedDateViewModel() - Constructor");

            SelectedDate = DateTime.Now;

            Debug.WriteLine("Leaving SelectedDateViewModel.SelectedDateViewModel() - Constructor");
        }

        public DateTime SelectedDate
        {
            get
            {
                return selectedDate;
            }

            set
            {
                if (selectedDate != value)
                {
                    selectedDate = value;
                    OnPropertyChanged("SelectedDate");
                }
            }
        }

        protected virtual void OnPropertyChanged(string propertyName)
        {
             if (PropertyChanged != null)
             {
                  PropertyChanged(this,
                         new PropertyChangedEventArgs(propertyName));
             }
        }
    }


问:
how to reset form group array in angular
I have a form array, but if I push another form this have setted the validations of previus form.

in this example [https://plnkr.co/edit/ApCn3YicMjfm2vhSOudj?p=preview][1]https://plnkr.co/edit/ApCn3YicMjfm2vhSOudj?p=preview you can see that the second form shows the name validation, how can I solve this?

答:
Based on the comments above and messing around with the plunker I think I finally see what you are asking.

The issue has to do with how forms work.

Forms have two pieces:

1) The form element itself displayed in the view.

2) The form data structure, which for reactive forms as you have are defined in the component code with the this.user variable. It is this data structure that tracks the forms values and validity state.

In looking at your code your ngFor is creating multiple form elements (#1 above) but using the same form data structure (#2 above). So the multiple forms will always show the same values and have the same validation state.

You'd need to build a formArray and create an entry in that array for every "form" you create.

I have an example of a form array here: https://github.com/DeborahK/Angular2-ReactiveForms


问:
Nested loop to fill a vector of vector of int in C++
I want to generate an std::vector of std::vector of int in order to represent k vectors each of which contains q integers in the following manner:

Vector 0: {0,1}

Vector 1: {2,3}

Vector 2: {4,5}

and so no. For this case k=3 and q=2, but they can be any integers >= 1. Due to the fact that this code belongs to a bigger project I have used a lot of declarations among which the following:

```<code>typedef int BlockId;
typedef vector< BlockId > ParallelClassIds;
</code>```

Let's say that each collection represent the notion of a "parallel class" and each integer the IDs of its elements what I call "blocks". I have implemented the following function that tries to create the above structure (k, q are private variables visible within the C++ class I declared)

```<code>vector< ParallelClassIds > generateResolutionIds(){

    //The variable to be returned
    vector< ParallelClassIds > ret(k, vector< BlockId >(q));

    for (int i = 0; i < k; i++){
        for(int j = 0; j < q; j++){
            printf("Current parallel class size %ld\n", ret.at(i).size());
            ret.at(i).push_back(i*q+j);
        }
    }

    return ret;
}
</code>```

But there are a lot of problems with this functions. First, the printf() sometimes print 2, sometimes 3 where I was expecting it to always print q==2. Also, instead of the above structure (I checked this by printing the returned structure) it seems to create something like this:

Vector 0: {0,0,0,1}

Vector 1: {0,0,2,3}

Vector 2: {0,0,4,5}

I really have no idea why this behavior is happening.

答:
The issue is with this line:

```<code>vector< ParallelClassIds > ret(k, vector< BlockId >(q));
</code>```

Combined with this line:

```<code>ret.at(i).push_back(i*q+j);
</code>```

You are creating k vectors of length q, which you then keep appending to the end, bringing them to a length of 2*q.

What you want to do is:

```<code>vector< ParallelClassIds > ret(k);
for (int i = 0; i < k; i++){
  ret[i].reserve(q);
  ...
</code>```

Body:
I want to generate an std::vector of std::vector of int in order to represent k vectors each of which contains q integers in the following manner:

Vector 0: {0,1}

Vector 1: {2,3}

Vector 2: {4,5}

and so no. For this case k=3 and q=2, but they can be any integers >= 1. Due to the fact that this code belongs to a bigger project I have used a lot of declarations among which the following:

typedef int BlockId;
typedef vector< BlockId > ParallelClassIds;

Let's say that each collection represent the notion of a "parallel class" and each integer the IDs of its elements what I call "blocks". I have implemented the following function that tries to create the above structure (k, q are private variables visible within the C++ class I declared)

vector< ParallelClassIds > generateResolutionIds(){

    //The variable to be returned
    vector< ParallelClassIds > ret(k, vector< BlockId >(q));

    for (int i = 0; i < k; i++){
        for(int j = 0; j < q; j++){
            printf("Current parallel class size %ld\n", ret.at(i).size());
            ret.at(i).push_back(i*q+j);
        }
    }

    return ret;
}

But there are a lot of problems with this functions. First, the printf() sometimes print 2, sometimes 3 where I was expecting it to always print q==2. Also, instead of the above structure (I checked this by printing the returned structure) it seems to create something like this:

Vector 0: {0,0,0,1}

Vector 1: {0,0,2,3}

Vector 2: {0,0,4,5}

I really have no idea why this behavior is happening.

Body:
The issue is with this line:

vector< ParallelClassIds > ret(k, vector< BlockId >(q));

Combined with this line:

ret.at(i).push_back(i*q+j);

You are creating k vectors of length q, which you then keep appending to the end, bringing them to a length of 2*q.

What you want to do is:

vector< ParallelClassIds > ret(k);
for (int i = 0; i < k; i++){
  ret[i].reserve(q);
  ...


问:
store variable value between program execution in c#
I have 2 console applications.

Application_B and Application_C. Both applications are collecting data from
Application_A.

Lets say if I run Application_B first and it gets data from Application_A. At the same time if I run Application_C it should  display message that values have been filled, or something like that.

答:
You question is not very clear but it seems Application_A is getting/generating data which Application_B or Application_C can collect. If one of them (B/C) has already collected data then other should show a message like 'data already collected' or 'no more data'.

Application_A must provide two things:

Store data somewhere. This can be protected for concurrent access. You can think of using Mutex.

A flag : This to indicate if more data is available. You can reset once data has been read by either B/C.

You can keep data at global place from where B/C can collect and A will write OR data can be maintained at C which will be passed to B/C after request. But for that you have to decide about protocol for inter-process communication.


问:
store data to 2 tables with foreign key in MySql php
I have two table in MySql, which are table 1 and table 2. As I want to link table 1 to 2 via userID. However, the funciton I have come out is not working.

MySQl tables are below:

In my case, userId will be the foreign key to link these 2 tables.
However, my functions are not working.
This is my function below:

```<code>function insert() {
    function adduserdetails($con, $accountId, $name, $contact) {

        $query = "insert into userdetails(accountId,name,contact)
            values('$accountId','$name','$contact')";
        //echo "{$sqlString}";

        $insertResult = mysqli_query($con, $query);

        if ($insertResult) {
            echo " Applicant Detail Added !<br />";
            echo "<a href='index.php'>Back to Home</a>";
        } else {
            echo " Error !";
            echo "{$query}";
            //header('Location: post.php');
        }
    }

}

if ($con->query($query) === TRUE) {
    $last_id = $con->insert_id;
    echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
    echo "Error: " . $query . "<br>" . $con->error;
}

function adduseremployment($con,$last_id,$occupationMain,$comapny){

    $query1 = "insert into useremployment(userId,Occupation,company)
            values('$last_id',$occupationMain','$comapny')";
                 //echo "{$sqlString}";

                 $insertResult = mysqli_query($con, $query1);

                 if($insertResult){
                     echo " Applicant Detail Added !<br />";
                     echo "<a href='index.php'>Back to Home</a>";
                 }
                 else {
                     echo " Error !";
                     echo "{$query1}";
                     //header('Location: post.php');
                 }

}
</code>```

答:
You have vertical table.

Check below code,

Be remember to prepare statement.

```<code><?php
    function addUser(){
        // parent table.
        $queryParent = ''; // Your userdetails table insert query
        $insertResult = mysqli_query($con, $queryParent);
        $userId = mysqli_insert_id($con); // This is your last inserted userId.

        // child table.
        $queryChild = ''; // Your useremployment table insert query with userId.
        $insertResult = mysqli_query($con, $queryChild);
    }
?>
</code>```

Body:
I have two table in MySql, which are table 1 and table 2. As I want to link table 1 to 2 via userID. However, the funciton I have come out is not working.

MySQl tables are below:

In my case, userId will be the foreign key to link these 2 tables.
However, my functions are not working.
This is my function below:

function insert() {
    function adduserdetails($con, $accountId, $name, $contact) {

        $query = "insert into userdetails(accountId,name,contact)
            values('$accountId','$name','$contact')";
        //echo "{$sqlString}";

        $insertResult = mysqli_query($con, $query);

        if ($insertResult) {
            echo " Applicant Detail Added !
";
            echo "Back to Home";
        } else {
            echo " Error !";
            echo "{$query}";
            //header('Location: post.php');
        }
    }

}

if ($con->query($query) === TRUE) {
    $last_id = $con->insert_id;
    echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
    echo "Error: " . $query . "
" . $con->error;
}

function adduseremployment($con,$last_id,$occupationMain,$comapny){

    $query1 = "insert into useremployment(userId,Occupation,company)
            values('$last_id',$occupationMain','$comapny')";
                 //echo "{$sqlString}";

                 $insertResult = mysqli_query($con, $query1);

                 if($insertResult){
                     echo " Applicant Detail Added !
";
                     echo "Back to Home";
                 }
                 else {
                     echo " Error !";
                     echo "{$query1}";
                     //header('Location: post.php');
                 }

}

Body:
You have vertical table.

Check below code,

Be remember to prepare statement.

<?php
    function addUser(){
        // parent table.
        $queryParent = ''; // Your userdetails table insert query
        $insertResult = mysqli_query($con, $queryParent);
        $userId = mysqli_insert_id($con); // This is your last inserted userId.

        // child table.
        $queryChild = ''; // Your useremployment table insert query with userId.
        $insertResult = mysqli_query($con, $queryChild);
    }
?>


问:
How do I import data using Django-Import-Export?
The documentation for django-import-export is a bit weak on how to configure the admin to import from a spreadsheet.  Does anyone have a full example? </p>

答:
This is not a fully complete module. But you can understand how it should be.

resources.py file

```<code>from import_export import resources
from .models import edxUser

class edxUserResource(resources.ModelResource):
    class Meta:
        model = edxUser
        #skip_unchanged = True
        #report_skipped = True
        #if you want to exclude any field from exporting
        exclude = ('id','edx_anonymized_id')
        fields = ('id', 'edx_id', 'edx_anonymized_id', 'edx_email', 'edx_name', 'time_created', 'created_by')
        #Order of the export fields
        export_order = ('edx_id', 'edx_email')
</code>```

admin.py file

```<code>from import_export.admin import ImportExportModelAdmin
from django.contrib import admin
from .models import edxUser
from resources import edxUserResource

@admin.register(edxUser)
class edxUserAdmin(ImportExportModelAdmin):
    resource_class = edxUserResource
</code>```

models.py file

```<code>from __future__ import unicode_literals
from django.conf import settings
from django.db import models

class edxUser(models.Model):
    edx_id = models.IntegerField('edX user id', blank=True, null=True)
    edx_anonymized_id = models.IntegerField("edX anonymized user id", blank=True, null=True)
    edx_email = models.EmailField('edx user email', max_length=75, blank=True)
    edx_name = models.CharField('edx name', max_length=75, blank=True, null=True)
    time_created = models.DateField('Created time', blank=True, null=True)
    created_by = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True)

    def __unicode__(self):
        return str(self.edx_id)
</code>```

Body:
This is not a fully complete module. But you can understand how it should be.

resources.py file

from import_export import resources
from .models import edxUser

class edxUserResource(resources.ModelResource):
    class Meta:
        model = edxUser
        #skip_unchanged = True
        #report_skipped = True
        #if you want to exclude any field from exporting
        exclude = ('id','edx_anonymized_id')
        fields = ('id', 'edx_id', 'edx_anonymized_id', 'edx_email', 'edx_name', 'time_created', 'created_by')
        #Order of the export fields
        export_order = ('edx_id', 'edx_email')

admin.py file

from import_export.admin import ImportExportModelAdmin
from django.contrib import admin
from .models import edxUser
from resources import edxUserResource

@admin.register(edxUser)
class edxUserAdmin(ImportExportModelAdmin):
    resource_class = edxUserResource

models.py file

from __future__ import unicode_literals
from django.conf import settings
from django.db import models

class edxUser(models.Model):
    edx_id = models.IntegerField('edX user id', blank=True, null=True)
    edx_anonymized_id = models.IntegerField("edX anonymized user id", blank=True, null=True)
    edx_email = models.EmailField('edx user email', max_length=75, blank=True)
    edx_name = models.CharField('edx name', max_length=75, blank=True, null=True)
    time_created = models.DateField('Created time', blank=True, null=True)
    created_by = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True)

    def __unicode__(self):
        return str(self.edx_id)


问:
Ruby/ RoR - String Hash to Integer Hash
I have an Hash  @answers = params[:Answers].to_hash;

<%= debug @answers %> outs

```<code>---
"1": "2"
"7": "3"
"6": "4"
"4": "0"
</code>```

Need to make the @answers to one like below

@ans = {1 => 2, 7 => 3, 6 => 4, 4 => 0}
<%= debug @answers %> outs

```<code>---
1: 2
7: 3
6: 4
4: 0
</code>```

答:
Here is the code

```<code>@ans = {"1" => "2", "7" => "3", "6" => "4", "4" => "0"}
@foo_hash ={} #new_hash
@ans.each_pair{|k,v| @foo_hash.store(k.to_i,v.to_i)}
</code>```

The @foo_hash will be {1 => 2, 7 => 3, 6 => 4, 4 => 0}

Then you can <%= debug @foo_hash %> to get the output in your YAML format

Title: Ruby/ RoR - String Hash to Integer Hash

Body:
I have an Hash  @answers = params[:Answers].to_hash;

<%= debug @answers %> outs

---
"1": "2"
"7": "3"
"6": "4"
"4": "0"

Need to make the @answers to one like below

@ans = {1 => 2, 7 => 3, 6 => 4, 4 => 0}
<%= debug @answers %> outs

---
1: 2
7: 3
6: 4
4: 0

Body:
Here is the code

@ans = {"1" => "2", "7" => "3", "6" => "4", "4" => "0"}
@foo_hash ={} #new_hash
@ans.each_pair{|k,v| @foo_hash.store(k.to_i,v.to_i)}

The @foo_hash will be {1 => 2, 7 => 3, 6 => 4, 4 => 0}

Then you can <%= debug @foo_hash %> to get the output in your YAML format


答:
your Query is wrong, please check this,

```<code>$query1 = "insert into useremployment(userId,occupation,company)
        values('$last_id',$occupationMain','$comapny')";
</code>```

you have to store record on userId as a refrence not to "accountID".

hope it helps,

Title: store data to 2 tables with foreign key in MySql php

Body:
your Query is wrong, please check this,

$query1 = "insert into useremployment(userId,occupation,company)
        values('$last_id',$occupationMain','$comapny')";

you have to store record on userId as a refrence not to "accountID".

hope it helps,


答:
```<code>x ={0: 0, 1: 4, 2: 0, 3: 2, 4: 2, 5: 4}

maximum = max(x.values())
keys = [key for key, value in x.items() if value == maximum]
print(keys)  # => [1, 5]
</code>```

Title: finding the keys of all the largest values in python dictionary?


问:
G-WAN v.7.12.6 content type handlers not work
I made a html.c script as below, in .../csp folder. It should output the additional headers with the default headers. But, actually it output the default headers only.

What have I done wrong? Did I miss anything?

Or, is it a bug in G-WAN?

```<code>#include "gwan.h" // G-WAN exported functions

#define CACHE "Expires: Fri, May 02 2042 00:00:00 GMT\r\nCache-Control: max-age=99999999\r\n"

int main(int argc, char *argv[ ])
{
    char  cache[ ] = CACHE;
    http_header(HEAD_ADD, cache, sizeof(CACHE) - 1, argv);
    return 200;
}
</code>```

答:
I can't check the code now but my guess is that http_header() has never been used from a content-type handler (only from servlets, like done in G-WAN examples).

It may simply be that the structures allocated by http_header() are never used. While http_header() is conveniently doing the work for you, G-WAN handler examples show how to build or access the reply buffer so you can do whatever header edition you need from this point.

Body:
I made a html.c script as below, in .../csp folder. It should output the additional headers with the default headers. But, actually it output the default headers only.

What have I done wrong? Did I miss anything?

Or, is it a bug in G-WAN?

#include "gwan.h" // G-WAN exported functions

#define CACHE "Expires: Fri, May 02 2042 00:00:00 GMT\r\nCache-Control: max-age=99999999\r\n"

int main(int argc, char *argv[ ])
{
    char  cache[ ] = CACHE;
    http_header(HEAD_ADD, cache, sizeof(CACHE) - 1, argv);
    return 200;
}


问:
ACCESS_FINE_LOCATION permission error emulator only
I'm having a weird error while using the emulator ONLY.
I found one question that has the same issue 9 months ago with no answers at all...

I'm using google play services locations to get locations in my app and I'm sure of my manifest permissions and everything works perfectly on my phone, the problem occurs when using an emulator only, and I tried different emulators on both my iMac and Windows machines.

I doubt that emulators don't support this basic function!

here is my manifest code:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.orderme.ordermeandroid" >
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
</code>```

and here is where the exception is firing:

```<code>    LocationRequest mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(10000);
    mLocationRequest.setFastestInterval(5000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,mLocationRequest,this);
</code>```

stack trace:

```<code>08-26 14:01:19.699  10157-10157/com.orderme.ordermeandroid E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.orderme.ordermeandroid, PID: 10157
java.lang.SecurityException: Client must have ACCESS_FINE_LOCATION permission to request PRIORITY_HIGH_ACCURACY locations.
        at android.os.Parcel.readException(Parcel.java:1599)
        at android.os.Parcel.readException(Parcel.java:1552)
        at com.google.android.gms.location.internal.zzg$zza$zza.zza(Unknown Source)
        at com.google.android.gms.location.internal.zzi.zza(Unknown Source)
        at com.google.android.gms.location.internal.zzj.zza(Unknown Source)
        at com.google.android.gms.location.internal.zzd$1.zza(Unknown Source)
        at com.google.android.gms.location.internal.zzd$1.zza(Unknown Source)
        at com.google.android.gms.common.api.zzc$zza.zzb(Unknown Source)
        at com.google.android.gms.common.api.zzf.zza(Unknown Source)
        at com.google.android.gms.common.api.zzf.zzb(Unknown Source)
        at com.google.android.gms.common.api.zzi.zzb(Unknown Source)
        at com.google.android.gms.location.internal.zzd.requestLocationUpdates(Unknown Source)
        at com.orderme.ordermeandroid.Main.MainActivity.onConnected(MainActivity.java:184)
        at com.google.android.gms.common.internal.zzk.zzh(Unknown Source)
        at com.google.android.gms.common.api.zzg.zznt(Unknown Source)
        at com.google.android.gms.common.api.zzg.onConnected(Unknown Source)
        at com.google.android.gms.common.api.zzi$2.onConnected(Unknown Source)
        at com.google.android.gms.common.internal.zzj$zzg.zzoD(Unknown Source)
        at com.google.android.gms.common.internal.zzj$zza.zzc(Unknown Source)
        at com.google.android.gms.common.internal.zzj$zza.zzs(Unknown Source)
        at com.google.android.gms.common.internal.zzj$zzc.zzoF(Unknown Source)
        at com.google.android.gms.common.internal.zzj$zzb.handleMessage(Unknown Source)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

答:
```<code><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</code>```

some times manifest have a missing line granting the permission of ACCESS_FINE_LOCATION. so you need to mention it in the manifest.

I did this and my problem was solved.

This generally happens because we have given the permission in the manifest so the app would create a problem as it would not be allowed to access the permissions and the file would crash.

```<code><?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme" >
    <activity android:name=".MainActivity" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</code>```

Body:
I'm having a weird error while using the emulator ONLY.
I found one question that has the same issue 9 months ago with no answers at all...

I'm using google play services locations to get locations in my app and I'm sure of my manifest permissions and everything works perfectly on my phone, the problem occurs when using an emulator only, and I tried different emulators on both my iMac and Windows machines.

I doubt that emulators don't support this basic function!

here is my manifest code:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.orderme.ordermeandroid" >
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

and here is where the exception is firing:

    LocationRequest mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(10000);
    mLocationRequest.setFastestInterval(5000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,mLocationRequest,this);

stack trace:

08-26 14:01:19.699  10157-10157/com.orderme.ordermeandroid E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.orderme.ordermeandroid, PID: 10157
java.lang.SecurityException: Client must have ACCESS_FINE_LOCATION permission to request PRIORITY_HIGH_ACCURACY locations.
        at android.os.Parcel.readException(Parcel.java:1599)
        at android.os.Parcel.readException(Parcel.java:1552)
        at com.google.android.gms.location.internal.zzg$zza$zza.zza(Unknown Source)
        at com.google.android.gms.location.internal.zzi.zza(Unknown Source)
        at com.google.android.gms.location.internal.zzj.zza(Unknown Source)
        at com.google.android.gms.location.internal.zzd$1.zza(Unknown Source)
        at com.google.android.gms.location.internal.zzd$1.zza(Unknown Source)
        at com.google.android.gms.common.api.zzc$zza.zzb(Unknown Source)
        at com.google.android.gms.common.api.zzf.zza(Unknown Source)
        at com.google.android.gms.common.api.zzf.zzb(Unknown Source)
        at com.google.android.gms.common.api.zzi.zzb(Unknown Source)
        at com.google.android.gms.location.internal.zzd.requestLocationUpdates(Unknown Source)
        at com.orderme.ordermeandroid.Main.MainActivity.onConnected(MainActivity.java:184)
        at com.google.android.gms.common.internal.zzk.zzh(Unknown Source)
        at com.google.android.gms.common.api.zzg.zznt(Unknown Source)
        at com.google.android.gms.common.api.zzg.onConnected(Unknown Source)
        at com.google.android.gms.common.api.zzi$2.onConnected(Unknown Source)
        at com.google.android.gms.common.internal.zzj$zzg.zzoD(Unknown Source)
        at com.google.android.gms.common.internal.zzj$zza.zzc(Unknown Source)
        at com.google.android.gms.common.internal.zzj$zza.zzs(Unknown Source)
        at com.google.android.gms.common.internal.zzj$zzc.zzoF(Unknown Source)
        at com.google.android.gms.common.internal.zzj$zzb.handleMessage(Unknown Source)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Body:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

some times manifest have a missing line granting the permission of ACCESS_FINE_LOCATION. so you need to mention it in the manifest.

I did this and my problem was solved.

This generally happens because we have given the permission in the manifest so the app would create a problem as it would not be allowed to access the permissions and the file would crash.

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme" >
    <activity android:name=".MainActivity" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>


问:
PHP Search query result ORDER BY not working
I have this code to search database. It now works perfectly but i want to change the order of which it displays. Below is my code.

```<code>if (isset($_GET["mainSearch"]))
{
  $condition = '';
  $query = explode(" ", $_GET["mainSearch"]);

  foreach ($query as $text)
  {
      $condition .= "question LIKE '%".SQLite3::escapeString($text)."%' OR ";
  }
  $condition = substr($condition, 0, -4);

  $order = "ORDER BY quiz_id DESC";
  $sql_query = "SELECT * FROM questions WHERE " . $condition;
  $sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition . $order;
  $result = $db->query($sql_query);
  $resultCount = $db->querySingle($sql_query_count);

  if ($resultCount > 0)
  {
  if ($result)
  {
      while ($row = $result->fetchArray(SQLITE3_ASSOC))
      {
           echo '<div class="quesbox_3">
            <div class="questitle">
                <h2>'.$row["question"].'</h2>
            </div>
            <div class="quesanswer">'.$row["answer"].'</div>
        </div>';
      }
  }
  }
  else
  {
      echo "No results found";
  }
}
</code>```

I want the ORDER of which result show to be from bottom to top. Please how can i add this properly as current code isn't working.

答:
Give 1 space in this string

```<code>$order = " ORDER BY quiz_id DESC ";
</code>```

It is not showing you because if you echo your query than it will show like this

```<code>SELECT COUNT(*) as count FROM questions WHERE question LIKE '%test%'ORDER BY quiz_id DESC
</code>```

You can see in this echo query there is a no space between ORDER and %test%

do Like this it will helps you.

Body:
I have this code to search database. It now works perfectly but i want to change the order of which it displays. Below is my code.

if (isset($_GET["mainSearch"]))
{
  $condition = '';
  $query = explode(" ", $_GET["mainSearch"]);

  foreach ($query as $text)
  {
      $condition .= "question LIKE '%".SQLite3::escapeString($text)."%' OR ";
  }
  $condition = substr($condition, 0, -4);

  $order = "ORDER BY quiz_id DESC";
  $sql_query = "SELECT * FROM questions WHERE " . $condition;
  $sql_query_count = "SELECT COUNT(*) as count FROM questions WHERE " . $condition . $order;
  $result = $db->query($sql_query);
  $resultCount = $db->querySingle($sql_query_count);

  if ($resultCount > 0)
  {
  if ($result)
  {
      while ($row = $result->fetchArray(SQLITE3_ASSOC))
      {
           echo '

'.$row["question"].'

'.$row["answer"].'

';
      }
  }
  }
  else
  {
      echo "No results found";
  }
}

I want the ORDER of which result show to be from bottom to top. Please how can i add this properly as current code isn't working.

Body:
Give 1 space in this string

$order = " ORDER BY quiz_id DESC ";

It is not showing you because if you echo your query than it will show like this

SELECT COUNT(*) as count FROM questions WHERE question LIKE '%test%'ORDER BY quiz_id DESC

You can see in this echo query there is a no space between ORDER and %test%

do Like this it will helps you.


问:
how can i set notifyicon under timer in c#
not showing the notifyIcon while running?Above Is my Code.Only sound is there</p>

```<code>   private void timerS_Tick(object sender, EventArgs ex)
    {

             if (File.Exists(path) == true)
            {
                notifyIcon1.BalloonTipText = "PLEASE CHECK ASHIDA\\MESSAGE\\Temp.txt";
                notifyIcon1.BalloonTipTitle = "MESSAGE FROM MUFITHA";
                notifyIcon1.ShowBalloonTip(3000);
                System.Media.SoundPlayer s = new System.Media.SoundPlayer();
                s.SoundLocation = @"\\SERVER-HARMONY\Ashida\MESSAGE\click_x.wav";
                s.Play();
                timerS.Stop();
                notifyIcon1.Dispose();
                timerS.Enabled = false;
                return;
            }
</code>```

答:
Before the statement:

```<code>notifyIcon1.ShowBalloonTip(3000);
</code>```

Try inserting the statement:

```<code>notifyIcon1.Visible = true;
</code>```

Body:
not showing the notifyIcon while running?Above Is my Code.Only sound is there

   private void timerS_Tick(object sender, EventArgs ex)
    {

             if (File.Exists(path) == true)
            {
                notifyIcon1.BalloonTipText = "PLEASE CHECK ASHIDA\\MESSAGE\\Temp.txt";
                notifyIcon1.BalloonTipTitle = "MESSAGE FROM MUFITHA";
                notifyIcon1.ShowBalloonTip(3000);
                System.Media.SoundPlayer s = new System.Media.SoundPlayer();
                s.SoundLocation = @"\\SERVER-HARMONY\Ashida\MESSAGE\click_x.wav";
                s.Play();
                timerS.Stop();
                notifyIcon1.Dispose();
                timerS.Enabled = false;
                return;
            }

Body:
Before the statement:

notifyIcon1.ShowBalloonTip(3000);

Try inserting the statement:

notifyIcon1.Visible = true;