问:
Clear ComboBox if RadioButton is deactivated
I have five RadioButton and five ComboBox controls.

Each RadioButton is connected to a ComboBox.

When I activate one RadioButton, the corresponding ComboBox, it gets enabled.
Now when I choose another RadioButton, the information in the previously selected ComboBox should clear but does not!

I have tried with ComboBox.Clear() as well as ComboBox.Reset(), but it doesn't work.

Here is my code for one of the ComboBox and RadioButton

```<code>if (radioButtondinner.Checked == true)
        {
            comboBoxdinner.DataSource = DList.Dwork();
            comboBoxdinner.DisplayMember = "dinner";
        }
</code>```

答:
As I said in comment: you can use one Combobox and only to change data sources when you check other RadioButton that should work sure
But If you want to have more Combobox then just type in else statements

```<code>comboBox.DataSource = null;
</code>```

Body:
I have five RadioButton and five ComboBox controls.

Each RadioButton is connected to a ComboBox.

When I activate one RadioButton, the corresponding ComboBox, it gets enabled.
Now when I choose another RadioButton, the information in the previously selected ComboBox should clear but does not!

I have tried with ComboBox.Clear() as well as ComboBox.Reset(), but it doesn't work.

Here is my code for one of the ComboBox and RadioButton

if (radioButtondinner.Checked == true)
        {
            comboBoxdinner.DataSource = DList.Dwork();
            comboBoxdinner.DisplayMember = "dinner";
        }

Body:
As I said in comment: you can use one Combobox and only to change data sources when you check other RadioButton that should work sure
But If you want to have more Combobox then just type in else statements

comboBox.DataSource = null;


来源: stackexchange

问:
How to Deserialize from web service JSON array or object?
I created one web service application in windows phone 7. this is JSON array get from belowed uri.
...[{"id":4,"name":"Bangalore"},{"id":1,"name":"Chennai"},{"id":3,"name":"Hyderabad"},{"id":2,"name":"Mumbai"}]...

List item = (List)ds.ReadObject(msnew);
In this line one bug(it says while run).

There was an error deserializing the object of type.Data at the root level is invalid. Line 1, position 1.

coding:

public MainPage()
        {
            InitializeComponent();
        }

```<code>    [DataContract]
    public class Item
    {

        [DataMember]
        public int id
        {
            get;
            set;
        }

        [DataMember]
        public string name
        {
            get;
            set;
        }
    }
    private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
    {
        WebClient wc = new WebClient();
        wc.DownloadStringAsync(new Uri("http://75.101.161.83:8080/CityGuide/Cities?authId=CITY4@$pir*$y$t*m$13GUID*5"));
        wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
    }

    void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
       string MyJsonString = e.Result;
      // MessageBox.Show(e.Result);
       DataContractSerializer ds = new DataContractSerializer(typeof(Item));
       MemoryStream msnew = new MemoryStream(Encoding.UTF8.GetBytes(MyJsonString));
       List<Item> item = (List<Item>)ds.ReadObject(msnew);
    }
</code>```

答:
You can add System.Json library from Silverlight SDK.

It isn't compiled for WP7, but for me it is working fine.

ContentLicense: CC BY-SA 2.5

Body:
I created one web service application in windows phone 7. this is JSON array get from belowed uri.
...[{"id":4,"name":"Bangalore"},{"id":1,"name":"Chennai"},{"id":3,"name":"Hyderabad"},{"id":2,"name":"Mumbai"}]...

List item = (List)ds.ReadObject(msnew);
In this line one bug(it says while run).

There was an error deserializing the object of type.Data at the root level is invalid. Line 1, position 1.

coding:

public MainPage()
        {
            InitializeComponent();
        }

    [DataContract]
    public class Item
    {

        [DataMember]
        public int id
        {
            get;
            set;
        }

        [DataMember]
        public string name
        {
            get;
            set;
        }
    }
    private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
    {
        WebClient wc = new WebClient();
        wc.DownloadStringAsync(new Uri("http://75.101.161.83:8080/CityGuide/Cities?authId=CITY4@$pir*$y$t*m$13GUID*5"));
        wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
    }

    void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
       string MyJsonString = e.Result;
      // MessageBox.Show(e.Result);
       DataContractSerializer ds = new DataContractSerializer(typeof(Item));
       MemoryStream msnew = new MemoryStream(Encoding.UTF8.GetBytes(MyJsonString));
       List<Item> item = (List<Item>)ds.ReadObject(msnew);
    }


问:
Why enums with default values are not working as expected in C#?
I was going through Jon skeet website on C# Brain teasers http://www.yoda.arachsys.com/csharp/teasers.html. Why item "Baz" is showing in the output even though I declared default values for all items in enum

---eg:1

```<code>class Test
{

    enum Foo { Bar, Baz,bread, jam };

    const int One = 1;
    const int Une = 1;

    static void Main()
    {
        Foo f = 0;
        Console.WriteLine(f);
        Console.ReadLine();
    }
}
// output :Bar
</code>```

--eg2

```<code>class Test
{
    enum Foo { Bar, Baz,bread=0, jam };

    const int One = 1;
    const int Une = 1;

    static void Main()
    {
        Foo f = 0;
        Console.WriteLine(f);
        Console.ReadLine();
    }
}
//output : Bar
</code>```

--eg3

```<code>class Test
{
    enum Foo { Bar, Baz=0, bread=0, jam };

    const int One = 1;
    const int Une = 1;

    static void Main()
    {
        Foo f = 0;
        Console.WriteLine(f);
        Console.ReadLine();
    }
}
//output :Baz
</code>```

--eg4

```<code>class Test
{
    enum Foo { Bar=0, Baz=0, bread=0, jam=0};

    const int One = 1;
    const int Une = 1;

    static void Main()
    {
        Foo f = 0;
        Console.WriteLine(f);
        Console.ReadLine();
    }
}
//output:Baz
</code>```

