问:
how to form group of same values and keys

In groovy, I am having a list of maps.Each map contains 3 keys with
respective values like:

```<code>def group= [] as DataList
def groupRequiredMap = ["a": Metadata.groupName,
                        "b": Metadata.instance,
                        "c": Metadata.color]
    group << groupRequiredMap
</code>```

The Output of group is as follows::

```<code>[[a:apple, b:0, c:red],
[a:apple, b:0, c:green],
[a:apple, b:0, c:blue],
[a:apple, b:1, c:brown],
[a:apple, b:1, c:violet],
[a:grapes, b:0, c:black],
[a:grapes, b:0, c:yellow],
[a:grapes, b:1, c:orange],
[a:grapes, b:1, c:pink]]
</code>```

I want to form a group of apple with b=0, a group of apple with b=1, a group of grapes with b=0 and a group of grapes with b=1 and so on.I want Output like this:

```<code>[[a:apple, b:0, c:[red, green, blue]],
 [a:apple, b:1, c:[brown,violet]],
 [a:grapes, b:0, c:[black,yellow]],
 [a:grapes, b:1, c:[orange,pink]]
</code>```

答:
groupBy is the first thing you want to go with.  So your key for the grouping is the subMap("a","b") - a map, that only holds the key/values for the "a" and "b" key of the original map.  After that you combine the "key map" with a new map containing all the "c"s via the spread-operator *..

```<code>list.groupBy{ it.subMap("a","b") }.collect{ k, ms -> k + [c: ms*.c] }
</code>```

Body:
In groovy, I am having a list of maps.Each map contains 3 keys with
respective values like:

def group= [] as DataList
def groupRequiredMap = ["a": Metadata.groupName,
                        "b": Metadata.instance,
                        "c": Metadata.color]
    group << groupRequiredMap

The Output of group is as follows::

[[a:apple, b:0, c:red],
[a:apple, b:0, c:green],
[a:apple, b:0, c:blue],
[a:apple, b:1, c:brown],
[a:apple, b:1, c:violet],
[a:grapes, b:0, c:black],
[a:grapes, b:0, c:yellow],
[a:grapes, b:1, c:orange],
[a:grapes, b:1, c:pink]]

I want to form a group of apple with b=0, a group of apple with b=1, a group of grapes with b=0 and a group of grapes with b=1 and so on.I want Output like this:

[[a:apple, b:0, c:[red, green, blue]],
 [a:apple, b:1, c:[brown,violet]],
 [a:grapes, b:0, c:[black,yellow]],
 [a:grapes, b:1, c:[orange,pink]]

Body:
groupBy is the first thing you want to go with.  So your key for the grouping is the subMap("a","b") - a map, that only holds the key/values for the "a" and "b" key of the original map.  After that you combine the "key map" with a new map containing all the "c"s via the spread-operator *..

list.groupBy{ it.subMap("a","b") }.collect{ k, ms -> k + [c: ms*.c] }


来源: stackexchange

问:
TF400324: Team Foundation services are not available from server
I have updated visual studio 2012 last night, this was Visual Studio 2012 Update 4. It was working fine before but now i am unable to connect with tfs server. Please let me know what i am doing wrong?

This is the error:

```<code>    TF400324: Team Foundation services are not available from server     https://myServer.visualstudio.com/defaultcollection.
Technical information (for administrator):
  Unable to connect to the remote server
</code>```

答:
I know this is an old thread but the problem still appeared in VS 2013 and TFS 2013.

In my case the IIS on the server side was not running. After starting it VS could immediate connect again.

ContentLicense: CC BY-SA 3.0

Body:
I have updated visual studio 2012 last night, this was Visual Studio 2012 Update 4. It was working fine before but now i am unable to connect with tfs server. Please let me know what i am doing wrong?

This is the error:

    TF400324: Team Foundation services are not available from server     https://myServer.visualstudio.com/defaultcollection.
Technical information (for administrator):
  Unable to connect to the remote server


问:
HIVE: CREATE TABLE AS SELECT command cannot specify the list of columns for the target table
How can I make this work?

```<code>  hive> desc temp;
  OK
  a                     int
  b                     int
  Time taken: 0.077 seconds, Fetched: 2 row(s)
</code>```

I want to create t2 HIVE table with column names c and d but getting below error.

```<code>  hive> create table t2(c int,d int) as select a,b from temp;
  FAILED: SemanticException [Error 10065]: CREATE TABLE AS SELECT command         cannot specify the list of columns for the target table
</code>```

答:
You need not to mention table schema again as you are specifying to take the schema from another table. So your table creation statement should be like</p>

```<code>create table t2 as select a,b from temp;
</code>```

Body:
How can I make this work?

  hive> desc temp;
  OK
  a                     int
  b                     int
  Time taken: 0.077 seconds, Fetched: 2 row(s)

I want to create t2 HIVE table with column names c and d but getting below error.

  hive> create table t2(c int,d int) as select a,b from temp;
  FAILED: SemanticException [Error 10065]: CREATE TABLE AS SELECT command         cannot specify the list of columns for the target table

Body:
You need not to mention table schema again as you are specifying to take the schema from another table. So your table creation statement should be like

create table t2 as select a,b from temp;


问:
Change Class to Hover Class
I have a couple of nested divs and have set a CSS class for one of the interior divs. How would I go about setting off the hover version of the class (class.hover) when the user hovers of the outer div, but not necessarily over the interior div's area.

I'm assuming this has to be done via JavaScript. I need some inputs with this.

Thanks

答:
Try this:

CSS:

```<code>.hoverDiv:hover {
    background-color: red;
}
</code>```

HTML:

```<code><div class="hoverDiv">
    <div>This is the inner div </div>
</div>
</code>```

that example will change the background color to red, but you can change it to whatever you want.

ContentLicense: CC BY-SA 2.5

Title: Change Class to Hover Class

Body:
Try this:

CSS:

.hoverDiv:hover {
    background-color: red;
}

HTML:

<div class="hoverDiv">
    <div>This is the inner div </div>
</div>

that example will change the background color to red, but you can change it to whatever you want.


问:
Select Count in Realm for Android
I saw some answers about this problem for iOS (here), but none for Android.

Let's say I have 2 columns A and B and I want the distincts couples of A and B and the count of the couple. I then want to filter my query when the count is <60.

```<code>A|B
1|1
1|1
1|1
2|1
2|1
2|1
1|2
1|2
1|2
1|2
</code>```

In pure SQL, I used the query :

```<code>SELECT A,B, COUNT(A) FROM myTable GROUP BY A,B
</code>```

Which give me something like [(1,1,3), (2,1,3), (1,2,4)]

How can I do so with Realm in Android ?

答:
Currently it is not possible to do in a single statement. You will have to do something like:</p>

```<code>RealmResults<MyObject> myObjects = realm.where(MyObject.class).distinct("A", "B");
for (MyObject myObject : myObjects) {
    long count = realm.where(MyObject.class).equalsTo("A", myObject.getA()).equalsTo("B", myObject.getB()).count();
    // use getA(), getB(), and count
}
</code>```

Title: Select Count in Realm for Android

Body:
I saw some answers about this problem for iOS (here), but none for Android.

Let's say I have 2 columns A and B and I want the distincts couples of A and B and the count of the couple. I then want to filter my query when the count is <60.

A|B
1|1
1|1
1|1
2|1
2|1
2|1
1|2
1|2
1|2
1|2

In pure SQL, I used the query :

SELECT A,B, COUNT(A) FROM myTable GROUP BY A,B

Which give me something like [(1,1,3), (2,1,3), (1,2,4)]

How can I do so with Realm in Android ?

Body:
Currently it is not possible to do in a single statement. You will have to do something like:

RealmResults<MyObject> myObjects = realm.where(MyObject.class).distinct("A", "B");
for (MyObject myObject : myObjects) {
    long count = realm.where(MyObject.class).equalsTo("A", myObject.getA()).equalsTo("B", myObject.getB()).count();
    // use getA(), getB(), and count
}


问:
"globally" manage app UI style (button, text field, etc) Obj-c
I am new into objective c. In current project, I always outlet each button, text field to respective Controller, and then style it.

Is there any same approach like CSS in globally set the UI's properties/style?

For example, in CSS we can do like following code

```<code>.button_global_1{
    border-radius: 8px;
}

//in html
<button class="button_global_1"></button>
<button class="button_global_1"></button>
//2 buttons implements the same style. saving time.
</code>```

Is there any such approach we can use in objective c? By outletting each UI components to each controller and then style it really consumes lots of time. And I started to find what is the best implementation to manage the UI's components.

Thanks!

答:
The only thing that comes close to what you describe is the UIAppearance protocol. It doesn't support your example but you can do other stuff like:

```<code>[[UIButton appearance] setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
</code>```

You can also create a UIButton subclass create a property for the corner radius and mark it with UI_APPEARANCE_SELECTOR. That way it is accessible through the UIAppearance protocol.

Body:
I am new into objective c. In current project, I always outlet each button, text field to respective Controller, and then style it.

Is there any same approach like CSS in globally set the UI's properties/style?

For example, in CSS we can do like following code

.button_global_1{
    border-radius: 8px;
}

//in html
<button class="button_global_1"></button>
<button class="button_global_1"></button>
//2 buttons implements the same style. saving time.

Is there any such approach we can use in objective c? By outletting each UI components to each controller and then style it really consumes lots of time. And I started to find what is the best implementation to manage the UI's components.

Thanks!

Body:
The only thing that comes close to what you describe is the UIAppearance protocol. It doesn't support your example but you can do other stuff like:

[[UIButton appearance] setTitleColor:[UIColor redColor] forState:UIControlStateNormal];

You can also create a UIButton subclass create a property for the corner radius and mark it with UI_APPEARANCE_SELECTOR. That way it is accessible through the UIAppearance protocol.


问:
Permut matrix and create news in R
I have a distance matix:

```<code>    A               B          C            D           E          F        G
A
B   0.6
C   0.38461538     0.42857143
D   0.25           0.5333      0.30769231
E   0.36363636     0.41666667  0.41666667   0.27272727
F   0.53846154     0.57142857  0.57142857   0.33333333  0.3
G   0.45454545     0.5         0.5          0.36363636  0.125 0.22222222
</code>```

Then, I want to permut this matrix in new matrix combinations of 4 x 4 where the order is not important, for example ABCD is equal to DCBA.

Any idea?

Thanks

答:
I would follow these steps:

1) Convert distance table into numeric matrix M <- as.matrix(dist)

2) Define the combinations of four elements between your 10 rows sam <- combn(1:10, 4). This is going to result on a matrix with 4 rows and as many columns as the combinations of 10 elements over 4 (210 in this case).

3) All the matrices you are interested on are M[sam[,i],sam[,i]] for i in 1:210

Title: Permut matrix and create news in R

Body:
I have a distance matix:

    A               B          C            D           E          F        G
A
B   0.6
C   0.38461538     0.42857143
D   0.25           0.5333      0.30769231
E   0.36363636     0.41666667  0.41666667   0.27272727
F   0.53846154     0.57142857  0.57142857   0.33333333  0.3
G   0.45454545     0.5         0.5          0.36363636  0.125 0.22222222

Then, I want to permut this matrix in new matrix combinations of 4 x 4 where the order is not important, for example ABCD is equal to DCBA.

Any idea?

Thanks


问:
How do I change the culture of a WinForms application at runtime
I have created Windows Form Program in C#. I have some problems with localization. I have resource files in 2 languages(one is for english and another is for french). I want to click each language button and change language at runtime.

But when i am clicking on button, it doesn't work. i am using this code.

```<code>private void btnfrench_Click(object sender, EventArgs e)
{
    getlanguage("fr-FR");
}

private void getlanguage(string lan)
{
    foreach (Control c in this.Controls)
    {
        ComponentResourceManager cmp =
            new ComponentResourceManager(typeof(BanksForm));
        cmp.ApplyResources(c, c.Name, new CultureInfo(lan));
    }
}
</code>```

