问:
how to plot gradient fill on the 3d bars in matplotlib
Right now there're some statistics plotted in 3d bar over (x, y). each bar height represents the density of the points in side the square grid of (x,y) plane. Right now, i can put different color on each bar. However, I want to put progressive color on the 3d bar, similar as the cmap, so the bar will be gradient filled depending on the density.

```<code>from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# height of the bars
z = np.ones((4, 4)) * np.arange(4)
# position of the bars
xpos, ypos = np.meshgrid(np.arange(4), np.arange(4))

xpos = xpos.flatten('F')

ypos = ypos.flatten('F')

zpos = np.zeros_like(xpos)

dx = 0.5 * np.ones_like(zpos)
dy = dx.copy()
dz = z.flatten()

ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b', zsort='average')

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

Output the above code:

答:
Let me first say that matplotlib may not be the tool of choice when it comes to sophisticated 3D plots.

That said, there is no built-in method to produce bar plots with differing colors over the extend of the bar.

We therefore need to mimic the bar somehow. A possible solution can be found below. Here, we use a plot_surface plot to create a bar that contains a gradient.

```<code>from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import matplotlib.colors
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection= Axes3D.name)

def make_bar(ax, x0=0, y0=0, width = 0.5, height=1 , cmap="viridis",
              norm=matplotlib.colors.Normalize(vmin=0, vmax=1), **kwargs ):
    # Make data
    u = np.linspace(0, 2*np.pi, 4+1)+np.pi/4.
    v_ = np.linspace(np.pi/4., 3./4*np.pi, 100)
    v = np.linspace(0, np.pi, len(v_)+2 )
    v[0] = 0 ;  v[-1] = np.pi; v[1:-1] = v_
    x = np.outer(np.cos(u), np.sin(v))
    y = np.outer(np.sin(u), np.sin(v))
    z = np.outer(np.ones(np.size(u)), np.cos(v))

    xthr = np.sin(np.pi/4.)**2 ;  zthr = np.sin(np.pi/4.)
    x[x > xthr] = xthr; x[x < -xthr] = -xthr
    y[y > xthr] = xthr; y[y < -xthr] = -xthr
    z[z > zthr] = zthr  ; z[z < -zthr] = -zthr

    x *= 1./xthr*width; y *= 1./xthr*width
    z += zthr
    z *= height/(2.*zthr)
    #translate
    x += x0; y += y0
    #plot
    ax.plot_surface(x, y, z, cmap=cmap, norm=norm, **kwargs)

def make_bars(ax, x, y, height, width=1):
    widths = np.array(width)*np.ones_like(x)
    x = np.array(x).flatten()
    y = np.array(y).flatten()

    h = np.array(height).flatten()
    w = np.array(widths).flatten()
    norm = matplotlib.colors.Normalize(vmin=0, vmax=h.max())
    for i in range(len(x.flatten())):
        make_bar(ax, x0=x[i], y0=y[i], width = w[i] , height=h[i], norm=norm)

X, Y = np.meshgrid([1,2,3], [2,3,4])
Z = np.sin(X*Y)+1.5

make_bars(ax, X,Y,Z, width=0.2, )
plt.show()
</code>```

Body:
Right now there're some statistics plotted in 3d bar over (x, y). each bar height represents the density of the points in side the square grid of (x,y) plane. Right now, i can put different color on each bar. However, I want to put progressive color on the 3d bar, similar as the cmap, so the bar will be gradient filled depending on the density.

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# height of the bars
z = np.ones((4, 4)) * np.arange(4)
# position of the bars
xpos, ypos = np.meshgrid(np.arange(4), np.arange(4))

xpos = xpos.flatten('F')

ypos = ypos.flatten('F')

zpos = np.zeros_like(xpos)

dx = 0.5 * np.ones_like(zpos)
dy = dx.copy()
dz = z.flatten()

ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b', zsort='average')

plt.show()

Output the above code:

Body:
Let me first say that matplotlib may not be the tool of choice when it comes to sophisticated 3D plots.

That said, there is no built-in method to produce bar plots with differing colors over the extend of the bar.

We therefore need to mimic the bar somehow. A possible solution can be found below. Here, we use a plot_surface plot to create a bar that contains a gradient.

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import matplotlib.colors
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection= Axes3D.name)

def make_bar(ax, x0=0, y0=0, width = 0.5, height=1 , cmap="viridis",
              norm=matplotlib.colors.Normalize(vmin=0, vmax=1), **kwargs ):
    # Make data
    u = np.linspace(0, 2*np.pi, 4+1)+np.pi/4.
    v_ = np.linspace(np.pi/4., 3./4*np.pi, 100)
    v = np.linspace(0, np.pi, len(v_)+2 )
    v[0] = 0 ;  v[-1] = np.pi; v[1:-1] = v_
    x = np.outer(np.cos(u), np.sin(v))
    y = np.outer(np.sin(u), np.sin(v))
    z = np.outer(np.ones(np.size(u)), np.cos(v))

    xthr = np.sin(np.pi/4.)**2 ;  zthr = np.sin(np.pi/4.)
    x[x > xthr] = xthr; x[x < -xthr] = -xthr
    y[y > xthr] = xthr; y[y < -xthr] = -xthr
    z[z > zthr] = zthr  ; z[z < -zthr] = -zthr

    x *= 1./xthr*width; y *= 1./xthr*width
    z += zthr
    z *= height/(2.*zthr)
    #translate
    x += x0; y += y0
    #plot
    ax.plot_surface(x, y, z, cmap=cmap, norm=norm, **kwargs)

def make_bars(ax, x, y, height, width=1):
    widths = np.array(width)*np.ones_like(x)
    x = np.array(x).flatten()
    y = np.array(y).flatten()

    h = np.array(height).flatten()
    w = np.array(widths).flatten()
    norm = matplotlib.colors.Normalize(vmin=0, vmax=h.max())
    for i in range(len(x.flatten())):
        make_bar(ax, x0=x[i], y0=y[i], width = w[i] , height=h[i], norm=norm)

X, Y = np.meshgrid([1,2,3], [2,3,4])
Z = np.sin(X*Y)+1.5

make_bars(ax, X,Y,Z, width=0.2, )
plt.show()


来源: stackexchange

问:
My Tools folder has gone how to get it
Today at morning about 6 hour ago I was updating tools and installing new features from SDK Manager. And due to my Internet connection shutdown Updating process canceled automatically. Now when I try to open Android SDK Manager it says

Failed to execute tools/android.bat.

  The system cannot find the file specified.

Then I try to find the android.bat file in tools And I realized that my Tools folder is missing with all its components. But  as I know everything is fine except this problem. How can I get that folder back or download that specific folder instead of the whole android SDK.

答: You need re-install or update Android SDK</p>

ContentLicense: CC BY-SA 3.0

Title: My Tools folder has gone how to get it


问:
Func detegate is not working with Entity Fromework
i am using entity fromework 6 and func is not working in right way here is my code

```<code>DbSet<vExpenseRegister> dbSet1 = Context.Set<vExpenseRegister>();
// got db set from dbcontext, it is ok

Func<vExpenseRegister, bool> where= a => a.InvoiceDate > fromDate;
// create a delegate and pass a condition

var result = dbSet1.Where(where).AsQueryable().ToList();

// but result is nothing, in spite of record exists in database
//but i change code eliminate Func delegate and condition write in where method //like

var result = dbSet1.Where(a => a.InvoiceDate > fromDate).AsQueryable().ToList();
//working fine
</code>```

kindly help me why Func is not working

Thanks,
Akmal.

答:
This should be an Expression<Func<...>>:

```<code>Func<vExpenseRegister, bool> where= a => a.InvoiceDate > fromDate;
</code>```

So

```<code>Expression<Func<vExpenseRegister, bool>> where = a => a.InvoiceDate > fromDate;
</code>```

If it is just a Func<...> it will be executed in memory after the entire table is returned.

If you look at the signature of dbSet1.Where you should see it takes an expression.

Body:
i am using entity fromework 6 and func is not working in right way here is my code

DbSet<vExpenseRegister> dbSet1 = Context.Set<vExpenseRegister>();
// got db set from dbcontext, it is ok

Func<vExpenseRegister, bool> where= a => a.InvoiceDate > fromDate;
// create a delegate and pass a condition

var result = dbSet1.Where(where).AsQueryable().ToList();

// but result is nothing, in spite of record exists in database
//but i change code eliminate Func delegate and condition write in where method //like

var result = dbSet1.Where(a => a.InvoiceDate > fromDate).AsQueryable().ToList();
//working fine

kindly help me why Func is not working

Thanks,
Akmal.

Body:
This should be an Expression<Func<...>>:

Func<vExpenseRegister, bool> where= a => a.InvoiceDate > fromDate;

So

Expression<Func<vExpenseRegister, bool>> where = a => a.InvoiceDate > fromDate;

If it is just a Func<...> it will be executed in memory after the entire table is returned.

If you look at the signature of dbSet1.Where you should see it takes an expression.


问:
Session timeout - Redirect user to same page on logging
In my Asp.Net webpage application when session timeout occurs the page will redirect to the login page and when we login again it goes to the home page.
But I want to redirect to the previously active page (where the session timeout occurs) instead of redirecting to the home page by default.
Is there is any way to achieve this.</p>

答:
Hello you can do following thing

When session expires at that time you can redirect user from that page to logged in page with below query string

```<code>Response.Redirect("Login.aspx?url=page.aspx");
</code>```

Where Page.aspx will be your current page name. you have to write this code on each page's load Event before if(!ispostback) condition.

and at time of logged in button click you can do

```<code>if (Request.QueryString["url"] != null)
            {
                Response.Redirect(Request.QueryString["url"].ToString());
            }