答:
Enums are just integers to .NET. Any time you think of them as a name (like ToString(), you're actually saying "try to find a defined enum label that matches the
integer value, and tell me the name of that". In this case, you have multiple enum labels with the same integer value, so which name in WriteLine is undefined. Note that WriteLine here is ultimately doing f.ToString(), which applies the "find a value" logic from above.

For --eg5, I would propose: Foo f = (Foo)-1327861;. Perfectly valid in .NET terms, but doesn't match any enum definition. It doesn't have to.

ContentLicense: CC BY-SA 3.0

Body:
I was going through Jon skeet website on C# Brain teasers http://www.yoda.arachsys.com/csharp/teasers.html. Why item "Baz" is showing in the output even though I declared default values for all items in enum

---eg:1

class Test
{

    enum Foo { Bar, Baz,bread, jam };

    const int One = 1;
    const int Une = 1;

    static void Main()
    {
        Foo f = 0;
        Console.WriteLine(f);
        Console.ReadLine();
    }
}
// output :Bar

--eg2

class Test
{
    enum Foo { Bar, Baz,bread=0, jam };

    const int One = 1;
    const int Une = 1;

    static void Main()
    {
        Foo f = 0;
        Console.WriteLine(f);
        Console.ReadLine();
    }
}
//output : Bar

--eg3

class Test
{
    enum Foo { Bar, Baz=0, bread=0, jam };

    const int One = 1;
    const int Une = 1;

    static void Main()
    {
        Foo f = 0;
        Console.WriteLine(f);
        Console.ReadLine();
    }
}
//output :Baz

--eg4

class Test
{
    enum Foo { Bar=0, Baz=0, bread=0, jam=0};

    const int One = 1;
    const int Une = 1;

    static void Main()
    {
        Foo f = 0;
        Console.WriteLine(f);
        Console.ReadLine();
    }
}
//output:Baz


问:
Is is possible to set the buffer size with mediaelement.js?
Is it possible to set a larger buffer size with mediaelement.js?

The idea would be to experiment with trading off a smoother playback at the cost of a slightly longer startup time,or visa versa.

答:
As time has passed and Adaptive Bir Rate (ABR) streaming has become much more common, I think it is worth updating to say that while the original question is still valid, ABR provides a method to allow quicker startup at the cost of video quality, or slower startup and better quality.

ABR format streaming essentially means that there is not just a single bit rate.

Multiple bit rate versions of the video are created and each one is broken down into equal length (by time) chunks - e.g. 10 second chunks.

The client player is then able to select the next chunk from the most appropriate bit rate stream for the current network conditions - if the network gets busy it can drop down to a lower bit rate for the next chunk and visa versa if the network is good.

It also allows a video to start more quickly by selecting a low bit rate initially and then to step up to higher bit rates, network conditions allowing, once the video is playing.

You can see a visualisation of the bit rate steps on YouTube by right clicking and looking at the 'stats for nerds' option - see example below:

You can also see the available bit rates, and force the player to select a single one by clicking on the 'wheel' in the bottom right hand corner.


问:
How to use one CSV file to pass data into multiple HTTP Samples in Jmeter?
I want to pass test data from one csv file to multiple http requests like first row should take by 1st http sample and second row should take by 2nd http sample.Please help how to use this in jmeter.</p>

答:
If you need to read a specific (arbitrary) line from a file with each Sampler you can use i.e. __groovy() function for this like:

${__groovy(new File('/path/to/your/file').readLines().get(0),)} - read 1st string

${__groovy(new File('/path/to/your/file').readLines().get(1),)} - read 2nd string

${__groovy(new File('/path/to/your/file').readLines().get(2),)} - read 3rd string

etc.

Demo:

File.readLines() method is a Groovy JDK enhancement to provide some "syntactic sugar" on top of "normal" Java to make developers lives easier.

See Groovy is the New Black article to get started with using Groovy scripting in JMeter tests.


问:
Angular 4 - getting json data from service not working
I have a file with dummy json data in my project, where I would like to get that data from and make a list with in my template with that. I have set up a method in services where I get the data from that json file.

```<code>get(): Observable<string[]> {
    return this.http.get('services/getUsers.json')
                    .map((res: Response) => console.log(res.json()))
                    .catch(this.handleError);
 }
</code>```

That part works fine, I get that data from the console.log(res.json() in the method.
The component that I have set up looks like this:

```<code>users: any[] = [];

ngOnInit() {
    this.getAddresses();
}

getUsers() {
   this.usersService.get()
      .subscribe(
        users => this.users = users,
        error => this.errorMessage = <any>error
    );
}
</code>```

But, when I try to display that data in the template, I don't get anything:

```<code><div class="row">
    <div class="col-md-6">
      <ul class="list-group posts">
          <li *ngFor="let user of users" class="list-group-item">
              {{ user.name }}
          </li>
      </ul>
    </div>
</div>
</code>```

答:
Change

```<code>.map((res: Response) => console.log(res.json()))
</code>```

to

```<code>.map((res: Response) => res.json())
</code>```

which is the short version of

```<code>.map((res: Response) => { return res.json();})
</code>```

you need to return something in your map function

Body:
I have a file with dummy json data in my project, where I would like to get that data from and make a list with in my template with that. I have set up a method in services where I get the data from that json file.

get(): Observable<string[]> {
    return this.http.get('services/getUsers.json')
                    .map((res: Response) => console.log(res.json()))
                    .catch(this.handleError);
 }

That part works fine, I get that data from the console.log(res.json() in the method.
The component that I have set up looks like this:

users: any[] = [];

ngOnInit() {
    this.getAddresses();
}

getUsers() {
   this.usersService.get()
      .subscribe(
        users => this.users = users,
        error => this.errorMessage = <any>error
    );
}

But, when I try to display that data in the template, I don't get anything:

              {{ user.name }}

Body:
Change

.map((res: Response) => console.log(res.json()))

to

.map((res: Response) => res.json())

which is the short version of

.map((res: Response) => { return res.json();})

you need to return something in your map function


问:
Linux terminal not working in VMware
Unfortunately I deleted some files when I login,I restarted my system and second open VMware and open my virtual machine after booting In login page is stuck,mouse not working to login</p>

答:
what files did you delete?
you can enter the text mode by pressing ctrl+alt+f2 and check your file system

Title: Linux terminal not working in VMware


问:
how to get average of certain column values in table
I'm a beginner so I'm not sure whats wrong here. What im trying to achieve is to check if certain cells in a table (column) has numerical values in them and if they do include them in calculating the average value upon losing focus (blur) so that it would kind of be real time.

I'm not sure if calculation function is wrong itself, or if I'm addressing wrong column maybe or trying to insert calculated value in the wrong way. help would be appreciated.

Here is JSfiddle and the code excerpts:
https://jsfiddle.net/NulisDefo/03rn7ew1/5/

table

```<code><table id="myTable" class="table table-inverse">
    <thead id = "headings" class = "thead-default">
      <tr>
        <th>Tabelio Nr.</th>
        <th>Vardas</th>
        <th>Pavardė</th>
        <th>Pareigos</th>
        <th>Bazinė alga, €</th>
        <th>Valandinis atlyginimas, €</th>
        <th>Veiksmai</th>
      </tr>
    </thead>
    <tfoot class = "thead-default">
      <tr>
        <td colspan = "4">Vidurkis</td>
        <!-- <td></td>
        <td></td>
        <td></td> -->
        <td id = "alga">0</td>
        <td id = "valandinis" colspan = "2">0</td>
        <!-- <td></td> -->
      </tr>
    </tfoot>
    <tbody>
      <tr>
        <td>1</td>
        <td>Mark</td>
        <td>Otto</td>
        <td>@mdo</td>
        <td>1000</td>
        <td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
        <td>
          <p class = "btn editbtn"><span class = "fa fa-edit"></span></p>
          <p class = "btn" onclick="deleteRow(this)"><span class = "fa fa-trash"></span></p>
        </td>
      </tr>
      <tr>
        <td>2</td>
        <td>Jacob</td>
        <td>Thornton</td>
        <td>@fat</td>
        <td>2000</td>
        <td>blum</td>
        <td>
          <p class = "btn editbtn"><span class = "fa fa-edit"></span></p>
          <p class = "btn" onclick="deleteRow(this)"><span class = "fa fa-trash"></span></p>
        </td>
      </tr>
      <tr class = "testas">
        <td>3</td>
        <td>Larry</td>
        <td>the Bird</td>
        <td>@twitter</td>
        <td>5000</td>
        <td>blum</td>
        <td>
          <p class = "btn editbtn"><span class = "fa fa-edit"></span></p>
          <p class = "btn" onclick="deleteRow(this)"><span class = "fa fa-trash"></span></p>
        </td>
      </tr>
    </tbody>
  </table>
</code>```

script for calculating and trigger

```<code>$("table").on("blur", "td", function(){
calculate();
} );

function calculate() {
  var sum = 0;
  var counter = 0 //daliklis
  $('#myTable tbody tr td:nth-child(5)').each(function() {
  // $("table tbody tr td:eq(4)").each(function(){
    if (!isNaN(this.value))
    {
      sum += parseFloat($(this).text());
      counter += 1;
    }
    });
    $("#alga").textContent(sum/counter);
};
</code>```

I should probably mention, that prior existing entries can be edited only after pressing edit button.

EDIT: Ok, so apparently all of the solutions work, but the problem is, that if cell is empty, instead of excluding that part from calculation the returned result is NaN

答:
Your loop was not proper. Checkout the jsFiddle Demo  .Now you just need to decide when to trigger calculate function which I think you can handle

```<code> function calculate() {
      var sum = 0;
      var counter = 0 //daliklis
      $('#myTable tbody tr').each(function() {
      // $("table tbody tr td:eq(4)").each(function(){
        var a = $(this).children('td:nth-child(5)');
        if (!isNaN(a.text()))
        {
          sum += parseFloat(a.html()); console.log(sum);
          counter += 1;
        }
        });
        $("#alga").text(sum/counter);
    }
</code>```

jsFiddle Demo

Body:
I'm a beginner so I'm not sure whats wrong here. What im trying to achieve is to check if certain cells in a table (column) has numerical values in them and if they do include them in calculating the average value upon losing focus (blur) so that it would kind of be real time.

I'm not sure if calculation function is wrong itself, or if I'm addressing wrong column maybe or trying to insert calculated value in the wrong way. help would be appreciated.

Here is JSfiddle and the code excerpts:
https://jsfiddle.net/NulisDefo/03rn7ew1/5/

table

        Tabelio Nr.
        Vardas
        Pavardė
        Pareigos
        Bazinė alga, €
        Valandinis atlyginimas, €
        Veiksmai

        Vidurkis

        0
        0

        1
        Mark
        Otto
        @mdo
        1000
        <input type="button" value="Delete" onclick="deleteRow(this)">

        2
        Jacob
        Thornton
        @fat
        2000
        blum

        3
        Larry
        the Bird
        @twitter
        5000
        blum

script for calculating and trigger

$("table").on("blur", "td", function(){
calculate();
} );

function calculate() {
  var sum = 0;
  var counter = 0 //daliklis
  $('#myTable tbody tr td:nth-child(5)').each(function() {
  // $("table tbody tr td:eq(4)").each(function(){
    if (!isNaN(this.value))
    {
      sum += parseFloat($(this).text());
      counter += 1;
    }
    });
    $("#alga").textContent(sum/counter);
};

I should probably mention, that prior existing entries can be edited only after pressing edit button.

EDIT: Ok, so apparently all of the solutions work, but the problem is, that if cell is empty, instead of excluding that part from calculation the returned result is NaN

Body:
Your loop was not proper. Checkout the jsFiddle Demo  .Now you just need to decide when to trigger calculate function which I think you can handle

 function calculate() {
      var sum = 0;
      var counter = 0 //daliklis
      $('#myTable tbody tr').each(function() {
      // $("table tbody tr td:eq(4)").each(function(){
        var a = $(this).children('td:nth-child(5)');
        if (!isNaN(a.text()))
        {
          sum += parseFloat(a.html()); console.log(sum);
          counter += 1;
        }
        });
        $("#alga").text(sum/counter);
    }

jsFiddle Demo


答:
Consider this example:

```<code>enum Foo { Bar, Baz,bread=0, jam=0};

public static void Main()
{
    Console.WriteLine((int)Foo.Bar);  // 0
    Console.WriteLine((int)Foo.Baz);  // 1
    Console.WriteLine((int)Foo.bread); // 0
    Console.WriteLine((int)Foo.jam);  // 0
}
</code>```

So we can say that if we wont assign any integer values to the first item in the enum will be assigned with 0 and next item will be previous item value + 1 if you assign some values then it will overwrite the default incremented values.

Take a look into this Example

Title: Why enums with default values are not working as expected in C#?

Body:
Consider this example:

enum Foo { Bar, Baz,bread=0, jam=0};

public static void Main()
{
    Console.WriteLine((int)Foo.Bar);  // 0
    Console.WriteLine((int)Foo.Baz);  // 1
    Console.WriteLine((int)Foo.bread); // 0
    Console.WriteLine((int)Foo.jam);  // 0
}

So we can say that if we wont assign any integer values to the first item in the enum will be assigned with 0 and next item will be previous item value + 1 if you assign some values then it will overwrite the default incremented values.

Take a look into this Example


问:
Direct way of telling ifelse to ignore NA
As explained here when the test condition in ifelse(test, yes, no) is NA, the evaluation is also NA. Hence the following returns...

```<code>df <- data.frame(a = c(1, 1, NA, NA, NA ,NA),
                 b = c(NA, NA, 1, 1, NA, NA),
                 c = c(rep(NA, 4), 1, 1))
ifelse(df$a==1, "a==1",
    ifelse(df$b==1, "b==1",
        ifelse(df$c==1, "c==1", NA)))
#[1] "a==1" "a==1" NA     NA     NA     NA
</code>```

... instead of the desired

```<code>#[1] "a==1" "a==1" "b==1" "b==1"  "c==1" "c==1"
</code>```

As suggested by Cath, I can circumvent this problem by formally specifying that the test condition should not include NA:

```<code>ifelse(df$a==1 &  !is.na(df$a), "a==1",
    ifelse(df$b==1 & !is.na(df$b), "b==1",
        ifelse(df$c==1 & !is.na(df$c), "c==1", NA)))
</code>```

However, as akrun also noted, this solution becomes rather lengthy with increasing number of columns.

A workaround would be to first replace all NAs with a value not present in the data.frame (e.g, 2 in this case):

```<code>df_noNA <- data.frame(a = c(1, 1, 2, 2, 2 ,2),
                 b = c(2, 2, 1, 1, 2, 2),
                 c = c(rep(2, 4), 1, 1))

ifelse(df_noNA$a==1, "a==1",
    ifelse(df_noNA$b==1, "b==1",
        ifelse(df_noNA$c==1, "c==1", NA)))
#[1] "a==1" "a==1" "b==1" "b==1"  "c==1" "c==1"
</code>```

However, I was wondering if there was a more direct way to tell ifelse to ignore NAs? Or is writing a function for & !is.na the most direct way?

```<code>ignorena <- function(column) {
        column ==1 & !is.na(column)
}
ifelse(ignorena(df$a), "a==1",
    ifelse(ignorena(df$b), "b==1",
        ifelse(ignorena(df$c), "c==1", NA)))
#[1] "a==1" "a==1" "b==1" "b==1"  "c==1" "c==1"
</code>```

答:
You can use %in% instead of == to sort-of ignore NAs.

```<code>ifelse(df$a %in% 1, "a==1",
       ifelse(df$b %in% 1, "b==1",
              ifelse(df$c %in% 1, "c==1", NA)))
</code>```

Unfortunately, this does not give any performance gain compared to the original while @arkun's solution is about 3 times faster.

```<code>solution_original <- function(){
  ifelse(df$a==1 &  !is.na(df$a), "a==1",
         ifelse(df$b==1 & !is.na(df$b), "b==1",
                ifelse(df$c==1 & !is.na(df$c), "c==1", NA)))
}

solution_akrun <- function(){
  v1 <- names(df)[max.col(!is.na(df)) * NA^!rowSums(!is.na(df))]
  i1 <- !is.na(v1)
  v1[i1] <- paste0(v1[i1], "==1")
}

solution_mine <- function(x){
  ifelse(df$a %in% 1, "a==1",
         ifelse(df$b %in% 1, "b==1",
                ifelse(df$c %in% 1, "c==1", NA)))
}
set.seed(1)
df <- data.frame(a = sample(c(1, rep(NA, 4)), 1e6, T),
                 b = sample(c(1, rep(NA, 4)), 1e6, T),
                 c = sample(c(1, rep(NA, 4)), 1e6, T))
microbenchmark::microbenchmark(
  solution_original(),
  solution_akrun(),
  solution_mine()
)
## Unit: milliseconds
##                expr      min       lq     mean   median       uq       max neval
## solution_original() 701.9413 839.3715 845.0720 853.1960 875.6151 1051.6659   100
##    solution_akrun() 217.4129 242.5113 293.2987 253.2144 387.1598  564.3981   100
##     solution_mine() 698.7628 845.0822 848.6717 858.7892 877.9676 1006.2872   100
</code>```

Was inspired by this: R: Dealing with TRUE, FALSE, NA and NaN

Edit

Following the comment by @arkun, I redid the benchmark and revised the statement.

Body:
As explained here when the test condition in ifelse(test, yes, no) is NA, the evaluation is also NA. Hence the following returns...

df <- data.frame(a = c(1, 1, NA, NA, NA ,NA),
                 b = c(NA, NA, 1, 1, NA, NA),
                 c = c(rep(NA, 4), 1, 1))
ifelse(df$a==1, "a==1",
    ifelse(df$b==1, "b==1",
        ifelse(df$c==1, "c==1", NA)))
#[1] "a==1" "a==1" NA     NA     NA     NA

... instead of the desired

#[1] "a==1" "a==1" "b==1" "b==1"  "c==1" "c==1"

As suggested by Cath, I can circumvent this problem by formally specifying that the test condition should not include NA:

ifelse(df$a==1 &  !is.na(df$a), "a==1",
    ifelse(df$b==1 & !is.na(df$b), "b==1",
        ifelse(df$c==1 & !is.na(df$c), "c==1", NA)))

However, as akrun also noted, this solution becomes rather lengthy with increasing number of columns.

A workaround would be to first replace all NAs with a value not present in the data.frame (e.g, 2 in this case):

df_noNA <- data.frame(a = c(1, 1, 2, 2, 2 ,2),
                 b = c(2, 2, 1, 1, 2, 2),
                 c = c(rep(2, 4), 1, 1))

ifelse(df_noNA$a==1, "a==1",
    ifelse(df_noNA$b==1, "b==1",
        ifelse(df_noNA$c==1, "c==1", NA)))
#[1] "a==1" "a==1" "b==1" "b==1"  "c==1" "c==1"

However, I was wondering if there was a more direct way to tell ifelse to ignore NAs? Or is writing a function for & !is.na the most direct way?

ignorena <- function(column) {
        column ==1 & !is.na(column)
}
ifelse(ignorena(df$a), "a==1",
    ifelse(ignorena(df$b), "b==1",
        ifelse(ignorena(df$c), "c==1", NA)))
#[1] "a==1" "a==1" "b==1" "b==1"  "c==1" "c==1"

Body:
You can use %in% instead of == to sort-of ignore NAs.

ifelse(df$a %in% 1, "a==1",
       ifelse(df$b %in% 1, "b==1",
              ifelse(df$c %in% 1, "c==1", NA)))

Unfortunately, this does not give any performance gain compared to the original while @arkun's solution is about 3 times faster.

solution_original <- function(){
  ifelse(df$a==1 &  !is.na(df$a), "a==1",
         ifelse(df$b==1 & !is.na(df$b), "b==1",
                ifelse(df$c==1 & !is.na(df$c), "c==1", NA)))
}

solution_akrun <- function(){
  v1 <- names(df)[max.col(!is.na(df)) * NA^!rowSums(!is.na(df))]
  i1 <- !is.na(v1)
  v1[i1] <- paste0(v1[i1], "==1")
}

solution_mine <- function(x){
  ifelse(df$a %in% 1, "a==1",
         ifelse(df$b %in% 1, "b==1",
                ifelse(df$c %in% 1, "c==1", NA)))
}
set.seed(1)
df <- data.frame(a = sample(c(1, rep(NA, 4)), 1e6, T),
                 b = sample(c(1, rep(NA, 4)), 1e6, T),
                 c = sample(c(1, rep(NA, 4)), 1e6, T))
microbenchmark::microbenchmark(
  solution_original(),
  solution_akrun(),
  solution_mine()
)
## Unit: milliseconds
##                expr      min       lq     mean   median       uq       max neval
## solution_original() 701.9413 839.3715 845.0720 853.1960 875.6151 1051.6659   100
##    solution_akrun() 217.4129 242.5113 293.2987 253.2144 387.1598  564.3981   100
##     solution_mine() 698.7628 845.0822 848.6717 858.7892 877.9676 1006.2872   100

Was inspired by this: R: Dealing with TRUE, FALSE, NA and NaN

Edit

Following the comment by @arkun, I redid the benchmark and revised the statement.


问:
How can I convert a comma-separated string to an array?
I have a comma-separated string that I want to convert into an array, so I can loop through it.

Is there anything built-in to do this?

For example, I have this string

```<code>var str = "January,February,March,April,May,June,July,August,September,October,November,December";
</code>```

Now I want to split this by the comma, and then store it in an array.

答:
Watch out if you are aiming at integers, like 1,2,3,4,5. If you intend to use the elements of your array as integers and not as strings after splitting the string, consider converting them into such.

```<code>var str = "1,2,3,4,5,6";
var temp = new Array();
// This will return an array with strings "1", "2", etc.
temp = str.split(",");
</code>```

Adding a loop like this,

```<code>for (a in temp ) {
    temp[a] = parseInt(temp[a], 10); // Explicitly include base as per Álvaro's comment
}
</code>```

will return an array containing integers, and not strings.

ContentLicense: CC BY-SA 4.0

Body:
I have a comma-separated string that I want to convert into an array, so I can loop through it.

Is there anything built-in to do this?

For example, I have this string

var str = "January,February,March,April,May,June,July,August,September,October,November,December";

Now I want to split this by the comma, and then store it in an array.

Body:
Watch out if you are aiming at integers, like 1,2,3,4,5. If you intend to use the elements of your array as integers and not as strings after splitting the string, consider converting them into such.

var str = "1,2,3,4,5,6";
var temp = new Array();
// This will return an array with strings "1", "2", etc.
temp = str.split(",");

Adding a loop like this,

for (a in temp ) {
    temp[a] = parseInt(temp[a], 10); // Explicitly include base as per Álvaro's comment
}

will return an array containing integers, and not strings.


问:
Make draggable Live Helper Chat widget iframe when draggable image is disallow
I have a WordPress website where I activated a protection for disallow image drag and drop because this allow visitor to drag and save on the Desktop images...

As soon I activate the option to disallow image drag is disabled also the possibility to drag the live helper chat widget that I have on footer right bottom of the screen.

I want exclude this element from the protection so user can move (drag) the widget of the chat. Any help or suggestion, please?

I know usually in the web is not liked protection like disable right click etc... but let me decide this on my website, I AM looking now for a solution to allow this x-frame option to be draggable again also with the active protection.
Thanks, any help will be very appreciated.

答:
OK I do not find how to solve this issue but I found that disable block to prevent image drag and put this code:

```<code>/* Example 1: Makes all the img non-reactive to any mouse events such as dragging, hovering, clicking etc */
img {
  pointer-events: none;
}
</code>```

Solve my issue by making the image not draggable.

Body:
OK I do not find how to solve this issue but I found that disable block to prevent image drag and put this code:

/* Example 1: Makes all the img non-reactive to any mouse events such as dragging, hovering, clicking etc */
img {
  pointer-events: none;
}

Solve my issue by making the image not draggable.


问:
How to get HttpOnly cookies from awesomium?
I want to get ALL cookies from the site, but most of them are HttpOnly.

JS does not work:

```<code>var cookie = webControl.ExecuteJavascriptWithResult("document.cookie;");
</code>```

How to get HttpOnly cookies?

答:
why you're trying to get Cookies back from Javascript? ...
the best opinion to get all Headers (including Cookies) is to use Awesomium with a Proxy written also in C# ...

Wiki: ProxyConfig
http://docs.awesomium.net/html/P_Awesomium_Core_WebPreferences_ProxyConfig.htm

Github C# Proxy:
https://github.com/justcoding121/Titanium-Web-Proxy

Titanium has 2 useful Events:

```<code>proxyServer.BeforeRequest += OnRequest;
proxyServer.BeforeResponse += OnResponse;
</code>```

a Simple implementation which gave you the SystemEventArgs is:

```<code>public async Task OnRequest(object sender, SessionEventArgs e)
public async Task OnResponse(object sender, SessionEventArgs e)
</code>```

After implementation you have the possibilty to grap all Headers and delete or modifiy it :)

Hope it helps ...

Body:
I want to get ALL cookies from the site, but most of them are HttpOnly.

JS does not work:

var cookie = webControl.ExecuteJavascriptWithResult("document.cookie;");

How to get HttpOnly cookies?

Body:
why you're trying to get Cookies back from Javascript? ...
the best opinion to get all Headers (including Cookies) is to use Awesomium with a Proxy written also in C# ...

Wiki: ProxyConfig
http://docs.awesomium.net/html/P_Awesomium_Core_WebPreferences_ProxyConfig.htm

Github C# Proxy:
https://github.com/justcoding121/Titanium-Web-Proxy

Titanium has 2 useful Events:

proxyServer.BeforeRequest += OnRequest;
proxyServer.BeforeResponse += OnResponse;

a Simple implementation which gave you the SystemEventArgs is:

public async Task OnRequest(object sender, SessionEventArgs e)
public async Task OnResponse(object sender, SessionEventArgs e)

After implementation you have the possibilty to grap all Headers and delete or modifiy it :)

Hope it helps ...


问:
How do I write a SQL Query to fetch data according to a specific format/ pattern of String?
I need to write a SQL query to fetch data according to a specific format of String. I need to fetch those records where the LOC column of my query looks like the following:

```<code>Cx-xxx-Lx
Or
Cxx-xxx-Lx
Or
x-xxx-Lx
Or
xx-xxx-Lx
Or
xxxxxLx_x
Or
xxxxxLx_xx
Or
BxxxLLxxxx
Where :-
x is a number (0 to 9)
L is a letter (A to Z)
</code>```

I have filtered the LOC column to fetch data where the length of the record is either 9 or 10. Although this is fetching correct data from the DB, this is not a correct way of doing so.

My current SQL:

```<code>select * from table
where length(LOC) in (9,10)
</code>```

Any help would be appreciated.

答:
You can use regular expressions.  Something like:

```<code>where regexp_like(LOC, '^C?[0-9]{1,2}-[0-9]{3}-[A-Z][0-9]$') or
      regexp_like(LOC, '^[0-9]{5}[A-Z][0-9]_[0-9]{1,2}$') or
      regexp_like(LOC, '^B[0-9]{3}[A-Z]{2}[0-9]{4}$')
</code>```

You can combine these into one regular expression using |.  I think it is easier to follow and debug as three separate expressions.

Body:
I need to write a SQL query to fetch data according to a specific format of String. I need to fetch those records where the LOC column of my query looks like the following:

Cx-xxx-Lx
Or
Cxx-xxx-Lx
Or
x-xxx-Lx
Or
xx-xxx-Lx
Or
xxxxxLx_x
Or
xxxxxLx_xx
Or
BxxxLLxxxx
Where :-
x is a number (0 to 9)
L is a letter (A to Z)

I have filtered the LOC column to fetch data where the length of the record is either 9 or 10. Although this is fetching correct data from the DB, this is not a correct way of doing so.

My current SQL:

select * from table
where length(LOC) in (9,10)

Any help would be appreciated.

Body:
You can use regular expressions.  Something like:

where regexp_like(LOC, '^C?[0-9]{1,2}-[0-9]{3}-[A-Z][0-9]$') or
      regexp_like(LOC, '^[0-9]{5}[A-Z][0-9]_[0-9]{1,2}$') or
      regexp_like(LOC, '^B[0-9]{3}[A-Z]{2}[0-9]{4}$')

You can combine these into one regular expression using |.  I think it is easier to follow and debug as three separate expressions.


问:
How to set default mode headset in android
I am working on a VoIP app, I get an issue when user unplugs headphone then device automatically switches to loud speaker but I want device to switch to normal speaker. Is there any way I can change it to normal speaker?</p>

答:
To turn on earpiece programmatically try this:

```<code>audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

private void useEarpiece() {
    audioManager.setMode(AudioManager.MODE_IN_CALL);
    audioManager.setSpeakerphoneOn(false);
}
</code>```

Check your permission:

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

To catch event:

```<code>private class HeadSetReceiver extends BroadcastReceiver {
    @Override public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
            int state = intent.getIntExtra("state", -1);
            switch (state) {
            case 0:
                // Headset unplugged
                break;
            case 1:
                // Headset plugged in
                break;
            }
        }
    }
}
</code>```

Body:
To turn on earpiece programmatically try this:

audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

private void useEarpiece() {
    audioManager.setMode(AudioManager.MODE_IN_CALL);
    audioManager.setSpeakerphoneOn(false);
}

Check your permission:

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

To catch event:

private class HeadSetReceiver extends BroadcastReceiver {
    @Override public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
            int state = intent.getIntExtra("state", -1);
            switch (state) {
            case 0:
                // Headset unplugged
                break;
            case 1:
                // Headset plugged in
                break;
            }
        }
    }
}


