问:
Storing column value types to an array
I want to refactor my code. I create a fix column so I always write "table.columns.Add(name, dataType) ...."´.

I want to keep it with a loop and store all these column informations into an two dimensional array.

The first value of this array is the column name, the second is the type of the column.

How can I store this type?

My current code:

```<code> object[,] tableColumns = { // Contains all column names + column dataType
            {"Predecessors", List<Process>},
            {"Successors", List<Process>},
            {"ProcessId", int},
            {"ProcessName", string},
            {"ProcessDuration", int},
            {"FAZ", int},
            {"SAZ", int},
            {"FEZ", int},
            {"SEZ", int},
            {"EntireBuffer", int},
            {"FreeBuffer", int},
            {"IsCritical", bool},
            {"IsStartProcess", bool},
            {"IsEndProcess", bool}
        };

        for (int i = 0; i < tableColumns.Length; i++) // create all these columns
        {
            ProcessTable.Columns.Add(tableColumns[i, 1].ToString(), tableColumns[i, 2] as Type);
        }
</code>```

So as you can see, the only thing missing here is the storing of the datatype in its correct way.

答:
```<code> var tableColumns = new Dictionary<string, Type>{ // Contains all column names + column dataType
        {"Predecessors", typeof( List<Process>)},
        {"Successors", typeof(List<Process>)},
        {"ProcessId", typeof(int)},
        {"ProcessName", typeof(string)},
        {"ProcessDuration", typeof(int)},
        {"FAZ", typeof(int)},
        {"SAZ", typeof(int)},
        {"FEZ", typeof(int)},
        {"SEZ", typeof(int)},
        {"EntireBuffer", typeof(int)},
        {"FreeBuffer", typeof(int)},
        {"IsCritical", typeof(bool)},
        {"IsStartProcess",  typeof(bool)},
        {"IsEndProcess",  typeof(bool)}
    };

  for (int i = 0; i < tableColumns.Length; i++) // create all these columns
  {
    ProcessTable.Columns.Add(tableColumns[i, 1].ToString(), tableColumns[i, 2]);
  }
</code>```

Title: Storing column value types to an array

Body:
I want to refactor my code. I create a fix column so I always write "table.columns.Add(name, dataType) ...."´.

I want to keep it with a loop and store all these column informations into an two dimensional array.

The first value of this array is the column name, the second is the type of the column.

How can I store this type?

My current code:

 object[,] tableColumns = { // Contains all column names + column dataType
            {"Predecessors", List<Process>},
            {"Successors", List<Process>},
            {"ProcessId", int},
            {"ProcessName", string},
            {"ProcessDuration", int},
            {"FAZ", int},
            {"SAZ", int},
            {"FEZ", int},
            {"SEZ", int},
            {"EntireBuffer", int},
            {"FreeBuffer", int},
            {"IsCritical", bool},
            {"IsStartProcess", bool},
            {"IsEndProcess", bool}
        };

        for (int i = 0; i < tableColumns.Length; i++) // create all these columns
        {
            ProcessTable.Columns.Add(tableColumns[i, 1].ToString(), tableColumns[i, 2] as Type);
        }

So as you can see, the only thing missing here is the storing of the datatype in its correct way.


来源: stackexchange

问:
How to store an item/image in a specific coordinate in Cordova/Ionic?
I am trying to make a simple Augment Reality app like pokemon go using Ionic, with a feature to view a pokemon appearing on top of a camera.

I made it work using a SDK called ezAR and my current output looks like this:

The problem here is that wherever I go or point the camera, the pokemon image is just static and what I wanted to do is to use a cordova plugin like Geolocation to fit my needs. I know how to use it but I don't know where to start.

The goal here that I want is to make the pokemon show at a specific coordinate. Is that possible with those plugins only? Any guide/help would be much appreciated.

答: This is enough to the client side. But you will need build a API that will be consumed by your app (client/server architecture). The app with geolocation plugin help will send to the server the user's position from time to time, then the server will check if the user is near enough to a registered point. If it's true,  the server will respond with the point's informations (pokemon, or anything)  and the app will start the camera and will render what you need, with the server passed information and the eZar's help.</p>

ContentLicense: CC BY-SA 3.0


问:
Angular2 Base64 sanitizing unsafe URL value
Response from my server looks like following:

```<code>[{"coreGoalId":1,"title":"Core goal 1","infrastructure":"Sample Infrastructure","audience":"People","subGoals":null,"benefits":[{"benefitId":1,"what":"string","coreGoalId":1}],"effects":null,"steps":null,"images":[{"imagelId":1,"base64":"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcU\nFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgo\nKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wgARCAIWAe4DASIA\nAhEBAxEB/8QAHAABAAIDAQEB"}]}]
</code>```

I am trying to display the base64 image returned in it.

In my component:

```<code>ngOnInit() {

    this.homeService.getGoals()
    .subscribe(
        goals => this.coreGoals = goals,
        error =>  this.errorMessage = <any>error);
}
</code>```

and then in template:

```<code><ul>
    <li *ngFor="let goal of coreGoals">
        {{goal.title}}
        <img [src]="'data:image/jpg;base64,'+goal.images[0].base64 | safeHtml" />
    </li>
</ul>
</code>```

Where safeHtml is a Pipe I created like following:

```<code>import { Pipe } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({name: 'safeHtml'})
export class SafeHtml {
  constructor(private sanitizer:DomSanitizer){}

  transform(html) {
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }
}
</code>```

This gives me Required a safe URL, got a HTML error. What is going wrong here? If I remove the pipe from  then it says unsafe url.

答:
You would need

```<code>bypassSecurityTrustResourceUrl(html);
</code>```

instead of

```<code>bypassSecurityTrustHtml(html);
</code>```

Body:
Response from my server looks like following:

[{"coreGoalId":1,"title":"Core goal 1","infrastructure":"Sample Infrastructure","audience":"People","subGoals":null,"benefits":[{"benefitId":1,"what":"string","coreGoalId":1}],"effects":null,"steps":null,"images":[{"imagelId":1,"base64":"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcU\nFhYaHSUfGhsjHBYWICwgIyYnKSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgo\nKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCj/wgARCAIWAe4DASIA\nAhEBAxEB/8QAHAABAAIDAQEB"}]}]

I am trying to display the base64 image returned in it.

In my component:

ngOnInit() {

    this.homeService.getGoals()
    .subscribe(
        goals => this.coreGoals = goals,
        error =>  this.errorMessage = <any>error);
}

and then in template:

        {{goal.title}}

Where safeHtml is a Pipe I created like following:

import { Pipe } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({name: 'safeHtml'})
export class SafeHtml {
  constructor(private sanitizer:DomSanitizer){}

  transform(html) {
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }
}

This gives me Required a safe URL, got a HTML error. What is going wrong here? If I remove the pipe from  then it says unsafe url.

Body:
You would need

bypassSecurityTrustResourceUrl(html);

instead of

bypassSecurityTrustHtml(html);


问:
Mvc Dynamic Menu Populating plain text
I have created the N'th level Dynamic Menu recursive method which creates a menu.

As seen in above picture the content is returned to ParialView named "_Menu.cshtml" and this Partial View file is empty.

and then there is a _LayoutPage.Cshtml

```<code>    <!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <div>
        <div>
            <input type="text" id="txtSearch" />
            <button id="btnSearch">Search</button>
         </div>
        <div id="Menu">
            @{Html.RenderAction("_Menu", "Home"); }
            @Html.Partial("_Menu")
        </div>
        <div>
            @RenderBody()
        </div>
    </div>
</body>
</html>
</code>```

it successfully puts the result into the browser but as a plain text as i mentioned above and can be seen below.

How can i make these act like links, not like a plaintext? Help will be appreciated. Thanks :)

答:
Though War resolved my query above. But i still want to answer for people for whom the above answer seem complex.
in most easiest possible way in MVC to populate Dynamic Navigation Menu from Database.

in Controller:

```<code>    public ActionResult Index()
{
    Menu menu_ = new Menu();
    ViewBag.Menu = menu_.getMenuList();
    return View();
}
</code>```

in _layoutpage.Cshtml

```<code>        <div id="Menu">
       @{ List<WebApplicationMVC.Core.Models.menu> All = ViewBag.Menu;}
        <ul>
            @foreach (var One in All.Where(m => m.ParentId == 0))
            {
                List<WebApplicationMVC.Core.Models.menu> Child = All.Where(m => One.id == m.ParentId).ToList();
                if (Child.Count > 0)
                {
                    if(One.ActionLink == "Yes")
                    {
                        <li>
                            @Html.ActionLink(One.Name, One.Action, One.Controller)
                            @SubMenu(One, All)
                        </li>
                    }
                    else
                    {
                        <li>
                            @One.Name;
                            @SubMenu(One, All)
                        </li>
                    }
                }
                else
                {
                    <li>@Html.ActionLink(One.Name, One.Action, One.Controller)</li>
                }
            }
        </ul>

        @helper SubMenu(WebApplicationMVC.Core.Models.menu Object, List<WebApplicationMVC.Core.Models.menu> List)
        {
        List<WebApplicationMVC.Core.Models.menu> subChilds = (from a in List where Object.id == a.ParentId select a).ToList();
        <ul>
            @foreach (var subOne in subChilds)
            {
                List<WebApplicationMVC.Core.Models.menu> InnerChilds = (from a in List where subOne.id == a.ParentId select a).ToList();
                if (InnerChilds.Count > 0)
                {
                    if (subOne.ActionLink == "Yes")
                    {
                        <li>
                            @Html.ActionLink(subOne.Name, subOne.Action, subOne.Controller)
                            @SubMenu(subOne, List)
                        </li>
                    }
                    else
                    {
                        <li>
                            @subOne.Name
                            @SubMenu(subOne, List)
                        </li>
                    }
                }
                else
                {
                    <li>@Html.ActionLink(subOne.Name, subOne.Action, subOne.Controller)</li>
                }
            }
        </ul>
        }
    </div>
</code>```

Title: Mvc Dynamic Menu Populating plain text

Body:
I have created the N'th level Dynamic Menu recursive method which creates a menu.

As seen in above picture the content is returned to ParialView named "_Menu.cshtml" and this Partial View file is empty.

and then there is a _LayoutPage.Cshtml

    <!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>

            <input type="text" id="txtSearch" />
            <button id="btnSearch">Search</button>

            @{Html.RenderAction("_Menu", "Home"); }
            @Html.Partial("_Menu")

            @RenderBody()

it successfully puts the result into the browser but as a plain text as i mentioned above and can be seen below.

How can i make these act like links, not like a plaintext? Help will be appreciated. Thanks :)