</code>```

after making query for user name and password before your redirect to default page.

Body:
Hello you can do following thing

When session expires at that time you can redirect user from that page to logged in page with below query string

Response.Redirect("Login.aspx?url=page.aspx");

Where Page.aspx will be your current page name. you have to write this code on each page's load Event before if(!ispostback) condition.

and at time of logged in button click you can do

if (Request.QueryString["url"] != null)
            {
                Response.Redirect(Request.QueryString["url"].ToString());
            }

after making query for user name and password before your redirect to default page.


问:
How does the NodeInterface and nodeField work in relayjs and what does they mean
how does the nodeInterface refetch and do object identification,

and what does the type represent and what does the obj represent, what is id here

and what does instanceof mean

```<code>const { nodeInterface, nodeField } = nodeDefinitions(
(globalId) => {
    const { type, id } = fromGlobalId(globalId);

    console.log('NodeDefinitions (globalId), id:', id);
    console.log('NodeDefinitions (globalId), type:', type);

    if (type === 'teacher') {
        return teacher.findOne({ _id: id }).exec();
    } else if (type === 'college') {
        return college.findOne({ _id: id }).exec();
    } else if (type === 'student') {
        return student.findOne({ _id: id }).exec();
    }
    return null;
},
(obj) => {
    if( obj instanceof Teacher) {
       return teacherType
     }
      // other types too
    return null;
});
</code>```

答:
InstanceOf in this case is checking the class type of the object with the given passed in globalID. See instanceof on Mozilla.

Regarding nodeInterface The simple answer, and what finally let me understand it, is that the nodeInterface is how the the app stays in contact with the object.Remember what you are doing with GraphQL when you create your schema. You are creating GraphQL class 'Types'. So nodeInterface, is checking your objects GraphQL Type. If you have no schema then you cant have types. The 'id' property is the idea on an instance of your type, or in this case, an instance of 'teacher', 'college' or 'student' GraphQLObjectType. So in a line, relay is saying, give me the objects type and id and I will keep track of it for you. Let me know if you need further explanation.

Body:
how does the nodeInterface refetch and do object identification,

and what does the type represent and what does the obj represent, what is id here

and what does instanceof mean

const { nodeInterface, nodeField } = nodeDefinitions(
(globalId) => {
    const { type, id } = fromGlobalId(globalId);

    console.log('NodeDefinitions (globalId), id:', id);
    console.log('NodeDefinitions (globalId), type:', type);

    if (type === 'teacher') {
        return teacher.findOne({ _id: id }).exec();
    } else if (type === 'college') {
        return college.findOne({ _id: id }).exec();
    } else if (type === 'student') {
        return student.findOne({ _id: id }).exec();
    }
    return null;
},
(obj) => {
    if( obj instanceof Teacher) {
       return teacherType
     }
      // other types too
    return null;
});


问:
Are vendor prefixes required for "none"?
Just a quick question about vendor prefixes that I've been wondering about but couldn't find the answer to - are they required when turning off/resetting the style with "none", "initial", "0", etc?  For example, if I set a box shadow like this:

```<code>   -webkit-box-shadow: -4px 0 10px 2px rgba(0, 0, 0, .1);
   -moz-box-shadow: -4px 0 10px 2px rgba(0, 0, 0, .1);
   box-shadow: -4px 0 10px 2px rgba(0, 0, 0, .1);
</code>```

If I didn't want the box shadow at a smaller screen size, in the media query would I do simply do "box-shadow: none;" or do I need to do:

```<code>  -webkit-box-shadow: none;
  -moz-box-shadow: none;
  box-shadow: none;
</code>```

答:
If you set your box-shadow like this...

```<code>-webkit-box-shadow: -4px 0 10px 2px rgba(0, 0, 0, .1);
-moz-box-shadow: -4px 0 10px 2px rgba(0, 0, 0, .1);
box-shadow: -4px 0 10px 2px rgba(0, 0, 0, .1);
</code>```

... you'll need to unset it like this :

```<code>-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
</code>```

Otherwise, browsers that don't support the non-prefixed version of box-shadow won't know that you're setting your box-shadow to none, just like they won't know that you're setting your box-shadow to -4px 0 10px 2px rgba(0, 0, 0, .1) if you only use the non-prefixed version.

Body:
Just a quick question about vendor prefixes that I've been wondering about but couldn't find the answer to - are they required when turning off/resetting the style with "none", "initial", "0", etc?  For example, if I set a box shadow like this:

   -webkit-box-shadow: -4px 0 10px 2px rgba(0, 0, 0, .1);
   -moz-box-shadow: -4px 0 10px 2px rgba(0, 0, 0, .1);
   box-shadow: -4px 0 10px 2px rgba(0, 0, 0, .1);

If I didn't want the box shadow at a smaller screen size, in the media query would I do simply do "box-shadow: none;" or do I need to do:

  -webkit-box-shadow: none;
  -moz-box-shadow: none;
  box-shadow: none;

Body:
If you set your box-shadow like this...

-webkit-box-shadow: -4px 0 10px 2px rgba(0, 0, 0, .1);
-moz-box-shadow: -4px 0 10px 2px rgba(0, 0, 0, .1);
box-shadow: -4px 0 10px 2px rgba(0, 0, 0, .1);

... you'll need to unset it like this :

-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;

Otherwise, browsers that don't support the non-prefixed version of box-shadow won't know that you're setting your box-shadow to none, just like they won't know that you're setting your box-shadow to -4px 0 10px 2px rgba(0, 0, 0, .1) if you only use the non-prefixed version.


问:
Is there a more concise way to combine many comparisons in Ruby?
I currently have this if statement:

```<code>if Time.now.day == 1 and Time.now.hour == 0 and Time.now.minute == 0 and Time.now.second == 0
</code>```

Is there a more concise way to do this?

答:
I guess that you are trying to make something similar to cron, i.e. you are in an endless loop and checking whether time has come to perform certain action.

If that is the case, I don't think you should rely that your timestamp check will fall exactly on the first second of the day. What would happen if is delayed (for any reason), and first it fires on 23:59:59, and the next cycle happens on 00:00:01 instead of :00? You will fail to perform desired action whatsoever.

Also, you would want to include some sleep, so that your empty loop wouldn't consume all you resources while waiting.

What you could do instead, is keep the last action timestamp, and compare now with the next action timestamp, performing the action if now >= next_timestamp. Something like:

```<code>last_action_on = Time.at(0)
loop do
  now = Time.now
  next_action_on = Time.local(now.year, now.month, 1) # beginning of the current day
  if last_action_on < next_action_on && now >= next_action_on
    last_action_on = now
    do_action
  end
  sleep 1
end
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I currently have this if statement:

if Time.now.day == 1 and Time.now.hour == 0 and Time.now.minute == 0 and Time.now.second == 0

Is there a more concise way to do this?

Body:
I guess that you are trying to make something similar to cron, i.e. you are in an endless loop and checking whether time has come to perform certain action.

If that is the case, I don't think you should rely that your timestamp check will fall exactly on the first second of the day. What would happen if is delayed (for any reason), and first it fires on 23:59:59, and the next cycle happens on 00:00:01 instead of :00? You will fail to perform desired action whatsoever.

Also, you would want to include some sleep, so that your empty loop wouldn't consume all you resources while waiting.

What you could do instead, is keep the last action timestamp, and compare now with the next action timestamp, performing the action if now >= next_timestamp. Something like:

last_action_on = Time.at(0)
loop do
  now = Time.now
  next_action_on = Time.local(now.year, now.month, 1) # beginning of the current day
  if last_action_on < next_action_on && now >= next_action_on
    last_action_on = now
    do_action
  end
  sleep 1
end


问:
type hyperlink not found in xmlns http://xamarin.com/schemas/2014/forms
I am trying to make an app, and I wanted to have text with hyperlink, but whenever I try to run my app it gives me this error: "Error       Position 68:40. Type Hyperlink not found in xmlns http://xamarin.com/schemas/2014/forms FamilyEvents    C:\desenv\Family\FamilyEvents\DetailsPage.xaml  68  "

My code is this:

My code

答:
<Hyperlink /> is not a Xamarin Forms control.

You can achieve something similar by using a Label control with a TapGestureRecognizer.


问:
Most efficient algorithm for merging sorted IEnumerable<T>
I have several huge sorted enumerable sequences that I want to merge. Theses lists are manipulated as IEnumerable but are already sorted. Since input lists are sorted, it should be possible to merge them in one trip, without re-sorting anything.

I would like to keep the defered execution behavior.

I tried to write a naive algorithm which do that (see below). However, it looks pretty ugly and I'm sure it can be optimized. It may exist a more academical algorithm...

```<code>IEnumerable<T> MergeOrderedLists<T, TOrder>(IEnumerable<IEnumerable<T>> orderedlists,
                                            Func<T, TOrder> orderBy)
{
    var enumerators = orderedlists.ToDictionary(l => l.GetEnumerator(), l => default(T));
    IEnumerator<T> tag = null;

    var firstRun = true;
    while (true)
    {
        var toRemove = new List<IEnumerator<T>>();
        var toAdd = new List<KeyValuePair<IEnumerator<T>, T>>();
        foreach (var pair in enumerators.Where(pair => firstRun || tag == pair.Key))
        {
            if (pair.Key.MoveNext())
                toAdd.Add(pair);
            else
                toRemove.Add(pair.Key);
        }

        foreach (var enumerator in toRemove)
            enumerators.Remove(enumerator);

        foreach (var pair in toAdd)
            enumerators[pair.Key] = pair.Key.Current;

        if (enumerators.Count == 0)
            yield break;

        var min = enumerators.OrderBy(t => orderBy(t.Value)).FirstOrDefault();
        tag = min.Key;
        yield return min.Value;

        firstRun = false;
    }
}
</code>```

The method can be used like that:

```<code>// Person lists are already sorted by age
MergeOrderedLists(orderedList, p => p.Age);
</code>```

assuming the following Person class exists somewhere:

```<code>    public class Person
    {
        public int Age { get; set; }
    }
</code>```

Duplicates should be conserved, we don't care about their order in the new sequence. Do you see any obvious optimization I could use?