问:
How read auto start permission for my app in MIUI phone
I am trying to get(programaticaly) auto start option value(on/off) of my app in MIUI devices. On the base of its value, i need to open security app from my app to set auto start value.

Your help is appreciated.
Thanks

答:
You can do it via official MI intent</p>

```<code>Intent intent = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS");
intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
intent.putExtra("extra_pkgname", "app_package_name");
</code>```

Body:
You can do it via official MI intent

Intent intent = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS");
intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
intent.putExtra("extra_pkgname", "app_package_name");


Title: How to sort a NumPy array of strings by the last column

Body:
Is there a way to sort the rows of an array by the last element, in this case the cell ids. The cell id is build as follows : "CellID_NumberOfCell

arr =np.array([['65.0','30.0','20.0','0.0','0_0'],
 ['2.0','29.0','24.0','0.0','1_0'],
 ['0.0','18.0','4.0','0.0','2_0'],
 ['16.0','9.0','0.0','9990.0','7_203'],
 ['16.0','9.0','0.0','9990.0','0_203'],
 ['20.0','23.0','31.0','9990.0','8_158'],
 ['65.0','30.0','20.0','0.0','0_10']])

So after sorting it should look like:

arr =np.array([['65.0','30.0','20.0','0.0','0_0'],
 ['65.0','30.0','20.0','0.0','0_10'],
 ['16.0','9.0','0.0','9990.0','0_203'],
 ['2.0','29.0','24.0','0.0','1_0'],
 ['0.0','18.0','4.0','0.0','2_0'],
 ['16.0','9.0','0.0','9990.0','7_203'],
 ['20.0','23.0','31.0','9990.0','8_158']])