would any pls help on this......

Many Thanks....

答:
Updating the CultureInfo at runtime might reset component size. This code preserves the size and position of the controls
(there will still be visible flickering though, which using SuspendLayout() couldn't fix)</p>

```<code>
    private void langItem_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
    {
        //I store the language codes in the Tag field of list items
        var itemClicked = e.ClickedItem;
        string culture = itemClicked.Tag.ToString().ToLower();

        Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(culture);
        ApplyResourceToControl(
        this,
        new ComponentResourceManager(typeof(GUI)),
        new CultureInfo(culture));
    }

    private void ApplyResourceToControl(
       Control control,
       ComponentResourceManager cmp,
       CultureInfo cultureInfo)
    {
        foreach (Control child in control.Controls)
        {
            //Store current position and size of the control
            var childSize = child.Size;
            var childLoc = child.Location;
            //Apply CultureInfo to child control
            ApplyResourceToControl(child, cmp, cultureInfo);
            //Restore position and size
            child.Location = childLoc;
            child.Size = childSize;
        }
        //Do the same with the parent control
        var parentSize = control.Size;
        var parentLoc = control.Location;
        cmp.ApplyResources(control, control.Name, cultureInfo);
        control.Location = parentLoc;
        control.Size = parentSize;
    }
</code>```

Body:
I have created Windows Form Program in C#. I have some problems with localization. I have resource files in 2 languages(one is for english and another is for french). I want to click each language button and change language at runtime.

But when i am clicking on button, it doesn't work. i am using this code.

private void btnfrench_Click(object sender, EventArgs e)
{
    getlanguage("fr-FR");
}

private void getlanguage(string lan)
{
    foreach (Control c in this.Controls)
    {
        ComponentResourceManager cmp =
            new ComponentResourceManager(typeof(BanksForm));
        cmp.ApplyResources(c, c.Name, new CultureInfo(lan));
    }
}

would any pls help on this......

Many Thanks....

Body:
Updating the CultureInfo at runtime might reset component size. This code preserves the size and position of the controls
(there will still be visible flickering though, which using SuspendLayout() couldn't fix)

    private void langItem_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
    {
        //I store the language codes in the Tag field of list items
        var itemClicked = e.ClickedItem;
        string culture = itemClicked.Tag.ToString().ToLower();

        Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(culture);
        ApplyResourceToControl(
        this,
        new ComponentResourceManager(typeof(GUI)),
        new CultureInfo(culture));
    }

    private void ApplyResourceToControl(
       Control control,
       ComponentResourceManager cmp,
       CultureInfo cultureInfo)
    {
        foreach (Control child in control.Controls)
        {
            //Store current position and size of the control
            var childSize = child.Size;
            var childLoc = child.Location;
            //Apply CultureInfo to child control
            ApplyResourceToControl(child, cmp, cultureInfo);
            //Restore position and size
            child.Location = childLoc;
            child.Size = childSize;
        }
        //Do the same with the parent control
        var parentSize = control.Size;
        var parentLoc = control.Location;
        cmp.ApplyResources(control, control.Name, cultureInfo);
        control.Location = parentLoc;
        control.Size = parentSize;
    }


问:
Writing a large ResultSet to a File
I'm tryin to write a large ResulSet (~1mm rows) to a single file. Is there a preferred/efficient way to do this in Java 1.6?</p>

答:
From GitHub: https://github.com/OhadR/ohadr.common/blob/master/src/main/java/com/ohadr/common/utils/resultset/ResultSetConverters.java</p>

```<code>public static void writeResultSetToWriter(ResultSet resultSet, PrintWriter writer) throws SQLException
{
ResultSetMetaData metadata = resultSet.getMetaData();
int numColumns = metadata.getColumnCount();
int numRows = 0;

while(resultSet.next())             //iterate rows
{
    ++numRows;
    JSONObject obj = new JSONObject();      //extends HashMap
    for (int i = 1; i <= numColumns; ++i)           //iterate columns
    {
        String column_name = metadata.getColumnName(i);
        obj.put(column_name, resultSet.getObject(column_name));
    }
    writer.println(obj.toJSONString());

    if(numRows % 1000 == 0)
        writer.flush();
}
</code>```

Title: Writing a large ResultSet to a File

Body:
From GitHub: https://github.com/OhadR/ohadr.common/blob/master/src/main/java/com/ohadr/common/utils/resultset/ResultSetConverters.java

public static void writeResultSetToWriter(ResultSet resultSet, PrintWriter writer) throws SQLException
{
ResultSetMetaData metadata = resultSet.getMetaData();
int numColumns = metadata.getColumnCount();
int numRows = 0;

while(resultSet.next())             //iterate rows
{
    ++numRows;
    JSONObject obj = new JSONObject();      //extends HashMap
    for (int i = 1; i <= numColumns; ++i)           //iterate columns
    {
        String column_name = metadata.getColumnName(i);
        obj.put(column_name, resultSet.getObject(column_name));
    }
    writer.println(obj.toJSONString());

    if(numRows % 1000 == 0)
        writer.flush();
}


问:
wp7, silverlight, Why event fires twice?
In this case when user click some UIElement I want this element yo be surrounded by dashed border. If there is some other object surrounded then this code removes it first.

Everything is fine but "private void activateElem" fires twice and I have no idea why. Maybe somebody can help, I really have no more ideas.

Anybody knows some ideas to debug issues like this? Maybe there is some way to print out all events queue. There is silverlight spy but I think it doesn't work for windows phone 7.

My code:

```<code> public class ManipulationEngine
{
    private Canvas sheet;
    private static FrameworkElement current_active_element;

    public ManipulationEngine(Canvas sheet)
    {
        this.sheet = sheet;

        foreach (FrameworkElement elem in sheet.Children)
        {
            elem.MouseLeftButtonUp += new MouseButtonEventHandler(activateElem);
        }

    }

    private void activateElem(object sender, MouseButtonEventArgs e)
    {
        FrameworkElement elem = sender as FrameworkElement;

        if (current_active_element != null)
        {
            desactivateElem();
        }

        Grid grid = new Grid();
        Rectangle recentagle = new Rectangle();

        grid.SetValue(Canvas.TopProperty, (double)elem.GetValue(Canvas.TopProperty) - 10);
        grid.SetValue(Canvas.LeftProperty, (double)elem.GetValue(Canvas.LeftProperty) - 10);

        DoubleCollection stroke = new DoubleCollection();
        stroke.Add(4);
        stroke.Add(2);
        recentagle.StrokeDashArray = stroke;

        grid.Children.Add(recentagle);
        sheet.Children.Remove(elem);
        elem.Margin = new Thickness(10);
        grid.Children.Add(elem);
        sheet.Children.Add(grid);

        current_active_element = elem;
    }

    private void desactivateElem()
    {
        if (current_active_element != null)
        {
            Grid grid = VisualTreeHelper.GetParent(current_active_element) as Grid;

            grid.Children.Remove(current_active_element);
            sheet.Children.Remove(grid);

            current_active_element.SetValue(Canvas.TopProperty, (double)grid.GetValue(Canvas.TopProperty) + 10);
            current_active_element.SetValue(Canvas.LeftProperty, (double)grid.GetValue(Canvas.LeftProperty) + 10);
            current_active_element.Margin = new Thickness(0);

            sheet.Children.Add(current_active_element);

            current_active_element = null;
        }
    }
</code>```

答:
I'd really advise looking into the Parts and States model. You may be able to do this with a button, or perhaps a radio button.

Usually if you're coding changes to the visual tree, you're not doing it right.

Karen Corby dealt with this very clearly at MIX08, take a look!

http://archive.visitmix.com/blogs/2008Sessions/T20/

Luke

Body:
In this case when user click some UIElement I want this element yo be surrounded by dashed border. If there is some other object surrounded then this code removes it first.

Everything is fine but "private void activateElem" fires twice and I have no idea why. Maybe somebody can help, I really have no more ideas.

Anybody knows some ideas to debug issues like this? Maybe there is some way to print out all events queue. There is silverlight spy but I think it doesn't work for windows phone 7.

My code:

 public class ManipulationEngine
{
    private Canvas sheet;
    private static FrameworkElement current_active_element;

    public ManipulationEngine(Canvas sheet)
    {
        this.sheet = sheet;

        foreach (FrameworkElement elem in sheet.Children)
        {
            elem.MouseLeftButtonUp += new MouseButtonEventHandler(activateElem);
        }

    }

    private void activateElem(object sender, MouseButtonEventArgs e)
    {
        FrameworkElement elem = sender as FrameworkElement;

        if (current_active_element != null)
        {
            desactivateElem();
        }

        Grid grid = new Grid();
        Rectangle recentagle = new Rectangle();

        grid.SetValue(Canvas.TopProperty, (double)elem.GetValue(Canvas.TopProperty) - 10);
        grid.SetValue(Canvas.LeftProperty, (double)elem.GetValue(Canvas.LeftProperty) - 10);

        DoubleCollection stroke = new DoubleCollection();
        stroke.Add(4);
        stroke.Add(2);
        recentagle.StrokeDashArray = stroke;

        grid.Children.Add(recentagle);
        sheet.Children.Remove(elem);
        elem.Margin = new Thickness(10);
        grid.Children.Add(elem);
        sheet.Children.Add(grid);

        current_active_element = elem;
    }

    private void desactivateElem()
    {
        if (current_active_element != null)
        {
            Grid grid = VisualTreeHelper.GetParent(current_active_element) as Grid;

            grid.Children.Remove(current_active_element);
            sheet.Children.Remove(grid);

            current_active_element.SetValue(Canvas.TopProperty, (double)grid.GetValue(Canvas.TopProperty) + 10);
            current_active_element.SetValue(Canvas.LeftProperty, (double)grid.GetValue(Canvas.LeftProperty) + 10);
            current_active_element.Margin = new Thickness(0);

            sheet.Children.Add(current_active_element);

            current_active_element = null;
        }
    }


问:
Laplacian Operator in netpbm/pgm
I need to create Laplacian Operator in library netpbm/pgm.
Processing image is simply - I calculate every pixel. I don't use
normalization because I know it is 0 and I want to simplify solution.

My code:

```<code>#include<stdio.h>
#include<stdlib.h>
#include <netpbm/pgm.h>

int main(int argc, char *argv[])
{
    gray **image; // pointer to 2d array image
    gray **image_out;
    gray max2;
    int cols,rows;
    int i,j;
    FILE* fp;
    int mask[3][3] = {{0,-1,0},{-1,4,-1},{0,-1,0} };
    int min = 2000;
    int max = -2000;

    pgm_init(&argc, argv);

    fp = fopen("/mhome/matkuz/cwiczenia/cw3/images/foto01.pgm","rb");
    image = pgm_readpgm(fp,&cols,&rows,&max2);
    image_out = pgm_allocarray(cols,rows);

    //printf("cols %d rows %d image%d",cols,rows,image[cols][rows]);

    for(i=1;i<rows-1;i++) //rowy to sa x
    {
       for(j=1;j<cols-1;j++) // cols to sa kolumny
       {
        float s,suma; // wiesz wczesiejszy image[i-1,j]
        s =
    mask[0][0]*image[i-1][j-1]+mask[0][1]*image[i-1][j]+
        mask[0][2]*image[i-1][j+1] +
        mask[1][0]*image[i][j-1]+mask[1][1]*image[i][j]+
                mask[1][2]*image[i][j+1] +
        mask[2][0]*image[i][j-1]+mask[2][1]*image[i+1][j]+
                mask[2][2]*image[i+1][j+1];

        // image_out[i][j] = (int) (s/suma);

        image_out[i-1][j-1] = (float) s;
      }
    }

    // normalization for display command
    for(i=1;i<rows-1;i++)
    {
        for(j=1;j<cols-1;j++)
        {
            image_out[i][j]= (float) (image_out[i][j]-min)/(float)(max-min)*255.0;
        }
    }

    pgm_writepgm(stdout,image_out,cols-1,rows-1,max2,1);

    // cleanup
    pgm_freearray(image,rows);
    pgm_freearray(image_out,rows);
    fclose(fp);

    return 0;
}
</code>```

Compile commend:

```<code>gcc program.c -lnetpbm -o program
</code>```

After try to use display I get only white pixels.

Any help? Thx in advance.

答:
This is an excellent example of how sloppy formatting makes it very difficult to spot errors. Here's your filtering code:

```<code>    s =
mask[0][0]*image[i-1][j-1]+mask[0][1]*image[i-1][j]+
    mask[0][2]*image[i-1][j+1] +
    mask[1][0]*image[i][j-1]+mask[1][1]*image[i][j]+
            mask[1][2]*image[i][j+1] +
    mask[2][0]*image[i][j-1]+mask[2][1]*image[i+1][j]+
            mask[2][2]*image[i+1][j+1];
</code>```

Can you see the error? How about if you format it with a bit more care?

```<code>    s = mask[0][0] * image[i-1][j-1]
      + mask[0][1] * image[i-1][j]
      + mask[0][2] * image[i-1][j+1]

      + mask[1][0] * image[i][j-1]
      + mask[1][1] * image[i][j]
      + mask[1][2] * image[i][j+1]

      + mask[2][0] * image[i][j-1]
      + mask[2][1] * image[i+1][j]
      + mask[2][2] * image[i+1][j+1];
</code>```

Can you see it now? mask[2][0] * image[i][j-1] should be mask[2][0] * image[i+1][j-1].

Title: Laplacian Operator in netpbm/pgm

Body:
I need to create Laplacian Operator in library netpbm/pgm.
Processing image is simply - I calculate every pixel. I don't use
normalization because I know it is 0 and I want to simplify solution.

My code:

#include<stdio.h>
#include<stdlib.h>
#include <netpbm/pgm.h>

int main(int argc, char *argv[])
{
    gray **image; // pointer to 2d array image
    gray **image_out;
    gray max2;
    int cols,rows;
    int i,j;
    FILE* fp;
    int mask[3][3] = {{0,-1,0},{-1,4,-1},{0,-1,0} };
    int min = 2000;
    int max = -2000;

    pgm_init(&argc, argv);

    fp = fopen("/mhome/matkuz/cwiczenia/cw3/images/foto01.pgm","rb");
    image = pgm_readpgm(fp,&cols,&rows,&max2);
    image_out = pgm_allocarray(cols,rows);

    //printf("cols %d rows %d image%d",cols,rows,image[cols][rows]);

    for(i=1;i<rows-1;i++) //rowy to sa x
    {
       for(j=1;j<cols-1;j++) // cols to sa kolumny
       {
        float s,suma; // wiesz wczesiejszy image[i-1,j]
        s =
    mask[0][0]*image[i-1][j-1]+mask[0][1]*image[i-1][j]+
        mask[0][2]*image[i-1][j+1] +
        mask[1][0]*image[i][j-1]+mask[1][1]*image[i][j]+
                mask[1][2]*image[i][j+1] +
        mask[2][0]*image[i][j-1]+mask[2][1]*image[i+1][j]+
                mask[2][2]*image[i+1][j+1];

        // image_out[i][j] = (int) (s/suma);

        image_out[i-1][j-1] = (float) s;
      }
    }

    // normalization for display command
    for(i=1;i<rows-1;i++)
    {
        for(j=1;j<cols-1;j++)
        {
            image_out[i][j]= (float) (image_out[i][j]-min)/(float)(max-min)*255.0;
        }
    }

    pgm_writepgm(stdout,image_out,cols-1,rows-1,max2,1);

    // cleanup
    pgm_freearray(image,rows);
    pgm_freearray(image_out,rows);
    fclose(fp);

    return 0;
}

Compile commend:

gcc program.c -lnetpbm -o program

After try to use display I get only white pixels.

Any help? Thx in advance.

Body:
This is an excellent example of how sloppy formatting makes it very difficult to spot errors. Here's your filtering code:

    s =
mask[0][0]*image[i-1][j-1]+mask[0][1]*image[i-1][j]+
    mask[0][2]*image[i-1][j+1] +
    mask[1][0]*image[i][j-1]+mask[1][1]*image[i][j]+
            mask[1][2]*image[i][j+1] +
    mask[2][0]*image[i][j-1]+mask[2][1]*image[i+1][j]+
            mask[2][2]*image[i+1][j+1];

Can you see the error? How about if you format it with a bit more care?

    s = mask[0][0] * image[i-1][j-1]
      + mask[0][1] * image[i-1][j]
      + mask[0][2] * image[i-1][j+1]

      + mask[1][0] * image[i][j-1]
      + mask[1][1] * image[i][j]
      + mask[1][2] * image[i][j+1]

      + mask[2][0] * image[i][j-1]
      + mask[2][1] * image[i+1][j]
      + mask[2][2] * image[i+1][j+1];

Can you see it now? mask[2][0] * image[i][j-1] should be mask[2][0] * image[i+1][j-1].


问:
How to set background color to button in table layout programatically?
I am making Tic Tac Toe game. And I have used buttons for tic tac toe board and set in table layout dynamically.
Problem is that, I can't set background property of the button.
My code is here.

```<code>TableLayout table = (TableLayout) findViewById(R.id.tableLayout1);
    table.removeAllViewsInLayout();

    int id = 0;

    for (int f = 0; f < board_size; f++) {
        TableRow tr = new TableRow(this);
        for (int c = 0; c < board_size; c++) {
            Button b = new Button(this);
            b.setId(id);
            b.setTextSize(15.0f);

       //below code assign color to whole table background
            //b.setBackground(Color.WHITE);
            b.setOnClickListener(this);
            id++;
            tr.addView(b, screenWidth / board_size, screenWidth / board_size);
        }
        table.addView(tr);
    }
</code>```

Please guide me. Thanks in Advance.

答:
Try b.setBackgroundColor(Color.Green);

set button width

b.setLayoutParams(new LinearLayout.LayoutParams(10, 100));

Body:
I am making Tic Tac Toe game. And I have used buttons for tic tac toe board and set in table layout dynamically.
Problem is that, I can't set background property of the button.
My code is here.

TableLayout table = (TableLayout) findViewById(R.id.tableLayout1);
    table.removeAllViewsInLayout();

    int id = 0;

    for (int f = 0; f < board_size; f++) {
        TableRow tr = new TableRow(this);
        for (int c = 0; c < board_size; c++) {
            Button b = new Button(this);
            b.setId(id);
            b.setTextSize(15.0f);

       //below code assign color to whole table background
            //b.setBackground(Color.WHITE);
            b.setOnClickListener(this);
            id++;
            tr.addView(b, screenWidth / board_size, screenWidth / board_size);
        }
        table.addView(tr);
    }

Please guide me. Thanks in Advance.


问:
Java multithreading - joining a CPU heavy thread and volatile keyword
So, follwoing some job interviews I wanted to write a small program to check that i++  really is non-atomic in java, and that one should, in practice,add some locking to protect it. Turns out you should, but this is not the question here.

So I wrote this program here just to check it.

The thing is, it hangs. It seems that the main thread is stuck on on t1.join()
 line, even though both worker threads should finish because of the stop = true from previous line.

I found that the hanging stops if :

I add some printing inside the worker threads (as in the comments), probably causing the worker threads to sometime give up CPU
or

If I mark the flag boolean stop as volatile, causing the write to immediately
be seen by worker threads, or

If I mark the counter tas volatile... for this I have no idea what causes the un-hanging.

Can someone explain what's going on? why do I see the hang and why does it stop in those three cases?

```<code>public class Test {

    static /* volatile */ long t = 0;
    static long[] counters = new long[2];
    static /* volatile */ boolean stop = false;

    static Object o = new Object();
    public static void main(String[] args)
    {
        Thread t1 = createThread(0);
        Thread t2 = createThread(1);

        t1.start();
        t2.start();

        Thread.sleep(1000);

        stop = true;

        t1.join();
        t2.join();

        System.out.println("counter : " + t + " counters : " + counters[0] + ", " + counters[1]  + " (sum  : " + (counters[0] + counters[1]) + ")");

    }

    private static Thread createThread(final int i)
    {
        Thread thread = new Thread() {
            public void run() {
                while (!stop)
                {
//                  synchronized (o) {
                        t++;
//                  }

//                  if (counters[i] % 1000000 == 0)
//                  {
//                      System.out.println(i + ")" + counters[i]);
//                  }
                    counters[i]++;
                }
            };
        };
        return thread;
    }
}
</code>```

答:
Those might be the possible reasons :

Marking "stop" as volatile prevents its value being cached in the worker threads states (e.g registers)

Marking "t" as volatile makes sure that updated value is read when "t" is accessed. However, this behavior might also get "stop"'s updated value if JVM arranged those variables near each other, so they might be read and stored in the same "cache line". Try adding @Contended annotation to see if behavior persists in this case as well .You may find additional information on : https://en.wikipedia.org/wiki/False_sharing , https://mechanical-sympathy.blogspot.am/2011/07/false-sharing.html , https://blogs.oracle.com/dave/entry/java_contented_annotation_to_help

Calling the "System.out.println()" actually performs a system call hence making a transition to the "native calls stack" which probably also makes the "processor cache" to purge. What does a JVM have to do when calling a native method?

If you are interested in digging deeper into the topic then I would suggest to go over "Java Concurrency in Practice by Brian Goetz" book.

Body:
So, follwoing some job interviews I wanted to write a small program to check that i++  really is non-atomic in java, and that one should, in practice,add some locking to protect it. Turns out you should, but this is not the question here.

So I wrote this program here just to check it.

The thing is, it hangs. It seems that the main thread is stuck on on t1.join()
 line, even though both worker threads should finish because of the stop = true from previous line.

I found that the hanging stops if :

I add some printing inside the worker threads (as in the comments), probably causing the worker threads to sometime give up CPU
or

If I mark the flag boolean stop as volatile, causing the write to immediately
be seen by worker threads, or

If I mark the counter tas volatile... for this I have no idea what causes the un-hanging.

Can someone explain what's going on? why do I see the hang and why does it stop in those three cases?

public class Test {

    static /* volatile */ long t = 0;
    static long[] counters = new long[2];
    static /* volatile */ boolean stop = false;

    static Object o = new Object();
    public static void main(String[] args)
    {
        Thread t1 = createThread(0);
        Thread t2 = createThread(1);

        t1.start();
        t2.start();

        Thread.sleep(1000);

        stop = true;

        t1.join();
        t2.join();

        System.out.println("counter : " + t + " counters : " + counters[0] + ", " + counters[1]  + " (sum  : " + (counters[0] + counters[1]) + ")");

    }

    private static Thread createThread(final int i)
    {
        Thread thread = new Thread() {
            public void run() {
                while (!stop)
                {
//                  synchronized (o) {
                        t++;
//                  }

//                  if (counters[i] % 1000000 == 0)
//                  {
//                      System.out.println(i + ")" + counters[i]);
//                  }
                    counters[i]++;
                }
            };
        };
        return thread;
    }
}


问:
Django Date Input Parsing?
I'm trying to get a date for an event from a user.
The input is just a simple html text input.
My main problem is that I don't know how to parse the date.

If I try to pass the raw string, I get a TypeError, as expected.

Does Django have any date-parsing modules?

答: (In 2017), you could now use django.utils.dateparse</p>

Title: Django Date Input Parsing?


问:
Alternate values from two SCSS @for loops and add comma separator
So the basic gist is that I eventually want to output a zig zag clip path like so:

clip-path: polygon(0 5px, 5px 0, 10px 5px, 15px 0, 20px 5px, 25px 0, 30px 5px );

You can see what I have done on Codepen

I'm using an SCSS function based on one of Hugo Giraudel's Math Sequences.

I have the code below outputting two sequences:
5px 0px 5px 0px 5px 0px 5px 0px 5px 0px 5px
and
0px 5px 10px 15px 20px 25px 30px 35px 40px 45px 50px

These are the values that I need as you can see in the clip-path but I can't find anywhere how to flip-flop between the x-coord and y-coord with the separator to make that final step.

Is that even possible or do I need to come at this from a different angle?

```<code>@function zigzag($n) {

    $x-coord: 0px; // +5 each time
    $y-coord: 5px; // flip flop 5, 0, 5, 0

    @for $i from 1 through $n {

        $last-x: nth($x-coord, length($x-coord));
        $new-x: $last-x + 5;

        $x-coord: append($x-coord, $new-x);

        $last-y: nth($y-coord, length($y-coord));
        $new-y: null;

        @if $last-y == 5px {

            $new-y: $last-y - 5px;

        } @else if $last-y == 0 {

            $new-y: $last-y + 5px;

        }

        $y-coord: append($y-coord, $new-y);

    }

    @return $y-coord $x-coord;

}
</code>```

答:
It seems like you are looking for the comma separator

```<code>@mixin zig-zag($n){
  $l: ();  // list to hold $x $y pairs
  $x: 0;   // increment by 5
  $y: 5px; // flip flop 5 or 0
  @for $i from 1 through $n {
    // append both $x and $y to the list using comma as separator
    $l:append($l, $x $y, comma);
    $x: $x + 5px;
    $y:if($y==0, 5px, 0);
  }
  clip-path: polygon($l);
}

// test
.class {
  @include zig-zag(7);
 }

// output
.class {
   clip-path: polygon(0 5px, 5px 0, 10px 5px, 15px 0, 20px 5px, 25px 0, 30px 5px);
}
</code>```

Body:
So the basic gist is that I eventually want to output a zig zag clip path like so:

clip-path: polygon(0 5px, 5px 0, 10px 5px, 15px 0, 20px 5px, 25px 0, 30px 5px );

You can see what I have done on Codepen

I'm using an SCSS function based on one of Hugo Giraudel's Math Sequences.

I have the code below outputting two sequences:
5px 0px 5px 0px 5px 0px 5px 0px 5px 0px 5px
and
0px 5px 10px 15px 20px 25px 30px 35px 40px 45px 50px

These are the values that I need as you can see in the clip-path but I can't find anywhere how to flip-flop between the x-coord and y-coord with the separator to make that final step.

Is that even possible or do I need to come at this from a different angle?

@function zigzag($n) {

    $x-coord: 0px; // +5 each time
    $y-coord: 5px; // flip flop 5, 0, 5, 0

    @for $i from 1 through $n {

        $last-x: nth($x-coord, length($x-coord));
        $new-x: $last-x + 5;

        $x-coord: append($x-coord, $new-x);

        $last-y: nth($y-coord, length($y-coord));
        $new-y: null;

        @if $last-y == 5px {

            $new-y: $last-y - 5px;

        } @else if $last-y == 0 {

            $new-y: $last-y + 5px;

        }

        $y-coord: append($y-coord, $new-y);

    }

    @return $y-coord $x-coord;

}

Body:
It seems like you are looking for the comma separator

@mixin zig-zag($n){
  $l: ();  // list to hold $x $y pairs
  $x: 0;   // increment by 5
  $y: 5px; // flip flop 5 or 0
  @for $i from 1 through $n {
    // append both $x and $y to the list using comma as separator
    $l:append($l, $x $y, comma);
    $x: $x + 5px;
    $y:if($y==0, 5px, 0);
  }
  clip-path: polygon($l);
}

// test
.class {
  @include zig-zag(7);
 }

// output
.class {
   clip-path: polygon(0 5px, 5px 0, 10px 5px, 15px 0, 20px 5px, 25px 0, 30px 5px);
}


问:
UIView touch event in controller
How can I add UIView touchbegin action or touchend action programmatically as Xcode is not providing from Main.storyboard?</p>

答:
Swift 4 / 5:

```<code>let gesture = UITapGestureRecognizer(target: self, action:  #selector(self.checkAction))
self.myView.addGestureRecognizer(gesture)

@objc func checkAction(sender : UITapGestureRecognizer) {
    // Do what you want
}
</code>```

Swift 3:

```<code>let gesture = UITapGestureRecognizer(target: self, action:  #selector(self.checkAction(sender:)))
self.myView.addGestureRecognizer(gesture)

func checkAction(sender : UITapGestureRecognizer) {
    // Do what you want
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: UIView touch event in controller

Body:
Swift 4 / 5:

let gesture = UITapGestureRecognizer(target: self, action:  #selector(self.checkAction))
self.myView.addGestureRecognizer(gesture)

@objc func checkAction(sender : UITapGestureRecognizer) {
    // Do what you want
}

Swift 3:

let gesture = UITapGestureRecognizer(target: self, action:  #selector(self.checkAction(sender:)))
self.myView.addGestureRecognizer(gesture)

func checkAction(sender : UITapGestureRecognizer) {
    // Do what you want
}


问:
How can I make a div 80% the size of the page?
I'd like to make a page container div have a top margin of 10% and bottom margin of 10%. How can I make the div take the remaining 80% of the page, all the time ( no matter if it has content or not )?</p>

答:
You can try:</p>

```<code>CSS
---
.container {
   margin-top:10%;
   margin-bottom:10%;
   height:80%;
}

<div class="container"></div>
</code>```

Body:
You can try:

CSS
---
.container {
   margin-top:10%;
   margin-bottom:10%;
   height:80%;
}

<div class="container"></div>


问:
void pointer in function call in C++ vs C
I have this piece of code that works in C but not C++, is that any way to make it work on both C and C++ ?

```<code>void foo(void* b)
{
   int *c = b;
   printf("%d\n",*c);

}

int main ()
{
 int a = 1000;

 foo(&a);
 return 0;
}
</code>```

output:

C++:

```<code>1 In function 'void foo(void*)':
2 Line 3: error: invalid conversion from 'void*' to 'int*'
3 compilation terminated due to -Wfatal-errors.
</code>```

C:

```<code>1000
</code>```

Please help

答:
C allows implicit conversion between void* and any pointer to object type, C++ does not. To make your code compatible with both languages, you could type foo( (void*)&a );.

However, using void pointers is discouraged in both languages - they should only be used as a last resort. If you want the function to be type-generic in C, you'd use the _Generic keyword. In C++ you'd use templates.

Body:
I have this piece of code that works in C but not C++, is that any way to make it work on both C and C++ ?

void foo(void* b)
{
   int *c = b;
   printf("%d\n",*c);

}

int main ()
{
 int a = 1000;

 foo(&a);
 return 0;
}

output:

C++:

1 In function 'void foo(void*)':
2 Line 3: error: invalid conversion from 'void*' to 'int*'
3 compilation terminated due to -Wfatal-errors.

C:

1000

Please help


问:
C socket programming receiving unknown length of data
Hi I designed a code to get the length of unknown data coming in to the socket
I need help because I can't find where my code get stuck in this function.
Thanks for any help</p>

```<code>int recvlen(int s){ //peak all received data and returns the length
  char *request;
  int total;
  total= 1024;//initial size
  int numbytes;
  printf("\n entered recvlen\n");
  while(1){
    if(( request= (char *)realloc(request,sizeof(char)*total+1)) <=0){
      fprintf(stderr,"error in realloc no memory or fail");
      return -1;
    }
    if((numbytes= recv(s,request,sizeof(request),MSG_PEEK))==-1){//get request
      fprintf(stderr,"\n error in receiveall \n");
      free(request);
      return -1;
    }
   if(numbytes != strlen(request)){
    total = numbytes+1;
    free(request);
    printf("\n recvlen returned total: %d\n",total);
    return total;//when the size is found
   }
  total += total;
  }
    }
</code>```

答:
I think your software desing is wrong, why
there is while(1),
when you call recv(s,request,sizeof(request),MSG_PEEK))
you will get number of bytes in recv queue, then you have to read bytes from array. if you dont read, recv queue will overload and while(1) will never finish</p>

Body:
Hi I designed a code to get the length of unknown data coming in to the socket
I need help because I can't find where my code get stuck in this function.
Thanks for any help

int recvlen(int s){ //peak all received data and returns the length
  char *request;
  int total;
  total= 1024;//initial size
  int numbytes;
  printf("\n entered recvlen\n");
  while(1){
    if(( request= (char *)realloc(request,sizeof(char)*total+1)) <=0){
      fprintf(stderr,"error in realloc no memory or fail");
      return -1;
    }
    if((numbytes= recv(s,request,sizeof(request),MSG_PEEK))==-1){//get request
      fprintf(stderr,"\n error in receiveall \n");
      free(request);
      return -1;
    }
   if(numbytes != strlen(request)){
    total = numbytes+1;
    free(request);
    printf("\n recvlen returned total: %d\n",total);
    return total;//when the size is found
   }
  total += total;
  }
    }


问:
Android lint shows up no issues in Sonarqube
I have setup my project to use with Sonarqube. I was using PMD and Checkstyle to run tests and all of them are successfully logged in Sonarqube console. But last day I decided to add Android lint rules also to my Quality profile. I have activated all Lint rules in a new profile and run the project. Now when I run the project, it is not showing up any errors or issues with this profile. When I run the lint locally I get about 400 issues. What could I be missing?

I am using Sonarqube plugin in Gradle and Sonarqube 6.2 on my server. My Sonarqube configuration is as follows

```<code>apply plugin: "org.sonarqube"

sonarqube {
//noinspection GroovyAssignabilityCheck
    properties {
//noinspection GroovyAssignabilityCheck
        property "sonar.projectName", "MyProject"
//noinspection GroovyAssignabilityCheck
        property "sonar.projectKey", "Testapplication"
//noinspection GroovyAssignabilityCheck
        property "sonar.projectVersion", "1.0"
//noinspection GroovyAssignabilityCheck
        property "sonar.analysis.mode", "publish"
//noinspection GroovyAssignabilityCheck
        property "sonar.language", "java"
//noinspection GroovyAssignabilityCheck
        property "sonar.sources", "src/main/"
//noinspection GroovyAssignabilityCheck
        property "sonar.profile", "FindBugs"
//noinspection GroovyAssignabilityCheck
        property "sonar.host.url", "http://192.168.21.33:9000"
//noinspection GroovyAssignabilityCheck
        property "sonar.login", "admin"
//noinspection GroovyAssignabilityCheck
        property "sonar.password", "admin"
        property "sonar.exclusions","es.miguelprietos.testapplication/R.java"
        property "sonar.android.lint.report", "build/outputs/lint-results.xml"
        property "sonar.binaries", "build/intermediates/classes/debug"
        property "sonar.java.binaries", "build/intermediates/classes/debug"

    }
}
</code>```

I use below command to run my Sonar task (no parameters).

```<code> ./gradlew sonarqube
</code>```

Lint options configured in my Gradle is as below

```<code>   lintOptions {
        // set to true to turn off analysis progress reporting by lint
        quiet true
        // if true, stop the gradle build if errors are found
        abortOnError false
        // if true, only report errors
        ignoreWarnings true
    }
</code>```

答:
I think "./gradlew lint" is what you are looking for.
As describe here, it will generate the missing XML report.
Be carful, it can generate a report for each build variant (Debug by default will generate build/outputs/lint-results-debug.xml). So you can call lintDebug, lintRelease... dependings on your build variant.

And change your report file-name accordingly to the generated file.

Body:
I have setup my project to use with Sonarqube. I was using PMD and Checkstyle to run tests and all of them are successfully logged in Sonarqube console. But last day I decided to add Android lint rules also to my Quality profile. I have activated all Lint rules in a new profile and run the project. Now when I run the project, it is not showing up any errors or issues with this profile. When I run the lint locally I get about 400 issues. What could I be missing?

I am using Sonarqube plugin in Gradle and Sonarqube 6.2 on my server. My Sonarqube configuration is as follows

apply plugin: "org.sonarqube"

sonarqube {
//noinspection GroovyAssignabilityCheck
    properties {
//noinspection GroovyAssignabilityCheck
        property "sonar.projectName", "MyProject"
//noinspection GroovyAssignabilityCheck
        property "sonar.projectKey", "Testapplication"
//noinspection GroovyAssignabilityCheck
        property "sonar.projectVersion", "1.0"
//noinspection GroovyAssignabilityCheck
        property "sonar.analysis.mode", "publish"
//noinspection GroovyAssignabilityCheck
        property "sonar.language", "java"
//noinspection GroovyAssignabilityCheck
        property "sonar.sources", "src/main/"
//noinspection GroovyAssignabilityCheck
        property "sonar.profile", "FindBugs"
//noinspection GroovyAssignabilityCheck
        property "sonar.host.url", "http://192.168.21.33:9000"
//noinspection GroovyAssignabilityCheck
        property "sonar.login", "admin"
//noinspection GroovyAssignabilityCheck
        property "sonar.password", "admin"
        property "sonar.exclusions","es.miguelprietos.testapplication/R.java"
        property "sonar.android.lint.report", "build/outputs/lint-results.xml"
        property "sonar.binaries", "build/intermediates/classes/debug"
        property "sonar.java.binaries", "build/intermediates/classes/debug"

    }
}

I use below command to run my Sonar task (no parameters).

 ./gradlew sonarqube

Lint options configured in my Gradle is as below

   lintOptions {
        // set to true to turn off analysis progress reporting by lint
        quiet true
        // if true, stop the gradle build if errors are found
        abortOnError false
        // if true, only report errors
        ignoreWarnings true
    }


问:
Drop Down List Giving Incorrect Values
I have followed the following tutorial for my project:

https://www.youtube.com/watch?v=h_ViuyVs4AE

The issue that I have is that when I click an item in the first drop down box, it does not give the correct values in the second box, it only gives one value and it is incorrect. It should display all the Model_Name's(Vehicle_Model table) that are for each Make_Name(Vehicle_Make table).

Index.cshtml code:

```<code>@model GoogleMap.Models.MyPageViewModel

<script>
    $(function () {
        $("#ContID").change(function () {
            $.get("/Map/GetModById", { MID: $("#ContID").val() }, function (data) {
                var $list = $("#St");
                $list.empty();
                $.each(data, function() {
                    $("<option />")
                        .val(this.Model_ID)
                        .text(this.Model_Name)
                        .appendTo($list);
                });
            })
        });
    });
</script>

@Html.DropDownListFor(p => p.SelectedMake_Id, ViewBag.Vehicle_Make as SelectList, "Select Vehicle Make", new { id = "ContID" })
</code>```

MapController.cs code:

```<code>public class MapController : Controller
{
    private GoogleMapEntities db = new GoogleMapEntities();
    //Get the select ID???
    int SelectedMake_Id = 0;

    // GET: Map
    public ActionResult Index()
    {
        GoogleMapEntities GE = new GoogleMapEntities();
        List<Vehicle_Details> vehList = db.Vehicle_Details.ToList();

        GoogleMapViewModel GMviewmodel = new GoogleMapViewModel();
        List<GoogleMapViewModel> GMviewmodelList = new List<GoogleMapViewModel>();

        //Populate the ViewModel
        MyPageViewModel vm = new Models.MyPageViewModel();
        vm.GoogleMapViewModelList = GMviewmodelList;
        vm.SelectedMake_Id = SelectedMake_Id;

        ViewBag.Vehicle_Make = new SelectList(db.Vehicle_Make, "Make_ID", "Make_Name");

        return View(vm);
    }

    public JsonResult GetModById(int MID)
    {
        db.Configuration.ProxyCreationEnabled = false;
        return Json(db.Vehicle_Model.Where(p => p.Model_ID == MID), JsonRequestBehavior.AllowGet);
    }

    [HttpPost]
    public ActionResult Search(string Location)
    {
        GoogleMapEntities GE = new GoogleMapEntities();
        ////SELECT Make_Name DATA FROM DB1
        // var result = GE.Vehicle_Model.Where(x => x.Model_Name.StartsWith(Location)).ToList();
        var GetVeh = db.GetMapSearch().Where(x => x.Model_Name.StartsWith(Location)).ToList();

        return Json(GetVeh, JsonRequestBehavior.AllowGet);
    }
}
</code>```

Vehicle_Make has Make_ID (pk) and Make_Name.

Vehicle_Model has Model_ID (pk) and Model_Name.

Vehicle_Details has Vehicle_ID (pk), Model_ID (fk), Make_ID (fk).

So what needs to happen is when I click a vehicle name(Make_Name), it must display all of it's Model_Name's in the second drop down list.

EDIT:
I have made a proc called DropDL which has the query that will display the Model name's with their Model_ID's and Make_ID's.

Query in proc:

```<code>SELECT          Vehicle_Model.Model_Name, Vehicle_Details.Model_ID,
                Vehicle_Details.Make_ID
FROM            Vehicle_Make INNER JOIN
                Vehicle_Details ON Vehicle_Make.Make_ID =
                Vehicle_Details.Make_ID INNER JOIN
                Vehicle_Model ON Vehicle_Details.Model_ID =
                Vehicle_Model.Model_ID
</code>```

The procedure that I have made(GetMapSearch) which linked 4 tables tables for something else, where it linked all of those tables using ID's and getting specific values from each table, worked well, so I do not understand why I'd need to add Make_ID to the Vehicle_Model table unless the drop down list does require that.

Updated code:

```<code>    public JsonResult GetModById(int MID)
    {
        db.Configuration.ProxyCreationEnabled = false;
        return Json(db.DropDL().Where(p => p.Model_ID == MID)
        .Select(p => new SelectListItem { Text = p.Model_Name, Value =
        p.Model_ID.ToString() }).ToList(),
        JsonRequestBehavior.AllowGet);
    }
</code>```

And Index.cshtml code:

```<code>@model GoogleMap.Models.MyPageViewModel

@using Mvc.CascadeDropDown

@Html.DropDownListFor(p => p.SelectedMake_Id, ViewBag.Vehicle_Make as
SelectList, "Select Vehicle Make", new { id = "ContID" })

@Html.CascadingDropDownListFor(
expression: m => m.SelectedModelId,
triggeredByPropertyWithId: "ContID",  //Parent property that trigers
dropdown data loading
url: Url.Action("GetModById", "Map"),  //Url of action that returns dropdown
data
ajaxActionParamName: "MID", //Parameter name for the selected parent value
that url action receives
optionLabel: "Please select a Model", // Option label
disabledWhenParentNotSelected: true, //If true, disables dropdown until
parent dropdown is selected
htmlAttributes: new { @class = "form-control" })
</code>```

Also, if I changed the ViewBag to use db.DropDL() instead of db.Vehicle_Make, it gets all of the makes but it brings all of the makes up multiple times.

After making the proc, I am still getting one or two Model_Name's for the Make_Name's and also some makes do not give model names. So it is linking the tables, but not correctly.

FIXED!

Okay I have fixed it, but does anyone know how to get it to display the Make_Name in alphabetical order and then Model_Name also in alphabetical order once a make name is clicked? Also, remove duplicate model_name's and show one of each instead ?

Also, how do I get the value from Model_Name, once clicked on, to work with my search:

Right now I have to search by typing, how do I get the clicked value's string (Model_Name) to be searched?

```<code>   [HttpPost]
    public ActionResult Search(string Location)
    {
        GoogleMapEntities GE = new GoogleMapEntities();

        var GetVeh = db.GetMapSearch().Where(x =>
        x.Model_Name.StartsWith(Location)).ToList();

        return Json(GetVeh, JsonRequestBehavior.AllowGet);

    }
</code>```

答:
You can use a CascadeDropDownHelpers library to simplify you case a little bit ( disclaimer: I am the author ) :

1) install the nuget package.

2) add to your model SelectedModelId property:

```<code>public class MyPageViewModel{

    public string SelectedModelId {get;set;}

    // other properties...
}
</code>```

3) modify GetModById action to return a list of SelectListItems as json

```<code>public JsonResult GetModById(int MID)
{
    db.Configuration.ProxyCreationEnabled = false;
    return Json(db.Vehicle_Model.Where(p => p.Model_ID == MID)
          .Select(p=>  new SelectListItem {Text = p.Model_Name, Value = p.Model_ID.ToString()}).ToList(),
    JsonRequestBehavior.AllowGet);
}
</code>```

4) modify the view (no script additional scrips required):

```<code>@model GoogleMap.Models.MyPageViewModel

@Html.DropDownListFor(p => p.SelectedMake_Id, ViewBag.Vehicle_Make as SelectList, "Select Vehicle Make", new { id = "ContID" })

@Html.CascadingDropDownListFor(
  expression: m => m.SelectedModelId,
  triggeredByPropertyWithId: "ContID",  //Parent property that trigers dropdown data loading
  url: Url.Action("GetModById", "Map"),  //Url of action that returns dropdown data
  ajaxActionParamName: "MID", //Parameter name for the selected parent value that url action receives
  optionLabel: "Please select a Model", // Option label
  disabledWhenParentNotSelected: true, //If true, disables dropdown until parent dropdown is selected
  htmlAttributes: new { @class = "form-control" })
</code>```

You can find additional usage examples here

Title: Drop Down List Giving Incorrect Values

Body:
I have followed the following tutorial for my project:

https://www.youtube.com/watch?v=h_ViuyVs4AE

The issue that I have is that when I click an item in the first drop down box, it does not give the correct values in the second box, it only gives one value and it is incorrect. It should display all the Model_Name's(Vehicle_Model table) that are for each Make_Name(Vehicle_Make table).

Index.cshtml code:

@model GoogleMap.Models.MyPageViewModel

@Html.DropDownListFor(p => p.SelectedMake_Id, ViewBag.Vehicle_Make as SelectList, "Select Vehicle Make", new { id = "ContID" })

MapController.cs code:

public class MapController : Controller
{
    private GoogleMapEntities db = new GoogleMapEntities();
    //Get the select ID???
    int SelectedMake_Id = 0;

    // GET: Map
    public ActionResult Index()
    {
        GoogleMapEntities GE = new GoogleMapEntities();
        List<Vehicle_Details> vehList = db.Vehicle_Details.ToList();

        GoogleMapViewModel GMviewmodel = new GoogleMapViewModel();
        List<GoogleMapViewModel> GMviewmodelList = new List<GoogleMapViewModel>();

        //Populate the ViewModel
        MyPageViewModel vm = new Models.MyPageViewModel();
        vm.GoogleMapViewModelList = GMviewmodelList;
        vm.SelectedMake_Id = SelectedMake_Id;

        ViewBag.Vehicle_Make = new SelectList(db.Vehicle_Make, "Make_ID", "Make_Name");

        return View(vm);
    }

    public JsonResult GetModById(int MID)
    {
        db.Configuration.ProxyCreationEnabled = false;
        return Json(db.Vehicle_Model.Where(p => p.Model_ID == MID), JsonRequestBehavior.AllowGet);
    }

    [HttpPost]
    public ActionResult Search(string Location)
    {
        GoogleMapEntities GE = new GoogleMapEntities();
        ////SELECT Make_Name DATA FROM DB1
        // var result = GE.Vehicle_Model.Where(x => x.Model_Name.StartsWith(Location)).ToList();
        var GetVeh = db.GetMapSearch().Where(x => x.Model_Name.StartsWith(Location)).ToList();

        return Json(GetVeh, JsonRequestBehavior.AllowGet);
    }
}

Vehicle_Make has Make_ID (pk) and Make_Name.

Vehicle_Model has Model_ID (pk) and Model_Name.

Vehicle_Details has Vehicle_ID (pk), Model_ID (fk), Make_ID (fk).

So what needs to happen is when I click a vehicle name(Make_Name), it must display all of it's Model_Name's in the second drop down list.

EDIT:
I have made a proc called DropDL which has the query that will display the Model name's with their Model_ID's and Make_ID's.

Query in proc:

SELECT          Vehicle_Model.Model_Name, Vehicle_Details.Model_ID,
                Vehicle_Details.Make_ID
FROM            Vehicle_Make INNER JOIN
                Vehicle_Details ON Vehicle_Make.Make_ID =
                Vehicle_Details.Make_ID INNER JOIN
                Vehicle_Model ON Vehicle_Details.Model_ID =
                Vehicle_Model.Model_ID

The procedure that I have made(GetMapSearch) which linked 4 tables tables for something else, where it linked all of those tables using ID's and getting specific values from each table, worked well, so I do not understand why I'd need to add Make_ID to the Vehicle_Model table unless the drop down list does require that.

Updated code:

    public JsonResult GetModById(int MID)
    {
        db.Configuration.ProxyCreationEnabled = false;
        return Json(db.DropDL().Where(p => p.Model_ID == MID)
        .Select(p => new SelectListItem { Text = p.Model_Name, Value =
        p.Model_ID.ToString() }).ToList(),
        JsonRequestBehavior.AllowGet);
    }

And Index.cshtml code:

@model GoogleMap.Models.MyPageViewModel

@using Mvc.CascadeDropDown

@Html.DropDownListFor(p => p.SelectedMake_Id, ViewBag.Vehicle_Make as
SelectList, "Select Vehicle Make", new { id = "ContID" })

@Html.CascadingDropDownListFor(
expression: m => m.SelectedModelId,
triggeredByPropertyWithId: "ContID",  //Parent property that trigers
dropdown data loading
url: Url.Action("GetModById", "Map"),  //Url of action that returns dropdown
data
ajaxActionParamName: "MID", //Parameter name for the selected parent value
that url action receives
optionLabel: "Please select a Model", // Option label
disabledWhenParentNotSelected: true, //If true, disables dropdown until
parent dropdown is selected
htmlAttributes: new { @class = "form-control" })

Also, if I changed the ViewBag to use db.DropDL() instead of db.Vehicle_Make, it gets all of the makes but it brings all of the makes up multiple times.

After making the proc, I am still getting one or two Model_Name's for the Make_Name's and also some makes do not give model names. So it is linking the tables, but not correctly.

FIXED!

Okay I have fixed it, but does anyone know how to get it to display the Make_Name in alphabetical order and then Model_Name also in alphabetical order once a make name is clicked? Also, remove duplicate model_name's and show one of each instead ?

Also, how do I get the value from Model_Name, once clicked on, to work with my search:

Right now I have to search by typing, how do I get the clicked value's string (Model_Name) to be searched?

   [HttpPost]
    public ActionResult Search(string Location)
    {
        GoogleMapEntities GE = new GoogleMapEntities();

        var GetVeh = db.GetMapSearch().Where(x =>
        x.Model_Name.StartsWith(Location)).ToList();

        return Json(GetVeh, JsonRequestBehavior.AllowGet);

    }

Body:
You can use a CascadeDropDownHelpers library to simplify you case a little bit ( disclaimer: I am the author ) :

1) install the nuget package.

2) add to your model SelectedModelId property:

public class MyPageViewModel{

    public string SelectedModelId {get;set;}

    // other properties...
}

3) modify GetModById action to return a list of SelectListItems as json

public JsonResult GetModById(int MID)
{
    db.Configuration.ProxyCreationEnabled = false;
    return Json(db.Vehicle_Model.Where(p => p.Model_ID == MID)
          .Select(p=>  new SelectListItem {Text = p.Model_Name, Value = p.Model_ID.ToString()}).ToList(),
    JsonRequestBehavior.AllowGet);
}

4) modify the view (no script additional scrips required):

@model GoogleMap.Models.MyPageViewModel

@Html.DropDownListFor(p => p.SelectedMake_Id, ViewBag.Vehicle_Make as SelectList, "Select Vehicle Make", new { id = "ContID" })

@Html.CascadingDropDownListFor(
  expression: m => m.SelectedModelId,
  triggeredByPropertyWithId: "ContID",  //Parent property that trigers dropdown data loading
  url: Url.Action("GetModById", "Map"),  //Url of action that returns dropdown data
  ajaxActionParamName: "MID", //Parameter name for the selected parent value that url action receives
  optionLabel: "Please select a Model", // Option label
  disabledWhenParentNotSelected: true, //If true, disables dropdown until parent dropdown is selected
  htmlAttributes: new { @class = "form-control" })

You can find additional usage examples here


问:
Binding XAML to Dictionary
Consider the following code:

```<code>public class Person {
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
}

public class HealthInfo {
public int BMI { get; set; }
public int HeartRate { get; set; }
public string DietPlan { get; set; }
}

Dictionary<Person, HealthInfo> myPersonInfo = new Dictionary<Person, HealthInfo>();

myPersonInfo.Add( new Person { Id = 1, Name = "Name1", Surname = "Surname1" }, new HealthInfo { BMI = 1, DietPlan = "Banting", HeartRate = 20 } );
myPersonInfo.Add( new Person { Id = 1, Name = "Name2", Surname = "Surname2" }, new HealthInfo { BMI = 1, DietPlan = "Banting", HeartRate = 20 } );
myPersonInfo.Add( new Person { Id = 1, Name = "Name3", Surname = "Surname3" }, new HealthInfo { BMI = 1, DietPlan = "Banting", HeartRate = 20 } );
myPersonInfo.Add( new Person { Id = 1, Name = "Name4", Surname = "Surname4" }, new HealthInfo { BMI = 1, DietPlan = "Banting", HeartRate = 20 } );
</code>```

I am trying to bind to this Dictionary(myPersonInfo ) from my xaml
For each person a tab gets created, where the tab Header will be the name of the person and then the content of that tab will display the HealtInfo.

I having dificulties binding to this dictionary in my XAML

I have the following:

```<code><TabControl ItemsSource="{Binding myPersonInfo.Keys}" SelectedIndex="0">
                <TabControl.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Path=Name}"/>
                    </DataTemplate>
                </TabControl.ItemTemplate>
                <TabControl.ContentTemplate>
                   <DataTemplate>
                       <TextBlock Text="{Binding Path=Key.Value.BMI}"/>
                   </DataTemplate>
                </TabControl.ContentTemplate>
</TabControl>
</code>```

How do I use the properties of the Key(Person) for the ItemTemplate
and
How do I use the properties of the Value(HealtInfo) for the ContentTemplate of the current Key?

答:
Create "aggregation" class and use it in ObservableCollection which nicely supported by data-binding

```<code> public class PersonHealthInfo
 {
     public Person Person {get; set; }
     public HealthInfo HealthInfo {get; set; }
 }

ObservableCollection<PersonHealthInfo> persons = new ObservableCollection<PersonHealthInfo>();

var person1 = new PersonHealthInfo
{
    Person = new Person { Id = 1, Name = "Name1", Surname = "Surname1" },
    HealthInfo = new HealthInfo { BMI = 1, DietPlan = "Banting", HeartRate = 20 }
}

persons.Add(person1);
</code>```

Title: Binding XAML to Dictionary

Body:
Consider the following code:

public class Person {
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
}

public class HealthInfo {
public int BMI { get; set; }
public int HeartRate { get; set; }
public string DietPlan { get; set; }
}

Dictionary<Person, HealthInfo> myPersonInfo = new Dictionary<Person, HealthInfo>();

myPersonInfo.Add( new Person { Id = 1, Name = "Name1", Surname = "Surname1" }, new HealthInfo { BMI = 1, DietPlan = "Banting", HeartRate = 20 } );
myPersonInfo.Add( new Person { Id = 1, Name = "Name2", Surname = "Surname2" }, new HealthInfo { BMI = 1, DietPlan = "Banting", HeartRate = 20 } );
myPersonInfo.Add( new Person { Id = 1, Name = "Name3", Surname = "Surname3" }, new HealthInfo { BMI = 1, DietPlan = "Banting", HeartRate = 20 } );
myPersonInfo.Add( new Person { Id = 1, Name = "Name4", Surname = "Surname4" }, new HealthInfo { BMI = 1, DietPlan = "Banting", HeartRate = 20 } );

I am trying to bind to this Dictionary(myPersonInfo ) from my xaml
For each person a tab gets created, where the tab Header will be the name of the person and then the content of that tab will display the HealtInfo.

I having dificulties binding to this dictionary in my XAML

I have the following:

<TabControl ItemsSource="{Binding myPersonInfo.Keys}" SelectedIndex="0">
                <TabControl.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Path=Name}"/>
                    </DataTemplate>
                </TabControl.ItemTemplate>
                <TabControl.ContentTemplate>
                   <DataTemplate>
                       <TextBlock Text="{Binding Path=Key.Value.BMI}"/>
                   </DataTemplate>
                </TabControl.ContentTemplate>
</TabControl>

How do I use the properties of the Key(Person) for the ItemTemplate
and
How do I use the properties of the Value(HealtInfo) for the ContentTemplate of the current Key?

Body:
Create "aggregation" class and use it in ObservableCollection which nicely supported by data-binding

 public class PersonHealthInfo
 {
     public Person Person {get; set; }
     public HealthInfo HealthInfo {get; set; }
 }

ObservableCollection<PersonHealthInfo> persons = new ObservableCollection<PersonHealthInfo>();

var person1 = new PersonHealthInfo
{
    Person = new Person { Id = 1, Name = "Name1", Surname = "Surname1" },
    HealthInfo = new HealthInfo { BMI = 1, DietPlan = "Banting", HeartRate = 20 }
}

persons.Add(person1);


问:
How can I return the range spreadsheet in the same form as in the that it is become row by row
I'm a beginner in programming.
I do a query to the spreadsheet in cell A2, then I filter data according to request and receive desired range “I1:L16”.Then I return the data to the tablet. Everything is fine back on the tablet,but it is uncomfortable to read, no line breaks!
Please tell me how can I return the range "I1:L16" in the same form as in the spreadsheet that it is became row by row .

My script

```<code>function doGet(e)
{
  var sheet = SpreadsheetApp.openById("1UBKi7VDo1aJjn6IwGMKvlxy4Jz9d9jVdY79zpOrkQP8");
  sheet.getRange("A2").setValue(e.parameter.p1) ;
  var n= sheet.getRange("I1:L16").getValues();
  return ContentService.createTextOutput(n);
}
</code>```

Spreadsheet
https://docs.google.com/spreadsheets/d/1UBKi7VDo1aJjn6IwGMKvlxy4Jz9d9jVdY79zpOrkQP8/edit?usp=sharing

URL Web applications: sample query
https://script.google.com/macros/s/AKfycbyHu7d5djciltlG-micI6O-cQheC6kN7yWKkevm5KwGCJiKROZB/exec?p1=1234567891118

Best regards, Alexander.

答:
You can do something like this:

```<code>function doGet(e)
{
  var sheet = SpreadsheetApp.openById("1UBKi7VDo1aJjn6IwGMKvlxy4Jz9d9jVdY79zpOrkQP8");
  sheet.getRange("A2").setValue(e.parameter.p1) ;
  var n= sheet.getRange("I1:L16").getValues();
  var retStr =""
  for(var i = 0 ; i< n.length ; i++){
   retStr += n[i].join("\t") +"\n" //Insert a tab between each element and newline at each row
  }
  return ContentService.createTextOutput(retStr);
}
</code>```

Edit: Alternative/Robust option

The better option is to service a Html content, that way you can make use of Html tag to improve presentation of your data.
In the below data I am assuming you want to highlight row 6, you do that using css element to make the text red and bold.
Code:

```<code>function doGet(e)
    {
      var sheet = SpreadsheetApp.openById("1UBKi7VDo1aJjn6IwGMKvlxy4Jz9d9jVdY79zpOrkQP8");
      sheet.getRange("A2").setValue(e.parameter.p1) ;
      var n= sheet.getRange("I1:L16").getValues();
      var retStr ="<style> .tcol { font-weight: bold; color : red; } </style> <table>"
      for(var i = 0 ; i< n.length ; i++){
       if ( i != 5) { //I assuming row 6 is what you want to highlight
        retStr +="<tr><td>"+ n[i].join("</td><td>") +"</td></tr>"
       } else {
        retStr +="<tr><td class = 'tcol'>" + n[i].join("</td><td class = 'tcol'>") +"</td></div></tr>"
       }

      }
      retStr += "</table>"
      return HtmlService.createHtmlOutput(retStr)
     }
</code>```

Hope that helps!

Body:
I'm a beginner in programming.
I do a query to the spreadsheet in cell A2, then I filter data according to request and receive desired range “I1:L16”.Then I return the data to the tablet. Everything is fine back on the tablet,but it is uncomfortable to read, no line breaks!
Please tell me how can I return the range "I1:L16" in the same form as in the spreadsheet that it is became row by row .

My script

function doGet(e)
{
  var sheet = SpreadsheetApp.openById("1UBKi7VDo1aJjn6IwGMKvlxy4Jz9d9jVdY79zpOrkQP8");
  sheet.getRange("A2").setValue(e.parameter.p1) ;
  var n= sheet.getRange("I1:L16").getValues();
  return ContentService.createTextOutput(n);
}

Spreadsheet
https://docs.google.com/spreadsheets/d/1UBKi7VDo1aJjn6IwGMKvlxy4Jz9d9jVdY79zpOrkQP8/edit?usp=sharing

URL Web applications: sample query
https://script.google.com/macros/s/AKfycbyHu7d5djciltlG-micI6O-cQheC6kN7yWKkevm5KwGCJiKROZB/exec?p1=1234567891118

Best regards, Alexander.

Body:
You can do something like this:

function doGet(e)
{
  var sheet = SpreadsheetApp.openById("1UBKi7VDo1aJjn6IwGMKvlxy4Jz9d9jVdY79zpOrkQP8");
  sheet.getRange("A2").setValue(e.parameter.p1) ;
  var n= sheet.getRange("I1:L16").getValues();
  var retStr =""
  for(var i = 0 ; i< n.length ; i++){
   retStr += n[i].join("\t") +"\n" //Insert a tab between each element and newline at each row
  }
  return ContentService.createTextOutput(retStr);
}

Edit: Alternative/Robust option

The better option is to service a Html content, that way you can make use of Html tag to improve presentation of your data.
In the below data I am assuming you want to highlight row 6, you do that using css element to make the text red and bold.
Code:

function doGet(e)
    {
      var sheet = SpreadsheetApp.openById("1UBKi7VDo1aJjn6IwGMKvlxy4Jz9d9jVdY79zpOrkQP8");
      sheet.getRange("A2").setValue(e.parameter.p1) ;
      var n= sheet.getRange("I1:L16").getValues();
      var retStr ="<style> .tcol { font-weight: bold; color : red; } </style> <table>"
      for(var i = 0 ; i< n.length ; i++){
       if ( i != 5) { //I assuming row 6 is what you want to highlight
        retStr +="<tr><td>"+ n[i].join("</td><td>") +"</td></tr>"
       } else {
        retStr +="<tr><td class = 'tcol'>" + n[i].join("</td><td class = 'tcol'>") +"</td></div></tr>"
       }

      }
      retStr += "</table>"
      return HtmlService.createHtmlOutput(retStr)
     }

Hope that helps!


问:
Multiple Custom UIPickerViews in the same UIView in swift
Im trying to have two different pickerViews on the same viewController and let them represent different data. I have tried a different ways to do this, but both picker views showing same Data, but can't put it all together. Any help would be awesome!

here is my code:

```<code> @IBOutlet weak var Eventtype: UITextField!

    let pickerView = UIPickerView()

    var Eventstype = ["Birthday" , "Marriege" , "Get together", "Conference"]

    @IBOutlet weak var datepickertxt: UITextField!

    var datepicker = UIDatePicker()

    @IBOutlet weak var Duration: UITextField!
     let duration = UIPickerView()

    var Durations = ["6-8","1-5","7-9","10-12"]

    override func viewDidLoad() {
        super.viewDidLoad()

        createDatePicker()
        pickerView.delegate = self
        pickerView.dataSource = self
        duration.delegate = self
        duration.dataSource = self
        Eventtype.inputView = pickerView
        Duration.inputView = duration
        // Do any additional setup after loading the view.
    }
    ////For Event Picker view

     func numberOfComponents(in pickerView: UIPickerView) -> Int {

        return 1

    }

     func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

        if (pickerView.tag == 0) {
            //pickerView1
            return Eventstype.count
        } else if (duration.tag == 1){
            //pickerView2
            return Durations.count
        }
        return 1
        //return DurationTxt.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if (pickerView.tag == 0) {

            return Eventstype[row]
        } else if (duration.tag == 1){

           return Durations[row]
        }

        return ""
    }
        //return DurationTxt[row]

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        if (pickerView.tag == 0) {
            Eventtype.text = Eventstype[row]
            self.view.endEditing(false)
        }else if (duration.tag == 1){
            Duration.text = Durations[row]
            self.view.endEditing(true)

        }

    }