答:
This is an alternate solution:</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Data;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{

    class Person
    {
        public string Name
        {
            get;
            set;
        }

        public int Age
        {
            get;
            set;
        }
    }

    public class Program
    {
        public static void Main()
        {
            Person[] persons1 = new Person[] { new Person() { Name = "Ahmed", Age = 20 }, new Person() { Name = "Ali", Age = 40 } };
            Person[] persons2 = new Person[] { new Person() { Name = "Zaid", Age = 21 }, new Person() { Name = "Hussain", Age = 22 } };
            Person[] persons3 = new Person[] { new Person() { Name = "Linda", Age = 19 }, new Person() { Name = "Souad", Age = 60 } };

            Person[][] personArrays = new Person[][] { persons1, persons2, persons3 };

            foreach(Person person in MergeOrderedLists<Person, int>(personArrays, person => person.Age))
            {
                Console.WriteLine("{0} {1}", person.Name, person.Age);
            }

            Console.ReadLine();
        }

        static IEnumerable<T> MergeOrderedLists<T, TOrder>(IEnumerable<IEnumerable<T>> orderedlists, Func<T, TOrder> orderBy)
        {
            List<IEnumerator<T>> enumeratorsWithData = orderedlists.Select(enumerable => enumerable.GetEnumerator())
                                                                   .Where(enumerator => enumerator.MoveNext()).ToList();

            while (enumeratorsWithData.Count > 0)
            {
                IEnumerator<T> minEnumerator = enumeratorsWithData[0];
                for (int i = 1; i < enumeratorsWithData.Count; i++)
                    if (((IComparable<TOrder>)orderBy(minEnumerator.Current)).CompareTo(orderBy(enumeratorsWithData[i].Current)) >= 0)
                        minEnumerator = enumeratorsWithData[i];

                yield return minEnumerator.Current;

                if (!minEnumerator.MoveNext())
                    enumeratorsWithData.Remove(minEnumerator);
            }
        }
    }
}
</code>```

Body:
I have several huge sorted enumerable sequences that I want to merge. Theses lists are manipulated as IEnumerable but are already sorted. Since input lists are sorted, it should be possible to merge them in one trip, without re-sorting anything.

I would like to keep the defered execution behavior.

I tried to write a naive algorithm which do that (see below). However, it looks pretty ugly and I'm sure it can be optimized. It may exist a more academical algorithm...

IEnumerable<T> MergeOrderedLists<T, TOrder>(IEnumerable<IEnumerable<T>> orderedlists,
                                            Func<T, TOrder> orderBy)
{
    var enumerators = orderedlists.ToDictionary(l => l.GetEnumerator(), l => default(T));
    IEnumerator<T> tag = null;

    var firstRun = true;
    while (true)
    {
        var toRemove = new List<IEnumerator<T>>();
        var toAdd = new List<KeyValuePair<IEnumerator<T>, T>>();
        foreach (var pair in enumerators.Where(pair => firstRun || tag == pair.Key))
        {
            if (pair.Key.MoveNext())
                toAdd.Add(pair);
            else
                toRemove.Add(pair.Key);
        }

        foreach (var enumerator in toRemove)
            enumerators.Remove(enumerator);

        foreach (var pair in toAdd)
            enumerators[pair.Key] = pair.Key.Current;

        if (enumerators.Count == 0)
            yield break;

        var min = enumerators.OrderBy(t => orderBy(t.Value)).FirstOrDefault();
        tag = min.Key;
        yield return min.Value;

        firstRun = false;
    }
}

The method can be used like that:

// Person lists are already sorted by age
MergeOrderedLists(orderedList, p => p.Age);

assuming the following Person class exists somewhere:

    public class Person
    {
        public int Age { get; set; }
    }

Duplicates should be conserved, we don't care about their order in the new sequence. Do you see any obvious optimization I could use?

Body:
This is an alternate solution:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Data;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{

    class Person
    {
        public string Name
        {
            get;
            set;
        }

        public int Age
        {
            get;
            set;
        }
    }

    public class Program
    {
        public static void Main()
        {
            Person[] persons1 = new Person[] { new Person() { Name = "Ahmed", Age = 20 }, new Person() { Name = "Ali", Age = 40 } };
            Person[] persons2 = new Person[] { new Person() { Name = "Zaid", Age = 21 }, new Person() { Name = "Hussain", Age = 22 } };
            Person[] persons3 = new Person[] { new Person() { Name = "Linda", Age = 19 }, new Person() { Name = "Souad", Age = 60 } };

            Person[][] personArrays = new Person[][] { persons1, persons2, persons3 };

            foreach(Person person in MergeOrderedLists<Person, int>(personArrays, person => person.Age))
            {
                Console.WriteLine("{0} {1}", person.Name, person.Age);
            }

            Console.ReadLine();
        }

        static IEnumerable<T> MergeOrderedLists<T, TOrder>(IEnumerable<IEnumerable<T>> orderedlists, Func<T, TOrder> orderBy)
        {
            List<IEnumerator<T>> enumeratorsWithData = orderedlists.Select(enumerable => enumerable.GetEnumerator())
                                                                   .Where(enumerator => enumerator.MoveNext()).ToList();

            while (enumeratorsWithData.Count > 0)
            {
                IEnumerator<T> minEnumerator = enumeratorsWithData[0];
                for (int i = 1; i < enumeratorsWithData.Count; i++)
                    if (((IComparable<TOrder>)orderBy(minEnumerator.Current)).CompareTo(orderBy(enumeratorsWithData[i].Current)) >= 0)
                        minEnumerator = enumeratorsWithData[i];

                yield return minEnumerator.Current;

                if (!minEnumerator.MoveNext())
                    enumeratorsWithData.Remove(minEnumerator);
            }
        }
    }
}


问:
php display records not showing
I am trying to show records in php with mysqli. this is my code for php display record which does not gives any error but does  not shows any records as well. insert operation is working but display not working what is missing here ???</p>

```<code>    <!DOCTYPE html>
<html>
<body>

<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

   movie_name<input type="text" name="movie_name"><br>
   movie_embedded_id<input type="text" name="movie_embedded_id"><br>
   rating_no<input type="text" name="rating_no"><br>
   movie_description<input type="text" name="movie_description"><br>
   <input type="submit" name="submit" value="Submit">

</form>

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname="mydb";

// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";

        if(isset($_POST['movie_name']) && $_POST['movie_name'] != "")
            {
                $sql = "INSERT INTO movies (movie_name, movie_embedded_id, rating_no, movie_description)VALUES ('".$_POST['movie_name']."', '".$_POST['movie_embedded_id']."', '".$_POST['rating_no']."','".$_POST['movie_description']."')";

            if ($conn->query($sql) === TRUE) {
            echo "New record created successfully";
            } else {
            echo "Error: " . $sql . "<br>" . $conn->error;
            }

        }

$conn->close();

?>

<?php

      if(isset($_POST['movie_name']) && $_POST['movie_name'] != "")
            {
$sql = "select * from movies where movie_id = ".$_GET["id"]."";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
     echo "<table><tr><th>ID</th><th>movie_name</th><th>movie_embedded_id</th><th>rating_no</th><th>movie_description</th></tr>";
     // output data of each row
     while($row = $result->fetch_assoc()) {
         echo "<tr><td>" . $row["id"]. "</td><td>" . $row["movie_name"]. " </td><td>" . $row["movie_embedded_id"]. " </td><td>" . $row["rating_no"]. "</td><td> " . $row["rating_no"]. "</td></tr>";
     }
     echo "</table>";
} else {
     echo "0 results";
}

    }

  ?>

</body>
</html>
</code>```

答:
let's try this

it will work

```<code> <?php

        if(isset($_POST['movie_name']) && $_POST['movie_name'] != "")
            {
$sql = "select * from movies where movie_id = ".$_GET['id'];
$result = $conn->query($sql);

if ($result->num_rows > 0) {
     echo "<table><tr><th>ID</th><th>movie_name</th><th>movie_embedded_id</th><th>rating_no</th><th>movie_description</th></tr>";
     // output data of each row
     while($row = $result->fetch_assoc()) {
         echo "<tr><td>" . $row["id"]. "</td><td>" . $row["movie_name"]. " </td><td>" . $row["movie_embedded_id"]. " </td><td>" . $row["rating_no"]. "</td><td> " . $row["rating_no"]. "</td></tr>";
     }
     echo "</table>";
} else {
     echo "0 results";
}

    }
</code>```

Title: php display records not showing

Body:
I am trying to show records in php with mysqli. this is my code for php display record which does not gives any error but does  not shows any records as well. insert operation is working but display not working what is missing here ???

    <!DOCTYPE html>

<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

   movie_name<input type="text" name="movie_name">

   movie_embedded_id<input type="text" name="movie_embedded_id">

   rating_no<input type="text" name="rating_no">

   movie_description<input type="text" name="movie_description">

   <input type="submit" name="submit" value="Submit">

</form>

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname="mydb";

// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";

        if(isset($_POST['movie_name']) && $_POST['movie_name'] != "")
            {
                $sql = "INSERT INTO movies (movie_name, movie_embedded_id, rating_no, movie_description)VALUES ('".$_POST['movie_name']."', '".$_POST['movie_embedded_id']."', '".$_POST['rating_no']."','".$_POST['movie_description']."')";

            if ($conn->query($sql) === TRUE) {
            echo "New record created successfully";
            } else {
            echo "Error: " . $sql . "
" . $conn->error;
            }

        }

$conn->close();

?>

<?php

      if(isset($_POST['movie_name']) && $_POST['movie_name'] != "")
            {
$sql = "select * from movies where movie_id = ".$_GET["id"]."";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
     echo "

ID	movie_name	movie_embedded_id	rating_no	movie_description
";
     // output data of each row
     while($row = $result->fetch_assoc()) {
         echo "
" . $row["id"]. "	" . $row["movie_name"]. " 	" . $row["movie_embedded_id"]. " 	" . $row["rating_no"]. "	 " . $row["rating_no"]. "
";
     }
     echo "
";
} else {
     echo "0 results";
}

    }

  ?>

Body:
let's try this

it will work

 <?php

        if(isset($_POST['movie_name']) && $_POST['movie_name'] != "")
            {
$sql = "select * from movies where movie_id = ".$_GET['id'];
$result = $conn->query($sql);

if ($result->num_rows > 0) {
     echo "<table><tr><th>ID</th><th>movie_name</th><th>movie_embedded_id</th><th>rating_no</th><th>movie_description</th></tr>";
     // output data of each row
     while($row = $result->fetch_assoc()) {
         echo "<tr><td>" . $row["id"]. "</td><td>" . $row["movie_name"]. " </td><td>" . $row["movie_embedded_id"]. " </td><td>" . $row["rating_no"]. "</td><td> " . $row["rating_no"]. "</td></tr>";
     }
     echo "</table>";
} else {
     echo "0 results";
}

    }


问:
Liferay deployment in linux Server
i have installed liferay 7 in linux server. but when i try start the server it doesnt start properly shows up without css .

Is there any procedure to install liferay in linux server

Browser Console

Some files are accessing with url localhost

```<code>http://localhost:8383/o/classic-theme/css/aui.css?browserId=firefox&themeId=classic_WAR_classictheme&minifierType=css&languageId=en_US&b=7002&t=32

http://localhost:8383/o/mentions-web/css/mentions.css