EDIT:

Is it also possible to delete the numbers after the underscore after sorting?. So that i just have the ID. Instead of 0_0 just 0.

EDIT2

After sorting the ID, it should also sort after time, so that every ID with 0 for example should also be sorted after time 0,1...9999 etc.

Body:
You can do it easely with sorted and lambda function and as suggested by @Divakar to get the numpy array back:

np.array(sorted(arr, key=lambda x :x[-1]))

output

[['65.0', '30.0', '20.0', '0.0', '0_0'],
['65.0', '30.0', '20.0', '0.0', '0_10'],
['16.0', '9.0', '0.0', '9990.0', '0_203'],
['2.0', '29.0', '24.0', '0.0', '1_0'],
['0.0', '18.0', '4.0', '0.0', '2_0'],
['16.0', '9.0', '0.0', '9990.0', '7_203'],
['20.0', '23.0', '31.0', '9990.0', '8_158']]

EDIT :
 you can do it by using this, not pretty, but does the work

np.array([ np.append(i[:-1],i[-1].split("_")[0]) for i in sorted(list(arr), key=lambda x :x[-1])])

ouput

array([['65.0', '30.0', '20.0', '0.0', '0'],
       ['65.0', '30.0', '20.0', '0.0', '0'],
       ['16.0', '9.0', '0.0', '9990.0', '0'],
       ['2.0', '29.0', '24.0', '0.0', '1'],
       ['0.0', '18.0', '4.0', '0.0', '2'],
       ['16.0', '9.0', '0.0', '9990.0', '7'],
       ['20.0', '23.0', '31.0', '9990.0', '8']],
      dtype='<U6')


问:
Swift indexPathsForSelectedRows returns nil
I am working on a tableView, goal is to implement a expandible/collapsible tableView cells. The number of cells is completely dynamic.