Body:
Though War resolved my query above. But i still want to answer for people for whom the above answer seem complex.
in most easiest possible way in MVC to populate Dynamic Navigation Menu from Database.

in Controller:

    public ActionResult Index()
{
    Menu menu_ = new Menu();
    ViewBag.Menu = menu_.getMenuList();
    return View();
}

in _layoutpage.Cshtml

        <div id="Menu">
       @{ List<WebApplicationMVC.Core.Models.menu> All = ViewBag.Menu;}
        <ul>
            @foreach (var One in All.Where(m => m.ParentId == 0))
            {
                List<WebApplicationMVC.Core.Models.menu> Child = All.Where(m => One.id == m.ParentId).ToList();
                if (Child.Count > 0)
                {
                    if(One.ActionLink == "Yes")
                    {
                        <li>
                            @Html.ActionLink(One.Name, One.Action, One.Controller)
                            @SubMenu(One, All)
                        </li>
                    }
                    else
                    {
                        <li>
                            @One.Name;
                            @SubMenu(One, All)
                        </li>
                    }
                }
                else
                {
                    <li>@Html.ActionLink(One.Name, One.Action, One.Controller)</li>
                }
            }
        </ul>

        @helper SubMenu(WebApplicationMVC.Core.Models.menu Object, List<WebApplicationMVC.Core.Models.menu> List)
        {
        List<WebApplicationMVC.Core.Models.menu> subChilds = (from a in List where Object.id == a.ParentId select a).ToList();
        <ul>
            @foreach (var subOne in subChilds)
            {
                List<WebApplicationMVC.Core.Models.menu> InnerChilds = (from a in List where subOne.id == a.ParentId select a).ToList();
                if (InnerChilds.Count > 0)
                {
                    if (subOne.ActionLink == "Yes")
                    {
                        <li>
                            @Html.ActionLink(subOne.Name, subOne.Action, subOne.Controller)
                            @SubMenu(subOne, List)
                        </li>
                    }
                    else
                    {
                        <li>
                            @subOne.Name
                            @SubMenu(subOne, List)
                        </li>
                    }
                }
                else
                {
                    <li>@Html.ActionLink(subOne.Name, subOne.Action, subOne.Controller)</li>
                }
            }
        </ul>
        }
    </div>


问:
Do i have to use _ID as a SQlite primary key? and does it have to be an INT? (Android Dev)
This is probably a silly question but i haven't been able to find the answer yet.

I want to use a TEXT column with my own unique names as the primary key in a table.
the little section of code to define this looks something like this in my project:

```<code>...blahblah..."CREATE TABLE " + CAT_BUD_TAB + " (" + CAT_ITEM_ID + "_ID TEXT PRIMARY KEY,    "...blahblah..
</code>```

Will this work as i intend? Or perhaps i need to use "AS ID"? I only ever see single tables with _ID as an autoincrementing integer in. Also this was intended to be a foreign key in another table but since i designed my database i've read more information and i'm not sure that'll really matter using android & SQLITE?

Thanks to the posters below but i'm a bit slow and not sure if i'm applying the info right, could you check?

So if i have a create statement like this:

```<code>"CREATE TABLE " + CAT_BUD_TAB + " (" + CAT_ITEM_ID + " TEXT PRIMARY KEY, " +
    IN_OUT + " TEXT, " + BUDGET_AMOUNT + " REAL, " + ACTUAL_AMOUNT_SPENT + " REAL, "
    + AMOUNT_STRAYED + " REAL, " + OVERBUDGET_TF + " INTEGER, " + AUTOSPEND_TF +
    " INTEGER);"
</code>```

Then have:
    db.execSQL("SELECT ID, ID AS CAT_ITEM_ID")

Can i then use them interchangeably? am i even anywhere near close? haha sorry i am trying!

答:
You can have anything you want as the primary key.

But if you for instance want to use a CursorAdapter that automatically shows items from a Cursor-query you need to have an integer column called _ID as this is used here.

But if this is not something you plan to use with your table, you can do what you want!

ContentLicense: CC BY-SA 2.5

Body:
This is probably a silly question but i haven't been able to find the answer yet.

I want to use a TEXT column with my own unique names as the primary key in a table.
the little section of code to define this looks something like this in my project:

...blahblah..."CREATE TABLE " + CAT_BUD_TAB + " (" + CAT_ITEM_ID + "_ID TEXT PRIMARY KEY,    "...blahblah..

Will this work as i intend? Or perhaps i need to use "AS ID"? I only ever see single tables with _ID as an autoincrementing integer in. Also this was intended to be a foreign key in another table but since i designed my database i've read more information and i'm not sure that'll really matter using android & SQLITE?

Thanks to the posters below but i'm a bit slow and not sure if i'm applying the info right, could you check?

So if i have a create statement like this:

"CREATE TABLE " + CAT_BUD_TAB + " (" + CAT_ITEM_ID + " TEXT PRIMARY KEY, " +
    IN_OUT + " TEXT, " + BUDGET_AMOUNT + " REAL, " + ACTUAL_AMOUNT_SPENT + " REAL, "
    + AMOUNT_STRAYED + " REAL, " + OVERBUDGET_TF + " INTEGER, " + AUTOSPEND_TF +
    " INTEGER);"

Then have:
    db.execSQL("SELECT ID, ID AS CAT_ITEM_ID")

Can i then use them interchangeably? am i even anywhere near close? haha sorry i am trying!


问:
HTML rendering model as string
This is a fork from another question.  I am passing a list into a partial view which is part of a main view.  However, when I view the page, I see:

```<code>System.Collections.Generic.List`1[...Models.OutcomeArea] List
</code>```

Now, the list is being rendered correctly, but I am not sure why the above line is showing in the html.

Index.cshtml:

```<code>@using (Html.BeginForm("Index", "Search", FormMethod.Get, new { @class = "form-inline" }))
{
    @Html.Action("_Checklist")
}
</code>```

_Checklist.cshtml:

```<code>@Model List<....Models.OutcomeArea>
<div class="row">
    <div class="col-md-4">
        <h4 class="text-center">Outcomes</h4>
        <p>
        @foreach (var list in Model)
        {
            <input type="checkbox" id="@list.ID" name="@list.ID" /> @list.Category <br />
        }
        </p>
    </div>
</div>
</code>```

SearchController:

```<code>public PartialViewResult _Checklist()
    {
        var outcomeAreas = db.OutcomeArea.Where(oa => oa.Category != "").GroupBy(oa => oa.Category).Select(oa => oa.FirstOrDefault());
        return PartialView("_Checklist", outcomeAreas.ToList());
    }
</code>```

答:
Nevermind, I have it working.  I needed to use lowercase @model for the _Checklist.cshtml.</p>

```<code>@model List<....Models.OutcomeArea>
</code>```

Title: HTML rendering model as string

Body:
This is a fork from another question.  I am passing a list into a partial view which is part of a main view.  However, when I view the page, I see:

System.Collections.Generic.List`1[...Models.OutcomeArea] List

Now, the list is being rendered correctly, but I am not sure why the above line is showing in the html.

Index.cshtml:

@using (Html.BeginForm("Index", "Search", FormMethod.Get, new { @class = "form-inline" }))
{
    @Html.Action("_Checklist")
}

_Checklist.cshtml:

@Model List<....Models.OutcomeArea>

Outcomes

        @foreach (var list in Model)
        {
            <input type="checkbox" id="@list.ID" name="@list.ID" /> @list.Category

        }

SearchController:

public PartialViewResult _Checklist()
    {
        var outcomeAreas = db.OutcomeArea.Where(oa => oa.Category != "").GroupBy(oa => oa.Category).Select(oa => oa.FirstOrDefault());
        return PartialView("_Checklist", outcomeAreas.ToList());
    }

Body:
Nevermind, I have it working.  I needed to use lowercase @model for the _Checklist.cshtml.

@model List<....Models.OutcomeArea>


问:
Clamav open source antivirus
I have been trying to study the source code of clamav open source antivirus as a part of my project. Hence I downloaded the latest stable release clamav.0.99.2.tar.gz from the website.

I'm using eclipse neon.2 Release 4.6.2 on Windows 10 64-bit.

I created an existing make file project using the clamav folder extracted, and then converted it into an C/C++ autotools project.

While configuring the project, I get an error "openssl not found", Although I have installed openssl in my cygwin64 terminal and also I run the ecipse from this terminal only.

Is my approach completely wrong?

答:
from the terminal in the linux VM, type:

```<code>sudo apt-get install libssl-dev
</code>```

to install the SSL then from the clamav-0.99.2 directory type:

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

when that completes then type:

```<code>make
</code>```

This will take a while to complete, then (if you want to actually install the clamav application) type:

```<code>make install
</code>```

Title: Clamav open source antivirus

Body:
from the terminal in the linux VM, type:

sudo apt-get install libssl-dev

to install the SSL then from the clamav-0.99.2 directory type:

./configure

when that completes then type:

make

This will take a while to complete, then (if you want to actually install the clamav application) type:

make install


问:
Spring Kafka: Multiple Listeners for different objects within an ApplicationContext
Can I please check with the community what is the best way to listen to multiple topics, with each topic containing a message of a different class?

I've been playing around with Spring Kafka for the past couple of days. My thought process so far:

Because you need to pass your deserializer into DefaultKafkaConsumerFactory when initializing a KafkaListenerContainerFactory. This seems to indicate that if I need multiple containers each deserializing a message of a different type, I will not be able to use the @EnableKafka and @KafkaListener annotations.

This leads me to think that the only way to do so would be to instantiate multiple KafkaMessageListenerContainers.

And given that KafkaMessageListenerContainers is single threaded and I need to listen to multiple topics at the same time, I really should be using multiple ConcurrentKafkaMessageListenerContainers.

Would I be on the right track here? Is there a better way to do this?

Thanks!

答:
You can use the annotations, you would just need to use a different listener container factory for each.

The framework will create a listener container for each annotation.

You can also listen to multiple topics on a single-threaded container but they would be processed, er, on a single thread.

Take a look at the code from my SpringOne Platform talk last year - you might want to look at app6, which shows how to use a MessageConverter instead of a deserializer, which might help simplify your configuration.


问:
Rails -PG::InvalidTextRepresentation: ERROR: malformed array literal
```<code>add_column :ssr_service_markets, :origin, :string, array: true, default: []
</code>```

and when i want to

```<code>SSRService::Market.where(origin: "*", destination: "*").first
</code>```

I have got

PG::InvalidTextRepresentation: ERROR:  malformed array literal: "*"
LINE 1: ...service_markets"  WHERE "ssr_service_markets"."origin" = '*'
DETAIL:  Array value must start with "{" or dimension information