/o url is not generating with hostname instead generates with localhost
</code>```

答:
I found the reason i added

```<code>web.server.host=domain
web.server.http.port=80
</code>```

in

```<code>portal-ext.properties
</code>```

It works now. Thanks for the replies

Title: Liferay deployment in linux Server

Body:
i have installed liferay 7 in linux server. but when i try start the server it doesnt start properly shows up without css .

Is there any procedure to install liferay in linux server

Browser Console

Some files are accessing with url localhost

http://localhost:8383/o/classic-theme/css/aui.css?browserId=firefox&themeId=classic_WAR_classictheme&minifierType=css&languageId=en_US&b=7002&t=32

http://localhost:8383/o/mentions-web/css/mentions.css

/o url is not generating with hostname instead generates with localhost

Body:
I found the reason i added

web.server.host=domain
web.server.http.port=80

in

portal-ext.properties

It works now. Thanks for the replies


问:
How to see all output from Ismeans?
I have run the linear mixed model using lme4 package. Then to see all pair of contrasts, I have to run the lsmeans function using lsmeans package. This is the function I run:

```<code>library('lme4')
library('lsmeans')
lsmeans(lmer1, pairwise ~ vowel * experience * lang_sound, adjust="tukey")
</code>```

However I cannot see the whole output as there are too many pairs. Can anyone tell me what I should do to get the output from this function?

I have tried 'sink()' but it doesn't work. Maybe because there is no name of the lsmeans command I ran. I am using RStudio on Windows.

答:
The sink function does work, but you have to give a file name to save the output. For example

```<code>sink(file = "lsm-output.txt")
lsmeans(...)
sink()
</code>```

The last sink() call reverts output back to the console.

That said, I don't think you need to see all those pairwise comparisons. I'd suggest doing the lsmeans and comparisons in separate calls. And you can do comparisons of one factor's levels conditionally on the other two by using pairs with a by argument:

```<code>library("lsmeans")
lmer1.lsm <- lsmeans(lmer1, ~ vowel * experience * lang_sound)
lmer1.lsm     # display the means
pairs(lmer1.lsm, by = c("experience", "lang_sound"))
pairs(lmer1.lsm, by = c("vowel", "lang_sound"))
pairs(lmer1.lsm, by = c("vowel", "experience"))
</code>```

I also think you should visualize the results you have, e.g. by constructing an interaction plot:

```<code>lsmip(lmer1.lsm, experience ~ vowel | lang_sound)
</code>```

some interchanging of the factors in this call may prove more satisfactory.

ContentLicense: CC BY-SA 4.0

Title: How to see all output from Ismeans?

Body:
I have run the linear mixed model using lme4 package. Then to see all pair of contrasts, I have to run the lsmeans function using lsmeans package. This is the function I run:

library('lme4')
library('lsmeans')
lsmeans(lmer1, pairwise ~ vowel * experience * lang_sound, adjust="tukey")

However I cannot see the whole output as there are too many pairs. Can anyone tell me what I should do to get the output from this function?

I have tried 'sink()' but it doesn't work. Maybe because there is no name of the lsmeans command I ran. I am using RStudio on Windows.

Body:
The sink function does work, but you have to give a file name to save the output. For example

sink(file = "lsm-output.txt")
lsmeans(...)
sink()

The last sink() call reverts output back to the console.

That said, I don't think you need to see all those pairwise comparisons. I'd suggest doing the lsmeans and comparisons in separate calls. And you can do comparisons of one factor's levels conditionally on the other two by using pairs with a by argument:

library("lsmeans")
lmer1.lsm <- lsmeans(lmer1, ~ vowel * experience * lang_sound)
lmer1.lsm     # display the means
pairs(lmer1.lsm, by = c("experience", "lang_sound"))
pairs(lmer1.lsm, by = c("vowel", "lang_sound"))
pairs(lmer1.lsm, by = c("vowel", "experience"))

I also think you should visualize the results you have, e.g. by constructing an interaction plot:

lsmip(lmer1.lsm, experience ~ vowel | lang_sound)

some interchanging of the factors in this call may prove more satisfactory.


问:
using multiple return statements in a c++ function
I was wondering if it might be sort of advantageous for a c++ compiler if there's only one return statement in a function. one of my ex-bosses once told me so but I don't get the point if there would be any difference between declaring a return variable or simply having multiple return statements, e.g. in a switch-case statement.

So my question is: is there any difference, maybe in quality, performance or stack memory savings?

答: Refer https://en.wikipedia.org/wiki/Return_statement sub-section Multiple return statements</p>


问:
Run alembic migrations on a flask elastic beanstalk instance
I have an elastic beanstalk instance with flask installed. I have alembic properly setup and I can run the command locally by running

```<code>cd migrations
alembic upgrade head
</code>```

I made a file in my .ebextensions which looks like this:

```<code>container_commands:
  00-run-alembic:
    command: alembic upgrade head
</code>```

But it's not working, I know i probably need to cd in to the proper dir, but im not sure where to do that.

答:
You need to specify working directory for that command, e.g.:</p>

```<code>container_commands:
  00-run-alembic:
    command: alembic upgrade head
    cwd: /put/your/directory/here
</code>```

Body:
I have an elastic beanstalk instance with flask installed. I have alembic properly setup and I can run the command locally by running

cd migrations
alembic upgrade head

I made a file in my .ebextensions which looks like this:

container_commands:
  00-run-alembic:
    command: alembic upgrade head

But it's not working, I know i probably need to cd in to the proper dir, but im not sure where to do that.

Body:
You need to specify working directory for that command, e.g.:

container_commands:
  00-run-alembic:
    command: alembic upgrade head
    cwd: /put/your/directory/here


答:
The type you are using Hyperlink is not a control within Xamarin.Forms, so it gives you an error that it is not a type which is found in the default namespace.

If you want such functionality use a Label control on which you can tap with a TapGestureRecognizer. The code could look like this:

```<code><Label Text="My link">
    <Label.GestureRecognizers>
        <TapGestureRecognizer Tapped="OnTapGestureRecognizerTapped" NumberOfTapsRequired="1" />
    </Label.GestureRecognizers>
</Label>
</code>```

And in your code behind implement the OnTapGestureRecognizerTapped event which opens your link.

Title: type hyperlink not found in xmlns http://xamarin.com/schemas/2014/forms

Body:
I am trying to make an app, and I wanted to have text with hyperlink, but whenever I try to run my app it gives me this error: "Error       Position 68:40. Type Hyperlink not found in xmlns http://xamarin.com/schemas/2014/forms FamilyEvents    C:\desenv\Family\FamilyEvents\DetailsPage.xaml  68  "

My code is this:

My code

Body:
The type you are using Hyperlink is not a control within Xamarin.Forms, so it gives you an error that it is not a type which is found in the default namespace.

If you want such functionality use a Label control on which you can tap with a TapGestureRecognizer. The code could look like this:

<Label Text="My link">
    <Label.GestureRecognizers>
        <TapGestureRecognizer Tapped="OnTapGestureRecognizerTapped" NumberOfTapsRequired="1" />
    </Label.GestureRecognizers>
</Label>

And in your code behind implement the OnTapGestureRecognizerTapped event which opens your link.


问:
Application gives error only on 64 bit version
My application runs well if is the 32 bit version, but when I added the new 64 bit platform to the Configuration manager and tried to run it, I got the following message at startup:

答:
After reading 64bit manifest problem / side by side issue I concluded the problem was the manifest line

```<code>#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"")
</code>```

<s>
So I add to branch it, conditioned by the platform:

```<code>#ifdef _WIN64
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"")
#else
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"")
#endif
</code>```

</s>

So, I add to turn it generic, independent of the platform:

```<code>#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
</code>```

Notice the difference in processorArchitecture value.

Now everything is working fine!

Body:
After reading 64bit manifest problem / side by side issue I concluded the problem was the manifest line

#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"")

<s>
So I add to branch it, conditioned by the platform:

#ifdef _WIN64
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"")
#else
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"")
#endif

</s>

So, I add to turn it generic, independent of the platform:

#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")

Notice the difference in processorArchitecture value.

Now everything is working fine!


问:
How to check if Data on column still exist using VB.Net
I have datatable tblEmployeeInfo and column EmployeeName with contains data.

```EmployeeName
Mike
Jay
Paul```

Also I have Textbox1 to type a name and button to "Verify".
How do I check if the Employee Name exists in the column EmployeeName?

For example, "Jay".

So far this is my code on button "Verify":

```<code>    conn.Open()
    cmd.Connection = conn
    cmd.CommandText = "SELECT [Employee Name] FROM tblHolidayOvertimeEntry WHERE [Employee Name] = '" & tbEmployeeName.Text & "' "
    Dim result1 as String = cmd.ExecuteNonQuery
    conn.Close()

    If result1 <> tbEmployeeName.Text Then

        MsgBox("No Employee Name found")
    Else

        MsgBox("Employee name still exist")

    End If
</code>```

答:
first of all clear concept about  ExecuteScalar, ExecuteReader and ExecuteNonQuery from this link:
When to use ExecuteScalar,ExecuteReader,ExecuteNonQuery?

and you have to set like

```<code>cmd.CommandText = "SELECT [Employee Name] FROM tblHolidayOvertimeEntry WHERE [Employee Name] = '" & tbEmployeeName.Text & "' "
Dim result1 as String = cmd.ExecuteScalar
</code>```

Body:
I have datatable tblEmployeeInfo and column EmployeeName with contains data.

EmployeeName
Mike
Jay
Paul

Also I have Textbox1 to type a name and button to "Verify".
How do I check if the Employee Name exists in the column EmployeeName?

For example, "Jay".

So far this is my code on button "Verify":

    conn.Open()
    cmd.Connection = conn
    cmd.CommandText = "SELECT [Employee Name] FROM tblHolidayOvertimeEntry WHERE [Employee Name] = '" & tbEmployeeName.Text & "' "
    Dim result1 as String = cmd.ExecuteNonQuery
    conn.Close()

    If result1 <> tbEmployeeName.Text Then

        MsgBox("No Employee Name found")
    Else

        MsgBox("Employee name still exist")

    End If

Body:
first of all clear concept about  ExecuteScalar, ExecuteReader and ExecuteNonQuery from this link:
When to use ExecuteScalar,ExecuteReader,ExecuteNonQuery?

and you have to set like

cmd.CommandText = "SELECT [Employee Name] FROM tblHolidayOvertimeEntry WHERE [Employee Name] = '" & tbEmployeeName.Text & "' "
Dim result1 as String = cmd.ExecuteScalar


问:
React separate instances call same method with separate values
I need to render two separate input[type="range] each one witha separate outputvalue.

I have created a set of components wich pass up and dow their data in order to render in the correct way.

BUT I cannot split the rendering of the two components I need to declare which state is been affected, I want to store that in a variable and pass it through in different cases.

Here is a code pen of what I'm doing:

http://codepen.io/wanbinkimoon/pen/NpEpre?editors=0011

Here are the lines I think are wrong:

```<code>handleChange() {
   let v = props.t;
   this.setState({
     v: event.target.value
 });
</code>```

Which is a function that refers to an instance of <Range /> declared like this:

```<code><Range
    name = 'X Value'
    t = {'xvalue'}
    value = {this.state.xvalue}
    change = {this.handleChange}
/>
</code>```

I tried to pass in some arguments but returns me errors.

答:
Pass a unique property from parent component for example: name, and assing that name to input field, try to use the same name as the state variable name.

Like this:

```<code><input
    type="range"
    min={min}
    max={max}
    step={step}
    name={this.props.name} //assigning name
    value={this.props.value}
    onChange={(e)=>this.props.change(e)}
/>
</code>```

Pass the event object to parent component. Use this event to update the state value. Like this:

```<code>handleChange(e) {
    //let v = props.t;
    let obj = {};
    obj[e.target.name] = e.target.value;
    this.setState(obj);
    console.log(event.target.value);
};
</code>```

Reason why it is working:

State is any object, it contains key value pair, since we used same name as the name of state variable, we can use that name to update state value. When we pass an object in setState it replaces the values of state  variable by values passed in that object. Its like:

state values = {x: 1, y: 2};

obj[x] = 5;

now when we do setState it will merge these two objects and new state values will be: {x: 5, y: 2}

Check the working code:

class Range extends React.Component {
  constructor(props) {
    super(props);
  };
  render() {
    let min = 0;
    let max = 500;
    let step = 1;
    return (
      <form>

{this.props.name}

        <input
           type="range"
           min={min}
           max={max}
           step={step}
           name={this.props.name}
           value={this.props.value}
           onChange={(e)=>this.props.change(e)}
         />
         <output>
           {this.props.value}
         </output>
       </form>
    )
  };
};

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      xvalue: 100,
      yvalue: 300,
    }
    this.handleChange = this.handleChange.bind(this);
  };

  handleChange(e) {
    let obj = {};
    obj[e.target.name] = e.target.value;
    this.setState(obj);
    console.log(event.target.value);
  };

  render() {
     return (

          <Range
              name = 'xvalue'
              t = {'xvalue'}
              value = {this.state.xvalue}
              change = {this.handleChange}
          />
          <Range
             name = 'yvalue'
             t = {'yvalue'}
             value = {this.state.yvalue}
             change = {this.handleChange}
          />

     )
   };
};

class Rect extends React.Component {
  constructor(props) {
    super(props);
  };

  render() {
     return (

           Rect

     )
  };
};

class Wrap extends React.Component {
  constructor(props) {
     super(props);
  }
  render() {
    return (

         <Form />

         <Rect />

    )
  };
};

ReactDOM.render(
  <Wrap />,
  document.getElementById('app')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'></code>```

Body:
I need to render two separate input[type="range] each one witha separate outputvalue.

I have created a set of components wich pass up and dow their data in order to render in the correct way.

BUT I cannot split the rendering of the two components I need to declare which state is been affected, I want to store that in a variable and pass it through in different cases.

Here is a code pen of what I'm doing:

http://codepen.io/wanbinkimoon/pen/NpEpre?editors=0011

Here are the lines I think are wrong:

handleChange() {
   let v = props.t;
   this.setState({
     v: event.target.value
 });

Which is a function that refers to an instance of <Range /> declared like this:

<Range
    name = 'X Value'
    t = {'xvalue'}
    value = {this.state.xvalue}
    change = {this.handleChange}
/>

I tried to pass in some arguments but returns me errors.

Body:
Pass a unique property from parent component for example: name, and assing that name to input field, try to use the same name as the state variable name.

Like this:

<input
    type="range"
    min={min}
    max={max}
    step={step}
    name={this.props.name} //assigning name
    value={this.props.value}
    onChange={(e)=>this.props.change(e)}
/>

Pass the event object to parent component. Use this event to update the state value. Like this:

handleChange(e) {
    //let v = props.t;
    let obj = {};
    obj[e.target.name] = e.target.value;
    this.setState(obj);
    console.log(event.target.value);
};

Reason why it is working:

State is any object, it contains key value pair, since we used same name as the name of state variable, we can use that name to update state value. When we pass an object in setState it replaces the values of state  variable by values passed in that object. Its like:

state values = {x: 1, y: 2};

obj[x] = 5;

now when we do setState it will merge these two objects and new state values will be: {x: 5, y: 2}

Check the working code:

class Range extends React.Component {
  constructor(props) {
    super(props);
  };
  render() {
    let min = 0;
    let max = 500;
    let step = 1;
    return (
      <form>
        <h4>{this.props.name}</h4>
        <input
           type="range"
           min={min}
           max={max}
           step={step}
           name={this.props.name}
           value={this.props.value}
           onChange={(e)=>this.props.change(e)}
         />
         <output>
           {this.props.value}
         </output>
       </form>
    )
  };
};

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      xvalue: 100,
      yvalue: 300,
    }
    this.handleChange = this.handleChange.bind(this);
  };

  handleChange(e) {
    let obj = {};
    obj[e.target.name] = e.target.value;
    this.setState(obj);
    console.log(event.target.value);
  };

  render() {
     return (
        <div className="formwrap">
          <Range
              name = 'xvalue'
              t = {'xvalue'}
              value = {this.state.xvalue}
              change = {this.handleChange}
          />
          <Range
             name = 'yvalue'
             t = {'yvalue'}
             value = {this.state.yvalue}
             change = {this.handleChange}
          />
        </div>
     )
   };
};