I have things working, but with a small problem. I am using didSelectRowAtIndexPath to toggle expand/collapse cell. So what happens now is the toggle executes by tapping anywhere on the cell. :-(

Inside the cell, I have two UIViews (Header and Detail precisely). I need the toggle expand/collapse to work only when I tap on Header and not the whole cell.

For that, I am fetching the indexPath like here but that doesn't work since indexPathsForSelectedRows returns nil.

```<code>func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myVouchers.count
    }

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if selectedIndex == indexPath.row {
            return 150.0
        }
        else {
            return 40.0
        }
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        cell = tableView.dequeueReusableCellWithIdentifier("CollapsedCell", forIndexPath: indexPath) as! CollapsedCell

        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(VoucherDetailViewController.expandCell(_:)))
        (cell as! CollapsedCell).headerView.addGestureRecognizer(tapGestureRecognizer)

        return cell
    }

    func getIndexPathForSelectedCell() -> NSIndexPath? {

        var indexPath: NSIndexPath?

        if tableView.indexPathsForSelectedRows?.count > 0 {   //**nil is returned here**
            indexPath = (tableView.indexPathsForSelectedRows?[0])! as NSIndexPath
        }
        return indexPath
    }

    func expandCell(sender: UITapGestureRecognizer) {
        if let myIndexPath = getIndexPathForSelectedCell() {
            if selectedIndex == myIndexPath.row {
                selectedIndex = -1
            }
            else {
                selectedIndex = myIndexPath.row
            }

            self.tableView.beginUpdates()
            self.tableView.reloadRowsAtIndexPaths([myIndexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
            self.tableView.endUpdates()
        }
    }
</code>```

Could someone give me a clue why the indexPathsForSelectedRows returns nil?

Many Thanks!

UPDATE 1:
Current Working demo

When I add my expand cell logic in didSelectRowAtIndexPath and remove my tapGestureRecognizer for the view inside the cell - it looks like this -

```<code>func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        if selectedIndex == indexPath.row {
            selectedIndex = -1
        }
        else {
            selectedIndex = indexPath.row
        }

        self.tableView.beginUpdates()
        self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
        self.tableView.endUpdates()
    }
</code>```

答:
From the indexPathsForSelectedRows documentation:

The value of this property is nil if there are no selected rows.

Therefore:

```<code>guard let selectedRows = tableView.indexPathsForSelectedRows else {
   return nil
}

return selectedRows[0]
</code>```

(no check for count is needed, the method never returns an empty array).

By the way, you could simplify the condition using:

```<code>return tableView.indexPathsForSelectedRows?.first
</code>```

or, if your table does not support multiple selection, directly call:

```<code>return tableView.indexPathForSelectedRow
</code>```

which is already there.

Body:
I am working on a tableView, goal is to implement a expandible/collapsible tableView cells. The number of cells is completely dynamic.

I have things working, but with a small problem. I am using didSelectRowAtIndexPath to toggle expand/collapse cell. So what happens now is the toggle executes by tapping anywhere on the cell. :-(

Inside the cell, I have two UIViews (Header and Detail precisely). I need the toggle expand/collapse to work only when I tap on Header and not the whole cell.

For that, I am fetching the indexPath like here but that doesn't work since indexPathsForSelectedRows returns nil.

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myVouchers.count
    }

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if selectedIndex == indexPath.row {
            return 150.0
        }
        else {
            return 40.0
        }
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        cell = tableView.dequeueReusableCellWithIdentifier("CollapsedCell", forIndexPath: indexPath) as! CollapsedCell

        let tapGestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(VoucherDetailViewController.expandCell(_:)))
        (cell as! CollapsedCell).headerView.addGestureRecognizer(tapGestureRecognizer)

        return cell
    }

    func getIndexPathForSelectedCell() -> NSIndexPath? {

        var indexPath: NSIndexPath?

        if tableView.indexPathsForSelectedRows?.count > 0 {   //**nil is returned here**
            indexPath = (tableView.indexPathsForSelectedRows?[0])! as NSIndexPath
        }
        return indexPath
    }

    func expandCell(sender: UITapGestureRecognizer) {
        if let myIndexPath = getIndexPathForSelectedCell() {
            if selectedIndex == myIndexPath.row {
                selectedIndex = -1
            }
            else {
                selectedIndex = myIndexPath.row
            }

            self.tableView.beginUpdates()
            self.tableView.reloadRowsAtIndexPaths([myIndexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
            self.tableView.endUpdates()
        }
    }

Could someone give me a clue why the indexPathsForSelectedRows returns nil?

Many Thanks!

UPDATE 1:
Current Working demo

When I add my expand cell logic in didSelectRowAtIndexPath and remove my tapGestureRecognizer for the view inside the cell - it looks like this -

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

        if selectedIndex == indexPath.row {
            selectedIndex = -1
        }
        else {
            selectedIndex = indexPath.row
        }

        self.tableView.beginUpdates()
        self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
        self.tableView.endUpdates()
    }

Body:
From the indexPathsForSelectedRows documentation:

The value of this property is nil if there are no selected rows.

Therefore:

guard let selectedRows = tableView.indexPathsForSelectedRows else {
   return nil
}

return selectedRows[0]

(no check for count is needed, the method never returns an empty array).

By the way, you could simplify the condition using:

return tableView.indexPathsForSelectedRows?.first

or, if your table does not support multiple selection, directly call:

return tableView.indexPathForSelectedRow

which is already there.


问:
How do you count the elements of an array in java
Say i have the array

```<code>int theArray = new int[20];
</code>```

The length of the array is 20 but the count is 0. How can i get the count?

答:
What do you mean by "the count"? The number of elements with a non-zero value? You'd just have to count them.

There's no distinction between that array and one which has explicitly been set with zero values. For example, these arrays are indistinguishable:

```<code>int[] x = { 0, 0, 0 };
int[] y = new int[3];
</code>```

Arrays in Java always have a fixed size - accessed via the length field. There's no concept of "the amount of the array currently in use".

Body:
Say i have the array

int theArray = new int[20];

The length of the array is 20 but the count is 0. How can i get the count?

Body:
What do you mean by "the count"? The number of elements with a non-zero value? You'd just have to count them.

There's no distinction between that array and one which has explicitly been set with zero values. For example, these arrays are indistinguishable:

int[] x = { 0, 0, 0 };
int[] y = new int[3];

Arrays in Java always have a fixed size - accessed via the length field. There's no concept of "the amount of the array currently in use".


问:
Converting <select></option> in  links (Ajax)
My ajax script is working fine with this:

```<code><head>
<script>
function showUser(str) {
    if (str == "") {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("txtHint").innerHTML = this.responseText;
            }
        };
        xmlhttp.open("GET","y.php?q="+str,true);
        xmlhttp.send();
    }
}
</script>
</head>

<select  onchange="showUser(this.value)">
  <option value="">Select a person:</option>
  <option value="1">Peter Griffin</option>
  <option value="2">Lois Griffin</option>
  <option value="3">Joseph Swanson</option>
  <option value="4">Glenn Quagmire</option>
  <option value="5">Glenn Quagmire</option>
  </select>
</code>```

But, instead of <select><option>I want to convert it into link.

But the ajax script do not work, when I do this:

```<code><div onchange="showUser(this.value)">
<a value="1" href="">1</a>
<a value="2" href="">2</a>
<a value="3" href="">3</a>
</div>
</code>```

How to change them? I need them for pagination.

答:
Quick and dirty hack:

```<code><div>
<a href="javascript:void(showUser(1));">Peter Griffin</a>
<a href="javascript:void(showUser(2));">Lois Griffin</a>
<a href="javascript:void(showUser(3));">Joseph Swanson</a>
<a href="javascript:void(showUser(4));">Glenn Quagmire</a>
...
</div>
</code>```

For a more elegant solution (progressive enhancement with HTML5 and jQuery) - assuming there's a profile.php page (or similar) that can actually be accessed when JavaScript is disabled.

You can still use this with an empty href if there's no profile page; it is cleaner - but, like the initial hack, it won't work if JS is disabled.

```<code><head>
...

<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("#user_filter > a").each(function() {
        $(this).click(function(event) {
            event.preventDefault();
            showUser($(this).attr("data-user-id"));
        });
    });
});
</script>

...
</head>
<body>
...

<div id="user_filter">
<a href="/link/to/profile.php?user=1" data-user-id="1">Peter Griffin</a>
<a href="/link/to/profile.php?user=2" data-user-id="2">Lois Griffin</a>
<a href="/link/to/profile.php?user=3" data-user-id="3">Joseph Swanson</a>
<a href="/link/to/profile.php?user=4" data-user-id="4">Glenn Quagmire</a>
...
</div>

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

Body:
My ajax script is working fine with this:

<select  onchange="showUser(this.value)">
  <option value="">Select a person:</option>
  <option value="1">Peter Griffin</option>
  <option value="2">Lois Griffin</option>
  <option value="3">Joseph Swanson</option>
  <option value="4">Glenn Quagmire</option>
  <option value="5">Glenn Quagmire</option>
  </select>

But, instead of <select><option>I want to convert it into link.

But the ajax script do not work, when I do this:

1
2
3

How to change them? I need them for pagination.

Body:
Quick and dirty hack:

<div>
<a href="javascript:void(showUser(1));">Peter Griffin</a>
<a href="javascript:void(showUser(2));">Lois Griffin</a>
<a href="javascript:void(showUser(3));">Joseph Swanson</a>
<a href="javascript:void(showUser(4));">Glenn Quagmire</a>
...
</div>

For a more elegant solution (progressive enhancement with HTML5 and jQuery) - assuming there's a profile.php page (or similar) that can actually be accessed when JavaScript is disabled.

You can still use this with an empty href if there's no profile page; it is cleaner - but, like the initial hack, it won't work if JS is disabled.

<head>
...

<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("#user_filter > a").each(function() {
        $(this).click(function(event) {
            event.preventDefault();
            showUser($(this).attr("data-user-id"));
        });
    });
});
</script>

...
</head>
<body>
...

<div id="user_filter">
<a href="/link/to/profile.php?user=1" data-user-id="1">Peter Griffin</a>
<a href="/link/to/profile.php?user=2" data-user-id="2">Lois Griffin</a>
<a href="/link/to/profile.php?user=3" data-user-id="3">Joseph Swanson</a>
<a href="/link/to/profile.php?user=4" data-user-id="4">Glenn Quagmire</a>
...
</div>

...
</body>


问:
How to put a List<class> into a JSONObject and then read that object?
I have a List<class> that I would like to convert into a json object and then traverse the data out of the json object.

If this were just a List<String> I could just do something like:

```<code>JSONObject obj = new JSONObject();
List<String> sList = new ArrayList<String>();
sList.add("val1");
sList.add("val2");

obj.put("list", sList);
</code>```

Then I could traverse the list like:

```<code>JSONArray jArray = obj.getJSONArray("list");
for (int ii = 0; ii < jArray.size(); ii++)
    System.out.println(jArray.getString(ii));
</code>```

The problem with using the class is that I need to have access to data within each class element of my List<class> and I don't know how to encode that / traverse it into JSON. Any help would be greatly appreciated.

答:
Let us assume that the class is Data with two objects name and dob which are both strings.

Initially, check if the list is empty. Then, add the objects from the list to a JSONArray

```<code>JSONArray allDataArray = new JSONArray();
List<Data> sList = new ArrayList<Data>();

//if List not empty
if (!sList.isEmpty()) {

    //Loop index size()
    for(int index = 0; index < sList.size(); index++) {
        JSONObject eachData = new JSONObject();
        try {
            eachData.put("name", sList.get(index).getName());
            eachData.put("dob", sList.get(index).getDob());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        allDataArray.put(eachData);
    }
} else {
    //Do something when sList is empty
}
</code>```

Finally, add the JSONArray to a JSONObject.

```<code>JSONObject root = new JSONObject();
try {
    root.put("data", allDataArray);
} catch (JSONException e) {
    e.printStackTrace();
}
</code>```

You can further get this data as a String too.

```<code>String jsonString = root.toString();
</code>```

Body:
I have a List<class> that I would like to convert into a json object and then traverse the data out of the json object.

If this were just a List<String> I could just do something like:

JSONObject obj = new JSONObject();
List<String> sList = new ArrayList<String>();
sList.add("val1");
sList.add("val2");

obj.put("list", sList);

Then I could traverse the list like:

JSONArray jArray = obj.getJSONArray("list");
for (int ii = 0; ii < jArray.size(); ii++)
    System.out.println(jArray.getString(ii));

The problem with using the class is that I need to have access to data within each class element of my List<class> and I don't know how to encode that / traverse it into JSON. Any help would be greatly appreciated.

Body:
Let us assume that the class is Data with two objects name and dob which are both strings.

Initially, check if the list is empty. Then, add the objects from the list to a JSONArray

JSONArray allDataArray = new JSONArray();
List<Data> sList = new ArrayList<Data>();

//if List not empty
if (!sList.isEmpty()) {

    //Loop index size()
    for(int index = 0; index < sList.size(); index++) {
        JSONObject eachData = new JSONObject();
        try {
            eachData.put("name", sList.get(index).getName());
            eachData.put("dob", sList.get(index).getDob());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        allDataArray.put(eachData);
    }
} else {
    //Do something when sList is empty
}

Finally, add the JSONArray to a JSONObject.

JSONObject root = new JSONObject();
try {
    root.put("data", allDataArray);
} catch (JSONException e) {
    e.printStackTrace();
}

You can further get this data as a String too.

String jsonString = root.toString();


问:
Delayed job, undefined method `taskmy' for class `Batch
I am trying to use delayed_job to run some code in background and give the user some response immediately.

```<code>class Batch

  def self.taskmy
    # some very long task
  end
  def taskmy
      self.taskmy
  end
  handle_asynchronously :taskmy
end
</code>```

My controller action look like below

```<code>def send_command
    count = 0
    count2 = 0
    Batch.delay.taskmy
    puts count
    puts count2
end
</code>```

But i get an error

ActiveRecord::ConnectionNotEstablished: No connection pool with id primary > > found

I started the job with

```<code>rake jobs:work
</code>```

答:
I was using the active record gem with mongodb.
i included following in my gemfile and restarted the job.
gem 'delayed_job_mongoid'</p>

Body:
I am trying to use delayed_job to run some code in background and give the user some response immediately.

class Batch

  def self.taskmy
    # some very long task
  end
  def taskmy
      self.taskmy
  end
  handle_asynchronously :taskmy
end

My controller action look like below

def send_command
    count = 0
    count2 = 0
    Batch.delay.taskmy
    puts count
    puts count2
end

But i get an error

ActiveRecord::ConnectionNotEstablished: No connection pool with id primary > > found

I started the job with

rake jobs:work


问:
Select check boxes as user wish Selenium webdriver
I want to click on checkboxes by getting user options. I have tried some code segments.How can I do it..It is better if it could get the list of check box labels and select options according to those options by the user.Can anyone please help.
Selenium 3.4
Chrome driver
I am new to test automation.I am using selenium web driver with java.
I have to do the automation by doing self learning.please help me
Thank you</p>

答:
I have checked the site and tried using getText(), but this approach is not working. We can use Map as a work around to key the number and checkbox values. Below codes might give you some idea.

```<code>public static void main(String[] args)
{
    System.setProperty("webdriver.chrome.driver", "");
    WebDriver driver = new ChromeDriver();

    //Add all the values as key value pait in Map
    HashMap<String, Integer> map = new HashMap<>();
    map.put("Automobile".toLowerCase(), 1);
    map.put("Baby & Toddler".toLowerCase(), 2);
    // Similary add for all 20 elements

    String toClick = "Automobile";
    WebElement element = findCheckBox(map,toClick,driver);

    //This clicks on the Automobile check box

}

private static WebElement findCheckBox(HashMap<String, Integer> map, String toClick, WebDriver driver)
{
    int number = map.get(toClick.toLowerCase());
    return driver.findElement(By.xpath("//div[@class='divleft50']["+number+"]/input"));

}
</code>```

Hope this helps you. Thanks.

Body:
I have checked the site and tried using getText(), but this approach is not working. We can use Map as a work around to key the number and checkbox values. Below codes might give you some idea.

public static void main(String[] args)
{
    System.setProperty("webdriver.chrome.driver", "");
    WebDriver driver = new ChromeDriver();

    //Add all the values as key value pait in Map
    HashMap<String, Integer> map = new HashMap<>();
    map.put("Automobile".toLowerCase(), 1);
    map.put("Baby & Toddler".toLowerCase(), 2);
    // Similary add for all 20 elements

    String toClick = "Automobile";
    WebElement element = findCheckBox(map,toClick,driver);

    //This clicks on the Automobile check box

}

private static WebElement findCheckBox(HashMap<String, Integer> map, String toClick, WebDriver driver)
{
    int number = map.get(toClick.toLowerCase());
    return driver.findElement(By.xpath("//div[@class='divleft50']["+number+"]/input"));

}

Hope this helps you. Thanks.


问:
arranging icons in gtk toolbar
I am trying to create a GTK toolbar with a bunch of items. My probelem is that I have not been able to space them out evenly. All icons are bunched together on the left of the bar. How do I get them to spread out? I would like to avoid using additional widgets like hbox, etc for performance reasons. Here's the code I have written:

```<code>GtkWidget* navbar = gtk_toolbar_new();
gtk_toolbar_set_style(GTK_TOOLBAR(navbar), GTK_TOOLBAR_ICONS);
gtk_toolbar_set_icon_size(GTK_TOOLBAR(navbar), GTK_ICON_SIZE_SMALL_TOOLBAR);

GtkToolItem* open = gtk_tool_button_new_from_stock(GTK_STOCK_JUMP_TO);
gtk_toolbar_insert(GTK_TOOLBAR(navbar), open, 0);

GtkToolItem* play = gtk_tool_button_new_from_stock(GTK_STOCK_MEDIA_PLAY);
gtk_toolbar_insert(GTK_TOOLBAR(navbar), play, 1);

GtkToolItem* pause = gtk_tool_button_new_from_stock(GTK_STOCK_MEDIA_PAUSE);
gtk_toolbar_insert(GTK_TOOLBAR(navbar), pause, 2);
</code>```

And here is the arrangement I get:

答:
You can add a GtkSeparatorToolItem in between each item; quoting from the GTK documentation,

If the property expand is TRUE and the property draw is FALSE, a GtkSeparatorToolItem will act as a "spring" that forces other items to the ends of the toolbar.

Listen to what unwind says though, and don't do it! Don't even place them in the center of the toolbar. GTK widgets are designed to work in all kinds of different sizes, resolutions, desktop themes, languages, and configurations. You design how the application works, GTK designs how it looks (and I assure you, the GTK team has thought more about usability than you have.) Users expect tool buttons to be in a certain place.

Title: arranging icons in gtk toolbar

Body:
I am trying to create a GTK toolbar with a bunch of items. My probelem is that I have not been able to space them out evenly. All icons are bunched together on the left of the bar. How do I get them to spread out? I would like to avoid using additional widgets like hbox, etc for performance reasons. Here's the code I have written:

GtkWidget* navbar = gtk_toolbar_new();
gtk_toolbar_set_style(GTK_TOOLBAR(navbar), GTK_TOOLBAR_ICONS);
gtk_toolbar_set_icon_size(GTK_TOOLBAR(navbar), GTK_ICON_SIZE_SMALL_TOOLBAR);

GtkToolItem* open = gtk_tool_button_new_from_stock(GTK_STOCK_JUMP_TO);
gtk_toolbar_insert(GTK_TOOLBAR(navbar), open, 0);

GtkToolItem* play = gtk_tool_button_new_from_stock(GTK_STOCK_MEDIA_PLAY);
gtk_toolbar_insert(GTK_TOOLBAR(navbar), play, 1);

GtkToolItem* pause = gtk_tool_button_new_from_stock(GTK_STOCK_MEDIA_PAUSE);
gtk_toolbar_insert(GTK_TOOLBAR(navbar), pause, 2);

And here is the arrangement I get:


问:
Yii2 Count all record in table
How to count all the records in database and post the result?
This is my codes i don't know whats wrong the result is only 0.</p>

```<code>$id = new reportDetails();
        $id->report_id;
        $dataProvider = new ActiveDataProvider([
        'query' => reportDetails::find()
                ->where(['report_id'=> $id]),
        ]);

        echo $dataProvider->getCount();
</code>```

答:
Your $id is wrong.

```<code>$id = new reportDetails();
$id->report_id;
</code>```

$id is object reportDetails, not integer.

Try:

```<code>$id = 3; //or your custom number
echo reportDetails::find()->where(['report_id'=> $id])->count();
</code>```

Title: Yii2 Count all record in table

Body:
How to count all the records in database and post the result?
This is my codes i don't know whats wrong the result is only 0.

$id = new reportDetails();
        $id->report_id;
        $dataProvider = new ActiveDataProvider([
        'query' => reportDetails::find()
                ->where(['report_id'=> $id]),
        ]);

        echo $dataProvider->getCount();

Body:
Your $id is wrong.

$id = new reportDetails();
$id->report_id;

$id is object reportDetails, not integer.

Try:

$id = 3; //or your custom number
echo reportDetails::find()->where(['report_id'=> $id])->count();


问:
Regression using K-NN for prediction using matlab?
I am interested to use k-NN method for training my datasets and then making prediction for the sample datasets. I have table (tb) each contains two variables of size 1X2000. Let us for the sake of simplicity,

The training data sets,   X = tb(1:1500,1)

```<code>      Y = tb(1:1500,2);     % both X and Y are training datasets
</code>```

Now the sample test are given as,

```<code>             x = tb(1501:2000,1);
             y= tb(1501:2000,2);
</code>```

Now I want to use k-NN method for  predicting new y value for given x value.

I have written code as below :

```<code> mdl = fitcknn(X,Y,'NumNeighbors',150,'Standardize',1);
      predictedY = predict(mdl,x);

      plot(x,predictedY)
</code>```

When I am running the code i am not getting correct result.

Based on some google search , I found that it this code is not for regression but for classification. I don't have any idea how k-NN can be used for regression. Any Help ?

答:
You should not use ClassificationKNN.fit - it will be removed in a future release. Instead you can use fitcknn:

```<code>model = fitcknn(X,Y,'NumNeighbors',150);
</code>```

Body:
I am interested to use k-NN method for training my datasets and then making prediction for the sample datasets. I have table (tb) each contains two variables of size 1X2000. Let us for the sake of simplicity,

The training data sets,   X = tb(1:1500,1)

      Y = tb(1:1500,2);     % both X and Y are training datasets

Now the sample test are given as,

             x = tb(1501:2000,1);
             y= tb(1501:2000,2);

Now I want to use k-NN method for  predicting new y value for given x value.

I have written code as below :

 mdl = fitcknn(X,Y,'NumNeighbors',150,'Standardize',1);
      predictedY = predict(mdl,x);

      plot(x,predictedY)

When I am running the code i am not getting correct result.

Based on some google search , I found that it this code is not for regression but for classification. I don't have any idea how k-NN can be used for regression. Any Help ?

Body:
You should not use ClassificationKNN.fit - it will be removed in a future release. Instead you can use fitcknn:

model = fitcknn(X,Y,'NumNeighbors',150);


问:
how to put legend title at left?
The following code creates a legend with a title.

```<code>from pylab import *
plt.plot([1,2],[2,3],label='sdfsdf')
legend(title='s')
</code>```

's' is located at the center of the legend.

I wonder how to put 's' to the left side.

答:
The easiest option would probably be to add a lot of whitespace behind the title

```<code>import matplotlib.pyplot as plt
plt.plot([1,2],[2,3],label='sdfsdf')
plt.legend(title='s                ')
plt.show()
</code>```

The drawback of this is of course that the amount of whitespace depends on the legend size.

The other option is therefore to change the alignment within the legend, using ._legend_box.align.

```<code>import matplotlib.pyplot as plt
plt.plot([1,2],[2,3],label='sdfsdf')
leg = plt.legend(title='s')
leg._legend_box.align = "left"

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

Note that this is the aligment of all the legend entries, as there is unfortunately no way to align the title independently. In most cases it will not matter, but one has to be aware of that if unforeseen issues arise with more complex legends (multicolumn etc.).

Title: how to put legend title at left?

Body:
The following code creates a legend with a title.

from pylab import *
plt.plot([1,2],[2,3],label='sdfsdf')
legend(title='s')

's' is located at the center of the legend.

I wonder how to put 's' to the left side.

Body:
The easiest option would probably be to add a lot of whitespace behind the title

import matplotlib.pyplot as plt
plt.plot([1,2],[2,3],label='sdfsdf')
plt.legend(title='s                ')
plt.show()

The drawback of this is of course that the amount of whitespace depends on the legend size.

The other option is therefore to change the alignment within the legend, using ._legend_box.align.

import matplotlib.pyplot as plt
plt.plot([1,2],[2,3],label='sdfsdf')
leg = plt.legend(title='s')
leg._legend_box.align = "left"

plt.show()

Note that this is the aligment of all the legend entries, as there is unfortunately no way to align the title independently. In most cases it will not matter, but one has to be aware of that if unforeseen issues arise with more complex legends (multicolumn etc.).


问:
How to integrate PayPal express checkout with shipping detail?
I am using PayPal express checkout NVP API for my payment solution but for my product there is no shipping address need because its digitalis  good.

Any one please help me how to integrate for digital good payment solution.

query string

```<code>$nvpstr="&NOSHIPPING=1&L_NAME0=".$L_NAME0."&L_NAME1=".$L_NAME1."&L_AMT0=".$L_AMT0."&L_AMT1=".$L_AMT1."&L_QTY0=".$L_QTY0."&L_QTY1=".$L_QTY1."&MAXAMT=".(string)$maxamt."&AMT=".(string)$amt."&ITEMAMT=".(string)$itemamt."&CALLBACKTIMEOUT=4&L_SHIPPINGOPTIONAMOUNT1=8.00&L_SHIPPINGOPTIONlABEL1=UPS Next Day Air&L_SHIPPINGOPTIONNAME1=UPS Air&L_SHIPPINGOPTIONISDEFAULT1=true&L_SHIPPINGOPTIONAMOUNT0=3.00&L_SHIPPINGOPTIONLABEL0=UPS Ground 7 Days&L_SHIPPINGOPTIONNAME0=Ground&L_SHIPPINGOPTIONISDEFAULT0=false&INSURANCEAMT=1.00&INSURANCEOPTIONOFFERED=true&CALLBACK=https://www.ppcallback.com/callback.pl&SHIPPINGAMT=8.00&SHIPDISCAMT=-3.00&TAXAMT=2.00&L_NUMBER0=1000&L_DESC0=Size: 8.8-oz&L_NUMBER1=10001&L_DESC1=Size: Two 24-piece boxes&L_ITEMWEIGHTVALUE1=0.5&L_ITEMWEIGHTUNIT1=lbs&ReturnUrl=".$returnURL."&CANCELURL=".$cancelURL ."&CURRENCYCODE=".$currencyCodeType."&PAYMENTACTION=".$paymentType;
</code>```

答:
To suppress the display of the buyer’s shipping address, set the NOSHIPPING parameter to 1 in the call to SetExpressCheckout. No shipping address displays on the PayPal pages whatsoever.

See this page for more details.

https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_ECCustomizing

Body:
I am using PayPal express checkout NVP API for my payment solution but for my product there is no shipping address need because its digitalis  good.

Any one please help me how to integrate for digital good payment solution.

query string

$nvpstr="&NOSHIPPING=1&L_NAME0=".$L_NAME0."&L_NAME1=".$L_NAME1."&L_AMT0=".$L_AMT0."&L_AMT1=".$L_AMT1."&L_QTY0=".$L_QTY0."&L_QTY1=".$L_QTY1."&MAXAMT=".(string)$maxamt."&AMT=".(string)$amt."&ITEMAMT=".(string)$itemamt."&CALLBACKTIMEOUT=4&L_SHIPPINGOPTIONAMOUNT1=8.00&L_SHIPPINGOPTIONlABEL1=UPS Next Day Air&L_SHIPPINGOPTIONNAME1=UPS Air&L_SHIPPINGOPTIONISDEFAULT1=true&L_SHIPPINGOPTIONAMOUNT0=3.00&L_SHIPPINGOPTIONLABEL0=UPS Ground 7 Days&L_SHIPPINGOPTIONNAME0=Ground&L_SHIPPINGOPTIONISDEFAULT0=false&INSURANCEAMT=1.00&INSURANCEOPTIONOFFERED=true&CALLBACK=https://www.ppcallback.com/callback.pl&SHIPPINGAMT=8.00&SHIPDISCAMT=-3.00&TAXAMT=2.00&L_NUMBER0=1000&L_DESC0=Size: 8.8-oz&L_NUMBER1=10001&L_DESC1=Size: Two 24-piece boxes&L_ITEMWEIGHTVALUE1=0.5&L_ITEMWEIGHTUNIT1=lbs&ReturnUrl=".$returnURL."&CANCELURL=".$cancelURL ."&CURRENCYCODE=".$currencyCodeType."&PAYMENTACTION=".$paymentType;


问:
MVC4 - Custom Controller for all calls (including WebAPI)
I am building an MVC4 application, where I have the normal MVC views and I have added a few WebAPI controllers.
I know that the corresponding controllers exist in different namespaces (System.Web.Mvc and System.Web.Http).

So, I want to create a custom controller which will capture all incoming calls (to webpages and to WebAPI), register the call and perform authorisation, all in one class for consistency.

Is there a MVC way to do that?
If this cannot be done with 1 custom controller, is there any other approach to this? Would a HttpModule be a good idea for an MVC application?

Right now, I have created 2 similar classes which derive from:
System.Web.Http.ApiController and
System.Web.Mvc.Controller
but does not seem like a good idea, as I almost duplicate the code.

答:
The easiest way to implement such functionality is to create a custom HttpModule and register it with Http Pipeline.

You can find the reference to Custom HttpModule and Registration process here


问:
How can I display my current git branch name in my PowerShell prompt?
Basically I'm after this but for PowerShell instead of bash.

I use git on windows through PowerShell. If possible, I'd like my current branch name to displayed as part of the command prompt.

答:
Here's my take on it. I've edited the colours a bit to make it more readable.

Microsoft.PowerShell_profile.ps1

```<code>function Write-BranchName () {
    try {
        $branch = git rev-parse --abbrev-ref HEAD

        if ($branch -eq "HEAD") {
            # we're probably in detached HEAD state, so print the SHA
            $branch = git rev-parse --short HEAD
            Write-Host " ($branch)" -ForegroundColor "red"
        }
        else {
            # we're on an actual branch, so print it
            Write-Host " ($branch)" -ForegroundColor "blue"
        }
    } catch {
        # we'll end up here if we're in a newly initiated git repo
        Write-Host " (no branches yet)" -ForegroundColor "yellow"
    }
}

function prompt {
    $base = "PS "
    $path = "$($executionContext.SessionState.Path.CurrentLocation)"
    $userPrompt = "$('>' * ($nestedPromptLevel + 1)) "

    Write-Host "`n$base" -NoNewline

    if (Test-Path .git) {
        Write-Host $path -NoNewline -ForegroundColor "green"
        Write-BranchName
    }
    else {
        # we're not in a repo so don't bother displaying branch name/sha
        Write-Host $path -ForegroundColor "green"
    }

    return $userPrompt
}
</code>```

Example 1:

Example 2:

Body:
Here's my take on it. I've edited the colours a bit to make it more readable.

Microsoft.PowerShell_profile.ps1

function Write-BranchName () {
    try {
        $branch = git rev-parse --abbrev-ref HEAD

        if ($branch -eq "HEAD") {
            # we're probably in detached HEAD state, so print the SHA
            $branch = git rev-parse --short HEAD
            Write-Host " ($branch)" -ForegroundColor "red"
        }
        else {
            # we're on an actual branch, so print it
            Write-Host " ($branch)" -ForegroundColor "blue"
        }
    } catch {
        # we'll end up here if we're in a newly initiated git repo
        Write-Host " (no branches yet)" -ForegroundColor "yellow"
    }
}

function prompt {
    $base = "PS "
    $path = "$($executionContext.SessionState.Path.CurrentLocation)"
    $userPrompt = "$('>' * ($nestedPromptLevel + 1)) "

    Write-Host "`n$base" -NoNewline

    if (Test-Path .git) {
        Write-Host $path -NoNewline -ForegroundColor "green"
        Write-BranchName
    }
    else {
        # we're not in a repo so don't bother displaying branch name/sha
        Write-Host $path -ForegroundColor "green"
    }

    return $userPrompt
}

Example 1:

Example 2:


问:
MS Access Database Multiple rows of static/constant data
So, this is a bit of a ridiculous questions, however, I have not been able to find an answer anywhere on the interwebs!

I have a MS Access DB which I am using in Access 2016. It is from a client and being used to provide data for another system.

Anyway, I am trying to mock some database data being returned from the table without changing the database data. So, I figured I would just do a select of constants, as I would in SQL or any other db language.

All I want returned is 2+ rows of data for 3 columns.

E.g.
Name, Value, Target
aaa, 1, 2,
bbb, 3, 4,
ccc, 5, 6,
...

I can do:
SELECT 'aaa' AS [Name], 2 AS [Target], 3 AS [Value]

however, any other attempt I use to return more than one row of data just gives me errors.
I've tried Unions, values(), multiple selects, etc, and none seem to work.

For sanity, can someone confirm that this is not possible, or am I missing something??

Many Thanks

答:
Select without FROM is non standard feature of Access, it would be better to do not rely on it. You can do what you want if you create a table with one row (tbl_Dual in the example), then you can select constants like this:</p>

```<code>SELECT 'aaa' AS [Name], 2 AS [Target], 3 AS [Value] from tbl_Dual
union all
SELECT 'bbb', 4, 5 from tbl_Dual
</code>```

Body:
Select without FROM is non standard feature of Access, it would be better to do not rely on it. You can do what you want if you create a table with one row (tbl_Dual in the example), then you can select constants like this:

SELECT 'aaa' AS [Name], 2 AS [Target], 3 AS [Value] from tbl_Dual
union all
SELECT 'bbb', 4, 5 from tbl_Dual


问:
How to get only text in Custom Material Spinner with Image and Text
I have a Material Spinner which displays an image and text, but i want to retrieve just the text in OnItemSelected. But it is returning null.

My Adapter Class

```<code>   public class SpinnerCustomAdapter extends BaseAdapter {
    Context context;
    int cat_pics[];
    ArrayList<String> categoryNames;
    LayoutInflater inflter;

    public SpinnerCustomAdapter(Context applicationContext, int[] cat_pics, ArrayList<String> categoryNames) {
        this.context = applicationContext;
        this.cat_pics = cat_pics;
        this.categoryNames = categoryNames;
        inflter = (LayoutInflater.from(applicationContext));
    }

    @Override
    public int getCount() {
        return cat_pics.length;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        view = inflter.inflate(R.layout.custom_spinner_items, null);
        ImageView icon = (ImageView) view.findViewById(R.id.imageView);
        TextView names = (TextView) view.findViewById(R.id.textView);
        icon.setImageResource(cat_pics[i]);
        names.setText(categoryNames.get(i));
        return view;
    }
}
</code>```

Setting the Adapter in Main Activity

```<code> customAdapter=newSpinnerCustomAdapter(getApplicationContext(),cat_pics,allCatNames);
    spCategories.setAdapter(customAdapter);
    spCategories.setOnItemSelectedListener(this);
</code>```

onItemSelected

```<code>@Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        Toast.makeText(parent.getContext(), "Selected Item : " + customAdapter.getItem(position) ,
                Toast.LENGTH_LONG).show();
    }
</code>```

答:
In your SpinnerCustomAdapter, your getItem() method returns null

```<code>@Override
public Object getItem(int i) {
    return null;
}
</code>```

Update getItem() method as below:

```<code>@Override
public Object getItem(int i) {
    return categoryNames.get(i);
}
</code>```

#. You can also use parent.getItemAtPosition(position) to get get selected item.

```<code>@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    Toast.makeText(getApplicationContext(), "Selected Item : "
                   + parent.getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();
}
</code>```

Body:
I have a Material Spinner which displays an image and text, but i want to retrieve just the text in OnItemSelected. But it is returning null.

My Adapter Class

   public class SpinnerCustomAdapter extends BaseAdapter {
    Context context;
    int cat_pics[];
    ArrayList<String> categoryNames;
    LayoutInflater inflter;

    public SpinnerCustomAdapter(Context applicationContext, int[] cat_pics, ArrayList<String> categoryNames) {
        this.context = applicationContext;
        this.cat_pics = cat_pics;
        this.categoryNames = categoryNames;
        inflter = (LayoutInflater.from(applicationContext));
    }

    @Override
    public int getCount() {
        return cat_pics.length;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        view = inflter.inflate(R.layout.custom_spinner_items, null);
        ImageView icon = (ImageView) view.findViewById(R.id.imageView);
        TextView names = (TextView) view.findViewById(R.id.textView);
        icon.setImageResource(cat_pics[i]);
        names.setText(categoryNames.get(i));
        return view;
    }
}

Setting the Adapter in Main Activity

 customAdapter=newSpinnerCustomAdapter(getApplicationContext(),cat_pics,allCatNames);
    spCategories.setAdapter(customAdapter);
    spCategories.setOnItemSelectedListener(this);

onItemSelected

@Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        Toast.makeText(parent.getContext(), "Selected Item : " + customAdapter.getItem(position) ,
                Toast.LENGTH_LONG).show();
    }