How to fix it?

答:
In Postgres, to check if an array contains given element, you can use @> array operator.

Read more: Array Operators

:origin is an array field in your ssr_service_markets table, which means that it can contain multiple values.

In your example, assuming that destination is an array field as well, you could try to do the searching this way:

```<code>Model.where(["origin @> ? AND destination @> ?", '{*}', '{*}')"])
</code>```

Remember about using curly braces when working with array values.

To write an array value as a literal constant, enclose the element
  values within curly braces [...]

Body:
add_column :ssr_service_markets, :origin, :string, array: true, default: []

and when i want to

SSRService::Market.where(origin: "*", destination: "*").first

I have got

PG::InvalidTextRepresentation: ERROR:  malformed array literal: "*"
LINE 1: ...service_markets"  WHERE "ssr_service_markets"."origin" = '*'
DETAIL:  Array value must start with "{" or dimension information

How to fix it?

Body:
In Postgres, to check if an array contains given element, you can use @> array operator.

Read more: Array Operators

:origin is an array field in your ssr_service_markets table, which means that it can contain multiple values.

In your example, assuming that destination is an array field as well, you could try to do the searching this way:

Model.where(["origin @> ? AND destination @> ?", '{*}', '{*}')"])

Remember about using curly braces when working with array values.

To write an array value as a literal constant, enclose the element
  values within curly braces [...]


问:
XSLT: wanting to group similar output values and give them relevant headers
I'm brand new to XML and XSLT, so any guidance is deeply appreciated. I am unable to resolve my issue through researching on my own.

The Tools I'm using: I am using the Enhanced Query Export extension for VSTS. This allows you to write an XML document to export your work items in a format of your desire.

The Goal: I'd like my output to group work items by their work item type, and give these grouped work types specific headers. For example:

FIXES:

Bugs we've fixed

```<code>TITLE   TYPE   DESCRIPTION
B1      Bug    B1info
B2      Bug    B2info
B3      Bug    B3info
</code>```

...

IMPROVEMENTS:

Improvements we've made to the current features.

```<code>TITLE   TYPE     DESCRIPTION
I1      Backlog  I1info
I2      Backlog  I2info
I3      Backlog  I3info
</code>```

...

Current HTML Output Example:

Here's an image of what my output looks like with my current code.

Current Code:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html" indent="yes"/>

<xsl:key name="workitem" match="//workitem" use="System.WorkItemType" />

  <xsl:template match="//workitem">
  <html>
<body>
    <table border="1">
      <tr bgcolor="#9acd32">
      <th>Title</th>
      <th>Type</th>
      <th>Description</th>
    </tr>
    <xsl:for-each select="key('workitem',System.WorkItemType)">

     <xsl:choose>

      <xsl:when test="System.WorkItemType = 'Bug' ">
              <h1>Fixes</h1>
              <h2>Bugs we've fixed.</h2>
                <tr>
                  <td><xsl:value-of select="System.Title"/></td>
                 <td><xsl:value-of select="System.WorkItemType"/></td>
                 <td><xsl:value-of select="System.Description"/></td>
               </tr>
      </xsl:when>
      <xsl:when test="System.WorkItemType = 'Product Backlog Item' ">
              <h1>Improvements</h1>
              <h2>Improvements we've made to existing functionality.</h2>
                <tr>
                  <td><xsl:value-of select="System.Title"/></td>
                 <td><xsl:value-of select="System.WorkItemType"/></td>
                 <td><xsl:value-of select="System.Description"/></td>
               </tr>
      </xsl:when>
     </xsl:choose>
    </xsl:for-each>
    </table>
  </body>
  </html>
  <xsl:apply-templates select="workitem" />
  </xsl:template>

</xsl:stylesheet>
</code>```

答:
Tried to post as comment but formatting was terrible, so I'll post as an answer.

You could also set up 2 for loops and only process if it matches each of the WorkItemTypes.

As I don't have your XML to work from, ill just put it in sudo code below.

```<code>Output Bug Header

for each workitem
  if workitem is bug
    output workitem
  end if
end for

Output backlog Header

for each workitem
  if workitem is backlog
    output workitem
  end if
end for
</code>```

Body:
I'm brand new to XML and XSLT, so any guidance is deeply appreciated. I am unable to resolve my issue through researching on my own.

The Tools I'm using: I am using the Enhanced Query Export extension for VSTS. This allows you to write an XML document to export your work items in a format of your desire.

The Goal: I'd like my output to group work items by their work item type, and give these grouped work types specific headers. For example:

FIXES:

Bugs we've fixed

TITLE   TYPE   DESCRIPTION
B1      Bug    B1info
B2      Bug    B2info
B3      Bug    B3info

...

IMPROVEMENTS:

Improvements we've made to the current features.

TITLE   TYPE     DESCRIPTION
I1      Backlog  I1info
I2      Backlog  I2info
I3      Backlog  I3info

...

Current HTML Output Example:

Here's an image of what my output looks like with my current code.

Current Code:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="html" indent="yes"/>

<xsl:key name="workitem" match="//workitem" use="System.WorkItemType" />

  <xsl:template match="//workitem">

      Title
      Type
      Description

    <xsl:for-each select="key('workitem',System.WorkItemType)">

     <xsl:choose>

      <xsl:when test="System.WorkItemType = 'Bug' ">

Fixes

Bugs we've fixed.

                  <xsl:value-of select="System.Title"/>
                 <xsl:value-of select="System.WorkItemType"/>
                 <xsl:value-of select="System.Description"/>

      </xsl:when>
      <xsl:when test="System.WorkItemType = 'Product Backlog Item' ">

Improvements

Improvements we've made to existing functionality.

                  <xsl:value-of select="System.Title"/>
                 <xsl:value-of select="System.WorkItemType"/>
                 <xsl:value-of select="System.Description"/>

      </xsl:when>
     </xsl:choose>
    </xsl:for-each>

  <xsl:apply-templates select="workitem" />
  </xsl:template>

</xsl:stylesheet>

Body:
Tried to post as comment but formatting was terrible, so I'll post as an answer.

You could also set up 2 for loops and only process if it matches each of the WorkItemTypes.

As I don't have your XML to work from, ill just put it in sudo code below.

Output Bug Header

for each workitem
  if workitem is bug
    output workitem
  end if
end for

Output backlog Header

for each workitem
  if workitem is backlog
    output workitem
  end if
end for


问:
Arangodump between two different AWS ec2 clusters
I have created a Graph database in ArangoDB in a 5 machine AWS cluster. I do not have enough space in the Database AWS cluster to store the dump. So I would like to take a dump of the database in an AWS instance in a different cluster. I have the key files to connect to the machines.  How to do it using Arangodump ? Thanks.</p>

答:
I do get that correctly that you're using DC/OS clusters on AWS?

The problem with arangoimp is, that it doesn't know howto authenticate with the DC/OS proxy, and thus can't reach the routes it would require to import to arangodb.

The problem is similar to Running Arango Shell on DC/OS cluster - you want to use sshutle as lalitlogical describes to forward the ArangoDB server port (usually 8529) to your target environment.


问:
Where can I find WP_CONTENT_DIR in Wordpress structure?
I am using Query Monitor plugin, but it didn't create db.php symlink in path/to/wordpress/wp-content/db.php, even if I changed permission of the wp-content folder. My changing permission is restricted to one folder or file each time.
I can't do Linux nor Windows command-line queries. There is only one db.php inside query-monitor folder.

This is a quote from Query Monitor plugin:

When Query Monitor is unable to symlink its db.php file into place

Occasionally PHP won't have the correct permissions to put this
  symlink in place. Query Monitor will still work fine in this
  situation, but you won't see extended information that makes Query
  Monitor much more useful.

You can manually create the symlink by running the following command
  on the command line:

Linux / OS X:

ln -s
  /path/to/wordpress/wp-content/plugins/query-monitor/wp-content/db.php
  /path/to/wordpress/wp-content/db.php

Windows (requires administrator privileges):

mklink C:\path\to\wordpress\wp-content\db.php
  C:\path\to\wordpress\wp-content\plugins\query-monitor\wp-content\db.php

> Alternatively, you can relax the file permissions on the
  WP_CONTENT_DIR directory and then de-activate and re-activate the
  plugin and it'll attempt to create the symlink again.

Changing query-monitor or wp-content folder to 777 and de-activate + re-activate plugin has no effect. I don't think I can change permissions in phpMyAdmin, but no idea if I can or not on a table, and no idea how to find and change permissions on that table neither.

Is WP_CONTENT_DIR a php file or line in a file or a table or something else and where is it?

In case it's a line in a php file, how can I change permissions on a php line ?

答:
After many tries, I found out. One thing important: needs a path that begins with /home and can't be done offline else you'll get a conflict because it points to your computer.

No need to download nothing.

Cpanel may have Cron Jobs, which allows one linux bash shell command line as seen in this article (they don't host me). SSH client can also do this but it's more complicated.

Go to Advanced then Cron Jobs then set Once per minute:

```<code>ln -s /home/YOUR_HOST_USER_OR_ID/public_html/YOUR_BLOG_FOLDER/wp-content/plugins/query-monitor/wp-content/db.php /home/YOUR_HOST_USER_OR_ID/public_html/YOUR_BLOG_FOLDER/wp-content/db.php
</code>```

Refresh till file is created, then delete Cron Job immediately after, to avoid repetition x2 on the 2nd minute.

So like that you avoid both errors:

Extended query information such as the component and affected rows is not available. Query Monitor was unable to symlink its db.php file into place. See this wiki page for more information.

Extended query information such as the component and affected rows is not available. A conflicting db.php file is present. See this wiki page for more information.

Body:
After many tries, I found out. One thing important: needs a path that begins with /home and can't be done offline else you'll get a conflict because it points to your computer.

No need to download nothing.

Cpanel may have Cron Jobs, which allows one linux bash shell command line as seen in this article (they don't host me). SSH client can also do this but it's more complicated.

Go to Advanced then Cron Jobs then set Once per minute:

ln -s /home/YOUR_HOST_USER_OR_ID/public_html/YOUR_BLOG_FOLDER/wp-content/plugins/query-monitor/wp-content/db.php /home/YOUR_HOST_USER_OR_ID/public_html/YOUR_BLOG_FOLDER/wp-content/db.php

Refresh till file is created, then delete Cron Job immediately after, to avoid repetition x2 on the 2nd minute.

So like that you avoid both errors:

Extended query information such as the component and affected rows is not available. Query Monitor was unable to symlink its db.php file into place. See this wiki page for more information.

Extended query information such as the component and affected rows is not available. A conflicting db.php file is present. See this wiki page for more information.


问:
Converting a list of tuple of 2+ elements to a dictionary
I have a list of tuples which have more that 2 elements where the first element of each tuple is a number which is unique across all the tuples. How can I convert that list of tuples into a dictionary where a key is the 1st element of each tuple?

I know I can use dict(mylist) but it works only for 2-element tuples.

Body:
You can use a dict comprehension

>>> l = [(1, 'a', 'b'),
         (2, 'c', 'd')]
>>> {i[0]: i[1:] for i in l}
{1: ('a', 'b'),
 2: ('c', 'd')}


问:
CSS3 Rounded corner for input element without js/images
Who I can make the rounded corner for input elements?

I need a way without using javascript and images..

Added:

```<code><!DOCTYPE html>
<html>
<head>
    <title>xx</title>
<style type="text/css">
input
{
    -webkit-border-radius: 15px;
    -moz-border-radius: 15px;
    border-radius: 15px;
}
</style>
</head>
<body>
<input type="text" value="test" />
</body>
</html>
</code>```

It does not work in firefox 3.6.12!

答:
the way you do it is correct (for modern browsers), the problem is you wrong opening style tag:

```<code><style type="text/css/">
                    ^^^ this / shouldn't be there
</code>```

note that the roundet corners won't work in IE with you css, to achive this, you'll have to take a look at http://css3pie.com/ or use images/jsvascript.

Body:
Who I can make the rounded corner for input elements?

I need a way without using javascript and images..

Added:

<!DOCTYPE html>

    <title>xx</title>

<input type="text" value="test" />

It does not work in firefox 3.6.12!

Body:
the way you do it is correct (for modern browsers), the problem is you wrong opening style tag:

<style type="text/css/">
                    ^^^ this / shouldn't be there

note that the roundet corners won't work in IE with you css, to achive this, you'll have to take a look at http://css3pie.com/ or use images/jsvascript.


问:
Secure way to pass image id to php file
Hello guys I'm working on a little picture upload site. I found a problem which can be exploitet I'll show you.

I do use a foreach to display every image so 1 image in html looks like this:

```<code><a href="edit.php?id=ID_OF_PIC"><img src="IMG_PATH"></a>
</code>```

The things written in caps are just examples but there are working values. In edit.php the id is used to update the pictures name. But if I'm a sneaky smart hacker I can change the id in the href and like this I can change another post. So how/where can I save/hide the id so that nobody can change it?

答:
Simple Solution: Use a form foreach image. Like:

```<code><form action="edit.php" method="post">
   <input type="hidden" value="ID_OF_PIC" name="id">
   <input type="hidden" value="TOKEN" name="tokenID_OF_PIC">
   <img src="IMG_PATH"><input type="submit" value="edit">
<form>
</code>```

Before sending the form, create the TOKEN and save it in the session in relevance to the id.

$_SESSION['tokens'][ID_OF_PIC]='TOKEN_FOR_ID_OF_PIC';

A TOKEN should be a unique string for each image id.

When the form is posted , you got the id and the token.
You know can check if the ID and the TOKEN are valid.

if($_SESSION['tokens'][ID_OF_PIC]==$_POST['tokenID_OF_PIC']){}

So this allowes user only edit pic that was sent by the server via the form with the right token.

But this does not prevent user to open a pic normal in the browser to view it, when the IMG_PATH also have the ID in it.

Title: Secure way to pass image id to php file

Body:
Hello guys I'm working on a little picture upload site. I found a problem which can be exploitet I'll show you.

I do use a foreach to display every image so 1 image in html looks like this:

The things written in caps are just examples but there are working values. In edit.php the id is used to update the pictures name. But if I'm a sneaky smart hacker I can change the id in the href and like this I can change another post. So how/where can I save/hide the id so that nobody can change it?

Body:
Simple Solution: Use a form foreach image. Like:

<form action="edit.php" method="post">
   <input type="hidden" value="ID_OF_PIC" name="id">
   <input type="hidden" value="TOKEN" name="tokenID_OF_PIC">
   <img src="IMG_PATH"><input type="submit" value="edit">
<form>

Before sending the form, create the TOKEN and save it in the session in relevance to the id.

$_SESSION['tokens'][ID_OF_PIC]='TOKEN_FOR_ID_OF_PIC';

A TOKEN should be a unique string for each image id.

When the form is posted , you got the id and the token.
You know can check if the ID and the TOKEN are valid.

if($_SESSION['tokens'][ID_OF_PIC]==$_POST['tokenID_OF_PIC']){}

So this allowes user only edit pic that was sent by the server via the form with the right token.

But this does not prevent user to open a pic normal in the browser to view it, when the IMG_PATH also have the ID in it.


问:
inconsistent accessibility:constrain type "special" is less accessible than item database generic save objects
i have an interface like this.

```<code>interface special
{
     int spz_ID { get; set; }

     string Specialization_name { get; set; }

}
</code>```

And I have a generic method expects T types that implemented interface.

```<code>public int SaveObjects<T>(T obj) where T : special
    {

        lock (locker)
        {
            if (obj.spz_ID != 0)
            {
                database.Update(obj);
                return obj.spz_ID;

            }
            else
            {
                return database.Insert(obj);
            }

        }
    }
</code>```

and other table has different interface like this

```<code>public  interface IObject
{
    int ID { get; set; }

    string Username { get; set; }
    string Password { get; set; }

}
</code>```

generic method for this table is  expects T types that implemented interface is

```<code> public int SaveObject<T>(T obj) where T : IObject
    {

        lock (locker)
        {
            if (obj.ID != 0)
            {
                database.Update(obj);
                return obj.ID;

            }
            else
            {
                return database.Insert(obj);
            }

        }
    }
</code>```

When I build my solution i have an error :
inconsistent accessibility:constrain type "special" is less accessible than item database generic save objects (T).

答:
You method is defined as public. That requires the generic type T also to be public. As it has a constraint of being of type special that type must also be public.

Interfaces by default are created as internal if not explicitly stated otherwise thus are less accessible than public.

Change your interface definition to public and you are fine:

```<code>public interface special
{
    //... member definitions
}
</code>```

If you do not want your interface to be public any method using that interface mustn't be either.

Body:
i have an interface like this.

interface special
{
     int spz_ID { get; set; }

     string Specialization_name { get; set; }

}

And I have a generic method expects T types that implemented interface.

public int SaveObjects<T>(T obj) where T : special
    {

        lock (locker)
        {
            if (obj.spz_ID != 0)
            {
                database.Update(obj);
                return obj.spz_ID;

            }
            else
            {
                return database.Insert(obj);
            }

        }
    }

and other table has different interface like this

public  interface IObject
{
    int ID { get; set; }

    string Username { get; set; }
    string Password { get; set; }

}

generic method for this table is  expects T types that implemented interface is

 public int SaveObject<T>(T obj) where T : IObject
    {

        lock (locker)
        {
            if (obj.ID != 0)
            {
                database.Update(obj);
                return obj.ID;

            }
            else
            {
                return database.Insert(obj);
            }

        }
    }

When I build my solution i have an error :
inconsistent accessibility:constrain type "special" is less accessible than item database generic save objects (T).

Body:
You method is defined as public. That requires the generic type T also to be public. As it has a constraint of being of type special that type must also be public.

Interfaces by default are created as internal if not explicitly stated otherwise thus are less accessible than public.

Change your interface definition to public and you are fine:

public interface special
{
    //... member definitions
}

If you do not want your interface to be public any method using that interface mustn't be either.


问:
how to custom modify a django form and keep default validation intact
i've been searching for some examples on how to use Django's modelforms default validation but also be able to change attributes.

Note: this is going to be a very high level explanation to avoid an extra long question

so far the easieast way to generate a form is to just do a

```<code><form id="some_form" method="post" action="/do/something/"
        enctype="multipart/form-data" autocomplete="off">
    {{ some_form }}
    <button name="submit" type="submit" class="btn btn-custom-primary">Submit</a>
</form>
</code>```

that part above will automatically use what you have on forms.py and views.py to render a fully functional form that will generate the validation for you, therefore when you hit submit if there's missing data it will let you know  what you are missing and it won't let you go through.

But what happens when you want to add/update attributes to the form? by attributes CSS attributes like class, id, etc. if i decide to go the 'manual' way where i can control what attibutes to have instead of letting django automatically render the form for me like below i loose the default validation settings that django has.

```<code><form>
{% for field in some_form %}
    <label class="some_class" for="{{ field.name }}">{{ field.label }}</label>
    {{ field }}
{% endfor %}
<button type="submit">Submit</button>
</form>
</code>```

Now, i have found a way to add some attributes on forms.py see below

```<code>class DoSomething(forms.ModelForm):
def __init__(self, user,  *args, **kwargs):
    super(DoSomething, self).__init__(*args, **kwargs)
    for field in self.Meta.fields:
        self.fields[field].widget.attrs.update({
            'class': 'form-control',
        })
</code>```

if i initialize the class like that, i can add attributes to input but i haven't been able to add attributes to labels, i think once i manage to do that i'll be able to render it correctly. It may be something simple at this point but i think i'm already tired.

how can i style the form without loosing the default validation? is what i've done so far ok or is there a different approach to do this?

please advise,

efx

答:
You can use field_args.
Let assume I have a form class city_form in which I am calling model city_master.</p>

```<code>class city_form(ModelForm):
    class Meta:
        model = city_master
        fields = ('city', 'state', 'status')
        field_args = {
                "city" : {
                    "error_messages" : {
                        "required" : "Please let us know what to call you!"
                    }
                },
                "state" : {
                    "+error_messages" : {
                        "required" : "Please also enter some notes.",
                        "invalid"  : "This is not a valid state."
                    }
                }
            }
</code>```

Body:
i've been searching for some examples on how to use Django's modelforms default validation but also be able to change attributes.

Note: this is going to be a very high level explanation to avoid an extra long question

so far the easieast way to generate a form is to just do a

<form id="some_form" method="post" action="/do/something/"
        enctype="multipart/form-data" autocomplete="off">
    {{ some_form }}
    <button name="submit" type="submit" class="btn btn-custom-primary">Submit
</form>

that part above will automatically use what you have on forms.py and views.py to render a fully functional form that will generate the validation for you, therefore when you hit submit if there's missing data it will let you know  what you are missing and it won't let you go through.

But what happens when you want to add/update attributes to the form? by attributes CSS attributes like class, id, etc. if i decide to go the 'manual' way where i can control what attibutes to have instead of letting django automatically render the form for me like below i loose the default validation settings that django has.

<form>
{% for field in some_form %}
    {{ field.label }}
    {{ field }}
{% endfor %}
<button type="submit">Submit</button>
</form>

Now, i have found a way to add some attributes on forms.py see below

class DoSomething(forms.ModelForm):
def __init__(self, user,  *args, **kwargs):
    super(DoSomething, self).__init__(*args, **kwargs)
    for field in self.Meta.fields:
        self.fields[field].widget.attrs.update({
            'class': 'form-control',
        })

if i initialize the class like that, i can add attributes to input but i haven't been able to add attributes to labels, i think once i manage to do that i'll be able to render it correctly. It may be something simple at this point but i think i'm already tired.

how can i style the form without loosing the default validation? is what i've done so far ok or is there a different approach to do this?

please advise,

efx

Body:
You can use field_args.
Let assume I have a form class city_form in which I am calling model city_master.

class city_form(ModelForm):
    class Meta:
        model = city_master
        fields = ('city', 'state', 'status')
        field_args = {
                "city" : {
                    "error_messages" : {
                        "required" : "Please let us know what to call you!"
                    }
                },
                "state" : {
                    "+error_messages" : {
                        "required" : "Please also enter some notes.",
                        "invalid"  : "This is not a valid state."
                    }
                }
            }


问:
Install MacVim in Sierra
I have a new laptop with Sierra. I brought my applications from my old mac with Time Machine and most of them are working fine. However, Macvim disappeared. I tried to install it.
I tried to re-install it by installing Homebrew and brew installing macvim. The install looks successful, but I still cannot find nor use macvim. I guess this is a matter again of application files no longer being in /usr/ but in Library/, but honestly I am a bit lost as to how to figure out whether this is the problem and how to fix it.

Can you please help me out with this?

How I installed Homebrew:

```<code>ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
</code>```

How I installed Macvim:

```<code>brew install macvim
</code>```

答:
MacVim is keg-only.

If you run this command after installation:

```<code>brew linkapps
</code>```

you will find MacVim in your Applications folder in finder.

ContentLicense: CC BY-SA 4.0

Title: Install MacVim in Sierra

Body:
I have a new laptop with Sierra. I brought my applications from my old mac with Time Machine and most of them are working fine. However, Macvim disappeared. I tried to install it.
I tried to re-install it by installing Homebrew and brew installing macvim. The install looks successful, but I still cannot find nor use macvim. I guess this is a matter again of application files no longer being in /usr/ but in Library/, but honestly I am a bit lost as to how to figure out whether this is the problem and how to fix it.

Can you please help me out with this?

How I installed Homebrew:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

How I installed Macvim:

brew install macvim

Body:
MacVim is keg-only.

If you run this command after installation:

brew linkapps

you will find MacVim in your Applications folder in finder.


答:
You can create and define tables as you wish, but if you will have to use the table via a CursorAdapter that won't work without a tweak.

```<code>CursorAdapter: The Cursor must include a column named "_id" or this class will not work.
</code>```

You must always issue a select col1 as _id ... to work.

So it's recommended to use _id in the table schema, and if you like to use by some other name you could this this. select _id, _id as customname ... so select the _id column twice with different names.

Title: Do i have to use _ID as a SQlite primary key? and does it have to be an INT? (Android Dev)

Body:
This is probably a silly question but i haven't been able to find the answer yet.

I want to use a TEXT column with my own unique names as the primary key in a table.
the little section of code to define this looks something like this in my project:

...blahblah..."CREATE TABLE " + CAT_BUD_TAB + " (" + CAT_ITEM_ID + "_ID TEXT PRIMARY KEY,    "...blahblah..

Will this work as i intend? Or perhaps i need to use "AS ID"? I only ever see single tables with _ID as an autoincrementing integer in. Also this was intended to be a foreign key in another table but since i designed my database i've read more information and i'm not sure that'll really matter using android & SQLITE?

Thanks to the posters below but i'm a bit slow and not sure if i'm applying the info right, could you check?

So if i have a create statement like this:

"CREATE TABLE " + CAT_BUD_TAB + " (" + CAT_ITEM_ID + " TEXT PRIMARY KEY, " +
    IN_OUT + " TEXT, " + BUDGET_AMOUNT + " REAL, " + ACTUAL_AMOUNT_SPENT + " REAL, "
    + AMOUNT_STRAYED + " REAL, " + OVERBUDGET_TF + " INTEGER, " + AUTOSPEND_TF +
    " INTEGER);"

Then have:
    db.execSQL("SELECT ID, ID AS CAT_ITEM_ID")

Can i then use them interchangeably? am i even anywhere near close? haha sorry i am trying!

Body:
You can create and define tables as you wish, but if you will have to use the table via a CursorAdapter that won't work without a tweak.

CursorAdapter: The Cursor must include a column named "_id" or this class will not work.

You must always issue a select col1 as _id ... to work.

So it's recommended to use _id in the table schema, and if you like to use by some other name you could this this. select _id, _id as customname ... so select the _id column twice with different names.


问:
how to make two divs next to each other
unfortunately i dont know how to make these divs(Boxes) next to each other like the picture and put the images of the cars like the image , can anyone please help me

if there is a way with tables or divs please help me to do it

here is the image

答: you can use float:left for your 2 divs inside a parent div</p>

Title: how to make two divs next to each other


答:
Wow. Took a while to spot the bug. Tricky one, this. Your model declaration is the problem:

```<code>@Model List<....Models.OutcomeArea>
</code>```

That should be @model, lowercase. You're literally telling to print out Model at the moment.

Title: HTML rendering model as string

Body:
This is a fork from another question.  I am passing a list into a partial view which is part of a main view.  However, when I view the page, I see:

System.Collections.Generic.List`1[...Models.OutcomeArea] List

Now, the list is being rendered correctly, but I am not sure why the above line is showing in the html.

Index.cshtml:

@using (Html.BeginForm("Index", "Search", FormMethod.Get, new { @class = "form-inline" }))
{
    @Html.Action("_Checklist")
}

_Checklist.cshtml:

@Model List<....Models.OutcomeArea>

Outcomes

        @foreach (var list in Model)
        {
            <input type="checkbox" id="@list.ID" name="@list.ID" /> @list.Category

        }

SearchController:

public PartialViewResult _Checklist()
    {
        var outcomeAreas = db.OutcomeArea.Where(oa => oa.Category != "").GroupBy(oa => oa.Category).Select(oa => oa.FirstOrDefault());
        return PartialView("_Checklist", outcomeAreas.ToList());
    }

Body:
Wow. Took a while to spot the bug. Tricky one, this. Your model declaration is the problem:

@Model List<....Models.OutcomeArea>

That should be @model, lowercase. You're literally telling to print out Model at the moment.


问:
Create Virtual Server Dynamically Using PHP
I am creating a webapp for multiple companies to use but i don't want all to be login through one place so i want to create virtual servers for every client whenever i want to add them. So Anyone Have Idea How I Would Be Able To Do that??</p>

答:
As Per PHP Manual :

PHP Built-in web server

As of PHP 5.4.0, the CLI SAPI provides a built-in web server.

The web server runs a only one single-threaded process, so PHP applications will stall if a request is blocked.

Example #1 Starting the web server

```<code>$ cd ~/public_html
$ php -S localhost:8000
</code>```

The terminal will show:

```<code>PHP 5.4.0 Development Server started at Thu Jul 21 10:43:28 2011
Listening on localhost:8000
Document root is /home/me/public_html
Press Ctrl-C to quit
</code>```

Note : This web server was designed to aid application development. It may also be useful for testing purposes or for application demonstrations that are run in controlled environments. It is not intended to be a full-featured web server. It should not be used on a public network.

Now, About Dynamically Creating Server :

Create a Loop PHP foreach or while

Using shell_exec

Pass your dynamic directory name instead of ~/public_html

Pass your dynamic Port Number instead of 8000

Hope This may help you.

Body:
As Per PHP Manual :

PHP Built-in web server

As of PHP 5.4.0, the CLI SAPI provides a built-in web server.

The web server runs a only one single-threaded process, so PHP applications will stall if a request is blocked.

Example #1 Starting the web server

$ cd ~/public_html
$ php -S localhost:8000

The terminal will show:

PHP 5.4.0 Development Server started at Thu Jul 21 10:43:28 2011
Listening on localhost:8000
Document root is /home/me/public_html
Press Ctrl-C to quit

Note : This web server was designed to aid application development. It may also be useful for testing purposes or for application demonstrations that are run in controlled environments. It is not intended to be a full-featured web server. It should not be used on a public network.

Now, About Dynamically Creating Server :

Create a Loop PHP foreach or while

Using shell_exec

Pass your dynamic directory name instead of ~/public_html

Pass your dynamic Port Number instead of 8000

Hope This may help you.


问:
Materialize CSS Remove table head spacing
I making a simple demo where i have few employees information. I am using materialize css table. But i am getting extra space between sr.no and other column names.

here is my code :

```<code>     <br/>

     <div class="row">
  <div class="col l8">
        <div class="card darken-2">
              <div class="card-content">
                    <span class="card-title">{{tableTitle}}</span>
                    <br/>
                    <div class="row">
                         <div class="input-field col s4">
                                <input id="empSearch" type="text" placeholder="Search">

                          </div>
                    </div>
                    <br/>
                    <div class="row">
                          <div class="col lg7">
                                <table class="bordered highlight responsive-table">
                                      <thead>
                                            <tr>
                                                  <th>Sr.no</th>
                                                  <th>Name</th>
                                                  <th>Age</th>
                                                  <th>Gender</th>
                                                  <th>Address</th>
                                                  <th>Designation</th>
                                                  <th>Department</th>
                                                  <th>Salary</th>
                                                  <th></th>
                                                  <th></th>

                                            </tr>
                                      </thead>
                                      <tbody>
                                            <tr *ngFor="let item of EmployeeData;let i= index">
                                                  <td>{{i+1}}</td>
                                                  <td>{{item.Name}}</td>
                                                  <td>{{item.Age}}</td>
                                                  <td>{{item.Gender}}</td>
                                                  <td>{{item.Address}}</td>
                                                  <td>{{item.Designation}}</td>
                                                  <td>{{item.Department}}</td>
                                                  <td>{{item.Salary}}</td>
                                                  <td>
                                                       <i class="material-icons">delete</i>
                                                  </td>
                                                   <td>
                                                       <i class="material-icons">mode_edit</i>
                                                  </td>
                                            </tr>
                                      </tbody>

                                </table>
                          </div>
                    </div>
              </div>
        </div>
  </div>
</code>```

答:
in the  you could set width="30px" or whatever your're comfortable with.
The icons, I'd put in one cell, and use text-align: right

<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.1/css/materialize.min.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

      Sr.no
      Name
      Age
      Gender
      Address
      Designation
      Department
      Salary

      {{i+1}}
      {{item.Name}}
      {{item.Age}}
      {{item.Gender}}
      {{item.Address}}
      {{item.Designation}}
      {{item.Department}}
      {{item.Salary}}

        delete
        mode_edit

```

Body:
I making a simple demo where i have few employees information. I am using materialize css table. But i am getting extra space between sr.no and other column names.

here is my code :

                    {{tableTitle}}

                                <input id="empSearch" type="text" placeholder="Search">

                                                  Sr.no
                                                  Name
                                                  Age
                                                  Gender
                                                  Address
                                                  Designation
                                                  Department
                                                  Salary

                                                  {{i+1}}
                                                  {{item.Name}}
                                                  {{item.Age}}
                                                  {{item.Gender}}
                                                  {{item.Address}}
                                                  {{item.Designation}}
                                                  {{item.Department}}
                                                  {{item.Salary}}

                                                       delete

                                                       mode_edit

Body:
in the <th> you could set width="30px" or whatever your're comfortable with.
The icons, I'd put in one cell, and use text-align: right

<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.1/css/materialize.min.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<table>
  <thead>
    <tr>
      <th width="30px">Sr.no</th>
      <th>Name</th>
      <th>Age</th>
      <th>Gender</th>
      <th>Address</th>
      <th>Designation</th>
      <th>Department</th>
      <th>Salary</th>
      <th></th>

    </tr>
  </thead>
  <tbody>
    <tr>
      <td>{{i+1}}</td>
      <td>{{item.Name}}</td>
      <td>{{item.Age}}</td>
      <td>{{item.Gender}}</td>
      <td>{{item.Address}}</td>
      <td>{{item.Designation}}</td>
      <td>{{item.Department}}</td>
      <td>{{item.Salary}}</td>
      <td style="text-align: right">
        <i class="material-icons">delete</i>
        <i class="material-icons">mode_edit</i>
      </td>
    </tr>
  </tbody>

</table>


问:
Python indexing for central differencing
I have a question about python indexing: I am trying to use central differencing to estimate 'dU' from an array 'U' and I'm doing this by initialising 'dU' with an array of 'nan' of length(U) and then applying central differencing such that dU(i) = (U(i+1) - U(i-1))/2 to the central elements. The output 'dU' array is currently giving me two 'nan' entries at the end of the vector. Can anyone explain why the second to last element isn't being updated?</p>

```<code>import numpy as np
U= np.array([1,2,3,4,5,6])
dU = np.zeros(len(U))
dU[:] = np.NAN
dU[1:-2] = (U[2:-1]-U[0:-3])/2

>>> dU
array([ nan,   1.,   1.,   1.,  nan,  nan])
</code>```

答:
To have second to last element included you would need:</p>

```<code>dU[1:-1] = (U[2:]-U[0:-2])/2
</code>```

Body:
I have a question about python indexing: I am trying to use central differencing to estimate 'dU' from an array 'U' and I'm doing this by initialising 'dU' with an array of 'nan' of length(U) and then applying central differencing such that dU(i) = (U(i+1) - U(i-1))/2 to the central elements. The output 'dU' array is currently giving me two 'nan' entries at the end of the vector. Can anyone explain why the second to last element isn't being updated?

import numpy as np
U= np.array([1,2,3,4,5,6])
dU = np.zeros(len(U))
dU[:] = np.NAN
dU[1:-2] = (U[2:-1]-U[0:-3])/2

>>> dU
array([ nan,   1.,   1.,   1.,  nan,  nan])

Body:
To have second to last element included you would need:

dU[1:-1] = (U[2:]-U[0:-2])/2


问:
page rendering takes more time
I have a aspx page which contains 6 user controls which will be displayed when the user clicks on any button using show model pop up extender. My page rendering takes more time. it taked 3 minuits to load the page. If i debug the page its traveling to page load of all the user controls.

Its not taking more time to fetch the data from database but its taking time to load the page. Is there any way to improve the perfomace .

Is there any place where i have to look into.

I am using VS 2010 and c# . Please let me know if you have any questions.

Regards,
Jebli.

答:
Other than the third party profilers you can actully use the VS2010 profiler too. MS has done a good job on this one.

As a regular coding practise you can check the following points to optimse the page performace:

Avoid fetching full tables from DB, fetch only what you need to display and have some paging mechanism to display rest of the info.

Cache whatever data you can, set sliding expiration if neccessary.

Try using HtmlControls with runat="server", if you can.

As of now, this is what I can think of, from the top of my head. Would add more as and when I can.

Title: page rendering takes more time


问:
custom validation in yii2 model
I am trying to add custom rule to form. I have added a custom function in model but it's not working for me.</p>

```<code>class BackendUser extends ActiveRecord implements IdentityInterface
{
public function rules()
{

    return [

        ['username','validateUsername','params'=>'username'=>'username']],

    ];
}

public function validateUsername($attribute, $params)
{
    if (preg_match('/[^a-z])/i', $this->$attribute)) {
        $this->addError($attribute, 'Username should only contain
    alphabets');
    }

}}
</code>```

答:
In PHP there is no construct like you used here (a => b => c, maybe it's a typo) and you don't have to pass any parameters anyway since you don't use them in the validator method. Simple

```<code>public function rules()
{
    return [
        ['username','validateUsername'],
    ];
}
</code>```

is enough.

Title: custom validation in yii2 model

Body:
I am trying to add custom rule to form. I have added a custom function in model but it's not working for me.

class BackendUser extends ActiveRecord implements IdentityInterface
{
public function rules()
{

    return [

        ['username','validateUsername','params'=>'username'=>'username']],

    ];
}

public function validateUsername($attribute, $params)
{
    if (preg_match('/[^a-z])/i', $this->$attribute)) {
        $this->addError($attribute, 'Username should only contain
    alphabets');
    }

}}

Body:
In PHP there is no construct like you used here (a => b => c, maybe it's a typo) and you don't have to pass any parameters anyway since you don't use them in the validator method. Simple

public function rules()
{
    return [
        ['username','validateUsername'],
    ];
}

is enough.


问:
SQL Prepared Statement & returning type
I have just created a method in my class file, were I insert data into my sql database.

1) Are these prepared statements correct?
2) I need to return a type car for the method (Where could this be done)?
.....As the error I get at the moment is the method must return a type Car (Car is the name of the class file)

```<code>public Car addVehicle(String aLicense, int aJourneys, String aUsername, String aPassword) {
    Car c = new Car();
    try {

        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection(url + dbName, userName, password);
        statement = conn.createStatement();
        String query = " insert into eflow.registration (cLicense, cJourneys, cUsername, cPassword)"
                + " values (?, ?, ?, ?)";

        PreparedStatement preparedStmt = conn.prepareStatement(query);
        preparedStmt.setString(1, aLicense);
        preparedStmt.setInt(2, aJourneys);
        preparedStmt.setString(3, aUsername);
        preparedStmt.setString(4, aPassword);

        preparedStmt.execute();

        conn.close();

    } catch (Exception e) {
        System.err.println("Got an exception!");
        System.err.println(e.getMessage());

    }
    return c;

}
</code>```

Calling the method returns an error that the method is not applicable for arguments

```<code>//int addingID = Integer.parseInt(enteringID.getText());
                String addingReg = enteringReg.getText();
                int addingJourneys = Integer.parseInt(enteringJourneys.getText());
                String addingUsername = enteringUsername.getText();
                @SuppressWarnings("deprecation")
                String addingPassword = enteringPassword.getText();
                Car newCar = new Car(addingReg, addingJourneys, addingUsername, addingPassword);
                int addStatus = myCar.addVehicle(newCar);
                if (addStatus == 1) {
                    JOptionPane.showMessageDialog(null, "Vehicle Added");
                    enteringID.setText("(eg. 1-999)");
                    enteringReg.setText("(eg. - 162-MH-749)");
                    enteringJourneys.setText("(eg. 7)");
                    enteringUsername.setText("(eg. - username@domain.com)");
                    enteringPassword.setText("");
                }

                else {
                    JOptionPane.showMessageDialog(null, "Error, Please Try Again");
                }
            } catch (Exception f) {
                JOptionPane.showMessageDialog(null, "Error, Please Try Again");
            }
        }
    });