class Rect extends React.Component {
  constructor(props) {
    super(props);
  };

  render() {
     return (
        <div>
           Rect
        </div>
     )
  };
};

class Wrap extends React.Component {
  constructor(props) {
     super(props);
  }
  render() {
    return (
      <div>
         <Form />
            <hr />
         <Rect />
      </div>
    )
  };
};

ReactDOM.render(
  <Wrap />,
  document.getElementById('app')
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'>


问:
.NET's GUID structure
http://msdn.microsoft.com/en-us/library/system.guid.aspx

How does it work? How does it guarantee unique ID? Does it only rely on probability or is there another trick? Can I always trust it to give unique id or what are cases where I should avoid guid?

答:
Here's a fun little program:

```<code>class Program
{
    static void Main(string[] args)
    {
        var guids = new HashSet<string>();
        var sw = Stopwatch.StartNew();

        while(true)
        {
            var guid = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 16);
            if (guids.Contains(guid)) break;
            guids.Add(guid);
        }

        Console.WriteLine("Duplicate found in {0} ms, after {1} items.", sw.ElapsedMilliseconds, guids.Count);
        Console.ReadLine();
    }
}
</code>```

I bet you'll run out of memory before it finds a dupe ;)

Edit: Even when using only half a Guid.

Title: .NET's GUID structure

Body:
Here's a fun little program:

class Program
{
    static void Main(string[] args)
    {
        var guids = new HashSet<string>();
        var sw = Stopwatch.StartNew();

        while(true)
        {
            var guid = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 16);
            if (guids.Contains(guid)) break;
            guids.Add(guid);
        }

        Console.WriteLine("Duplicate found in {0} ms, after {1} items.", sw.ElapsedMilliseconds, guids.Count);
        Console.ReadLine();
    }
}

I bet you'll run out of memory before it finds a dupe ;)

Edit: Even when using only half a Guid.


问:
Nested Flexbox height issue
Trying to get to grips with flexbox, never really used it before so apologies if I'm missing something very basic.

I have created a CodePen and simplified back to basics to show my issue.

My left column will most likely contain more content than the right, but using flex box i get them to both be the same height which is fine.

The right column i would like to contain multiple sub items but would like them to fill the full height split between them which is my issue here.

I have hard-coded a couple things to make the example easier height:400px;

/*uncomment this line to see desired effect*/
//height:184px;

答:
When you inspect the elements, you see that the cars elements have 2 parents .card-content and .flex-container-2 but they don't have any specific style so their height is determined only by the content inside them. In order to fix this you need to set the height to 100%:

```<code>.card-content,.flex-container-2 {height: 100%;}
</code>```

This is the full working example:

body {
    background: #000;
}

.card-content,.flex-container-2 {height: 100%;} /* My addition */

.flex-container {
    max-width: 1000px;
    margin: 0 auto;
    background: #fff;
    display: flex;
    align-items: stretch;
    flex-flow: row wrap;
    justify-content: space-between;
}

.flex-container-2 {
  display: flex;
  align-items: stretch;
  flex-flow: row wrap;
  justify-content: space-between;
}

.flex-item {
  display: flex;
  flex: 2 1 auto;
  padding: 0.5em;
  align-items: stretch;
}

.card-1 {
  background:grey;
  height:400px;
  width:300px;
}
.card-2 {
  width:300px;
  background:lightgrey;
}