Body:
In your SpinnerCustomAdapter, your getItem() method returns null

@Override
public Object getItem(int i) {
    return null;
}

Update getItem() method as below:

@Override
public Object getItem(int i) {
    return categoryNames.get(i);
}

#. You can also use parent.getItemAtPosition(position) to get get selected item.

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    Toast.makeText(getApplicationContext(), "Selected Item : "
                   + parent.getItemAtPosition(position).toString(), Toast.LENGTH_LONG).show();
}


问:
How to put Movesense into DFU mode with Nrf Connect
Can I put the movesense in DFU mode directly using the Nrf Connect App? How?</p>

答:
There is currently no way to do DFU directly from Nrf Connect. The thinking was that people that make Movesense applications have their own mobile app so they can integrate the nRF toolkit library to it directly and use that to make the OTA firmware update. I can see how that makes updating a bit clumsy when developing (I do it myself a lot during testing).

Some useful tips:

Keep nRF Connect / nRF Toolbox active so you can switch easily between the apps

If you have your own mobile app, integrate the nRF DFU library so that you can do the update from your own app

I hope this helps.

Full Disclosure: I work for Movesense team


问:
How can I import my excel file to php myadmin without converting it to csv format
How can I import my excel file to php myadmin without converting it to csv format, considering the excel file is too large.</p>