</code>```

答:
```<code> @IBOutlet weak var Eventtype: UITextField!

    let pickerView = UIPickerView()

    var Eventstype = ["Birthday" , "Marriege" , "Get together", "Conference"]

    @IBOutlet weak var datepickertxt: UITextField!

    var datepicker = UIDatePicker()

    @IBOutlet weak var Duration: UITextField!
     let duration = UIPickerView()

    var Durations = ["6-8","1-5","7-9","10-12"]

    override func viewDidLoad() {
        super.viewDidLoad()

        createDatePicker()
        pickerView.delegate = self
        pickerView.dataSource = self
        duration.delegate = self
        duration.dataSource = self
        Eventtype.inputView = pickerView
        Duration.inputView = duration
        pickerView.tag = 0
        duration.tag = 1
        // Do any additional setup after loading the view.
    }
    ////For Event Picker view

     func numberOfComponents(in pickerView: UIPickerView) -> Int {

        return 1

    }

     func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

        if (pickerView.tag == 0) {
            //pickerView1
            return Eventstype.count
        } else if (duration.tag == 1){
            //pickerView2
            return Durations.count
        }
        return 1
        //return DurationTxt.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if (pickerView.tag == 0) {

            return Eventstype[row]
        } else if (duration.tag == 1){

           return Durations[row]
        }

        return ""
    }
        //return DurationTxt[row]

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        if (pickerView.tag == 0) {
            Eventtype.text = Eventstype[row]
            self.view.endEditing(false)
        }else if (duration.tag == 1){
            Duration.text = Durations[row]
            self.view.endEditing(true)

        }

    }