.sub-card {
  width:100%;
  background:lightblue;

  /*uncomment this line to see desired effect*/
  //height:184px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex-container">

  <div class="flex-item">
    <div class="card card-1">
      <div class="card-content">
      <h1>Title</h1>
            <p>Lorem ipsum!</p>
        </div>
    </div>
  </div>

  <div class="flex-item">
    <div class="card card-2">
      <div class="card-content">
      <div class="flex-container-2">

          <div class="flex-item">
            <div class="card sub-card">
              <div class="card-content">
              <h2>subtitle1</h2>
                    <p>text one</p>
                </div>
            </div>
          </div>

        <div class="flex-item">
            <div class="card sub-card">
              <div class="card-content">
              <h2>subtitle2</h2>
                    <p>text two</p>
                </div>
            </div>
          </div>

        <div class="flex-item">
            <div class="card sub-card">
              <div class="card-content">
              <h2>subtitle3</h2>
                    <p>text three</p>
                </div>
            </div>
          </div>

        <div class="flex-item">
            <div class="card sub-card">
              <div class="card-content">
              <h2>subtitle4</h2>
                    <p>text four</p>
                </div>
            </div>
          </div>

</div>
    </div>
  </div>

</div></code>```

Title: Nested Flexbox height issue

Body:
When you inspect the elements, you see that the cars elements have 2 parents .card-content and .flex-container-2 but they don't have any specific style so their height is determined only by the content inside them. In order to fix this you need to set the height to 100%:

.card-content,.flex-container-2 {height: 100%;}

This is the full working example:

body {
    background: #000;
}

.card-content,.flex-container-2 {height: 100%;} /* My addition */

.flex-container {
    max-width: 1000px;
    margin: 0 auto;
    background: #fff;
    display: flex;
    align-items: stretch;
    flex-flow: row wrap;
    justify-content: space-between;
}

.flex-container-2 {
  display: flex;
  align-items: stretch;
  flex-flow: row wrap;
  justify-content: space-between;
}

.flex-item {
  display: flex;
  flex: 2 1 auto;
  padding: 0.5em;
  align-items: stretch;
}

.card-1 {
  background:grey;
  height:400px;
  width:300px;
}
.card-2 {
  width:300px;
  background:lightgrey;
}

.sub-card {
  width:100%;
  background:lightblue;

  /*uncomment this line to see desired effect*/
  //height:184px;
}

<div class="flex-container">

  <div class="flex-item">
    <div class="card card-1">
      <div class="card-content">
      <h1>Title</h1>
            <p>Lorem ipsum!</p>
        </div>
    </div>
  </div>

  <div class="flex-item">
    <div class="card card-2">
      <div class="card-content">
      <div class="flex-container-2">

          <div class="flex-item">
            <div class="card sub-card">
              <div class="card-content">
              <h2>subtitle1</h2>
                    <p>text one</p>
                </div>
            </div>
          </div>

        <div class="flex-item">
            <div class="card sub-card">
              <div class="card-content">
              <h2>subtitle2</h2>
                    <p>text two</p>
                </div>
            </div>
          </div>

        <div class="flex-item">
            <div class="card sub-card">
              <div class="card-content">
              <h2>subtitle3</h2>
                    <p>text three</p>
                </div>
            </div>
          </div>

        <div class="flex-item">
            <div class="card sub-card">
              <div class="card-content">
              <h2>subtitle4</h2>
                    <p>text four</p>
                </div>
            </div>
          </div>

</div>
    </div>
  </div>

</div>


问:
Querying another database from a Firebase Realtime Trigger
I'm trying to write a firebase realtime trigger that will query another database in the same project onWrite. How can i do so ?

```<code>  exports.trackit = functions.database.ref('/tags/{readId}').onWrite(event => {
  const snaps = event.data;
  var ref = functions.database().ref('/routes');

  ref.on("value", function(snapshot) {
     console.log(snapshot.val());
  }, function (error) {
     console.log("Error: " + error.code);
  });
})
</code>```

The above is a sample code put together from the samples and reference.

答:
You must have been looking at the wrong samples and docs then. This example from the documentation on creating your first function has an example:

```<code>const admin = require('firebase-admin');

// Take the text parameter passed to this HTTP endpoint and insert it into the
// Realtime Database under the path /messages/:pushId/original
exports.addMessage = functions.https.onRequest((req, res) => {
  // Grab the text parameter.
  const original = req.query.text;
  // Push it into the Realtime Database then send a response
  admin.database().ref('/messages').push({original: original}).then(snapshot => {
    // Redirect with 303 SEE OTHER to the URL of the pushed object in the Firebase console.
    res.redirect(303, snapshot.ref);
  });
});
</code>```

So use var ref = admin.database().ref('/routes').

Also see the full code in the github repo.

Body:
I'm trying to write a firebase realtime trigger that will query another database in the same project onWrite. How can i do so ?

  exports.trackit = functions.database.ref('/tags/{readId}').onWrite(event => {
  const snaps = event.data;
  var ref = functions.database().ref('/routes');

  ref.on("value", function(snapshot) {
     console.log(snapshot.val());
  }, function (error) {
     console.log("Error: " + error.code);
  });
})

The above is a sample code put together from the samples and reference.

Body:
You must have been looking at the wrong samples and docs then. This example from the documentation on creating your first function has an example:

const admin = require('firebase-admin');

// Take the text parameter passed to this HTTP endpoint and insert it into the
// Realtime Database under the path /messages/:pushId/original
exports.addMessage = functions.https.onRequest((req, res) => {
  // Grab the text parameter.
  const original = req.query.text;
  // Push it into the Realtime Database then send a response
  admin.database().ref('/messages').push({original: original}).then(snapshot => {
    // Redirect with 303 SEE OTHER to the URL of the pushed object in the Firebase console.
    res.redirect(303, snapshot.ref);
  });
});

So use var ref = admin.database().ref('/routes').

Also see the full code in the github repo.


问:
How to use Matlab function ordfilt2 to C++ with OpenCV
I need to use the fuction of Matlab ordfilt2 in order to filter a noised image.

example of my code:

```<code>#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/core/core.hpp"
#include <opencv/cv.h>
#include <iostream>
#include <Windows.h>

using namespace std;
using namespace cv;

int main(int, char**)
{
Mat image = imread("C:\lena.bmp", 0);
Mat result = image.clone();
Mat final2 = image.clone();

if (image.empty())//check if empty
{
    printf("Image is not read! File is probably missing! Press any key to exim program");//message for error
    Sleep(10000); //10 second delay for showing message to user
}
else
{
    double value = 0.3;

    //printf("Give double for noise [0.00-1.00] :\n");
    //cin >> value;

    if (value >= 0.00 && value <= 1.00)
    {
        // imGray is the grayscale of the input image
        Mat noise = Mat(image.size(), CV_64F);
        normalize(image, result, 0.0, 1.0, CV_MINMAX, CV_64F);
        randn(noise, 0, value);

        result = result + noise;
        normalize(result, result, 0.0, 1.0, CV_MINMAX, CV_64F);
        imshow("Output image with noise", result);
        // I found this function (from OpenCV documentation) but I get syntax error
        dilate(result, final2, NULL, 1);

        namedWindow("Image blur", 1);
        imshow("Image blur", result);

        namedWindow("Original Image", 1);
        imshow("Original Image", image);

        waitKey();
    }
    else
    {
        printf("Wrong input! Try again!\n");
    }
}
return 0;
}
</code>```

EDIT Matlab code:

```<code>x=imread('cameraman.tif');
x=Im2double(x);
sigma=20;
y=x+sigma*rabdn(size(x))/255;
z1=ordfilt2(y,3*3,ones(3,3));
z2=ordfilt2(y,1,ones(3,3));
z=1/2*(z1*z2);
Imshow(y,());
figure; Imshow (z1,());
figure; Imshow (z2,());
figure; Imshow (z,());
</code>```

I have tried using dilate function, but with no luck.

I think ordfilt2 means order statistic filter. But when I look for it on the web, it seems I can't find anything usefull. All my attempts has fail so far, so, can you please help me?

Thank you very much in advance for your help.

答:
The code you are concerned about is here:

```<code>z1=ordfilt2(y,3*3,ones(3,3));
z2=ordfilt2(y,1,ones(3,3));
</code>```

You are correct in that it is an order-statistics filter.  It specifically takes sliding neighbourhoods and outputs the desired rank of the window.  You have set this to be a 3 x 3 neighbourhood and the first line outputs rank 9, or the highest rank or highest value.  This is the local maximum and you can accomplish this with a dilation operator using morphological operations.  Similarly, the next line outputs the lowest rank, rank 1 or the lowest value.  This is the local minimum and you can accomplish this with an erosion operation using morphological operations.

You first need to use cv::getStructuringElement to create the window that you want to operate one.  You basically want a 3 x 3 square, so you would use the MORPH_RECT property.  You would then use cv::dilate, then cv::erode respectively.

Therefore, replace your current dilate line code with this:

```<code>//...
imshow("Output image with noise", result);

Mat se = getStructuringElement(MORPH_RECT, Size(3, 3));
dilate(result, final2, se);
erode(final2, final2, se);

//...
</code>```

cv::dilate and cv::erode require structuring element to operate on for the third parameter.  Admittedly, you can specify Mat() as the third element which will operate on using a 3 x 3 neighbourhood by default.

You'll also want to change your imshow command to display the final image, not the intermediate one:

```<code>namedWindow("Image blur", 1);
imshow("Image blur", final2); // Change here
</code>```

Body:
I need to use the fuction of Matlab ordfilt2 in order to filter a noised image.

example of my code:

#include "opencv2/objdetect/objdetect.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/core/core.hpp"
#include <opencv/cv.h>
#include <iostream>
#include <Windows.h>

using namespace std;
using namespace cv;

int main(int, char**)
{
Mat image = imread("C:\lena.bmp", 0);
Mat result = image.clone();
Mat final2 = image.clone();

if (image.empty())//check if empty
{
    printf("Image is not read! File is probably missing! Press any key to exim program");//message for error
    Sleep(10000); //10 second delay for showing message to user
}
else
{
    double value = 0.3;

    //printf("Give double for noise [0.00-1.00] :\n");
    //cin >> value;

    if (value >= 0.00 && value <= 1.00)
    {
        // imGray is the grayscale of the input image
        Mat noise = Mat(image.size(), CV_64F);
        normalize(image, result, 0.0, 1.0, CV_MINMAX, CV_64F);
        randn(noise, 0, value);

        result = result + noise;
        normalize(result, result, 0.0, 1.0, CV_MINMAX, CV_64F);
        imshow("Output image with noise", result);
        // I found this function (from OpenCV documentation) but I get syntax error
        dilate(result, final2, NULL, 1);

        namedWindow("Image blur", 1);
        imshow("Image blur", result);

        namedWindow("Original Image", 1);
        imshow("Original Image", image);

        waitKey();
    }
    else
    {
        printf("Wrong input! Try again!\n");
    }
}
return 0;
}

EDIT Matlab code:

x=imread('cameraman.tif');
x=Im2double(x);
sigma=20;
y=x+sigma*rabdn(size(x))/255;
z1=ordfilt2(y,3*3,ones(3,3));
z2=ordfilt2(y,1,ones(3,3));
z=1/2*(z1*z2);
Imshow(y,());
figure; Imshow (z1,());
figure; Imshow (z2,());
figure; Imshow (z,());

I have tried using dilate function, but with no luck.

I think ordfilt2 means order statistic filter. But when I look for it on the web, it seems I can't find anything usefull. All my attempts has fail so far, so, can you please help me?

Thank you very much in advance for your help.

Body:
The code you are concerned about is here:

z1=ordfilt2(y,3*3,ones(3,3));
z2=ordfilt2(y,1,ones(3,3));

You are correct in that it is an order-statistics filter.  It specifically takes sliding neighbourhoods and outputs the desired rank of the window.  You have set this to be a 3 x 3 neighbourhood and the first line outputs rank 9, or the highest rank or highest value.  This is the local maximum and you can accomplish this with a dilation operator using morphological operations.  Similarly, the next line outputs the lowest rank, rank 1 or the lowest value.  This is the local minimum and you can accomplish this with an erosion operation using morphological operations.

You first need to use cv::getStructuringElement to create the window that you want to operate one.  You basically want a 3 x 3 square, so you would use the MORPH_RECT property.  You would then use cv::dilate, then cv::erode respectively.

Therefore, replace your current dilate line code with this:

//...
imshow("Output image with noise", result);

Mat se = getStructuringElement(MORPH_RECT, Size(3, 3));
dilate(result, final2, se);
erode(final2, final2, se);

//...

cv::dilate and cv::erode require structuring element to operate on for the third parameter.  Admittedly, you can specify Mat() as the third element which will operate on using a 3 x 3 neighbourhood by default.

You'll also want to change your imshow command to display the final image, not the intermediate one:

namedWindow("Image blur", 1);
imshow("Image blur", final2); // Change here


问:
Print command with multiple update statements
I am trying to run multiple updates, with a message printed after each one so I can keep track of any errors. The issue I'm having is that if it fails on say the third update, it throws just the error, and none of my messages go through for the successful updates. How would I go about having the query run the print after each update statement, without putting 'GO' after each one? (I want to be able to collapse the included piece as one region)</p>

```<code>SET NOCOUNT ON
BEGIN TRANSACTION --CUSTOMERS

SELECT *INTO #T FROM CUST where cus_pk !=1
ALTER TABLE #T ADD NEW_PK INT NOT NULL IDENTITY(50955001,1000)

UPDATE P
SET P.CUS_FK= T.NEW_PK
FROM PRUDUCT P
JOIN #T T ON T.CUS_PK= P.CUS_FK
PRINT'UPDATED PRODUCT CUS_FK'

UPDATE I
SET I.CUS_FK= T.NEW_PK
FROM ITEMS I
JOIN #T T ON T.CUS_PK= I.CUS_FK
PRINT'UPDATED ITEMS CUS_FK'

UPDATE A
SET A.CUS_FK= T.NEW_PK
FROM ACCT A
JOIN #T T ON T.CUS_PK= A.CUS_FK
PRINT'UPDATED ACCT_FK'

UPDATE S
SET S.CUS_FK= T.NEW_PK
FROM SOLD S
JOIN #T T ON T.CUS_PK= S.CUS_FK
PRINT'UPDATED SOLD CUS_FK'

UPDATE c
SET C.CUS_PK= T.NEW_PK
FROM CUST C
JOIN #T T ON T.CUS_PK= C.CUS_PK
PRINT'UPDATED CUST CUS_PK'

DROP TABLE #T
ALTER TABLE CUST NOCHECK CONSTRAINT FK_CUST_LOOKUP_C3
ALTER TABLE CUST NOCHECK CONSTRAINT FK_CUST_LOOKUP_C5

INSERT INTO CUST SELECT * FROM [DATABSE2].DBO.cust where cus_pk != 1

ALTER TABLE CUST CHECK CONSTRAINT FK_CUST_LOOKUP_C3
ALTER TABLE CUST CHECK CONSTRAINT FK_CUST_LOOKUP_C5
PRINT'NEW CUSTOMERS ADDED'
GO
</code>```

答:
Yes putting GO is the way. Also, you should include statement terminator ; after end of each SQL statement like

```<code>UPDATE P
SET P.CUS_FK= T.NEW_PK
FROM PRUDUCT P
JOIN #T T ON T.CUS_PK= P.CUS_FK;
PRINT'UPDATED PRODUCT CUS_FK';

UPDATE I
SET I.CUS_FK= T.NEW_PK
FROM ITEMS I
JOIN #T T ON T.CUS_PK= I.CUS_FK;
PRINT'UPDATED ITEMS CUS_FK';
</code>```

Again, instead of using PRINT statement you can consider using a SELECT statement like

```<code>UPDATE I
SET I.CUS_FK= T.NEW_PK
FROM ITEMS I
JOIN #T T ON T.CUS_PK= I.CUS_FK;
SELECT 'UPDATED ITEMS CUS_FK';
</code>```

Body:
I am trying to run multiple updates, with a message printed after each one so I can keep track of any errors. The issue I'm having is that if it fails on say the third update, it throws just the error, and none of my messages go through for the successful updates. How would I go about having the query run the print after each update statement, without putting 'GO' after each one? (I want to be able to collapse the included piece as one region)

SET NOCOUNT ON
BEGIN TRANSACTION --CUSTOMERS

SELECT *INTO #T FROM CUST where cus_pk !=1
ALTER TABLE #T ADD NEW_PK INT NOT NULL IDENTITY(50955001,1000)

UPDATE P
SET P.CUS_FK= T.NEW_PK
FROM PRUDUCT P
JOIN #T T ON T.CUS_PK= P.CUS_FK
PRINT'UPDATED PRODUCT CUS_FK'

UPDATE I
SET I.CUS_FK= T.NEW_PK
FROM ITEMS I
JOIN #T T ON T.CUS_PK= I.CUS_FK
PRINT'UPDATED ITEMS CUS_FK'

UPDATE A
SET A.CUS_FK= T.NEW_PK
FROM ACCT A
JOIN #T T ON T.CUS_PK= A.CUS_FK
PRINT'UPDATED ACCT_FK'

UPDATE S
SET S.CUS_FK= T.NEW_PK
FROM SOLD S
JOIN #T T ON T.CUS_PK= S.CUS_FK
PRINT'UPDATED SOLD CUS_FK'

UPDATE c
SET C.CUS_PK= T.NEW_PK
FROM CUST C
JOIN #T T ON T.CUS_PK= C.CUS_PK
PRINT'UPDATED CUST CUS_PK'

DROP TABLE #T
ALTER TABLE CUST NOCHECK CONSTRAINT FK_CUST_LOOKUP_C3
ALTER TABLE CUST NOCHECK CONSTRAINT FK_CUST_LOOKUP_C5

INSERT INTO CUST SELECT * FROM [DATABSE2].DBO.cust where cus_pk != 1

ALTER TABLE CUST CHECK CONSTRAINT FK_CUST_LOOKUP_C3
ALTER TABLE CUST CHECK CONSTRAINT FK_CUST_LOOKUP_C5
PRINT'NEW CUSTOMERS ADDED'
GO

Body:
Yes putting GO is the way. Also, you should include statement terminator ; after end of each SQL statement like

UPDATE P
SET P.CUS_FK= T.NEW_PK
FROM PRUDUCT P
JOIN #T T ON T.CUS_PK= P.CUS_FK;
PRINT'UPDATED PRODUCT CUS_FK';

UPDATE I
SET I.CUS_FK= T.NEW_PK
FROM ITEMS I
JOIN #T T ON T.CUS_PK= I.CUS_FK;
PRINT'UPDATED ITEMS CUS_FK';

Again, instead of using PRINT statement you can consider using a SELECT statement like

UPDATE I
SET I.CUS_FK= T.NEW_PK
FROM ITEMS I
JOIN #T T ON T.CUS_PK= I.CUS_FK;
SELECT 'UPDATED ITEMS CUS_FK';


问:
Open Source Control Libraries with liberal licences for Winforms, WPF and ASP.NET
I am looking for free "Open Source" controls (respectivels control libraries) for Winforms, WPF and ASP.NET with (very) liberal licences (like MIT-, Apache or BSD-Licence; not GPL or LGPL!), which can be used in commercial projects with proprietary licences.

Which ones are your suggestions and what would you recommend?

答: CodePlex.com has a bunch. You'd have to check the licenses of each project you are interested in.</p>


问:
Facebook login button not refreshing to logout automatically
Using 'Facebook Login for the Web with the JavaScript SDK', I have a login button which works fine, i.e. user is logged in OK.(https://developers.facebook.com/docs/facebook-login/web#loginbutton).

However, the button does not change to the Logout button until I refresh the page. After refresh the logout button is displayed and when clicked reverts to  login button as expected. Following is the full code which can be run from within IIS. I put it in my default web site and called http://localhost/aspnet_client/system_web/4_0_30319/test.html.

NOTE: Add your App Id where it says, ADD YOUR APP ID HERE.

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
</head>

<body>
    <div class="row margin-bottom-small">
        <div id="login-button" class="fb-login-button" data-max-rows="1" data-size="xlarge" data-show-faces="false" data-auto-logout-link="true" onlogin="checkLoginState();"></div>
        <div id="status"></div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    <script>
        function statusChangeCallback(response) {
            console.log('statusChangeCallback');
            console.log(response);
            if (response.status === 'connected') {
                testAPI();
            }
        }
        function checkLoginState() {
            FB.getLoginStatus(function(response) {
                statusChangeCallback(response);
            });
        }
        window.fbAsyncInit = function() {
                                FB.init({
                                appId      : 'ADD YOUR APP ID HERE',
                                cookie     : true,  // enable cookies to allow the server to access the session
                                xfbml      : true,  // parse social plugins on this page
                                version    : 'v2.8' // use graph api version 2.8
                            });
            FB.getLoginStatus(function(response) {
                statusChangeCallback(response);
            });
        };
        // Load the SDK asynchronously
        (function(d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) return;
            js = d.createElement(s); js.id = id;
            js.src = "//connect.facebook.net/en_US/sdk.js";
            fjs.parentNode.insertBefore(js, fjs);
        }(document, 'script', 'facebook-jssdk'));

        // Here we run a very simple test of the Graph API after login is
        // successful.  See statusChangeCallback() for when this call is made.
        function testAPI() {
            console.log('Welcome!  Fetching your information.... ');
            FB.api('/me', function(response) {
                console.log('Successful login for: ' + response.name);
                document.getElementById('status').innerHTML =
                'Thanks for logging in, ' + response.name + '!';
            });
        }
    </script>
</body>
</html>
</code>```

FB code is from https://developers.facebook.com/docs/facebook-login/web#example

I don't want to refresh the page programatically. It is a single page application and refreshing the page will take me to the start.

Thanks.

答:
Well, I couldn't figure out why it wouldn't refresh automatically - perhaps that by design. Here is my workaround - basically add the logout button and call FB.logout myself. If someone from Facebook dev team can provide a more elegant solution, I'd love to know. Thanks.

NOTE: Add your App Id where it says, ADD YOUR APP ID HERE.

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
</head>

<body>
    <div class="row margin-bottom-small">
        <div id="login-button" class="fb-login-button" data-max-rows="1" data-size="small" data-show-faces="false" data-auto-logout-link="false" onlogin="checkLoginState();"></div>
        <div hidden id="logout-button" class="fb-login-button" data-max-rows="1" data-size="small" data-show-faces="false" data-auto-logout-link="false" onlogin="logout();">Log Out</div>
        <div id="status"></div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    <script>
        function statusChangeCallback(response) {
            console.log('statusChangeCallback');
            console.log(response);
            if (response.status === 'connected') {
                testAPI();
            } else {
                // The person is not logged into your app or we are unable to tell.
                //document.getElementById('status').innerHTML = 'Please log into this app.';
                document.getElementById('login-button').style.display = 'block';
                document.getElementById('logout-button').style.display = 'none';
            }
        }
        function checkLoginState() {
            FB.getLoginStatus(function(response) {
                statusChangeCallback(response);
            });
        }
        function logout() {
            FB.logout(function (response) {
                document.getElementById('logout-button').style.display = 'none';
                document.getElementById('login-button').style.display = '';
                document.getElementById('status').innerHTML = 'You have been logged out!';
            });
        }
        window.fbAsyncInit = function() {
                                FB.init({
                                appId      : 'ADD YOUR APP ID HERE',
                                cookie     : true,  // enable cookies to allow the server to access the session
                                xfbml      : true,  // parse social plugins on this page
                                version    : 'v2.8' // use graph api version 2.8
                            });
            FB.getLoginStatus(function(response) {
                statusChangeCallback(response);
            });
        };
        // Load the SDK asynchronously
        (function(d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) return;
            js = d.createElement(s); js.id = id;
            js.src = "//connect.facebook.net/en_US/sdk.js";
            fjs.parentNode.insertBefore(js, fjs);
        }(document, 'script', 'facebook-jssdk'));

        // Here we run a very simple test of the Graph API after login is
        // successful.  See statusChangeCallback() for when this call is made.
        function testAPI() {
            console.log('Welcome!  Fetching your information.... ');
            FB.api('/me', function(response) {
                console.log('Successful login for: ' + response.name);
                 document.getElementById('login-button').style.display = 'none';
                document.getElementById('logout-button').style.display = 'block';
                document.getElementById('status').innerHTML = 'Thanks for logging in, ' + response.name + '!';
            });
        }
    </script>