答:
got my answer...and it worked perfectly.

answer-  http://itsolutionstuff.com/post/php-import-excel-file-into-mysql-database-tutorialexample.html


问:
ReflectionException: Class db does not exist
I am creating a library that uses \Illuminate\Support\Facades\DB to reference the database. I'm getting the following exception on the call to DB::table()->where()->get(): "ReflectionException: Class db does not exist." What is the problem and what do I need to do to overcome it?

I know that there is a process using \Illuminate\Database\Capsule\Manager to establish a connection to the database. But I haven't found any example on how to make this work with \Illuminate\Support\Facades\DB.

Code sample:

```<code>use \Illuminate\Support\Facades\DB;

abstract class Data
{
    public static function tables($prefix, $mode=null)
    {
        $outbound = array();
        $tables = DB::table('information_schema.tables')->where('TABLE_NAME', 'LIKE', $prefix.'_%')->get();
        foreach ($tables as $table) {
            ...
        }
        return $outbound;
    }
}
</code>```

Stack trace:

```<code>~/vendor/laravel/framework/src/Illuminate/Container/Container.php:749
~/vendor/laravel/framework/src/Illuminate/Container/Container.php:644
~/vendor/laravel/framework/src/Illuminate/Foundation/Application.php:709
~/vendor/laravel/framework/src/Illuminate/Container/Container.php:1203
~/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:175
~/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:144
~/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:231
~/Data.php:XXX
</code>```

答:
this is not correct way but you can write this way. give a '/' before DB

$tables = \DB::table('information_schema.tables')->where('TABLE_NAME', 'LIKE', $prefix.'_%')->get()

Body:
I am creating a library that uses \Illuminate\Support\Facades\DB to reference the database. I'm getting the following exception on the call to DB::table()->where()->get(): "ReflectionException: Class db does not exist." What is the problem and what do I need to do to overcome it?

I know that there is a process using \Illuminate\Database\Capsule\Manager to establish a connection to the database. But I haven't found any example on how to make this work with \Illuminate\Support\Facades\DB.

Code sample:

use \Illuminate\Support\Facades\DB;