</code>```

This is done by tag or else yo can check in delegate like

```<code>if pickerView == duration
</code>```

Body:
Im trying to have two different pickerViews on the same viewController and let them represent different data. I have tried a different ways to do this, but both picker views showing same Data, but can't put it all together. Any help would be awesome!

here is my code:

 @IBOutlet weak var Eventtype: UITextField!

    let pickerView = UIPickerView()

    var Eventstype = ["Birthday" , "Marriege" , "Get together", "Conference"]

    @IBOutlet weak var datepickertxt: UITextField!

    var datepicker = UIDatePicker()

    @IBOutlet weak var Duration: UITextField!
     let duration = UIPickerView()

    var Durations = ["6-8","1-5","7-9","10-12"]

    override func viewDidLoad() {
        super.viewDidLoad()

        createDatePicker()
        pickerView.delegate = self
        pickerView.dataSource = self
        duration.delegate = self
        duration.dataSource = self
        Eventtype.inputView = pickerView
        Duration.inputView = duration
        // Do any additional setup after loading the view.
    }
    ////For Event Picker view

     func numberOfComponents(in pickerView: UIPickerView) -> Int {

        return 1

    }

     func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

        if (pickerView.tag == 0) {
            //pickerView1
            return Eventstype.count
        } else if (duration.tag == 1){
            //pickerView2
            return Durations.count
        }
        return 1
        //return DurationTxt.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if (pickerView.tag == 0) {

            return Eventstype[row]
        } else if (duration.tag == 1){

           return Durations[row]
        }

        return ""
    }
        //return DurationTxt[row]

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        if (pickerView.tag == 0) {
            Eventtype.text = Eventstype[row]
            self.view.endEditing(false)
        }else if (duration.tag == 1){
            Duration.text = Durations[row]
            self.view.endEditing(true)

        }

    }

Body:
 @IBOutlet weak var Eventtype: UITextField!

    let pickerView = UIPickerView()

    var Eventstype = ["Birthday" , "Marriege" , "Get together", "Conference"]

    @IBOutlet weak var datepickertxt: UITextField!

    var datepicker = UIDatePicker()

    @IBOutlet weak var Duration: UITextField!
     let duration = UIPickerView()

    var Durations = ["6-8","1-5","7-9","10-12"]

    override func viewDidLoad() {
        super.viewDidLoad()

        createDatePicker()
        pickerView.delegate = self
        pickerView.dataSource = self
        duration.delegate = self
        duration.dataSource = self
        Eventtype.inputView = pickerView
        Duration.inputView = duration
        pickerView.tag = 0
        duration.tag = 1
        // Do any additional setup after loading the view.
    }
    ////For Event Picker view

     func numberOfComponents(in pickerView: UIPickerView) -> Int {

        return 1

    }

     func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

        if (pickerView.tag == 0) {
            //pickerView1
            return Eventstype.count
        } else if (duration.tag == 1){
            //pickerView2
            return Durations.count
        }
        return 1
        //return DurationTxt.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if (pickerView.tag == 0) {

            return Eventstype[row]
        } else if (duration.tag == 1){

           return Durations[row]
        }

        return ""
    }
        //return DurationTxt[row]

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        if (pickerView.tag == 0) {
            Eventtype.text = Eventstype[row]
            self.view.endEditing(false)
        }else if (duration.tag == 1){
            Duration.text = Durations[row]
            self.view.endEditing(true)

        }

    }

This is done by tag or else yo can check in delegate like

if pickerView == duration


问:
How do you Change the mobile nav menu background only
I have a site in wordpress i would like to change its mobile menu background. I   have tried so many times in the css but seem not work.
Each menu appears very fine on the main site and the mobile view too. I want  to have different background for the menu on both the mobile and desktop view. PLease find below the html code and the css code.

```<code>    <!-- Start Header -->
        <nav class="navbar navbar-inverse navbar-fixed-top">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
              <!-- Your Logo -->

                    <a href="http://www.rgfghana.org/">
                <img src="http://www.rgfghana.org/wp-content/themes/idas/image/logo.png" alt="RGF - Remittance Grant Facility" id="logo"/>
            </a>
            </div>
            <div id="navbar" class="navbar-collapse collapse" style="font-size:17px; float:right">
                  <div id="mega-menu-wrap-primary" class="mega-menu-wrap"><div class="mega-menu-toggle" tabindex="0"><div class='mega-toggle-block mega-menu-toggle-block mega-toggle-block-right mega-toggle-block-1' id='mega-toggle-block-1'></div></div><ul id="mega-menu-primary" class="mega-menu mega-menu-horizontal mega-no-js" data-event="hover" data-effect="fade_up" data-effect-speed="200" data-second-click="go" data-document-click="collapse" data-vertical-behaviour="standard" data-breakpoint="600" data-unbind="true"><li class='mega-menu-item mega-menu-item-type-custom mega-menu-item-object-custom mega-menu-item-home mega-align-bottom-left mega-menu-flyout mega-menu-item-13' id='mega-menu-item-13'><a class="mega-menu-link" href="http://www.rgfghana.org/" tabindex="0">Home</a></li><li class='mega-menu-item mega-menu-item-type-custom mega-menu-item-object-custom mega-current-menu-ancestor mega-current-menu-parent mega-menu-item-has-children mega-align-bottom-left mega-menu-flyout mega-menu-item-364' id='mega-menu-item-364'><a class="mega-menu-link" href="#" aria-haspopup="true" tabindex="0">About Us</a>

    </li><li class='mega-menu-item mega-menu-item-type-custom mega-menu-item-object-custom mega-menu-item-has-children mega-align-bottom-left mega-menu-flyout mega-menu-item-369' id='mega-menu-item-369'><a class="mega-menu-link" href="#" aria-haspopup="true" tabindex="0">Our Objectives</a>
    <ul class="mega-sub-menu">
    <li class='mega-menu-item mega-menu-item-type-post_type mega-menu-item-object-page mega-menu-item-193' id='mega-menu-item-193'><a class="mega-menu-link" href="http://www.rgfghana.org/our-goals/">Objectives</a></li><li class='mega-menu-item mega-menu-item-type-post_type mega-menu-item-object-page mega-menu-item-396' id='mega-menu-item-396'><a class="mega-menu-link" href="http://www.rgfghana.org/expected-impact/">Expected Impact</a></li></ul>
    </div>
            </div>
             </div>
            </nav>

        <!-- End Header -->