</code>```

答:
This is not a final answer for your question, but purely to clarify my comment.

If you want your method to return a Car object, you'll have to create an instance of class Car and return it:

```<code>public Car addVehicle(String aLicense, int aJourneys, String aUsername, String aPassword) {
try {
    Class.forName("com.mysql.jdbc.Driver");
    Connection conn = DriverManager.getConnection(url + dbName, userName, password);
    statement = conn.createStatement();
    String query = " insert into eflow.registration (cLicense, cJourneys, cUsername, cPassword)"
            + " values (?, ?, ?, ?)";

    PreparedStatement preparedStmt = conn.prepareStatement(query);
    preparedStmt.setString(1, "'" + aLicense + "'");
    preparedStmt.setInt(2, aJourneys);
    preparedStmt.setString(3, "'" + aUsername + "'");
    preparedStmt.setString(4, "'" + aPassword + "'");

    preparedStmt.execute();

    conn.close();

    Car c = new Car();
    //Do anything with the car object that you like.
    //for example: c.setColor("blue");
    return c;

} catch (Exception e) {
    System.err.println("Got an exception!");
    System.err.println(e.getMessage());
    //kayaman is correct here: we still need to return something here in order to be able to compile
    return null;
}
</code>```

Title: SQL Prepared Statement & returning type

Body:
I have just created a method in my class file, were I insert data into my sql database.

1) Are these prepared statements correct?
2) I need to return a type car for the method (Where could this be done)?
.....As the error I get at the moment is the method must return a type Car (Car is the name of the class file)

public Car addVehicle(String aLicense, int aJourneys, String aUsername, String aPassword) {
    Car c = new Car();
    try {

        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection(url + dbName, userName, password);
        statement = conn.createStatement();
        String query = " insert into eflow.registration (cLicense, cJourneys, cUsername, cPassword)"
                + " values (?, ?, ?, ?)";

        PreparedStatement preparedStmt = conn.prepareStatement(query);
        preparedStmt.setString(1, aLicense);
        preparedStmt.setInt(2, aJourneys);
        preparedStmt.setString(3, aUsername);
        preparedStmt.setString(4, aPassword);

        preparedStmt.execute();

        conn.close();

    } catch (Exception e) {
        System.err.println("Got an exception!");
        System.err.println(e.getMessage());

    }
    return c;

}

Calling the method returns an error that the method is not applicable for arguments

//int addingID = Integer.parseInt(enteringID.getText());
                String addingReg = enteringReg.getText();
                int addingJourneys = Integer.parseInt(enteringJourneys.getText());
                String addingUsername = enteringUsername.getText();
                @SuppressWarnings("deprecation")
                String addingPassword = enteringPassword.getText();
                Car newCar = new Car(addingReg, addingJourneys, addingUsername, addingPassword);
                int addStatus = myCar.addVehicle(newCar);
                if (addStatus == 1) {
                    JOptionPane.showMessageDialog(null, "Vehicle Added");
                    enteringID.setText("(eg. 1-999)");
                    enteringReg.setText("(eg. - 162-MH-749)");
                    enteringJourneys.setText("(eg. 7)");
                    enteringUsername.setText("(eg. - username@domain.com)");
                    enteringPassword.setText("");
                }

                else {
                    JOptionPane.showMessageDialog(null, "Error, Please Try Again");
                }
            } catch (Exception f) {
                JOptionPane.showMessageDialog(null, "Error, Please Try Again");
            }
        }
    });

Body:
This is not a final answer for your question, but purely to clarify my comment.

If you want your method to return a Car object, you'll have to create an instance of class Car and return it:

public Car addVehicle(String aLicense, int aJourneys, String aUsername, String aPassword) {
try {
    Class.forName("com.mysql.jdbc.Driver");
    Connection conn = DriverManager.getConnection(url + dbName, userName, password);
    statement = conn.createStatement();
    String query = " insert into eflow.registration (cLicense, cJourneys, cUsername, cPassword)"
            + " values (?, ?, ?, ?)";

    PreparedStatement preparedStmt = conn.prepareStatement(query);
    preparedStmt.setString(1, "'" + aLicense + "'");
    preparedStmt.setInt(2, aJourneys);
    preparedStmt.setString(3, "'" + aUsername + "'");
    preparedStmt.setString(4, "'" + aPassword + "'");

    preparedStmt.execute();

    conn.close();

    Car c = new Car();
    //Do anything with the car object that you like.
    //for example: c.setColor("blue");
    return c;

} catch (Exception e) {
    System.err.println("Got an exception!");
    System.err.println(e.getMessage());
    //kayaman is correct here: we still need to return something here in order to be able to compile
    return null;
}


问:
Execute the output of previous command line
I need to execute the result of a previous command, but I don't know how I can process.

I have a first command that returns an instruction to log in to the server and then I want to execute it just after.

my-first-command returns: docker login ...

For example:

> my-first-comnand | execute the result of my-first-command

答:
I use $(!!) for this. As Charles points out, this may not be what everyone wants to do, but it works for me and suits my purpose better than the other answer.

```<code>$ find ./ -type f -name "some.sh"
$ $(!!)
</code>```

!! is a variable that holds the last command, and putting into $( ) makes it get executed.

This is also useful for taking other actions on the output, since $( ) is treated as a variable.

Body:
I use $(!!) for this. As Charles points out, this may not be what everyone wants to do, but it works for me and suits my purpose better than the other answer.

$ find ./ -type f -name "some.sh"
$ $(!!)

!! is a variable that holds the last command, and putting into $( ) makes it get executed.

This is also useful for taking other actions on the output, since $( ) is treated as a variable.


Title: pyspark dataframe from rdd containing key and values as list of lists

Body:
I have a RDD like below with keys and values as list of list containing some parameters.

(32719, [[[u'200.73.55.34', u'192.16.48.217', 0, 6, 10163, 443, 0], [u'177.207.76.243', u'192.16.58.8', 0, 6, 59575, 80, 0]])
(32897, [[[u'200.73.55.34', u'193.16.48.217', 0, 6, 10163, 443, 0], [u'167.207.76.243', u'194.16.58.8', 0, 6, 59575, 80, 0]])

I want to create a dataframe with rows and columns as below

32719, '200.73.55.34', u'192.16.48.217', 0, 6, 10163, 443, 0
32719, '177.207.76.243', u'192.16.58.8', 0, 6, 59575, 80, 0
32897, 200.73.55.34', u'193.16.48.217', 0, 6, 10163, 443, 0

Or just a dataframe of all the values but grouped by the key. How can I do this.

Body:
Use flat map Values

a =[(32719, [[[u'200.73.55.34', u'192.16.48.217', 0, 6, 10163, 443, 0], [u'177.207.76.243', u'192.16.58.8', 0, 6, 59575, 80, 0]]]),
(32897, [[[u'200.73.55.34', u'193.16.48.217', 0, 6, 10163, 443, 0], [u'167.207.76.243', u'194.16.58.8', 0, 6, 59575, 80, 0]]])]

rdd =sc.parallelize(a)

rdd.flatMapValues(lambda x:x[0]).map(lambda x: [x[0]]+x[1]).toDF().show()

Output

+-------+----------------+---------------+----+----+-------+-----+----+
|  _1   |       _2       |      _3       | _4 | _5 |  _6   | _7  | _8 |
+-------+----------------+---------------+----+----+-------+-----+----+
| 32719 | 200.73.55.34   | 192.16.48.217 |  0 |  6 | 10163 | 443 |  0 |
| 32719 | 177.207.76.243 | 192.16.58.8   |  0 |  6 | 59575 |  80 |  0 |
| 32897 | 200.73.55.34   | 193.16.48.217 |  0 |  6 | 10163 | 443 |  0 |
| 32897 | 167.207.76.243 | 194.16.58.8   |  0 |  6 | 59575 |  80 |  0 |
+-------+----------------+---------------+----+----+-------+-----+----+


问:
Yii2 Object of class ..... could not be converted to string
i want to show one data from table client when create data Goods, but i got error Object of class frontend\modules\cargo\models\Client could not be converted.

here is GoodsController

```<code>public function actionCreate()
{
  $model = new Goods();
  $idClient = Yii::$app->user->identity->id_client;
  $client = Client::find($idClient)->one();

  if ($model->loadAll(Yii::$app->request->post()) && $model->saveAll()) {
      return $this->redirect(['view', 'id' => $model->id]);
  } else {
      return $this->render('create', [
          'model' => $model,
          'client' => $client,
      ]);
  }
}
</code>```

I need to display data client in _form Goods.somebody could help me?

答:
To get object of Client with that specific id you can do it in two ways.

```<code>Client::find($idClient);
</code>```

or with ->one():

```<code>Client::find()->where(['id' => $idClient])->one();
</code>```

Body:
i want to show one data from table client when create data Goods, but i got error Object of class frontend\modules\cargo\models\Client could not be converted.

here is GoodsController

public function actionCreate()
{
  $model = new Goods();
  $idClient = Yii::$app->user->identity->id_client;
  $client = Client::find($idClient)->one();

  if ($model->loadAll(Yii::$app->request->post()) && $model->saveAll()) {
      return $this->redirect(['view', 'id' => $model->id]);
  } else {
      return $this->render('create', [
          'model' => $model,
          'client' => $client,
      ]);
  }
}

I need to display data client in _form Goods.somebody could help me?

Body:
To get object of Client with that specific id you can do it in two ways.

Client::find($idClient);

or with ->one():

Client::find()->where(['id' => $idClient])->one();


问:
Arangodb - @include configuration file
In configuration file I can put

```<code>@include some_other_file
</code>```

The "issue" is that this "some_other_file.conf" has to be under:

```<code>/etc/arangodb3/some_other_file.conf
</code>```

I tried absolute path, but it seams I can include other files only if they are in /etc/arangodb3/.

/etc/arangodb3/ corresponds to @SYSCONFDIR@ variable I can use in configuration file.

Is there any way to include configuration file from any location ?

Or maybe some way to set @SYSCONFDIR@ to point to directory I want ?

答: This issue has been meanwhile resolved in ArangoDB 3.1. </p>

Title: Arangodb - @include configuration file

Body:
In configuration file I can put

@include some_other_file

The "issue" is that this "some_other_file.conf" has to be under:

/etc/arangodb3/some_other_file.conf

I tried absolute path, but it seams I can include other files only if they are in /etc/arangodb3/.

/etc/arangodb3/ corresponds to @SYSCONFDIR@ variable I can use in configuration file.

Is there any way to include configuration file from any location ?

Or maybe some way to set @SYSCONFDIR@ to point to directory I want ?


问:
Why should redux action types be in UPPER_CASE?
Is there any deeper reason why action types in redux should be strings in all upper case with underscores?

A string is just a string, right? Why not use the the names of action creators (typically in camelCase) also as the type of the actions created by them?

答:
It is mainly because of actions is being refereed from multiple modules, be it saga or react ui.
It is just the convention, and gives easy readability in code.
In ReactJs, actions are important focus as they are meant to change the state of the reactUI.  </p>


问:
How can I Log on to Exchange Web Services
I need to add a calendar event for an exchange user from a web app.

The web app knows the exchange users email address.
The web application that is not integrated with Active Directory.
Ideally user should not need to accept the event in outlook

We discussed a few posibilities:

Store the users exchange passwords in the web app DB (discounted)

Set up an dummy exchange user for the web app, and send the caledar event to the real user as a request from the dummy user (not ideal as the real user would need to accept, and client does not have specs for what to do in case of rejection)

Integrate with Active Directory, and impersonate the user (requires either windows authentication, or the users password, and the person using the app to add the appointment will not be the person whose calendar it needs to go into, so windows authentication wouldn't help.)

So is this possible?

答:
Yes, you can do this.

Exchange Web Services operations provide you the ability to impersonate another user, so your application would authenticate to EWS using its own name/pw, then set the proper impersonation parameters on the "add calendar event" operation, specifying the user that it's acting on behalf of.

Obviously, the account your application is using would need to be granted the appropriate permissions in Exchange to allow it to impersonate any user.


问:
Perform object recognition based on colour
I have captured each frame of a video .Then I have used background subtraction to eliminate the background .Now I have the people with their bounding boxes.I have to compare the colour features of this person with the features of the same person in another video. The person will be wearing the same dress in every video.
I am developing this in opencv 2.4 and python 2.7

Here it the background subtraction code I have used:

```<code>import numpy as np
import cv2
cap = cv2.VideoCapture('test.mp4')
fgbg = cv2.BackgroundSubtractorMOG()
j=0
count = int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT))
while j<count:
    ret, frame = cap.read()
    cmask = fgbg.apply(frame)
    fgmask = cmask.copy()
    floodfill =cmask.copy()

    (cnts, _) = cv2.findContours(cmask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    cnts = sorted(cnts, key = cv2.contourArea, reverse = True)
    if(len(cnts)!=0):
        h, w = floodfill.shape[:2]
        mask = np.zeros((h+2, w+2), np.uint8)
        cv2.floodFill(floodfill, mask, (0,0), 255)
        floodfill_inv = cv2.bitwise_not(floodfill)
        fgmask=fgmask|floodfill_inv

    # screenCnt = None
    print "K="+str(j)
    j+=1
    for cnt in cnts:
        x,y,w,h = cv2.boundingRect(cnt)
        cv2.rectangle(fgmask,(x,y),(x+w,y+h),255,4)
    if(len(cnts)!=0):
        cv2.imshow('frame',fgmask)

    k = cv2.waitKey(30) & 0xff

    if k == 27:
        break
cap.release()
cv2.destroyAllWindows()
</code>```

Is there any method for comparing objects based on the colour?

I have not used face recognition because I don't have pictures of the people in the video

Any help would be appreciated

答:
I'd consider to match using template matching on color images.

Another option, if applicable, is to extract and match features using feature based methods (SIFT, ect). best option.

Another option (sort of a shortcut) would be to calculate the histogram between the blobs, find the most common color, than match the colors on HSV color space.

Good luck

Body:
I have captured each frame of a video .Then I have used background subtraction to eliminate the background .Now I have the people with their bounding boxes.I have to compare the colour features of this person with the features of the same person in another video. The person will be wearing the same dress in every video.
I am developing this in opencv 2.4 and python 2.7

Here it the background subtraction code I have used:

import numpy as np
import cv2
cap = cv2.VideoCapture('test.mp4')
fgbg = cv2.BackgroundSubtractorMOG()
j=0
count = int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_COUNT))
while j<count:
    ret, frame = cap.read()
    cmask = fgbg.apply(frame)
    fgmask = cmask.copy()
    floodfill =cmask.copy()

    (cnts, _) = cv2.findContours(cmask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    cnts = sorted(cnts, key = cv2.contourArea, reverse = True)
    if(len(cnts)!=0):
        h, w = floodfill.shape[:2]
        mask = np.zeros((h+2, w+2), np.uint8)
        cv2.floodFill(floodfill, mask, (0,0), 255)
        floodfill_inv = cv2.bitwise_not(floodfill)
        fgmask=fgmask|floodfill_inv

    # screenCnt = None
    print "K="+str(j)
    j+=1
    for cnt in cnts:
        x,y,w,h = cv2.boundingRect(cnt)
        cv2.rectangle(fgmask,(x,y),(x+w,y+h),255,4)
    if(len(cnts)!=0):
        cv2.imshow('frame',fgmask)

    k = cv2.waitKey(30) & 0xff

    if k == 27:
        break
cap.release()
cv2.destroyAllWindows()

Is there any method for comparing objects based on the colour?

I have not used face recognition because I don't have pictures of the people in the video

Any help would be appreciated


答:
Try this html+bootstrap will work fine for mobile views :</p>

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <div class="row">
    <div class="col-sm-4">
     Image 1
    </div>
    <div class="col-sm-4">
      Image 2
    </div>
    <div class="col-sm-4">
      Image 3
    </div>
  </div>
</div>

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

Title: how to make two divs next to each other

Body:
unfortunately i dont know how to make these divs(Boxes) next to each other like the picture and put the images of the cars like the image , can anyone please help me

if there is a way with tables or divs please help me to do it

here is the image

Body:
Try this html+bootstrap will work fine for mobile views :

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <div class="row">
    <div class="col-sm-4">
     Image 1
    </div>
    <div class="col-sm-4">
      Image 2
    </div>
    <div class="col-sm-4">
      Image 3
    </div>
  </div>
</div>

</body>
</html>


问:
How to set the Default Page in ASP.NET?
Is there any section or code which allows us to set default page in web.config?

For example, when people first visit my website, I want them to see CreateThing.aspx rather than Default.aspx.

The solutions I already know:

Put this line of code => Response.Redirect("CreateThings.aspx") in Default.aspx Page_Load event but this method is really naive.

We can use IIS (default page configuration,) but I wanna do the same thing over on my ASP.NET application.

This could be another solution for now:

```<code><defaultDocument>
    <files>
        <clear />
        <add value="Default.aspx" />
        <add value="Default.htm" />
        <add value="Default.asp" />
        <add value="index.htm" />
        <add value="index.html" />
        <add value="iisstart.htm" />
    </files>
</defaultDocument>
</code>```

答:
I had done all the above solutions but it did not work.

My default page wasn't an aspx page, it was an html page.

This article solved the problem.  https://weblog.west-wind.com/posts/2013/aug/15/iis-default-documents-vs-aspnet-mvc-routes

Basically, in my \App_Start\RouteConfig.cs file, I had to add a line:

```<code>public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.IgnoreRoute("");   // This was the line I had to add here!

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}
</code>```

Hope this helps someone, it took me a goodly while to find the answer.

Title: How to set the Default Page in ASP.NET?

Body:
Is there any section or code which allows us to set default page in web.config?

For example, when people first visit my website, I want them to see CreateThing.aspx rather than Default.aspx.

The solutions I already know:

Put this line of code => Response.Redirect("CreateThings.aspx") in Default.aspx Page_Load event but this method is really naive.

We can use IIS (default page configuration,) but I wanna do the same thing over on my ASP.NET application.

This could be another solution for now:

<defaultDocument>
    <files>
        <clear />
        <add value="Default.aspx" />
        <add value="Default.htm" />
        <add value="Default.asp" />
        <add value="index.htm" />
        <add value="index.html" />
        <add value="iisstart.htm" />
    </files>
</defaultDocument>

Body:
I had done all the above solutions but it did not work.

My default page wasn't an aspx page, it was an html page.

This article solved the problem.  https://weblog.west-wind.com/posts/2013/aug/15/iis-default-documents-vs-aspnet-mvc-routes

Basically, in my \App_Start\RouteConfig.cs file, I had to add a line:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.IgnoreRoute("");   // This was the line I had to add here!

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

Hope this helps someone, it took me a goodly while to find the answer.


问:
Magento Cash on Delivery success page throwing error after upgarding to 1.9.2
After upgrading to magento 1.9.2 and also updating the theme, when I was checking the payment option after i selected the cashondelivery payment option and clicked on place an order got a message that "Your order has been received.
Thank you for your purchase!" but below that page I got this error -
Fatal error: Call to a member function loadByIncrementId() on a non-object in /public_html/app/design/frontend/theme/default/template/checkout/success.phtml on line 87

Could someone please help me to resolve this issue?

答: I debugged checkout/success.phtml and found that the some useless code for send order mail which not found helper class so I found fatal error. I removed it and the error is not coming up anymore.</p>


问:
Polymer 2.0 syntax difference
I am new to Polymer and I am trying to clear the ideas.

I see this syntax around:

```<code><script>