</body>
</html>
</code>```

Body:
Using 'Facebook Login for the Web with the JavaScript SDK', I have a login button which works fine, i.e. user is logged in OK.(https://developers.facebook.com/docs/facebook-login/web#loginbutton).

However, the button does not change to the Logout button until I refresh the page. After refresh the logout button is displayed and when clicked reverts to  login button as expected. Following is the full code which can be run from within IIS. I put it in my default web site and called http://localhost/aspnet_client/system_web/4_0_30319/test.html.

NOTE: Add your App Id where it says, ADD YOUR APP ID HERE.

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

FB code is from https://developers.facebook.com/docs/facebook-login/web#example

I don't want to refresh the page programatically. It is a single page application and refreshing the page will take me to the start.

Thanks.

Body:
Well, I couldn't figure out why it wouldn't refresh automatically - perhaps that by design. Here is my workaround - basically add the logout button and call FB.logout myself. If someone from Facebook dev team can provide a more elegant solution, I'd love to know. Thanks.

NOTE: Add your App Id where it says, ADD YOUR APP ID HERE.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
</head>

<body>
    <div class="row margin-bottom-small">
        <div id="login-button" class="fb-login-button" data-max-rows="1" data-size="small" data-show-faces="false" data-auto-logout-link="false" onlogin="checkLoginState();"></div>
        <div hidden id="logout-button" class="fb-login-button" data-max-rows="1" data-size="small" data-show-faces="false" data-auto-logout-link="false" onlogin="logout();">Log Out</div>
        <div id="status"></div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    <script>
        function statusChangeCallback(response) {
            console.log('statusChangeCallback');
            console.log(response);
            if (response.status === 'connected') {
                testAPI();
            } else {
                // The person is not logged into your app or we are unable to tell.
                //document.getElementById('status').innerHTML = 'Please log into this app.';
                document.getElementById('login-button').style.display = 'block';
                document.getElementById('logout-button').style.display = 'none';
            }
        }
        function checkLoginState() {
            FB.getLoginStatus(function(response) {
                statusChangeCallback(response);
            });
        }
        function logout() {
            FB.logout(function (response) {
                document.getElementById('logout-button').style.display = 'none';
                document.getElementById('login-button').style.display = '';
                document.getElementById('status').innerHTML = 'You have been logged out!';
            });
        }
        window.fbAsyncInit = function() {
                                FB.init({
                                appId      : 'ADD YOUR APP ID HERE',
                                cookie     : true,  // enable cookies to allow the server to access the session
                                xfbml      : true,  // parse social plugins on this page
                                version    : 'v2.8' // use graph api version 2.8
                            });
            FB.getLoginStatus(function(response) {
                statusChangeCallback(response);
            });
        };
        // Load the SDK asynchronously
        (function(d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) return;
            js = d.createElement(s); js.id = id;
            js.src = "//connect.facebook.net/en_US/sdk.js";
            fjs.parentNode.insertBefore(js, fjs);
        }(document, 'script', 'facebook-jssdk'));

        // Here we run a very simple test of the Graph API after login is
        // successful.  See statusChangeCallback() for when this call is made.
        function testAPI() {
            console.log('Welcome!  Fetching your information.... ');
            FB.api('/me', function(response) {
                console.log('Successful login for: ' + response.name);
                 document.getElementById('login-button').style.display = 'none';
                document.getElementById('logout-button').style.display = 'block';
                document.getElementById('status').innerHTML = 'Thanks for logging in, ' + response.name + '!';
            });
        }
    </script>
</body>
</html>


问:
Can I read the hash portion of the URL on my server-side application (PHP, Ruby, Python, etc.)?
Assuming a URL of:

```<code>www.example.com/?val=1#part2
</code>```

PHP can read the request variables val1 using the GET array.

Is the hash value part2 also readable? Or is this only upto the browser and JavaScript?

答:
Another solution is to add a hidden input field to the php page:

```<code><input type="hidden" id="myHiddenLocationHash" name="myHiddenLocationHash" value="">
</code>```

Using javascript/jQuery you can set the value of this field on the page load or responding to an event :

```<code>$('#myHiddenLocationHash').val(document.location.hash.replace('#',''));
</code>```

In php on the server side you can read this value using the $_POST collection:

```<code>$server_location_hash = $_POST['myHiddenLocationHash'];
</code>```

Body:
Assuming a URL of:

www.example.com/?val=1#part2

PHP can read the request variables val1 using the GET array.

Is the hash value part2 also readable? Or is this only upto the browser and JavaScript?

Body:
Another solution is to add a hidden input field to the php page:

<input type="hidden" id="myHiddenLocationHash" name="myHiddenLocationHash" value="">

Using javascript/jQuery you can set the value of this field on the page load or responding to an event :

$('#myHiddenLocationHash').val(document.location.hash.replace('#',''));

In php on the server side you can read this value using the $_POST collection:

$server_location_hash = $_POST['myHiddenLocationHash'];


问:
Buttons on the same row - Css/Html
I am tryin get all the buttons on the same line of height. Tried different min-height options for different classes but have no idea how to actually fix it. It's the red buttons under each product. Could you advise how I would go about fixing it?</p>

答:
```<code>ul.products li.product h3 {
font-size: 1.1em;
min-height: 53px;
</code>```

<p>}</p>

Title: Buttons on the same row - Css/Html

Body:
ul.products li.product h3 {
font-size: 1.1em;
min-height: 53px;

}


问:
Separating while loop tags from each other using (,)
```<code>while($loop = . . . .){
     $loopy = $loop['tag'];
     echo "<a>$loopy</a>";
}
</code>```

Using this code i get the tags outputted like this

```<code>Tag1Tag2Tag3Tag4Tag5Tag6
</code>```

How do i separate them to be Tag1, Tag2, Tag3, Tag4, Tag5, Tag6

答:
Looks like it is a html at the end, so you have to add   at the end:</p>

```<code>while($loop = . . . .){
     $loopy = $loop['tag'];
     echo "<a>$loopy,  </a>";
}
</code>```

Body:
while($loop = . . . .){
     $loopy = $loop['tag'];
     echo "$loopy";
}

Using this code i get the tags outputted like this

Tag1Tag2Tag3Tag4Tag5Tag6

How do i separate them to be Tag1, Tag2, Tag3, Tag4, Tag5, Tag6

Body:
Looks like it is a html at the end, so you have to add   at the end:

while($loop = . . . .){
     $loopy = $loop['tag'];
     echo "<a>$loopy, &nbsp;</a>";
}


问:
C# how to Regex.Replace "\r\n" (the actual characters, not the line break)
I've got some horrible text that I'm cleaning up using several c# regular expressions. One issue that has me stumped is there are a number of '\r\n' strings in the text, the actual characters not the line breaks.

I've tried:

```<code>content = Regex.Replace(content, "\\r\\n", "");
</code>```

and:

```<code>content = Regex.Replace(content, "\r\n", "");
</code>```

but neither of them work. In the end I had to use:

```<code>content = content.Replace("\\r\\n", "\r\n");
</code>```

to get the project finished, but not being able to do it in a regex annoys me.

答:
```<code>content = Regex.Replace(content, "\\\\r\\\\n", "");
</code>```

might work. More info here.

Quote:

In literal C# strings, as well as in
  C++ and many other .NET languages, the
  backslash is an escape character. The
  literal string "\\" is a single
  backslash. In regular expressions, the
  backslash is also an escape character.
  The regular expression \\ matches a
  single backslash. This regular
  expression as a C# string, becomes
  "\\\\". That's right: 4 backslashes
  to match a single one.

Note: I had to write 8 backslashes in the next to last sentence so 4 backslashes would get displayed ;-)

Body:
I've got some horrible text that I'm cleaning up using several c# regular expressions. One issue that has me stumped is there are a number of '\r\n' strings in the text, the actual characters not the line breaks.

I've tried:

content = Regex.Replace(content, "\\r\\n", "");

and:

content = Regex.Replace(content, "\r\n", "");

but neither of them work. In the end I had to use:

content = content.Replace("\\r\\n", "\r\n");

to get the project finished, but not being able to do it in a regex annoys me.

Body:
content = Regex.Replace(content, "\\\\r\\\\n", "");

might work. More info here.

Quote:

In literal C# strings, as well as in
  C++ and many other .NET languages, the
  backslash is an escape character. The
  literal string "\\" is a single
  backslash. In regular expressions, the
  backslash is also an escape character.
  The regular expression \\ matches a
  single backslash. This regular
  expression as a C# string, becomes
  "\\\\". That's right: 4 backslashes
  to match a single one.

Note: I had to write 8 backslashes in the next to last sentence so 4 backslashes would get displayed ;-)


问:
Divide the navbar into 3 equal parts
I have 3 menu items in my navbar. I want the entire nav to be divided into 3 parts for my 3 menus. I tried with the following code but the last menu item takes bit extra space than others. How do i fix it?

 .navbar {
         border : 1px solid #ffffff;
     }
     #intr1, #intr2 {
         border-right: 1px solid #ffffff;
     }
     .menuLabel {
         text-align: center;
         font-size: 17px;
         font-weight: bold;
         color: #ffffff;
     }```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <html>
    <head>
     <title></title>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    </head>
    <body>
    <div class="container-fluid">
     <div class="navbar navbar-inverse">
      <div class="navbar-header ">
             <ul class="nav navbar-nav container">
              <li class="col-md-4" id="intr1"><div class="menuLabel">INTERIOR DESIGN <span class="glyphicon glyphicon-arrow-right"></span></div></li>
              <li class="col-md-4" id="intr2"><div class="menuLabel">INTERIOR DESIGN <span class="glyphicon glyphicon-arrow-right"></span></div></li>
              <li class="col-md-4" id="intr3"><div class="menuLabel">INTERIOR DESIGN <span class="glyphicon glyphicon-arrow-right"></span></div></li>
             </ul>
           </div>
     </div>
    </div>

    </body>
    </html></code>```

答:
Try with something like this:</p>

```<code><body>
  <div class="container-fluid">
   <div class="navbar navbar-inverse">
     <div class="container-fluid">
       <ul>
         <li class="col-md-4" id="intr1">
           <a href="#">
             <div class="menuLabel">INTERIOR DESIGN <span class="glyphicon glyphicon-arrow-right"></span></div>
           </a>
         </li>
         <li class="col-md-4" id="intr2">
           <a href="#">
             <div class="menuLabel">INTERIOR DESIGN <span class="glyphicon glyphicon-arrow-right"></span></div>
           </a>
         </li>
         <li class="col-md-4" id="intr3">
           <a href="#">
             <div class="menuLabel">INTERIOR DESIGN <span class="glyphicon glyphicon-arrow-right"></span></div>
           </a>
         </li>
       </ul>
     </div>
   </div>
 </div>
</body>
</code>```

Title: Divide the navbar into 3 equal parts

Body:
I have 3 menu items in my navbar. I want the entire nav to be divided into 3 parts for my 3 menus. I tried with the following code but the last menu item takes bit extra space than others. How do i fix it?

 .navbar {
         border : 1px solid #ffffff;
     }
     #intr1, #intr2 {
         border-right: 1px solid #ffffff;
     }
     .menuLabel {
         text-align: center;
         font-size: 17px;
         font-weight: bold;
         color: #ffffff;
     }

     <title></title>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

INTERIOR DESIGN

INTERIOR DESIGN

INTERIOR DESIGN

Body:
Try with something like this:

<body>
  <div class="container-fluid">
   <div class="navbar navbar-inverse">
     <div class="container-fluid">
       <ul>
         <li class="col-md-4" id="intr1">
           <a href="#">
             <div class="menuLabel">INTERIOR DESIGN&nbsp;<span class="glyphicon glyphicon-arrow-right"></span></div>
           </a>
         </li>
         <li class="col-md-4" id="intr2">
           <a href="#">
             <div class="menuLabel">INTERIOR DESIGN&nbsp;<span class="glyphicon glyphicon-arrow-right"></span></div>
           </a>
         </li>
         <li class="col-md-4" id="intr3">
           <a href="#">
             <div class="menuLabel">INTERIOR DESIGN&nbsp;<span class="glyphicon glyphicon-arrow-right"></span></div>
           </a>
         </li>
       </ul>
     </div>
   </div>
 </div>
</body>


问:
Invalid init of non-const reference of type std::basic_string<char>::const_iterator& from rvalue of type std::basic_string<char>::const_iterator
I'm get the above error when I compile the following MWE on GCC

```<code>#include <string>

void frobnigate( const std::string& str )
{
    std::string::const_iterator& iter = str.begin();
}

int main()
{
    frobnigate( "all things!!!" );
}
</code>```

Am I doing something wrong or is this a GCC issue?

答:
You should do this:

```<code>std::string::const_iterator iter = str.begin();
</code>```

That is, remove the reference, because begin() returns a value, not a reference, and you need to manage the lifetime of that iterator (which will be a simple, small, cheap value such as a pointer).

Body:
I'm get the above error when I compile the following MWE on GCC

#include <string>

void frobnigate( const std::string& str )
{
    std::string::const_iterator& iter = str.begin();
}

int main()
{
    frobnigate( "all things!!!" );
}

Am I doing something wrong or is this a GCC issue?

Body:
You should do this:

std::string::const_iterator iter = str.begin();

That is, remove the reference, because begin() returns a value, not a reference, and you need to manage the lifetime of that iterator (which will be a simple, small, cheap value such as a pointer).