</code>```

the css code looks like this;

```<code>    .header {
        box-shadow: 0 0 7px rgba(0, 255, 0, 0.3);
        -webkit-box-shadow: 0 0 7px rgba(0,0,0,.05);
        -moz-box-shadow: 0 0 7px rgba(0,0,0,.05);
            -ms-box-shadow: 0 0 7px rgba(0,0,0,.05);
            -o-box-shadow: 0 0 7px rgba(0,0,0,.05);
            background:#fff;
            position:fixed;
            top:0px;
            left:0px;
            width:100%;
            z-index:9999;

    }

      position: absolute;
      background:#605f5e;
      background: url('image/image-back.jpg') ;
      background-size: 100% 100%;
      z-index: -107;
    }
    @media only screen and (min-width: 600px) {
        .col-s-1 {width: 8.33%;}
        .col-s-2 {width: 16.66%;}
        .col-s-3 {width: 25%;}
        .col-s-4 {width: 33.33%;}
        .col-s-5 {width: 41.66%;}
        .col-s-6 {width: 50%;}
        .col-s-7 {width: 58.33%;}
        .col-s-8 {width: 66.66%;}
        .col-s-9 {width: 75%;}
        .col-s-10 {width: 83.33%;}
        .col-s-11 {width: 91.66%;}
        .col-s-12 {width: 100%;}
    background: #428bca;
    }
    @media only screen and (min-width: 768px) {
        .col-1 {width: 8.33%;}
        .col-2 {width: 16.66%;}
        .col-3 {width: 25%;}
        .col-4 {width: 33.33%;}
        .col-5 {width: 41.66%;}
        .col-6 {width: 50%;}
        .col-7 {width: 58.33%;}
        .col-8 {width: 66.66%;}
        .col-9 {width: 75%;}
        .col-10 {width: 83.33%;}
        .col-11 {width: 91.66%;}
        .col-12 {width: 100%;}
       background: #428bca;
    }
    @media (max-width: 640px) {
        .mobile-nav .show-nav {
            display: block;
            padding: 1em 40px;
            color: #fff;
            background: #000;
            cursor: pointer;
            border-bottom: 1px solid #000;
        }
    }

    /*-------------------------------------------------Navbar------------------------------------------------------------------------------------------------------------------------*/
    .navbar-inverse .navbar-brand {
        padding: 30px 15px;
        margin-right: 30px;
        color: inherit;
    }
    .navbar-inverse .navbar-brand:hover, .navbar-inverse .navbar-brand:focus {
        color: #000;
    }
    .navbar-inverse {
                background-color: rgba(255, 255, 255, .9);

        border: none;
    }
    .navbar-right button {
        margin: 23px 0;
    }
    .navbar-nav>li>a {
        padding: 30px 0;
        margin: 0 15px;
    }
    .navbar-inverse .navbar-nav>li>a {
        color: inherit;
        text-transform: uppercase;
        font-size: 12px;
    }
    .navbar-inverse .navbar-nav>li>a:hover, .navbar-inverse .navbar-nav>li>a:focus,
    .navbar-inverse .navbar-nav>.active>a, .navbar-inverse .navbar-nav>.active>a:hover, .navbar-inverse .navbar-nav>.active>a:focus {
        background-color: transparent;
        background-color: rgba(255, 255, 255, 0);
        color: #3498db;
    }
    .header-button {
        margin-left: 15px;
    }
    .navbar-brand
    {
        color:#fff;
        padding-top:10px;
        font-size:1.5em;
    }
    .navbar-nav .active .dropdown-menu{
      background : white;
    }