abstract class Data
{
    public static function tables($prefix, $mode=null)
    {
        $outbound = array();
        $tables = DB::table('information_schema.tables')->where('TABLE_NAME', 'LIKE', $prefix.'_%')->get();
        foreach ($tables as $table) {
            ...
        }
        return $outbound;
    }
}

Stack trace:

~/vendor/laravel/framework/src/Illuminate/Container/Container.php:749
~/vendor/laravel/framework/src/Illuminate/Container/Container.php:644
~/vendor/laravel/framework/src/Illuminate/Foundation/Application.php:709
~/vendor/laravel/framework/src/Illuminate/Container/Container.php:1203
~/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:175
~/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:144
~/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:231
~/Data.php:XXX


问:
How to deploy on forge when using queue
I have a project on forge with one queue worker (with database driver).
Currently I need manually restart queue worker after each deploy:

My deployment script:

```<code>cd /home/forge/default
git pull origin master
git log -1
composer install --no-interaction --no-dev --prefer-dist
php artisan migrate --force
</code>```

How extend my script for automatic restart queue worker?

I tried php artisan queue:restart. But this command just truncate all items in queue. And uptime of worker didn't reset.

Perhaps I can use failed-table, but I don't know how.

答: Running php artisan queue:restart would also restart supervisor and you won't need to do sudo supervisorctl as a forge user.

Title: How to deploy on forge when using queue

Body:
I have a project on forge with one queue worker (with database driver).
Currently I need manually restart queue worker after each deploy:

My deployment script:

cd /home/forge/default
git pull origin master
git log -1
composer install --no-interaction --no-dev --prefer-dist
php artisan migrate --force

How extend my script for automatic restart queue worker?

I tried php artisan queue:restart. But this command just truncate all items in queue. And uptime of worker didn't reset.

Perhaps I can use failed-table, but I don't know how.


问:
Linq to many objects using MVC
I am trying to use Linq to create an object which itself contains 2 data objects. From the Linq expression I am trying to set up the objects directly rather than having an inbetween function in the containing class.

The containing class looks like this:

```<code>public class SupplierCategories
{

    public  category _category;
    public category_sub _category_sub;
    private bool _IsActive;
    private int? _SupplierID;

    public SupplierCategories()
    {

    }

    public bool IsActive
    {
        get
        {
            return _IsActive;
        }
        set
        {
            _IsActive = value;
        }
    }

    public int? SupplierID
    {
        get
        {
            return _SupplierID;
        }
        set
        {
            _SupplierID = value;
            if (_SupplierID != null) // The county is active if there is a supplier ID matching
            {
                _IsActive = true;
            }
        }

    }
}
</code>```

Note: category and category_sub objects are all set up through the Entity Framework.

My link expression has 2 tables and looks like this:

```<code>    public IEnumerable<SupplierCategories> GetAllOrdered()
    {
        IEnumerable<SupplierCategories> areaList;

        var results = from cat in dbContext.categories
                      join sub in dbContext.category_sub on cat.id equals sub.categoryid
                      orderby cat.id ascending, sub.name ascending
                      select new SupplierCategories
                      {
                          _category = { new category { cat.id, cat.name } },
                          _category_sub = { new category_sub { sub.id, sub.categoryid, sub.name } }
                      };

        areaList = results.ToList();

        return areaList;
    }
</code>```

Hopefully you can see that I am trying to create the "_category" and "_category_sub" objects directly.

The error I get is:

Error 5 Cannot initialize type
  'Essential_Collections.Models.category'
  with a collection initializer because
  it does not implement
  'System.Collections.IEnumerable'
  D:\Websites\Essential
  Collections\development\build\Essential
  Collections\Models\SupplierCategories\SupplierCategoriesRepository.cs
  51 37 Essential Collections

Any solutions or possibly other approaches would be gratefully received

答:
```<code>public IEnumerable<SupplierCategories> GetAllOrdered()
{
    IEnumerable<SupplierCategories> areaList;

    var results = from cat in dbContext.categories
                  join sub in dbContext.category_sub on cat.id equals sub.categoryid
                  orderby cat.id ascending, sub.name ascending
                  select new SupplierCategories
                  {
                      _category = new category { cat.id, cat.name } , //removed the curly braces here
                      _category_sub = new category_sub { sub.id, sub.categoryid, sub.name } //removed the curly braces here
                  };

    areaList = results.ToList();

    return areaList;
}
</code>```

The error you're getting is because of those curly braces I removed. This still won't compile because you need to explicitly spell out which property you're setting in the object initializer:

```<code>_category = new category { ID = cat.id, Name = cat.name }
</code>```

or if your category class has a constructor overload that takes those args, then pass those in.

Title: Linq to many objects using MVC

Body:
I am trying to use Linq to create an object which itself contains 2 data objects. From the Linq expression I am trying to set up the objects directly rather than having an inbetween function in the containing class.

The containing class looks like this:

public class SupplierCategories
{

    public  category _category;
    public category_sub _category_sub;
    private bool _IsActive;
    private int? _SupplierID;

    public SupplierCategories()
    {

    }

    public bool IsActive
    {
        get
        {
            return _IsActive;
        }
        set
        {
            _IsActive = value;
        }
    }

    public int? SupplierID
    {
        get
        {
            return _SupplierID;
        }
        set
        {
            _SupplierID = value;
            if (_SupplierID != null) // The county is active if there is a supplier ID matching
            {
                _IsActive = true;
            }
        }

    }
}

Note: category and category_sub objects are all set up through the Entity Framework.

My link expression has 2 tables and looks like this:

    public IEnumerable<SupplierCategories> GetAllOrdered()
    {
        IEnumerable<SupplierCategories> areaList;

        var results = from cat in dbContext.categories
                      join sub in dbContext.category_sub on cat.id equals sub.categoryid
                      orderby cat.id ascending, sub.name ascending
                      select new SupplierCategories
                      {
                          _category = { new category { cat.id, cat.name } },
                          _category_sub = { new category_sub { sub.id, sub.categoryid, sub.name } }
                      };

        areaList = results.ToList();

        return areaList;
    }

Hopefully you can see that I am trying to create the "_category" and "_category_sub" objects directly.

The error I get is:

Error 5 Cannot initialize type
  'Essential_Collections.Models.category'
  with a collection initializer because
  it does not implement
  'System.Collections.IEnumerable'
  D:\Websites\Essential
  Collections\development\build\Essential
  Collections\Models\SupplierCategories\SupplierCategoriesRepository.cs
  51 37 Essential Collections

Any solutions or possibly other approaches would be gratefully received

Body:
public IEnumerable<SupplierCategories> GetAllOrdered()
{
    IEnumerable<SupplierCategories> areaList;

    var results = from cat in dbContext.categories
                  join sub in dbContext.category_sub on cat.id equals sub.categoryid
                  orderby cat.id ascending, sub.name ascending
                  select new SupplierCategories
                  {
                      _category = new category { cat.id, cat.name } , //removed the curly braces here
                      _category_sub = new category_sub { sub.id, sub.categoryid, sub.name } //removed the curly braces here
                  };

    areaList = results.ToList();

    return areaList;
}

The error you're getting is because of those curly braces I removed. This still won't compile because you need to explicitly spell out which property you're setting in the object initializer:

_category = new category { ID = cat.id, Name = cat.name }

or if your category class has a constructor overload that takes those args, then pass those in.


问:
How to deploy a Django/WSGI as an azure webapp with a different Python runtime?
I'm trying to deploy a Django webapp on a Microsoft Azure webapp instance (it is a managed Windows VM). The documentation here,

https://learn.microsoft.com/en-us/azure/app-service-web/web-sites-python-configure

describes how to deploy an application with either Python 2.7 or Python 3.4. I'm trying to deploy an app built with Python 3.6 (not a runtime supported by Azure out-of-box). I installed the runtime using the 'Site Extensions' feature of Azure. Here's the link to the extension (I think),

https://www.siteextensions.net/packages/python361x86/

I primarily work on Linux systems using Apache. The difficulty I'm facing here is how to configure IIS on the Azure instance to use Python 3.6 to run my django webapp (it works on my development system using the runserver command). Sadly, I cannot request to use a Linux VM on azure (business constraint).

One problem I'm having is how to write the web.config file on the project. The reference Python3.4 one uses a virtualenv which, oddly enough, is explicitly disabled on Python with site extensions ( ref: https://github.com/Azure/azure-python-siteextensions/issues/6 ).

Another issue I'm having is that I'd like to use waitress WSGI instead of FastCGI (ref: http://docs.pylonsproject.org/projects/waitress/en/latest/ ).

Can someone point me to a web.config + python wsgi script combination which runs on azure using Python 3.6 ? Alternate suggestions are also welcome.

答:
Please refer to the content of Example web.config for Python 3.4 in the section Web.config of the document Configuring Python with Azure App Service Web Apps to use these content below instead of the related content, if you were follow the tutorial to create your Django project.

Using <add key="WSGI_ALT_VIRTUALENV_HANDLER" value="django.core.wsgi.get_wsgi_application()" /> instead of <add key="WSGI_ALT_VIRTUALENV_HANDLER" value="app.wsgi_app" />

Using

```<code><add name="Python FastCGI" path="handler.fcgi" verb="*" modules="FastCgiModule"
     scriptProcessor="D:\home\Python36\python.exe|D:\home\Python36\Scripts\wfastcgi.py"
     resourceType="Unspecified" requireAccess="Script" />
</code>```

instead of the content of the xml path <system.webServer>/<handlers>.

And there is an Azure offical sample Django project on GitHub, which you can also refer to.

Body:
Please refer to the content of Example web.config for Python 3.4 in the section Web.config of the document Configuring Python with Azure App Service Web Apps to use these content below instead of the related content, if you were follow the tutorial to create your Django project.

Using <add key="WSGI_ALT_VIRTUALENV_HANDLER" value="django.core.wsgi.get_wsgi_application()" /> instead of <add key="WSGI_ALT_VIRTUALENV_HANDLER" value="app.wsgi_app" />

Using

<add name="Python FastCGI" path="handler.fcgi" verb="*" modules="FastCgiModule"
     scriptProcessor="D:\home\Python36\python.exe|D:\home\Python36\Scripts\wfastcgi.py"
     resourceType="Unspecified" requireAccess="Script" />

instead of the content of the xml path <system.webServer>/<handlers>.

And there is an Azure offical sample Django project on GitHub, which you can also refer to.


问:
application id is not associated with package while signing in google play?
As title says, I encounter this problem. Documentation says to do this:

```<code><meta-data android:name="com.google.android.gms.APP_ID"
android:value="@string/app_id" />
</code>```

I had done and my app_id is 12 digits. Other people getting this similar error was their app_id s were more than 12 digits. But mine is 12. However, it does not work, I cant sign in. Error also says check your manifest. I have checked and it is the same as above. Why is application id ,which i got it from google play console, not associated with my package name? Do i have to do something with sha1 key? (I am now in th alpha test)

Regards

答:
you must also check that users gmail id is added in testing or not ?
if not then add it to Play Console -> Game Services -> Testing

Body:
As title says, I encounter this problem. Documentation says to do this:

<meta-data android:name="com.google.android.gms.APP_ID"
android:value="@string/app_id" />

I had done and my app_id is 12 digits. Other people getting this similar error was their app_id s were more than 12 digits. But mine is 12. However, it does not work, I cant sign in. Error also says check your manifest. I have checked and it is the same as above. Why is application id ,which i got it from google play console, not associated with my package name? Do i have to do something with sha1 key? (I am now in th alpha test)

Regards