Polymer({
  is: 'shop-app',
  properties: {
    page: {
      type: String,
      reflectToAttribute: true,
      observer: '_pageChanged'
    },
    //...
    </script>
</code>```

But in many tutorials (including this one from google https://codelabs.developers.google.com/codelabs/polymer-2-carousel) another syntax is used. I cannot seem to catch the difference. Why is used one instead of the other?

```<code><script>

// Extend Polymer.Element base class
class MyCarousel extends Polymer.Element {

  static get is() { return 'my-carousel' }

  connectedCallback() {
    super.connectedCallback();
  }

}

// Register custom element definition using standard platform API
customElements.define(MyCarousel.is, MyCarousel);

 </script>
</code>```

答:
The first code block you have posted is the Polymer 1.x way of doing things. You can still actually use those elements in Polymer 2.0, by importing the polymer/polymer.html as well as polymer/polymer-elements.html. They are known as hybrid components.

The class type syntax came along with javascript ES6. Not all javascript engines understand ES6 yet, so it is often necessary to use Babel to transpile the ES6 code to ES5.

Polymer 2.0 embraces ES6 with gusto and so you can now use the code in the second code block you posted to write Polymer elements. This new way is meant to show the developer just how close you are working to the browser components. Polymer.Element is actually an extension of a HTMLElement, which is the basic building block of elements in a browser.

Title: Polymer 2.0 syntax difference

Body:
I am new to Polymer and I am trying to clear the ideas.

I see this syntax around:

But in many tutorials (including this one from google https://codelabs.developers.google.com/codelabs/polymer-2-carousel) another syntax is used. I cannot seem to catch the difference. Why is used one instead of the other?


问:
Change ListView's ScrollBar/FastScroll color?
My app has an orange theme all over but the ScrollBar/FastScroll is appearing green. I've tried to search a lot but can't find any way to change this. It just stays the way it is.

I found a "android:fastScrollTextColor" property but that changes the color of the B inside the bubble. And I can't find any property to change the color of this bubble or the ScrollBar next to it.

In case it makes a difference I'm using the custom PinnedHeaderListView that I got from here to mimic the sticky headers in the lollipop contacts app.

答:
android:scrollbarThumbVertical will work fine. But if fastscroll is enabled in listView you should define android:fastScrollThumbDrawable in AppTheme or any theme and use it for the activity (in AndroidManifest) which contains listview with fastscroll enabled.

Part of styles.xml

```<code><style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:fastScrollThumbDrawable">@drawable/fast_scrollbar_vertical</item>
</style>
</code>```

part of manifest

```<code>    <activity
        android:name=".ListActivity"
        android:label="@string/title_activity_list"
        android:theme="@style/AppTheme" />
</code>```

and scrollbar drawable should be gradient

```<code><shape xmlns:android="http://schemas.android.com/apk/res/android" >

<gradient
    android:angle="45"
    android:endColor="@color/scroll_color"
    android:centerColor="@color/scroll_color"
    android:startColor="@color/scroll_color" />

<corners android:radius="8dp" />
<size android:width="8dp" android:height="100dp"/>
<padding
    android:left="0.5dp"
    android:right="0.5dp" />

</shape>
</code>```

Body:
android:scrollbarThumbVertical will work fine. But if fastscroll is enabled in listView you should define android:fastScrollThumbDrawable in AppTheme or any theme and use it for the activity (in AndroidManifest) which contains listview with fastscroll enabled.

Part of styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:fastScrollThumbDrawable">@drawable/fast_scrollbar_vertical</item>
</style>

part of manifest

    <activity
        android:name=".ListActivity"
        android:label="@string/title_activity_list"
        android:theme="@style/AppTheme" />

and scrollbar drawable should be gradient

<shape xmlns:android="http://schemas.android.com/apk/res/android" >

<gradient
    android:angle="45"
    android:endColor="@color/scroll_color"
    android:centerColor="@color/scroll_color"
    android:startColor="@color/scroll_color" />

<corners android:radius="8dp" />
<size android:width="8dp" android:height="100dp"/>
<padding
    android:left="0.5dp"
    android:right="0.5dp" />

</shape>