</code>```

答:
This will need a little bit of debugging via DOM Inspector. Please make sure that the styles are at least appearing in the inspector even if not taking effect. (Pls see: https://www.youtube.com/watch?v=v9RhfT7JxAo )

Next try to force the background color using the !important declaration. Please see: What does !important in CSS mean?

Body:
I have a site in wordpress i would like to change its mobile menu background. I   have tried so many times in the css but seem not work.
Each menu appears very fine on the main site and the mobile view too. I want  to have different background for the menu on both the mobile and desktop view. PLease find below the html code and the css code.

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            Toggle navigation

          </button>

Home

About Us

Our Objectives

Objectives

Expected Impact

the css code looks like this;

    .header {
        box-shadow: 0 0 7px rgba(0, 255, 0, 0.3);
        -webkit-box-shadow: 0 0 7px rgba(0,0,0,.05);
        -moz-box-shadow: 0 0 7px rgba(0,0,0,.05);
            -ms-box-shadow: 0 0 7px rgba(0,0,0,.05);
            -o-box-shadow: 0 0 7px rgba(0,0,0,.05);
            background:#fff;
            position:fixed;
            top:0px;
            left:0px;
            width:100%;
            z-index:9999;

    }

      position: absolute;
      background:#605f5e;
      background: url('image/image-back.jpg') ;
      background-size: 100% 100%;
      z-index: -107;
    }
    @media only screen and (min-width: 600px) {
        .col-s-1 {width: 8.33%;}
        .col-s-2 {width: 16.66%;}
        .col-s-3 {width: 25%;}
        .col-s-4 {width: 33.33%;}
        .col-s-5 {width: 41.66%;}
        .col-s-6 {width: 50%;}
        .col-s-7 {width: 58.33%;}
        .col-s-8 {width: 66.66%;}
        .col-s-9 {width: 75%;}
        .col-s-10 {width: 83.33%;}
        .col-s-11 {width: 91.66%;}
        .col-s-12 {width: 100%;}
    background: #428bca;
    }
    @media only screen and (min-width: 768px) {
        .col-1 {width: 8.33%;}
        .col-2 {width: 16.66%;}
        .col-3 {width: 25%;}
        .col-4 {width: 33.33%;}
        .col-5 {width: 41.66%;}
        .col-6 {width: 50%;}
        .col-7 {width: 58.33%;}
        .col-8 {width: 66.66%;}
        .col-9 {width: 75%;}
        .col-10 {width: 83.33%;}
        .col-11 {width: 91.66%;}
        .col-12 {width: 100%;}
       background: #428bca;
    }
    @media (max-width: 640px) {
        .mobile-nav .show-nav {
            display: block;
            padding: 1em 40px;
            color: #fff;
            background: #000;
            cursor: pointer;
            border-bottom: 1px solid #000;
        }
    }

    /*-------------------------------------------------Navbar------------------------------------------------------------------------------------------------------------------------*/
    .navbar-inverse .navbar-brand {
        padding: 30px 15px;
        margin-right: 30px;
        color: inherit;
    }
    .navbar-inverse .navbar-brand:hover, .navbar-inverse .navbar-brand:focus {
        color: #000;
    }
    .navbar-inverse {
                background-color: rgba(255, 255, 255, .9);

        border: none;
    }
    .navbar-right button {
        margin: 23px 0;
    }
    .navbar-nav>li>a {
        padding: 30px 0;
        margin: 0 15px;
    }
    .navbar-inverse .navbar-nav>li>a {
        color: inherit;
        text-transform: uppercase;
        font-size: 12px;
    }
    .navbar-inverse .navbar-nav>li>a:hover, .navbar-inverse .navbar-nav>li>a:focus,
    .navbar-inverse .navbar-nav>.active>a, .navbar-inverse .navbar-nav>.active>a:hover, .navbar-inverse .navbar-nav>.active>a:focus {
        background-color: transparent;
        background-color: rgba(255, 255, 255, 0);
        color: #3498db;
    }
    .header-button {
        margin-left: 15px;
    }
    .navbar-brand
    {
        color:#fff;
        padding-top:10px;
        font-size:1.5em;
    }
    .navbar-nav .active .dropdown-menu{
      background : white;
    }


问:
Order by SQL timestamp
I have a timestamp field added to every of my records with an SQL timestamp, (yes, the format is actually TIMESTAMP). I want to display my records by date and time; can I just ORDER BY in an SQL statement?</p>

```<code>SELECT * FROM table ORDER BY timestamp DESC
</code>```

答:
Assuming its MySQL,

```<code>SELECT *
FROM randomTable
ORDER BY timestampfield DESC;
</code>```

is just perfect.

Title: Order by SQL timestamp

Body:
I have a timestamp field added to every of my records with an SQL timestamp, (yes, the format is actually TIMESTAMP). I want to display my records by date and time; can I just ORDER BY in an SQL statement?

SELECT * FROM table ORDER BY timestamp DESC

Body:
Assuming its MySQL,

SELECT *
FROM randomTable
ORDER BY timestampfield DESC;

is just perfect.


答:
R.color.red is an ID (which is also an int), but is not a color.

Use one of the following instead:

```<code>// If you're in an activity:
Button.setBackgroundColor(getResources().getColor(R.color.red));
// OR, if you're not:
Button.setBackgroundColor(Button.getContext().getResources().getColor(R.color.red));
</code>```

Or, alternatively:

```<code>Button.setBackgroundColor(Color.RED); // From android.graphics.Color
</code>```

Or, for more pro skills:

```<code>Button.setBackgroundColor(0xFFFF0000); // 0xAARRGGBB
</code>```

Title: How to set background color to button in table layout programatically?

Body:
I am making Tic Tac Toe game. And I have used buttons for tic tac toe board and set in table layout dynamically.
Problem is that, I can't set background property of the button.
My code is here.

TableLayout table = (TableLayout) findViewById(R.id.tableLayout1);
    table.removeAllViewsInLayout();

    int id = 0;

    for (int f = 0; f < board_size; f++) {
        TableRow tr = new TableRow(this);
        for (int c = 0; c < board_size; c++) {
            Button b = new Button(this);
            b.setId(id);
            b.setTextSize(15.0f);

       //below code assign color to whole table background
            //b.setBackground(Color.WHITE);
            b.setOnClickListener(this);
            id++;
            tr.addView(b, screenWidth / board_size, screenWidth / board_size);
        }
        table.addView(tr);
    }

Please guide me. Thanks in Advance.

Body:
R.color.red is an ID (which is also an int), but is not a color.

Use one of the following instead:

// If you're in an activity:
Button.setBackgroundColor(getResources().getColor(R.color.red));
// OR, if you're not:
Button.setBackgroundColor(Button.getContext().getResources().getColor(R.color.red));

Or, alternatively:

Button.setBackgroundColor(Color.RED); // From android.graphics.Color

Or, for more pro skills:

Button.setBackgroundColor(0xFFFF0000); // 0xAARRGGBB