问:
Where does finite-state machine code belong in µC?
I asked this question on EE forum. You guys on StackOverflow know more about coding than we do on EE so maybe you can give more detail information about this :)

When I learned about micrcontrollers, teachers taught me to always end the code with  while(1); with no code inside that loop.

This was to be sure that the software get "stuck" to keep interruption working. When I asked them if it was possible to put some code in this infinite loop, they told me it was a bad idea. Knowing that, I now try my best to keep this loop empty.

I now need to implement a finite state machine in a microcontroller. At first view, it seems that that code belong in this loop. That makes coding easier.

Is that a good idea? What are the pros and cons?

This is what I plan to do :

```<code>void main(void)
{
    // init phase

 while(1)
 {
    switch(current_State)
    {
    case 1:
        if(...)
        {
            current_State = 2;
        }
        else(...)
        {
            current_State = 3;
        }
        else
            current_State = 4;
        break;

    case 2:
        if(...)
        {
            current_State = 3;
        }
        else(...)
        {
            current_State = 1;
        }
        else
            current_State = 5;
        break;
   }
}
</code>```

Instead of:

```<code> void main(void)
    {
        // init phase

     while(1);
    }
</code>```

And manage the FSM with interrupt

答:
What should you implement is your choice and debugging easiness of your code.
There are times that it will be right to use the while(1); statement at the end of the code if your uC will handle interrupts completely (ISR). While at some other application the uC will be used with a code inside an infinite loop (called a polling method):

```<code>while(1)
{

//code here;

}
</code>```

And at some other application, you might mix the ISR method with the polling method.

When said 'debugging easiness', using only ISR methods (putting the while(1); statement at the end), will give you hard time debugging your code since when triggering an interrupt event the debugger of choice will not give you a step by step event register reading and following. Also, please note that writing a completely ISR code is not recommended since ISR events should do minimal coding (such as increment a counter, raise/clear a flag, e.g.) and being able to exit swiftly.

Body:
I asked this question on EE forum. You guys on StackOverflow know more about coding than we do on EE so maybe you can give more detail information about this :)

When I learned about micrcontrollers, teachers taught me to always end the code with  while(1); with no code inside that loop.

This was to be sure that the software get "stuck" to keep interruption working. When I asked them if it was possible to put some code in this infinite loop, they told me it was a bad idea. Knowing that, I now try my best to keep this loop empty.

I now need to implement a finite state machine in a microcontroller. At first view, it seems that that code belong in this loop. That makes coding easier.

Is that a good idea? What are the pros and cons?

This is what I plan to do :

void main(void)
{
    // init phase

 while(1)
 {
    switch(current_State)
    {
    case 1:
        if(...)
        {
            current_State = 2;
        }
        else(...)
        {
            current_State = 3;
        }
        else
            current_State = 4;
        break;

    case 2:
        if(...)
        {
            current_State = 3;
        }
        else(...)
        {
            current_State = 1;
        }
        else
            current_State = 5;
        break;
   }
}

Instead of:

 void main(void)
    {
        // init phase

     while(1);
    }

And manage the FSM with interrupt

Body:
What should you implement is your choice and debugging easiness of your code.
There are times that it will be right to use the while(1); statement at the end of the code if your uC will handle interrupts completely (ISR). While at some other application the uC will be used with a code inside an infinite loop (called a polling method):

while(1)
{

//code here;

}

And at some other application, you might mix the ISR method with the polling method.

When said 'debugging easiness', using only ISR methods (putting the while(1); statement at the end), will give you hard time debugging your code since when triggering an interrupt event the debugger of choice will not give you a step by step event register reading and following. Also, please note that writing a completely ISR code is not recommended since ISR events should do minimal coding (such as increment a counter, raise/clear a flag, e.g.) and being able to exit swiftly.


来源: stackexchange

问:
TeamCity - how to combine VCS Triggers
Here is the situation: in git repo I have 3 folders:
A
B
C
If changes were made to A or C, build must be started. In any other case, if changes were made to B as well, it should not be started. How to achieve such behavior with TeamCity VCS Trigger(s)?</p>

答:
You should configure VCS trigger rules for that VCS root.
Add VCS trigger as usual and then add this to the rules:

```<code>-:B/**
</code>```

This will trigger for everything in your VCS root, except folder B.
Or you could do it differently and trigger the build only for the changes in A or C folder:

```<code>+:A/**
+:C/**
</code>```

That will work because

When entering rules, please note that as soon as you enter any "+"
  rule, TeamCity will remove the default "include all" setting. To
  include all the files, use "+:." rule.

ContentLicense: CC BY-SA 3.0

Title: TeamCity - how to combine VCS Triggers

Body:
You should configure VCS trigger rules for that VCS root.
Add VCS trigger as usual and then add this to the rules:

-:B/**

This will trigger for everything in your VCS root, except folder B.
Or you could do it differently and trigger the build only for the changes in A or C folder:

+:A/**
+:C/**

That will work because

When entering rules, please note that as soon as you enter any "+"
  rule, TeamCity will remove the default "include all" setting. To
  include all the files, use "+:." rule.


问:
jQuery help: trying to set placeholder values for input fields
So, here's my jQuery code:

```<code> if($('#quotation_request_payment_option_lease').is(':checked')){
    $('#quotation_request_down_payment').attr('placeholder', "1300");
  }

 else if($('#quotation_request_payment_option_finance').is(':checked'))
  {
    $('#quotation_request_down_payment').attr('placeholder', "1500");
  }
</code>```

If the quotation_request_payment_option_lease checkbox is checked, then I want to set the placeholder in the quotation_request_down_payment input field to 1300.

And if the quotation_request_payment_option_finance checkbox is checked, then I want to set the placeholder in the quotation_request_down_payment input field to 1500.

Right now, the default for the page is that the quotation_request_payment_option_lease checkbox is checked, so when I load the page, the placeholder for the quoation_request_down_payment input field is set to 1300 (which is what I want).

The problem I'm having is that when I check the quotation_request_payment_option_finance checkbox (note: it's set so that only one of the two checkboxes can be checked at once), the placeholder remains 1300, it doesn't change to 1500.

Can anyone think of a way to fix this?

答:
You must have handle the onclick so that you can initiate the check you want to perform.
Something like this.
Add a class to both checkbox, and then add click listener of that class.</p>

```<code>$('check_box_class').on('click', function(){
      if($('#quotation_request_payment_option_lease').is(':checked')) {
          $('#quotation_request_down_payment').attr('placeholder', "1300");
      }else if($('#quotation_request_payment_option_finance').is(':checked')) {
          $('#quotation_request_down_payment').attr('placeholder', "1500");
      }
});
</code>```

Body:
So, here's my jQuery code:

 if($('#quotation_request_payment_option_lease').is(':checked')){
    $('#quotation_request_down_payment').attr('placeholder', "1300");
  }

 else if($('#quotation_request_payment_option_finance').is(':checked'))
  {
    $('#quotation_request_down_payment').attr('placeholder', "1500");
  }

If the quotation_request_payment_option_lease checkbox is checked, then I want to set the placeholder in the quotation_request_down_payment input field to 1300.

And if the quotation_request_payment_option_finance checkbox is checked, then I want to set the placeholder in the quotation_request_down_payment input field to 1500.

Right now, the default for the page is that the quotation_request_payment_option_lease checkbox is checked, so when I load the page, the placeholder for the quoation_request_down_payment input field is set to 1300 (which is what I want).

The problem I'm having is that when I check the quotation_request_payment_option_finance checkbox (note: it's set so that only one of the two checkboxes can be checked at once), the placeholder remains 1300, it doesn't change to 1500.

Can anyone think of a way to fix this?

Body:
You must have handle the onclick so that you can initiate the check you want to perform.
Something like this.
Add a class to both checkbox, and then add click listener of that class.

$('check_box_class').on('click', function(){
      if($('#quotation_request_payment_option_lease').is(':checked')) {
          $('#quotation_request_down_payment').attr('placeholder', "1300");
      }else if($('#quotation_request_payment_option_finance').is(':checked')) {
          $('#quotation_request_down_payment').attr('placeholder', "1500");
      }
});


问:
URL Routing and Relative Links Behavior
I'm building a website that stores a number of articles. The URL for each articles implements URL routing in the form /Articles/{categoryid}/{articleslug}.

Some articles have links to a graphics file. The link does not specify the full path so I'm storing the graphics file at /Articles/{categoryid}/{articleslug}/graphic.jpg.

This works fine on my desktop. But when I deployed the site to a shared hosting account, the behavior is different.

Now, the link only works if I store the graphics file at /Articles/{categoryid}/graphic.jpg. In other words, on my desktop, the {articleslug} is assumed to be a directory, but on the web it is assumed to be the name of the current page.

Does anyone know why the behavior changes? You can seen an example at http://www.blackbeltcoder.com/Articles/asp/creating-website-thumbnails-in-asp-net. Both the screenshot and download link near the top are broken links.

答:
Thanks for the input. There probably wasn't enough information here for anyone to resolve this unless they've specifically seen the issue already.

At any rate, I was able to resolve it myself and I describe the resolution in a related question I posted at Relative Links with Extension-less URLs.

Thanks.

ContentLicense: CC BY-SA 2.5

Title: URL Routing and Relative Links Behavior


问:
implement a read operation list in debugfs
i'm implementing a kernel module. using several techniques.
1 of them is to give read/write to different module variables.
i was able to read/write all variables except the list i have in my module.
the linked list:

```<code>    static struct node {
        struct list_head list;
        unsigned int x;
        struct tm time;
    };
</code>```

i would like to have a corresponding file in debugfs that will print the full list.
i tried all the 'simple' read functions , but none of them actually work.. :(

答:
You can read list using function similar to this one:</p>

```<code>struct k_list {
        struct list_head links;
        int data;
};

struct k_list my_list;

static ssize_t pop_queue(struct file * file,
                                char *buf,
                                size_t count,
                                loff_t *ppos)
{
        struct list_head *pos, *q;
        struct k_list *tmp;

        printk(KERN_INFO "--Listing inserted numbers--");
        list_for_each_safe(pos, q, &my_list.links) {
                tmp = list_entry(pos, struct k_list, links);
                printk(KERN_INFO "object: %d ", tmp->data);
        }
        printk(KERN_INFO "--End of list--");

        return count;
}
</code>```

Body:
i'm implementing a kernel module. using several techniques.
1 of them is to give read/write to different module variables.
i was able to read/write all variables except the list i have in my module.
the linked list:

    static struct node {
        struct list_head list;
        unsigned int x;
        struct tm time;
    };

i would like to have a corresponding file in debugfs that will print the full list.
i tried all the 'simple' read functions , but none of them actually work.. :(

Body:
You can read list using function similar to this one:

struct k_list {
        struct list_head links;
        int data;
};

struct k_list my_list;

static ssize_t pop_queue(struct file * file,
                                char *buf,
                                size_t count,
                                loff_t *ppos)
{
        struct list_head *pos, *q;
        struct k_list *tmp;

        printk(KERN_INFO "--Listing inserted numbers--");
        list_for_each_safe(pos, q, &my_list.links) {
                tmp = list_entry(pos, struct k_list, links);
                printk(KERN_INFO "object: %d ", tmp->data);
        }
        printk(KERN_INFO "--End of list--");

        return count;
}


问:
Element changes after being pushed to my array - React Native

Problem

When I set an object in a button navigation function and then navigate to the new screen, it outputs the wrong data.

Code

Here is a replication and oversimplification of my problem. This is pseudo code and will not work, but it should give an idea for what is happening. I did not post my "real" code, because it is much more complex and I think that explaining it will take up unnecessary time, however if it is helpful just ask me and I will give it to you.

```<code>var array = [];

for (var i = 0; i < 10; i++) {
  array.push(
    <button
      onPress={() => navigate('screen', {x:i} )}
      key={'img' + i}
      title={'click me'}
    />
    )
}

//after navigation to screen
console.log(params.x);
//x:10
console.log(params.x);
//x:10
console.log(params.x);
//x:10
console.log(params.x);
//x:10
console.log(params.x);
//x:10
console.log(params.x);
//x:10
console.log(params.x);
//x:10
console.log(params.x);
//x:10
console.log(params.x);
//x:10
console.log(params.x);
//x:10
</code>```

答:
Okay, the problem is, that "click" happens sometime in the future, after user interaction.

for loop in your example creates onPress callback function - all good here. The problem here is at the time of press event, i equals to 10 in every case. It is not bound!

I will show two examples where I try to explain solution of this problem for you.

for loop

First uses for loop and binds i to callback function.

```<code>const array = [];

for (var i = 0; i < 10; i++) {
  function bindIndex(boundIndex) {
    return {
      onPress: () => console.log(boundIndex)
    }
  }

  array.push(bindIndex(i))
}

array[5].onPress()
</code>```

Array.map

In second example, array of length of 10 is created and mapped into new array with indexes bound already.

```<code>// Create array of length of N (10 in this case)
const arrOfN = Array.from(Array(10))

const array = arrOfN.map((value, index) => ({
  onPress: () => console.log(index)
}))

array[5].onPress()
</code>```

Choose solution that fits you best and adjust your code accordingly.

Running example here

Body:
Problem

When I set an object in a button navigation function and then navigate to the new screen, it outputs the wrong data.

Code

Here is a replication and oversimplification of my problem. This is pseudo code and will not work, but it should give an idea for what is happening. I did not post my "real" code, because it is much more complex and I think that explaining it will take up unnecessary time, however if it is helpful just ask me and I will give it to you.

var array = [];

for (var i = 0; i < 10; i++) {
  array.push(
    <button
      onPress={() => navigate('screen', {x:i} )}
      key={'img' + i}
      title={'click me'}
    />
    )
}

//after navigation to screen
console.log(params.x);
//x:10
console.log(params.x);
//x:10
console.log(params.x);
//x:10
console.log(params.x);
//x:10
console.log(params.x);
//x:10
console.log(params.x);
//x:10
console.log(params.x);
//x:10
console.log(params.x);
//x:10
console.log(params.x);
//x:10
console.log(params.x);
//x:10

Body:
Okay, the problem is, that "click" happens sometime in the future, after user interaction.

for loop in your example creates onPress callback function - all good here. The problem here is at the time of press event, i equals to 10 in every case. It is not bound!

I will show two examples where I try to explain solution of this problem for you.

for loop

First uses for loop and binds i to callback function.

const array = [];

for (var i = 0; i < 10; i++) {
  function bindIndex(boundIndex) {
    return {
      onPress: () => console.log(boundIndex)
    }
  }

  array.push(bindIndex(i))
}

array[5].onPress()

Array.map

In second example, array of length of 10 is created and mapped into new array with indexes bound already.

// Create array of length of N (10 in this case)
const arrOfN = Array.from(Array(10))

const array = arrOfN.map((value, index) => ({
  onPress: () => console.log(index)
}))

array[5].onPress()

Choose solution that fits you best and adjust your code accordingly.

Running example here


问:
Iterate i'th row in vector of vectors
I have a created one 2d array using vector of vectors

```<code>vector< vector<int> > vvi;
</code>```

I can iterate this whole vector with below iterators:

```<code>std::vector< std::vector<int> >::iterator row;
std::vector<int>::iterator col;

for (row = vvi.begin(); row != vvi.end(); ++row)
{
     for (col = row->begin(); col != row->end(); ++col)
     {
        std::cout << *col;
     }
}
</code>```

Instead of traversing the whole 2d array, I need to traverse any i'th row like this but it's not working

```<code>std::vector< std::vector<int> >::iterator row;
std::vector<int>::iterator col;
row = vvi[i];
for (col = row->begin(); col != row->end(); col++) {
        std::cout << *col;
}
</code>```

How can I solve this problem.Any help will be appreciated!!

答:
In your code, row is an iterator so you can't assign vvi[i] to it.
In your situation, this can work:

```<code>#include <iterator>
// ...
std::vector<std::vector<int> >::iterator row = vvi.begin();
std::advance(row, i);

for (std::vector<int>::iterator col = row->begin(); col != row->end(); ++col) {
  std::cout << *col << std::endl;
}
</code>```

You could also do something simple like (C++11 below):

```<code>for (auto const& x : vvi[i]) { std::cout << x << std::endl; }
</code>```

If you wouldn't like to use the range-for syntax, one more alternative solution could be:

```<code>auto const& row = vvi[i];
for (auto col = row.cbegin(); col != row.cend(); ++col)
{
  std::cout << *col << std::endl;
}
</code>```

Note please, that here I used cbegin() and cend() instead of begin() and end(). (If you uncertain about the differences, please do some research about iterators and const_iterators.)

A final remark: I used the increment operator as a prefix (++col) in both examples (just like you did in your first one): in your case, there is no need for the overhead that the suffix version provides. (Even this is a subtle performance plus, it's just not necessary.)

Truly hope that I could help.

Title: Iterate i'th row in vector of vectors

Body:
I have a created one 2d array using vector of vectors

vector< vector<int> > vvi;

I can iterate this whole vector with below iterators:

std::vector< std::vector<int> >::iterator row;
std::vector<int>::iterator col;

for (row = vvi.begin(); row != vvi.end(); ++row)
{
     for (col = row->begin(); col != row->end(); ++col)
     {
        std::cout << *col;
     }
}

Instead of traversing the whole 2d array, I need to traverse any i'th row like this but it's not working

std::vector< std::vector<int> >::iterator row;
std::vector<int>::iterator col;
row = vvi[i];
for (col = row->begin(); col != row->end(); col++) {
        std::cout << *col;
}

How can I solve this problem.Any help will be appreciated!!

Body:
In your code, row is an iterator so you can't assign vvi[i] to it.
In your situation, this can work:

#include <iterator>
// ...
std::vector<std::vector<int> >::iterator row = vvi.begin();
std::advance(row, i);

for (std::vector<int>::iterator col = row->begin(); col != row->end(); ++col) {
  std::cout << *col << std::endl;
}

You could also do something simple like (C++11 below):

for (auto const& x : vvi[i]) { std::cout << x << std::endl; }

If you wouldn't like to use the range-for syntax, one more alternative solution could be:

auto const& row = vvi[i];
for (auto col = row.cbegin(); col != row.cend(); ++col)
{
  std::cout << *col << std::endl;
}

Note please, that here I used cbegin() and cend() instead of begin() and end(). (If you uncertain about the differences, please do some research about iterators and const_iterators.)

A final remark: I used the increment operator as a prefix (++col) in both examples (just like you did in your first one): in your case, there is no need for the overhead that the suffix version provides. (Even this is a subtle performance plus, it's just not necessary.)

Truly hope that I could help.


问:
npm notice created a lockfile as package-lock.json. You should commit this file
I have been trying to load the skeleton of express with npm install express. It outputs the following line:

npm notice created a lockfile as package-lock.json. You should commit this file.

What should I do in order to load the template ejs and css engine automatically?

答:
Yes. You should add this file to your version control system, i.e. You should commit it.

This file is intended to be committed into source repositories

You can read more about what it is/what it does here:

package-lock.json is automatically generated for any operations where npm modifies either the node_modules tree, or package.json. It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.


问:
Array ref empty when received by a sub
I am trying to access elements of arrays by reference, passing references into a sub. Here is my code snippet:

```<code>my @arr1 = (1,2);
my @arr2 = (3,4);
my @arr3;

push @arr3, \@arr1;
push @arr3, \@arr2;

for my $i (@arr3) {
  print "$i\n";
}

print "Entered Sub func()\n";

for my $i (@arr3) {
  func($i);
}

sub func{
  my $par = shift;
  print $par."\n";
}
print "------------------------\n";

for my $elem(@$par) {
  print $elem."\n";
}
</code>```

And here is the ouput:

```<code>C:\Users\ag194y>perl arrs.pl
ARRAY(0x357b28)
ARRAY(0x3575e8)
Entered Sub func()
ARRAY(0x357b28)
ARRAY(0x3575e8)
------------------------

C:\Users\ag194y>
</code>```

I was expecting to access the elements of @arr1 and a@rr2 with the for loop in the sub, but it looks like array refs are empty. What am I doing wrong? Many thanks.

答:
I think the problem is, loop being outside of func. You are calling func twice, and only after that you are looping through $par, which is undefined at the time.

You might be looking for something like:

```<code>sub func{
  my $par = shift;

  print $par."\n";
  print "------------------------\n";

  for my $elem (@$par){
    print $elem."\n";
  }
}
</code>```

Title: Array ref empty when received by a sub

Body:
I am trying to access elements of arrays by reference, passing references into a sub. Here is my code snippet:

my @arr1 = (1,2);
my @arr2 = (3,4);
my @arr3;

push @arr3, \@arr1;
push @arr3, \@arr2;

for my $i (@arr3) {
  print "$i\n";
}

print "Entered Sub func()\n";

for my $i (@arr3) {
  func($i);
}

sub func{
  my $par = shift;
  print $par."\n";
}
print "------------------------\n";

for my $elem(@$par) {
  print $elem."\n";
}

And here is the ouput:

C:\Users\ag194y>perl arrs.pl
ARRAY(0x357b28)
ARRAY(0x3575e8)
Entered Sub func()
ARRAY(0x357b28)
ARRAY(0x3575e8)
------------------------

C:\Users\ag194y>

I was expecting to access the elements of @arr1 and a@rr2 with the for loop in the sub, but it looks like array refs are empty. What am I doing wrong? Many thanks.

Body:
I think the problem is, loop being outside of func. You are calling func twice, and only after that you are looping through $par, which is undefined at the time.

You might be looking for something like:

sub func{
  my $par = shift;

  print $par."\n";
  print "------------------------\n";

  for my $elem (@$par){
    print $elem."\n";
  }
}


问:
How to update resources file in .apk
When creating my (unsigned) apk file, my res/values/ folder disappears when viewing the apk file through an unzipping program. However, the res/drawables and res/layout folders show up. Is there any way to ensure the apk file contains the res/values/ folder?

The main use case I have is updating various values in the resources file located in res/values depending on the customer's needs.

Thanks in advance!

答: This is as intended. The values folder is compile in binary format and you cannot retrieve it. If you need to change something, then you need to repackage everything again. </p>

Title: How to update resources file in .apk


问:
Dropdown menu in Bootstrap
```<code><!DOCTYPE html>
<html>
<head>
<title>Dropdown</title>
<link rel="stylesheet" href="css/bootstrap.css">
<script src="js/jquery.js"></script>
<script src="js/bootstrap.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown">Article<span class="caret"></span></button>
<ul class="dropdown-menu">
<li>Technology</li>
<li>Technology 2</li>
<li>Technology 3</li>
</ul>
</div>
</body>
</html>
</code>```

this code is not working properly on my Browser(firefox),the dropdown-list is not apearing when I click the button.. Please help

答:
Please try this.

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

  <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Article
  </button>

Technology 1

Technology 2

Technology 3

```

Title: Dropdown menu in Bootstrap

Body:
<!DOCTYPE html>

<title>Dropdown</title>
<link rel="stylesheet" href="css/bootstrap.css">

<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown">Article</button>

Technology

Technology 2

Technology 3

this code is not working properly on my Browser(firefox),the dropdown-list is not apearing when I click the button.. Please help

Body:
Please try this.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="dropdown">
  <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Article
  <span class="caret"></span></button>
  <ul class="dropdown-menu">
    <li><a href="#">Technology 1</a></li>
    <li><a href="#">Technology 2</a></li>
    <li><a href="#">Technology 3</a></li>
  </ul>
</div>


问:
Split CSV file after specified row Python
I'm trying to split a CSV file that has 201 rows. The first 136 rows contains information that is different from the remaining 65 rows. Is there anyway I can split the CSV file after 136 rows?

The solutions I have found so far split the file evenly. I have looked into this as a possible solution as well: https://gist.github.com/jrivero/1085501

答:
You can use two csv.reader objects on your file object. Slice the first reader object up to the specified number of rows using itertools.islice, and then read the rest of the rows using the second reader.

If the two parts are different by say delimiters, the two csv.reader objects can easily handle this:

```<code>import csv
from itertools import islice

with open('your_file_name.csv') as f:
    first_rows = list(islice(csv.reader(f), None, 136))
    last_rows = list(csv.reader(f, delimiter=';')) # use a different delim or quote char
</code>```

Body:
You can use two csv.reader objects on your file object. Slice the first reader object up to the specified number of rows using itertools.islice, and then read the rest of the rows using the second reader.

If the two parts are different by say delimiters, the two csv.reader objects can easily handle this:

import csv
from itertools import islice

with open('your_file_name.csv') as f:
    first_rows = list(islice(csv.reader(f), None, 136))
    last_rows = list(csv.reader(f, delimiter=';')) # use a different delim or quote char


问:
How to make an element transparent so its background is 2 layers behind?
I have an animated background (background), a div on it with a background-color (A), and another div in it (B). I want B to be transparent so through it we see the animated background, but B is in A, which already have a background-color.

Any ideas to achieve this?

答:
You could achieve this using the CSS clip-path property as long as you only wanted 'B' to be the cutout of 'A', in which case you wouldn't need 'B' at all.

HTML:

```<code><div class="animated-bg">
  <div class="inner-a">
  </div>
</div>
</code>```

CSS:

```<code>.animated-bg {
  background-color: black;
  width: 100%;
  height: 700px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.inner-a {
  background-color: white;
  width: 600px;
  height: 400px;
  margin: 0 auto;
  -webkit-clip-path: polygon(0% 0%, 0% 100%, 25% 100%, 25% 25%, 75% 25%, 75% 75%, 25% 75%, 25% 100%, 100% 100%, 100% 0%);
}
</code>```

Otherwise if you wanted 'B' to hold something e.g text you could absolute position it behind clipped 'A' and give it a transparent background.

Something like this:

HTML

```<code><div class="animated-bg">
  <div class="inner-b">
    hello
  </div>
  <div class="inner-a">
  </div>
</div>
</code>```

CSS:

```<code>.animated-bg {
  background-image: url(http://www.animateit.net/data/media/august2009/twi.gif);
  width: 100%;
  height: 700px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.inner-a {
  position: absolute;
  background-color: white;
  width: 600px;
  height: 400px;
  margin: 0 auto;
  -webkit-clip-path: polygon(0% 0%, 0% 100%, 25% 100%, 25% 25%, 75% 25%, 75% 75%, 25% 75%, 25% 100%, 100% 100%, 100% 0%);
  z-index: 2;
}

.inner-b {
  width: 400px;
  height: 300px;
  margin: 0 auto;
  position: absolute;
  background: transparent;
  z-index: 1;
  color: white;
  text-align: center;
  line-height: 300px;
}
</code>```

Clippy is really good to get the right sized clip: http://bennettfeely.com/clippy/

Fiddle 1st Example: https://jsfiddle.net/fjr7qvcm/1/

Fiddle 2nd Example: https://jsfiddle.net/fjr7qvcm/4/

Body:
You could achieve this using the CSS clip-path property as long as you only wanted 'B' to be the cutout of 'A', in which case you wouldn't need 'B' at all.

HTML:

<div class="animated-bg">
  <div class="inner-a">
  </div>
</div>

CSS:

.animated-bg {
  background-color: black;
  width: 100%;
  height: 700px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.inner-a {
  background-color: white;
  width: 600px;
  height: 400px;
  margin: 0 auto;
  -webkit-clip-path: polygon(0% 0%, 0% 100%, 25% 100%, 25% 25%, 75% 25%, 75% 75%, 25% 75%, 25% 100%, 100% 100%, 100% 0%);
}

Otherwise if you wanted 'B' to hold something e.g text you could absolute position it behind clipped 'A' and give it a transparent background.

Something like this:

HTML

<div class="animated-bg">
  <div class="inner-b">
    hello
  </div>
  <div class="inner-a">
  </div>
</div>

CSS:

.animated-bg {
  background-image: url(http://www.animateit.net/data/media/august2009/twi.gif);
  width: 100%;
  height: 700px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.inner-a {
  position: absolute;
  background-color: white;
  width: 600px;
  height: 400px;
  margin: 0 auto;
  -webkit-clip-path: polygon(0% 0%, 0% 100%, 25% 100%, 25% 25%, 75% 25%, 75% 75%, 25% 75%, 25% 100%, 100% 100%, 100% 0%);
  z-index: 2;
}

.inner-b {
  width: 400px;
  height: 300px;
  margin: 0 auto;
  position: absolute;
  background: transparent;
  z-index: 1;
  color: white;
  text-align: center;
  line-height: 300px;
}

Clippy is really good to get the right sized clip: http://bennettfeely.com/clippy/

Fiddle 1st Example: https://jsfiddle.net/fjr7qvcm/1/

Fiddle 2nd Example: https://jsfiddle.net/fjr7qvcm/4/

ContentLicense: CC BY-SA 4.0


问:
Define return value in Spark Scala UDF
Imagine the following code:

```<code>def myUdf(arg: Int) = udf((vector: MyData) => {
  // complex logic that returns a Double
})
</code>```

How can I define the return type for myUdf so that people looking at the code will know immediately that it returns a Double?

答:
Spark functions define several udf methods that have the following modifier/type: static <RT,A1, ..., A10> UserDefinedFunction

You can specify the input/output data types in square brackets as follows:

```<code>def myUdf(arg: Int) = udf[Double, MyData]((vector: MyData) => {
  // complex logic that returns a Double
})
</code>```

Title: Define return value in Spark Scala UDF

Body:
Imagine the following code:

def myUdf(arg: Int) = udf((vector: MyData) => {
  // complex logic that returns a Double
})

How can I define the return type for myUdf so that people looking at the code will know immediately that it returns a Double?

Body:
Spark functions define several udf methods that have the following modifier/type: static <RT,A1, ..., A10> UserDefinedFunction

You can specify the input/output data types in square brackets as follows:

def myUdf(arg: Int) = udf[Double, MyData]((vector: MyData) => {
  // complex logic that returns a Double
})


问:
Why Android HttpURLConnection is not able to create Asset on Azure Media Services using REST API?
I am trying to create an Asset on Azure Media Services using REST API from Android. I am following this documentation and this is my code to connect with AMS endpoint from Android,

```<code>urlConnection = (HttpURLConnection) this._url.openConnection();
    urlConnection.setRequestProperty("Content-Type", String.valueOf("application/json"));
    urlConnection.setRequestProperty("DataServiceVersion", String.valueOf("1.0;NetFx"));
    urlConnection.setRequestProperty("MaxDataServiceVersion", String.valueOf("3.0;NetFx"));
    urlConnection.setRequestProperty("Accept", String.valueOf("application/json"));
    urlConnection.setRequestProperty("Accept-Charset", String.valueOf("UTF-8"));
    urlConnection.setRequestProperty("Authorization", String.format(Locale.ENGLISH, "Bearer %s", _token));
    urlConnection.setRequestProperty("x-ms-version", String.valueOf(2.11));
    urlConnection.setRequestProperty("x-ms-client-request-id", UUID.randomUUID().toString());
    urlConnection.setRequestProperty("Host", this._host);
    urlConnection.setRequestProperty("Content-Length", String.valueOf(this._postData.length));
    urlConnection.setRequestProperty("Expect", String.valueOf("100-continue"));

    urlConnection.setConnectTimeout(CONNECTION_TIME_OUT);
    urlConnection.setReadTimeout(CONNECTION_READ_TIME_OUT);
    urlConnection.setInstanceFollowRedirects(true);
    urlConnection.setRequestMethod("POST");
    urlConnection.setUseCaches(false);
    urlConnection.setDoOutput(true);
    urlConnection.setDoInput(true);

    OutputStream wr= urlConnection.getOutputStream();
    wr.write(_postData);
    wr.flush();
    wr.close();
</code>```

And my _postData variable is byte array which I am converting from json,

```<code>_fileName = _fileName.replace(" ", "-");

    JSONObject jo = new JSONObject();
    jo.put("Name", _fileName+".mp4");
    jo.put("Options", String.valueOf(0));

    this._postData = jo.toString().getBytes("UTF-8");
</code>```

I have tried using Google Chrome's REST api client extension to check the post request and It works fine. I got the response I was expecting from chrome's REST api client extension but using Android, I am not getting the same response. I am getting this response from this code which is the step I have already performed before running this code. I have used both endpoints https://media.windows.net/ and https://wamsbayclus001rest-hs.cloudapp.net/ but it is not working from Android. I believe that Android is changing Headers or something is wrong with headers that AMS not parsing properly. Can anyone guide me how to achieve this using Android HttpUrlConnection?

Thanks.

答:
I fixed it by changing OutputStream to DataOutputStream

```<code>DataOutputStream wrr = new DataOutputStream(urlConnection.getOutputStream());
        wrr.write(this._postData);
        wrr.flush();
        wrr.close();
</code>```

and changed my json array to string,

String s = "{\"Name\":\"" + _fileName + ".mp4\", \"Options\":\"0\"}";

and it worked fine.

Body:
I am trying to create an Asset on Azure Media Services using REST API from Android. I am following this documentation and this is my code to connect with AMS endpoint from Android,

urlConnection = (HttpURLConnection) this._url.openConnection();
    urlConnection.setRequestProperty("Content-Type", String.valueOf("application/json"));
    urlConnection.setRequestProperty("DataServiceVersion", String.valueOf("1.0;NetFx"));
    urlConnection.setRequestProperty("MaxDataServiceVersion", String.valueOf("3.0;NetFx"));
    urlConnection.setRequestProperty("Accept", String.valueOf("application/json"));
    urlConnection.setRequestProperty("Accept-Charset", String.valueOf("UTF-8"));
    urlConnection.setRequestProperty("Authorization", String.format(Locale.ENGLISH, "Bearer %s", _token));
    urlConnection.setRequestProperty("x-ms-version", String.valueOf(2.11));
    urlConnection.setRequestProperty("x-ms-client-request-id", UUID.randomUUID().toString());
    urlConnection.setRequestProperty("Host", this._host);
    urlConnection.setRequestProperty("Content-Length", String.valueOf(this._postData.length));
    urlConnection.setRequestProperty("Expect", String.valueOf("100-continue"));

    urlConnection.setConnectTimeout(CONNECTION_TIME_OUT);
    urlConnection.setReadTimeout(CONNECTION_READ_TIME_OUT);
    urlConnection.setInstanceFollowRedirects(true);
    urlConnection.setRequestMethod("POST");
    urlConnection.setUseCaches(false);
    urlConnection.setDoOutput(true);
    urlConnection.setDoInput(true);

    OutputStream wr= urlConnection.getOutputStream();
    wr.write(_postData);
    wr.flush();
    wr.close();

And my _postData variable is byte array which I am converting from json,

_fileName = _fileName.replace(" ", "-");

    JSONObject jo = new JSONObject();
    jo.put("Name", _fileName+".mp4");
    jo.put("Options", String.valueOf(0));

    this._postData = jo.toString().getBytes("UTF-8");

I have tried using Google Chrome's REST api client extension to check the post request and It works fine. I got the response I was expecting from chrome's REST api client extension but using Android, I am not getting the same response. I am getting this response from this code which is the step I have already performed before running this code. I have used both endpoints https://media.windows.net/ and https://wamsbayclus001rest-hs.cloudapp.net/ but it is not working from Android. I believe that Android is changing Headers or something is wrong with headers that AMS not parsing properly. Can anyone guide me how to achieve this using Android HttpUrlConnection?

Thanks.

Body:
I fixed it by changing OutputStream to DataOutputStream

DataOutputStream wrr = new DataOutputStream(urlConnection.getOutputStream());
        wrr.write(this._postData);
        wrr.flush();
        wrr.close();

and changed my json array to string,

String s = "{\"Name\":\"" + _fileName + ".mp4\", \"Options\":\"0\"}";

and it worked fine.


问:
Conversation.SendToConversation throw error unknown botId
I'm developing a ChatBot with the Microsoft Botframework. When I'm sending a message with activity.CreateReply and ReplyToActivityAsync everythink working fine in WebChat, Skype and Telegram:

```<code>var reply = activity.CreateReply(activity.Recipient.Id);
await connectorClient.Conversations.ReplyToActivityAsync(reply);
</code>```

But when I try to send a new message directly without a previous activity, in Telegram I'm getting a unknown botId Exception. Skype and WebChat are working fine.

```<code>new ConnectorClient(new Uri(data.ServiceUrl)).Conversations.SendToConversationAsync(
    new Activity
    {
        ChannelId = data.ChannelId,
        From = new ChannelAccount(id: data.BotId),
        Conversation = new ConversationAccount(id: data.ConversationId),
        Type = ActivityTypes.Message,
        Text = text
    });
</code>```

I've tried different botIds for the "From" part. Currently I'm using the original id from the activity, when I'm storring the data, but I've tried the Telegram name and the BotFramework handle too.

The unknown botid exception has a whitespace behind botid, but there is nothing behind:

```<code>// Code to Output exception:
ex.GetType().Name + ": " + ex.Message

// result
"HttpOperationException: Unknown botId "
</code>```

答: This error occurs if you only specify the ID new ChannelAccount(botId) If you add the name new ChannelAccount(botId, botName), everything will work

Body:
I'm developing a ChatBot with the Microsoft Botframework. When I'm sending a message with activity.CreateReply and ReplyToActivityAsync everythink working fine in WebChat, Skype and Telegram:

var reply = activity.CreateReply(activity.Recipient.Id);
await connectorClient.Conversations.ReplyToActivityAsync(reply);

But when I try to send a new message directly without a previous activity, in Telegram I'm getting a unknown botId Exception. Skype and WebChat are working fine.

new ConnectorClient(new Uri(data.ServiceUrl)).Conversations.SendToConversationAsync(
    new Activity
    {
        ChannelId = data.ChannelId,
        From = new ChannelAccount(id: data.BotId),
        Conversation = new ConversationAccount(id: data.ConversationId),
        Type = ActivityTypes.Message,
        Text = text
    });

I've tried different botIds for the "From" part. Currently I'm using the original id from the activity, when I'm storring the data, but I've tried the Telegram name and the BotFramework handle too.

The unknown botid exception has a whitespace behind botid, but there is nothing behind:

// Code to Output exception:
ex.GetType().Name + ": " + ex.Message

// result
"HttpOperationException: Unknown botId "


Title: Wide to long format in R list: 3D to 2D array with 3rd dimension as ID

Body:
I have imported a *.mat data set of ECG data and it turns out to be an array nested in a list with (1:19, 1:2000, 1:45) dimensions.

I'd like to convert this array into a data.table in long format where each of the 1:45 are 'ids'. I like the look of reshape2 and tidyr but I don't see an easy way of doing it when a 'list' is involved. Any thoughts?

ADDED: E.g. as the following picture:

EDIT: Added dput from ECGa

    dput(ECGa[1:4,1:4,1:4])
structure(c(0.266687798848186, 0.243782451327742, 0.256932437720159,
0.298861598151174, 0.198233672667731, 0.0917952258522064, 0.0911852809187542,
0.0896079263551856, 0.236398290801764, 0.0864552727199747, 0.0745517747485495,
0.141094205953345, 0.134887167694073, 0.0747942533151883, 0.0955856952160322,
0.0351423350784724, 0.0280172116375036, 0.0137183766752048, 0.00632054977574689,
0.0140727955279187, 0.0690137281047283, 0.078048395374513, 0.103558903741209,
0.0440585188615387, 0.156352265056089, 0.112594108595364, 0.162727838219577,
0.171253189308951, 0.10110879614821, 0.0815894300030362, 0.11782535820017,
0.0422632188213653, 0.0555849641766514, 0.0677027788598739, 0.0459698146330784,
0.0388415858274208, 0.0843241755529416, 0.0607574029475139, 0.0572549162201976,
0.0507991887467287, 0.0505785290171543, 0.064132492222132, 0.0527843866043094,
0.0354988312446934, 0.104654374350645, 0.0881949907935882, 0.0429712078085868,
0.0576943626267035, 0.0382280461459995, 0.124883693856915, 0.0481763535955804,
0.0397818749456581, 0.0782161984603273, 0.155594086108477, 0.121039425233015,
0.0563997196467123, 0.0513952066155024, 0.209997229543773, 0.0745673273804948,
0.0647872565452434, 0.0801540099609934, 0.147046389860838, 0.162708859129276,
0.0766361733056703), .Dim = c(4L, 4L, 4L), .Dimnames = list(NULL,
    c("P7", "P4", "Cz", "Pz"), NULL))

I've tried doing:
ECGa<-as.data.frame(ECGa)
gives the right dimensions but it renames all the columns (e.g. the first becomes P7.1, P7.2 ... P7.45) I want to make a new column called ID that gives a value of 1 for the first patient and 2 for the second, up to 45 for the forty fifth.

NEW ADDITION:
I've found that using abind does part of the job I want. But imagine I had a 1000 arrays, can I automate it?
e.g.

 abind(ECGa[,,1],ECGa[,,2],ECGa[,,3],ECGa[,,4],ECGa[,,5],along=1)
> dim(abind(ECGa[,,1],ECGa[,,2],ECGa[,,3],ECGa[,,4],ECGa[,,5],along=1))
[1] 10000    19

Body:
I think you can do without abind, perhaps as simple as:

Reduce(rbind, sapply(1:dim(df)[3], function(i) {
  x <- data.frame(df[,,i])
  x$id <- i
  x
}, simplify = FALSE))
#            P7         P4         Cz         Pz id
# 1  0.26668780 0.19823367 0.23639829 0.13488717  1
# 2  0.24378245 0.09179523 0.08645527 0.07479425  1
# 3  0.25693244 0.09118528 0.07455177 0.09558570  1
# 4  0.29886160 0.08960793 0.14109421 0.03514234  1
# 5  0.02801721 0.06901373 0.15635227 0.10110880  2
# 6  0.01371838 0.07804840 0.11259411 0.08158943  2
# 7  0.00632055 0.10355890 0.16272784 0.11782536  2
# 8  0.01407280 0.04405852 0.17125319 0.04226322  2
# 9  0.05558496 0.08432418 0.05057853 0.10465437  3
# 10 0.06770278 0.06075740 0.06413249 0.08819499  3
# 11 0.04596981 0.05725492 0.05278439 0.04297121  3
# 12 0.03884159 0.05079919 0.03549883 0.05769436  3
# 13 0.03822805 0.07821620 0.05139521 0.08015401  4
# 14 0.12488369 0.15559409 0.20999723 0.14704639  4
# 15 0.04817635 0.12103943 0.07456733 0.16270886  4
# 16 0.03978187 0.05639972 0.06478726 0.07663617  4

If by chance your third dimension actually has names (faked with your data using dimnames(df)[[3]] <- paste("id", 1:dim(df)[3], sep = "")), then you can do:

head(
  Reduce(rbind, sapply(dimnames(df)[[3]], function(nm) {
    x <- data.frame(df[,,nm])
    x$id <- nm
    x
  }, simplify = FALSE))
)
#            P7         P4         Cz         Pz  id
# 1  0.26668780 0.19823367 0.23639829 0.13488717 id1
# 2  0.24378245 0.09179523 0.08645527 0.07479425 id1
# 3  0.25693244 0.09118528 0.07455177 0.09558570 id1
# 4  0.29886160 0.08960793 0.14109421 0.03514234 id1
# 5  0.02801721 0.06901373 0.15635227 0.10110880 id2
# 6  0.01371838 0.07804840 0.11259411 0.08158943 id2


问:
Submit SPARQL query with Angular 2 Typescript and AJAX
I'm querying DBPedia with SPARQL. The query works fine. Now I want to get the Data from this query in my Angular 2 Project. We need to do this with AJAX. The given method looks like this: getSPARQLTypes(): void {} I don't know how to use SPARQL with AJAX and Typescript.

答:
You can use the Http service provided by the framework to do it.

The request you described in the other post would look something like this.

import { Component } from '@angular/core';
import { Http, RequestOptionsArgs, Headers, URLSearchParams } from '@angular/http';
import 'rxjs/add/operator/map'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  private sparkqlData = null;
  constructor(private http: Http) { }

  sparkql() {
    let headers: Headers = new Headers({
      'Content-type': 'application/x-www-form-urlencoded',
      'Accept': 'application/json'
    });

    let params = new URLSearchParams();
    params.append('query', 'SELECT * WHERE { <http://dbpedia.org/resource/Awolnation> ?pref ?obj } LIMIT 10');
    params.append('format', 'json');

    let options: RequestOptionsArgs = {
      headers: headers,
      params: URLSearchParams
    };

    this.http.get('http://dbpedia.org/sparql', options) // 1
      .map(response => response.json())
      .subscribe(data => {
          console.log(data);
          this.sparkqlData = data; // 3
       });
     console.log(this.sparkqlData);  // 2
  }
}
```

You can save the date to work with it later but keep in mind that the request is asynchronous and it the variable won't be filled in as you might expect.

I added comments with the order of execution of the statements.

Body:
You can use the Http service provided by the framework to do it.

The request you described in the other post would look something like this.

import { Component } from '@angular/core';
import { Http, RequestOptionsArgs, Headers, URLSearchParams } from '@angular/http';
import 'rxjs/add/operator/map'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  private sparkqlData = null;
  constructor(private http: Http) { }

  sparkql() {
    let headers: Headers = new Headers({
      'Content-type': 'application/x-www-form-urlencoded',
      'Accept': 'application/json'
    });

    let params = new URLSearchParams();
    params.append('query', 'SELECT * WHERE { <http://dbpedia.org/resource/Awolnation> ?pref ?obj } LIMIT 10');
    params.append('format', 'json');

    let options: RequestOptionsArgs = {
      headers: headers,
      params: URLSearchParams
    };

    this.http.get('http://dbpedia.org/sparql', options) // 1
      .map(response => response.json())
      .subscribe(data => {
          console.log(data);
          this.sparkqlData = data; // 3
       });
     console.log(this.sparkqlData);  // 2
  }
}

You can save the date to work with it later but keep in mind that the request is asynchronous and it the variable won't be filled in as you might expect.

I added comments with the order of execution of the statements.


问:
Java minesweeper game problem. hiding mines when the game begins?
I've been able to successfully initiate a minefield when the game begins with 10 mines randomly scattered over the field. However, I'm having problems hiding these mines from the user when the game begins. As you know, the point of minesweeper is to find where the mines are WITHOUT being able to see them. I need help figuring out how to hide the mines.

Below is the code I have written for my Grid class which initiates the grid and includes a method which fills it with mines. How can I hide these mines and only reveal them when they are clicked on? Thanks for the help!

```<code>public class Grid {

 private int[][] grid;
 private boolean isHidden;
 private  int rows;
 private final int columns;
 private final int mines;

 public Grid() {
  this.rows = 8;
  this.columns = 8;
  this.mines = 10;
  this.grid = new int[rows][columns];

 }

 public int[][] getGrid() {
  return grid;
 }

 public int getRows() {
  return rows;
 }

 public int getColumns() {
  return columns;
  }

 public void fillGrid() {
  Random ranGen = new Random();

  for(int i = 0; i < this.mines; ) {
   int row = ranGen.nextInt(this.rows - 1);
   int column = ranGen.nextInt(this.columns - 1);

   if(grid[row][column] != MinesweeperGUI.MINE) {
    grid[row][column] = MinesweeperGUI.MINE;
    i++;
   }
  }
    }
</code>```

答:
Lots of methods. Easiest to implement here would be a 2d array of booleans: Opened and unopened. If not opened, show a closed square. Else, show what's there.

An alternative method would be to turn this more object oriented, and make a Tile class: it holds a boolean for a mine, and a enum for open/closed/flagged/question mark.

Body:
I've been able to successfully initiate a minefield when the game begins with 10 mines randomly scattered over the field. However, I'm having problems hiding these mines from the user when the game begins. As you know, the point of minesweeper is to find where the mines are WITHOUT being able to see them. I need help figuring out how to hide the mines.

Below is the code I have written for my Grid class which initiates the grid and includes a method which fills it with mines. How can I hide these mines and only reveal them when they are clicked on? Thanks for the help!

public class Grid {

 private int[][] grid;
 private boolean isHidden;
 private  int rows;
 private final int columns;
 private final int mines;

 public Grid() {
  this.rows = 8;
  this.columns = 8;
  this.mines = 10;
  this.grid = new int[rows][columns];

 }

 public int[][] getGrid() {
  return grid;
 }

 public int getRows() {
  return rows;
 }

 public int getColumns() {
  return columns;
  }

 public void fillGrid() {
  Random ranGen = new Random();

  for(int i = 0; i < this.mines; ) {
   int row = ranGen.nextInt(this.rows - 1);
   int column = ranGen.nextInt(this.columns - 1);

   if(grid[row][column] != MinesweeperGUI.MINE) {
    grid[row][column] = MinesweeperGUI.MINE;
    i++;
   }
  }
    }


问:
Detecting if user is playing music from another app
My game has an in-game soundtrack and I would like to pause the music if the user is playing music of their own from a media app on Android or iOS.

Is there a way to do this that is efficient enough to run in an update() function?

Thanks in advance!

答:
You can check if music is playing as described from this post.

```<code>AudioManager manager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
if(manager.isMusicActive())
 {
     // do something - or do it not
 }
</code>```

Wrap it around a class in Java then call it from C# with the help of the AndroidJavaClass API.

But that requires Java. You can take that code and convert it to C# without Java at-all. Get UnityPlayerPlayer, Activity then the Context. The rest can be handled by AndroidJavaClass.

Here is the ported C# version that does not require Java plugin.

```<code>bool isMusicPlaying()
{
    const string AUDIO_SERVICE = "audio";
    AndroidJavaClass unityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
    AndroidJavaObject unityActivity = unityClass.GetStatic<AndroidJavaObject>("currentActivity");
    AndroidJavaObject unityContext = unityActivity.Call<AndroidJavaObject>("getApplicationContext");

    bool mIsPlaying;
    using (AndroidJavaObject audioManager = unityContext.Call<AndroidJavaObject>("getSystemService", AUDIO_SERVICE))
    {
        mIsPlaying = audioManager.Call<bool>("isMusicActive");
    }
    return mIsPlaying;
}
</code>```

Body:
You can check if music is playing as described from this post.

AudioManager manager = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
if(manager.isMusicActive())
 {
     // do something - or do it not
 }

Wrap it around a class in Java then call it from C# with the help of the AndroidJavaClass API.

But that requires Java. You can take that code and convert it to C# without Java at-all. Get UnityPlayerPlayer, Activity then the Context. The rest can be handled by AndroidJavaClass.

Here is the ported C# version that does not require Java plugin.

bool isMusicPlaying()
{
    const string AUDIO_SERVICE = "audio";
    AndroidJavaClass unityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
    AndroidJavaObject unityActivity = unityClass.GetStatic<AndroidJavaObject>("currentActivity");
    AndroidJavaObject unityContext = unityActivity.Call<AndroidJavaObject>("getApplicationContext");

    bool mIsPlaying;
    using (AndroidJavaObject audioManager = unityContext.Call<AndroidJavaObject>("getSystemService", AUDIO_SERVICE))
    {
        mIsPlaying = audioManager.Call<bool>("isMusicActive");
    }
    return mIsPlaying;
}


问:
Wifi-Direct always disconnects after thirty minutes
I am creating a WifiP2pGroup with WifiP2pManager.connect(). This works fine but the group is always disbanded after thirty minutes, no matter whether data is being transferred or not. Does anyone know why this happens, or if it can be prevented?

I have tried sending data continuously between the devices and keeping the screens on the entire time with a wake lock but it makes no difference. I have made sure wifi is set not to sleep, and also obtained a wifilock, and turned off battery optimization for the app and for wifi direct, but these don't help either. After thirty minutes (or to be specific, 29m 18s - it's very consistent) I get the CONNECTION_STATE_CHANGE broadcast and the devices are no longer paired.

The devices are a Nexus 7 running Android 7 (LineageOS) and a Samsung Galaxy A5 running Android 6.

Thanks!

Edit: I have tried running with mobile data off and wifi not connected. The app is not being paused or destroyed and no other apps have permission to change the wifi state. In the wifi logs on one of the devices I found this event around the time of the disconnection:

```<code>E/DhcpStateMachine: DHCP renew failed on p2p-wlan0-0: Timed out waiting for DHCP Renew to finish
D/WifiP2pService: GroupCreatedState{ what=196613 }
E/WifiP2pService: DHCP failed
</code>```

On the other device I found this at the beginning of the disconnect process:

```<code>552-813/system_process V/WifiHAL: event received NL80211_CMD_DEL_STATION
552-846/system_process D/WifiMonitor: Event [IFNAME=p2p-p2p0-11 AP-STA-DISCONNECTED b6:22:8b:b1:df:0f p2p_dev_addr=f2:62:6f:d1:5f:0c]
552-846/system_process D/WifiMonitor: p2p0 cnt=6442 dispatchEvent: AP-STA-DISCONNECTED b6:22:8b:b1:df:0f p2p_dev_addr=f2:62:6f:d1:5f:0c
552-629/system_process D/WifiP2pService: Client list empty, remove non-persistent p2p group
</code>```

答: This appears to be a bug in the LineageOS build I am using, as it only happens when the tablet is the group owner. When the phone is the group owner, the disconnection doesn't happen.</p>

Body:
I am creating a WifiP2pGroup with WifiP2pManager.connect(). This works fine but the group is always disbanded after thirty minutes, no matter whether data is being transferred or not. Does anyone know why this happens, or if it can be prevented?

I have tried sending data continuously between the devices and keeping the screens on the entire time with a wake lock but it makes no difference. I have made sure wifi is set not to sleep, and also obtained a wifilock, and turned off battery optimization for the app and for wifi direct, but these don't help either. After thirty minutes (or to be specific, 29m 18s - it's very consistent) I get the CONNECTION_STATE_CHANGE broadcast and the devices are no longer paired.

The devices are a Nexus 7 running Android 7 (LineageOS) and a Samsung Galaxy A5 running Android 6.

Thanks!

Edit: I have tried running with mobile data off and wifi not connected. The app is not being paused or destroyed and no other apps have permission to change the wifi state. In the wifi logs on one of the devices I found this event around the time of the disconnection:

E/DhcpStateMachine: DHCP renew failed on p2p-wlan0-0: Timed out waiting for DHCP Renew to finish
D/WifiP2pService: GroupCreatedState{ what=196613 }
E/WifiP2pService: DHCP failed

On the other device I found this at the beginning of the disconnect process:

552-813/system_process V/WifiHAL: event received NL80211_CMD_DEL_STATION
552-846/system_process D/WifiMonitor: Event [IFNAME=p2p-p2p0-11 AP-STA-DISCONNECTED b6:22:8b:b1:df:0f p2p_dev_addr=f2:62:6f:d1:5f:0c]
552-846/system_process D/WifiMonitor: p2p0 cnt=6442 dispatchEvent: AP-STA-DISCONNECTED b6:22:8b:b1:df:0f p2p_dev_addr=f2:62:6f:d1:5f:0c
552-629/system_process D/WifiP2pService: Client list empty, remove non-persistent p2p group


问:
PuTTY outputs weird stuff when selecting in MySQL
I've encountered a strange problem when I was using PuTTY to query the following MySQL command: select * from gts_camera

The output seems extremely weird:

As you can see, putty outputs loads of "PuTTYPuTTYPuTTY..."

Maybe it's because of the table attribute set:

```<code>    mysql> describe gts_kamera;
+---------+----------+------+-----+-------------------+----------------+
| Field   | Type     | Null | Key | Default           | Extra          |
+---------+----------+------+-----+-------------------+----------------+
| id      | int(11)  | NO   | PRI | NULL              | auto_increment |
| datum   | datetime | YES  |     | CURRENT_TIMESTAMP |                |
| picture | longblob | YES  |     | NULL              |                |
+---------+----------+------+-----+-------------------+----------------+
</code>```

This table stores some big pictures and their date of creation.
(The weird ASCII-characters you can see on top of the picture is the content.)

Does anybody know why PuTTY outputs such strange stuff, and how to solve/clean this?

Cause I can't type any other commands afterwards. I have to reopen the session again.

Sincerely,
Michael.

答:
The reason this happens is because of the contents of the file (as you have a column defined with longblob). It may have some characters that Putty will not understand, therefore it will break as it is happening with you.

There is a configuration that may help though.

You can also not select every column in that table (at least not the *blob ones) as:

```<code>select id, datum from gts_camera;
</code>```

Or If you still want to do it use the MySql funtion HEX:

```<code>select id, datum, HEX(picture) as pic from gts_camera;
</code>```

Body:
I've encountered a strange problem when I was using PuTTY to query the following MySQL command: select * from gts_camera

The output seems extremely weird:

As you can see, putty outputs loads of "PuTTYPuTTYPuTTY..."

Maybe it's because of the table attribute set:

    mysql> describe gts_kamera;
+---------+----------+------+-----+-------------------+----------------+
| Field   | Type     | Null | Key | Default           | Extra          |
+---------+----------+------+-----+-------------------+----------------+
| id      | int(11)  | NO   | PRI | NULL              | auto_increment |
| datum   | datetime | YES  |     | CURRENT_TIMESTAMP |                |
| picture | longblob | YES  |     | NULL              |                |
+---------+----------+------+-----+-------------------+----------------+

This table stores some big pictures and their date of creation.
(The weird ASCII-characters you can see on top of the picture is the content.)

Does anybody know why PuTTY outputs such strange stuff, and how to solve/clean this?

Cause I can't type any other commands afterwards. I have to reopen the session again.

Sincerely,
Michael.

Body:
The reason this happens is because of the contents of the file (as you have a column defined with longblob). It may have some characters that Putty will not understand, therefore it will break as it is happening with you.

There is a configuration that may help though.

You can also not select every column in that table (at least not the *blob ones) as:

select id, datum from gts_camera;

Or If you still want to do it use the MySql funtion HEX:

select id, datum, HEX(picture) as pic from gts_camera;


问:
When do you use if then else or elif in python
When im using python on codecademy the tutorials on there use if(): statement then else(): statement. But sometimes it uses if(): then elif(): statement. I dont understand when your suppose to switch them out or which to use first.</p>

```<code>def fruit_color(fruit):
    if fruit == "apple":
        return "red"
    elif fruit == "banana":
        return "yellow"
    elif fruit == "pear":
        return "green"
</code>```

答:
We could survive in a world in which there was no elif statement.  We could do this:

```<code>def fruit_color(fruit):
    if fruit == "apple":
        color = "red"
    else:
            if fruit == "banana":
                color = "yellow"
            else:
                if fruit == "pear":
                    color = "green"
                # ...
                    # ....
                        # ...
                    # ...
                        # ...
                            # ... --->
    return color
</code>```

but it's rather inconvenient that the nesting keeps increasing and increasing---limited only by the number of types of fruit you want to check, which may be large.   It makes code hard to follow, and in Python it also means the indentation must keep increasing: soon you won't be able to see all your code within the same screen-width.

The elif statement solves this inconvenience by allowing you to collapse an else followed immediately by an if into a single statement that doesn't require an increase in nesting.

Body:
When im using python on codecademy the tutorials on there use if(): statement then else(): statement. But sometimes it uses if(): then elif(): statement. I dont understand when your suppose to switch them out or which to use first.

def fruit_color(fruit):
    if fruit == "apple":
        return "red"
    elif fruit == "banana":
        return "yellow"
    elif fruit == "pear":
        return "green"

Body:
We could survive in a world in which there was no elif statement.  We could do this:

def fruit_color(fruit):
    if fruit == "apple":
        color = "red"
    else:
            if fruit == "banana":
                color = "yellow"
            else:
                if fruit == "pear":
                    color = "green"
                # ...
                    # ....
                        # ...
                    # ...
                        # ...
                            # ... --->
    return color

but it's rather inconvenient that the nesting keeps increasing and increasing---limited only by the number of types of fruit you want to check, which may be large.   It makes code hard to follow, and in Python it also means the indentation must keep increasing: soon you won't be able to see all your code within the same screen-width.

The elif statement solves this inconvenience by allowing you to collapse an else followed immediately by an if into a single statement that doesn't require an increase in nesting.


答:
You can not use a div like a mask to hide background of its parent. So alternatively you can change the background-color of div.A to be border so that you can have the transparent effect like the following example

.out {
  background: repeating-linear-gradient( 45deg, #606dbc, #606dbc 10px, #465298 10px, #465298 20px);
  height: 200px;
  padding: 30px;
}

.A {
  border-style: solid;
  border-color: red;
  border-width: 20px 40px 20px 40px;
  height: 100px;
}

.B {
  background: transparent;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="out">
  <div class="A">
    <div class="B">
    </div>
  </div>
</div></code>```

Title: How to make an element transparent so its background is 2 layers behind?

Body:
I have an animated background (background), a div on it with a background-color (A), and another div in it (B). I want B to be transparent so through it we see the animated background, but B is in A, which already have a background-color.

Any ideas to achieve this?

Body:
You can not use a div like a mask to hide background of its parent. So alternatively you can change the background-color of div.A to be border so that you can have the transparent effect like the following example

.out {
  background: repeating-linear-gradient( 45deg, #606dbc, #606dbc 10px, #465298 10px, #465298 20px);
  height: 200px;
  padding: 30px;
}

.A {
  border-style: solid;
  border-color: red;
  border-width: 20px 40px 20px 40px;
  height: 100px;
}

.B {
  background: transparent;
}

<div class="out">
  <div class="A">
    <div class="B">
    </div>
  </div>
</div>


问:
Clearing textboxs in tabcointrols in vb.net
I have tabcontrol of three tabs and each tabs contains textbox and i want to clear all textboxes in each tabs and a one click of button(button event or any alternate way to clear all textboxes)

i have already tried many code however that only effective for first tab only

```<code>Private Sub ClearFields(ByVal cntr As Control)
    For Each page As TabPage In TabControl1.TabPages
        For Each ctl As Control In page.Controls
            If TypeOf ctl Is TextBox Then
                ctl.Text = ""
            End If
            If TypeOf ctl Is ComboBox Then
                ctl.Text = ""
            End If
            If ctl.HasChildren Then
                For Each thing As Control In ctl.Controls
                    If TypeOf thing Is TextBox Then
                        thing.Text = ""
                    End If
                Next
            End If
        Next
    Next
End Sub
</code>```

答:
That should look something more like:</p>

```<code>Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    ClearTabControl(TabControl1)
End Sub

Private Sub ClearTabControl(ByVal tb As TabControl)
    For Each page As TabPage In TabControl1.TabPages
        ClearFields(page)
    Next
End Sub

Private Sub ClearFields(ByVal cntr As Control)
    For Each ctl As Control In cntr.Controls
        If TypeOf ctl Is TextBox OrElse TypeOf ctl Is ComboBox Then
            ctl.Text = ""
        ElseIf ctl.HasChildren Then
            ClearFields(ctl)
        End If
    Next
End Sub
</code>```

Body:
I have tabcontrol of three tabs and each tabs contains textbox and i want to clear all textboxes in each tabs and a one click of button(button event or any alternate way to clear all textboxes)

i have already tried many code however that only effective for first tab only

Private Sub ClearFields(ByVal cntr As Control)
    For Each page As TabPage In TabControl1.TabPages
        For Each ctl As Control In page.Controls
            If TypeOf ctl Is TextBox Then
                ctl.Text = ""
            End If
            If TypeOf ctl Is ComboBox Then
                ctl.Text = ""
            End If
            If ctl.HasChildren Then
                For Each thing As Control In ctl.Controls
                    If TypeOf thing Is TextBox Then
                        thing.Text = ""
                    End If
                Next
            End If
        Next
    Next
End Sub

Body:
That should look something more like:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    ClearTabControl(TabControl1)
End Sub

Private Sub ClearTabControl(ByVal tb As TabControl)
    For Each page As TabPage In TabControl1.TabPages
        ClearFields(page)
    Next
End Sub

Private Sub ClearFields(ByVal cntr As Control)
    For Each ctl As Control In cntr.Controls
        If TypeOf ctl Is TextBox OrElse TypeOf ctl Is ComboBox Then
            ctl.Text = ""
        ElseIf ctl.HasChildren Then
            ClearFields(ctl)
        End If
    Next
End Sub


问:
Error - "Pivot" does not exist in the namespace - Windows phone 8.1
I am very new to Windows phone development. recently i am working on a project. i have got some code which uses pivot. but it is showing

error as:

The name "Pivot" does not exist in the namespace "http://schemas.microsoft.com/winfx/2006/xaml/presentation"

How can this be resolved ?

答: If you getting this error while developing Windows UWP app version 8.1 - bear in mind: Windows 8.1 have no Pivot control. Only Windows Phone 8.1 have Pivot control. So, the error appears while VS are building Windows 8.1 part of UWP app.</p>


问:
need to clear adapter from listview
i am trying to clear adapter from list view but nothing happen
here it  is my code  </p>

```<code> @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    search_button = (Button) findViewById(R.id.next_button);
    editText = (EditText) findViewById(R.id.edit_text);
    emptyTextView = (TextView) findViewById(R.id.empty_view);

    bookListView = (ListView) findViewById(R.id.list_view);

    // Get a reference to the ConnectivityManager to check state of network connectivity
    ConnectivityManager connMgr = (ConnectivityManager)
            getSystemService(Context.CONNECTIVITY_SERVICE);

    // Get details on the currently active default data network
    final NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

    search_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (networkInfo != null && networkInfo.isConnected()) {

                new GetBook().execute(BOOK_REQUEST_URL);
            } else {
</code>```

<p>//here need to clear adapter but nothin happen</p>

```<code>                emptyTextView.setText(R.string.NoConnect);
                bookListView.setEmptyView(emptyTextView);
                bookAdapter.clear();

            }
        }
</code>```

答: after bookAdapter.clear() include bookAdapter.notifyDataSetChanged() in your code

Title: need to clear adapter from listview

Body:
i am trying to clear adapter from list view but nothing happen
here it  is my code

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    search_button = (Button) findViewById(R.id.next_button);
    editText = (EditText) findViewById(R.id.edit_text);
    emptyTextView = (TextView) findViewById(R.id.empty_view);

    bookListView = (ListView) findViewById(R.id.list_view);

    // Get a reference to the ConnectivityManager to check state of network connectivity
    ConnectivityManager connMgr = (ConnectivityManager)
            getSystemService(Context.CONNECTIVITY_SERVICE);

    // Get details on the currently active default data network
    final NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

    search_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (networkInfo != null && networkInfo.isConnected()) {

                new GetBook().execute(BOOK_REQUEST_URL);
            } else {

//here need to clear adapter but nothin happen

                emptyTextView.setText(R.string.NoConnect);
                bookListView.setEmptyView(emptyTextView);
                bookAdapter.clear();

            }
        }


问:
Display decimal point with NSString stringWithFormat in Objective C
I'm a complete novice to objective C/iPad development, but I am trying to build a simple four function calculator on the iPad.

My current biggest difficulty is simply displaying a . when the decimal button is pressed. Here is what happens when a button (like two) is pressed.

```<code>-(IBAction)inTwo:(id)sender {
    display = display*10+2;
    [resultfield setText:[NSString stringWithFormat:@"%f",display]];
}
</code>```

Trying to just do

```<code>display = display*10+.
</code>```

Is obviously not working. Any way to append a period to the end of display?

Thanks

答:
You've only missed it by a little bit:

```<code>[resultfield setText:[NSString stringWithFormat:@"%f.", display]];
</code>```

If for some reason the parser is identifying the decimal point after the %f as some kind of specifier about the accuracy of the float or something (nearly positive it doesn't do this), just escape the decimal point:

```<code>[resultfield setText:[NSString stringWithFormat:@"%f\.", display]];
</code>```

Body:
I'm a complete novice to objective C/iPad development, but I am trying to build a simple four function calculator on the iPad.

My current biggest difficulty is simply displaying a . when the decimal button is pressed. Here is what happens when a button (like two) is pressed.

-(IBAction)inTwo:(id)sender {
    display = display*10+2;
    [resultfield setText:[NSString stringWithFormat:@"%f",display]];
}

Trying to just do

display = display*10+.

Is obviously not working. Any way to append a period to the end of display?

Thanks

Body:
You've only missed it by a little bit:

[resultfield setText:[NSString stringWithFormat:@"%f.", display]];

If for some reason the parser is identifying the decimal point after the %f as some kind of specifier about the accuracy of the float or something (nearly positive it doesn't do this), just escape the decimal point:

[resultfield setText:[NSString stringWithFormat:@"%f\.", display]];


问:
how to display the English DisplayName in .net core view instead of the localized string
i have a .net core project where in one of my views i have to display the
DisplayName  in English and in Arabic in the same view
only i get one language as the view have localized resource file </p>

<p>i created an extension method which take the model and return the DisplayName  metadata
actually my method and the original @html helper return one language
here the method i hope some one can modify it so it return the original English metadata instead of the localized value </p>

```<code>using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Internal;
using System;
using System.Linq.Expressions;

namespace iSee.IHtmlHelpers
{

    public static class HtmlExtensions
    {
        public static IHtmlContent DisplayNameForEn<TModel, TValue>(
            this IHtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression
        )
        {
            var modelExplorer = ExpressionMetadataProvider.FromLambdaExpression(expression, htmlHelper.ViewData, htmlHelper.MetadataProvider);
            var metadata = modelExplorer.Metadata;
            var DisplayName = metadata.DisplayName;
            return new HtmlString(DisplayName);
        }
    }
}
</code>```

答:
Thanks to @Nick Polideropoulos the answer above was helpful and inspired me to find an answer for the question
here the answer in case some one else search for </p>

```<code>using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq.Expressions;
using System.Reflection;

namespace iSee.IHtmlHelpers
{

    public static class HtmlExtensions
    {

        public static IHtmlContent DisplayNameForLatin<TModel, TValue>(
        this IHtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression)
        {

            var memberExpression = expression.Body as MemberExpression;
            if (memberExpression == null)
            {
                return new HtmlString("");
            }

            var displayAttribute = memberExpression.Member.GetCustomAttribute<DisplayAttribute>();

            return new HtmlString(displayAttribute.Name);

        }

    }
}
</code>```

Body:
i have a .net core project where in one of my views i have to display the
DisplayName  in English and in Arabic in the same view
only i get one language as the view have localized resource file

i created an extension method which take the model and return the DisplayName  metadata
actually my method and the original @html helper return one language
here the method i hope some one can modify it so it return the original English metadata instead of the localized value

using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures.Internal;
using System;
using System.Linq.Expressions;

namespace iSee.IHtmlHelpers
{

    public static class HtmlExtensions
    {
        public static IHtmlContent DisplayNameForEn<TModel, TValue>(
            this IHtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression
        )
        {
            var modelExplorer = ExpressionMetadataProvider.FromLambdaExpression(expression, htmlHelper.ViewData, htmlHelper.MetadataProvider);
            var metadata = modelExplorer.Metadata;
            var DisplayName = metadata.DisplayName;
            return new HtmlString(DisplayName);
        }
    }
}

Body:
Thanks to @Nick Polideropoulos the answer above was helpful and inspired me to find an answer for the question
here the answer in case some one else search for

using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq.Expressions;
using System.Reflection;

namespace iSee.IHtmlHelpers
{

    public static class HtmlExtensions
    {

        public static IHtmlContent DisplayNameForLatin<TModel, TValue>(
        this IHtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression)
        {

            var memberExpression = expression.Body as MemberExpression;
            if (memberExpression == null)
            {
                return new HtmlString("");
            }

            var displayAttribute = memberExpression.Member.GetCustomAttribute<DisplayAttribute>();

            return new HtmlString(displayAttribute.Name);

        }

    }
}


答: You have to call notifyDataSetChanged() method for your adapter that will notifies the adapter that the data has been changed and any View reflecting the data set should refresh itself.</p>

Title: need to clear adapter from listview


问:
Correlation matrix in panel data in R
I have a time-series panel dataset which is structured in the following way:

df <- data.frame(
  year = c(2012L, 2013L, 2014L, 2012L, 2013L, 2014L),
  id = c(1L, 1L, 1L, 2L, 2L, 2L),
  c = c(11L, 13L, 13L, 16L, 15L, 15L)
)

#>   year id  c
#> 1 2012  1 11
#> 2 2013  1 13
#> 3 2014  1 13
#> 4 2012  2 16
#> 5 2013  2 15
#> 6 2014  2 15
```

<p>I would like to find the cross-correlation between values in column C given their id number.
Something similar to this: </p>

<pre class="lang-r prettyprint-override"><code>#>     1  2
#> 1   1  0.8
#> 2   0.8  1
</code>```

I have been using dplyr package to find the cross-correlation between two variables in my panel data but for some reason, I can't do the same for cross correlation in one veriable grouped by id.

答:
Do you mean something like the following?  I used the reshape package to cast based on the value of your id, followed by the cor() function in baseR.

```<code>> mydf <- data.frame(year=c("12","13","14","12","13","14"),id=c(1,1,1,2,2,2),c=c(11,13,13,16,15,156))
> library(reshape2)
> mydf
  year id   c
1   12  1  11
2   13  1  13
3   14  1  13
4   12  2  16
5   13  2  15
6   14  2 156
> my_wide_data <- dcast(mydf, year~id,value.var="c")
> cor(my_wide_data[,2:3])
          1         2
1 1.0000000 0.4946525
2 0.4946525 1.0000000
</code>```

So @Henrik's comment was much more simple and elegant, so including here.

```<code>> cor(unstack(mydf[ , -1], c ~ id))
          X1        X2
X1 1.0000000 0.4946525
X2 0.4946525 1.0000000
</code>```

Title: Correlation matrix in panel data in R

Body:
I have a time-series panel dataset which is structured in the following way:

df <- data.frame(
  year = c(2012L, 2013L, 2014L, 2012L, 2013L, 2014L),
  id = c(1L, 1L, 1L, 2L, 2L, 2L),
  c = c(11L, 13L, 13L, 16L, 15L, 15L)
)

#>   year id  c
#> 1 2012  1 11
#> 2 2013  1 13
#> 3 2014  1 13
#> 4 2012  2 16
#> 5 2013  2 15
#> 6 2014  2 15

I would like to find the cross-correlation between values in column C given their id number.
Something similar to this:

#>     1  2
#> 1   1  0.8
#> 2   0.8  1

I have been using dplyr package to find the cross-correlation between two variables in my panel data but for some reason, I can't do the same for cross correlation in one veriable grouped by id.

Body:
Do you mean something like the following?  I used the reshape package to cast based on the value of your id, followed by the cor() function in baseR.

> mydf <- data.frame(year=c("12","13","14","12","13","14"),id=c(1,1,1,2,2,2),c=c(11,13,13,16,15,156))
> library(reshape2)
> mydf
  year id   c
1   12  1  11
2   13  1  13
3   14  1  13
4   12  2  16
5   13  2  15
6   14  2 156
> my_wide_data <- dcast(mydf, year~id,value.var="c")
> cor(my_wide_data[,2:3])
          1         2
1 1.0000000 0.4946525
2 0.4946525 1.0000000

So @Henrik's comment was much more simple and elegant, so including here.

> cor(unstack(mydf[ , -1], c ~ id))
          X1        X2
X1 1.0000000 0.4946525
X2 0.4946525 1.0000000


问:
how can you take an ArrayList of chars and return all those elements from the ArrayList into a String
This is the code for trying to answer my question. I'm kind of new with ArrayLists. I used a for loop trying to read every element from the Arraylist and put it in the new String "full" but this won't compile. I need some editing. I don't think this code properly works. I used .add so that I can try adding the elements from the String List to String full. This is what tried to do so far.</p>

```<code>public void String() {

   ArrayList<Character> StringList = new ArrayList<Character>();
   String full;
   for(int i = 0; i < arr.length; i++) {
       full.add(StringList[i]);
   }
   return full;
}
</code>```

答:
One effective way is to append each character to the string:

```<code>String myString = "";
for (Character c : myList) {
    myString += c;
}
</code>```

If myList.toString() gives: [a, b, c, d, e, f], then myString gives: abcdef.

Body:
This is the code for trying to answer my question. I'm kind of new with ArrayLists. I used a for loop trying to read every element from the Arraylist and put it in the new String "full" but this won't compile. I need some editing. I don't think this code properly works. I used .add so that I can try adding the elements from the String List to String full. This is what tried to do so far.

public void String() {

   ArrayList<Character> StringList = new ArrayList<Character>();
   String full;
   for(int i = 0; i < arr.length; i++) {
       full.add(StringList[i]);
   }
   return full;
}

Body:
One effective way is to append each character to the string:

String myString = "";
for (Character c : myList) {
    myString += c;
}

If myList.toString() gives: [a, b, c, d, e, f], then myString gives: abcdef.


问:
Convert a c hex value into a char*
How to convert a hex value in c into an equivalent char* value. For example if the hex value is 1df2 the char* should also contain 1df2.

I am using the VinC compiler and the VinL linker for the VNC2 USB Chip from FTDI. It has these following header files; stdlib, stdio and string. These are however subsets of the main c libraries and don't have the obvious answers such as snprintf or sprintf.

The docs say the following types are valid,

There are certain definitions for variable and function types which are used  throughout the kernel and drivers. They are available to applications in the vos.h header file.

Null pointer and logic definitions:

```<code>#define NULL                0
#define TRUE                1
#define FALSE               0
</code>```

Variable type definitions:

```<code>#define uint8               unsigned char
#define int8                char
#define int16               short
#define uint16              unsigned short
#define uint32              unsigned int
#define pvoid               unsigned char *
</code>```

Function type definitions:

```<code>typedef uint8 (*PF)(uint8);
typedef void (*PF_OPEN)(void *);
typedef void (*PF_CLOSE)(void *);
typedef uint8 (*PF_IOCTL)(pvoid);
typedef uint8 (*PF_IO)(uint8 *, unsigned short, unsigned short *);
typedef void (*PF_INT)(void);
</code>```

Any suggestions?

答:
Use snprintf():

```<code>int to_hex(char *output, size_t len, unsigned n)
{
    return snprintf(output, len, "%.4x", n);
}
</code>```

Given the new information that it's a fairly basic embedded system, then if you're only interested in 16 bit numbers a minimal solution like this probably suffices:

```<code>/* output points to buffer of at least 5 chars */
void to_hex_16(char *output, unsigned n)
{
    static const char hex_digits[] = "0123456789abcdef";

    output[0] = hex_digits[(n >> 12) & 0xf];
    output[1] = hex_digits[(n >> 8) & 0xf];
    output[2] = hex_digits[(n >> 4) & 0xf];
    output[3] = hex_digits[n & 0xf];
    output[4] = '\0';
}
</code>```

(It should be clear how to extend it to wider numbers).

Title: Convert a c hex value into a char*

Body:
How to convert a hex value in c into an equivalent char* value. For example if the hex value is 1df2 the char* should also contain 1df2.

I am using the VinC compiler and the VinL linker for the VNC2 USB Chip from FTDI. It has these following header files; stdlib, stdio and string. These are however subsets of the main c libraries and don't have the obvious answers such as snprintf or sprintf.

The docs say the following types are valid,

There are certain definitions for variable and function types which are used  throughout the kernel and drivers. They are available to applications in the vos.h header file.

Null pointer and logic definitions:

#define NULL                0
#define TRUE                1
#define FALSE               0

Variable type definitions:

#define uint8               unsigned char
#define int8                char
#define int16               short
#define uint16              unsigned short
#define uint32              unsigned int
#define pvoid               unsigned char *

Function type definitions:

typedef uint8 (*PF)(uint8);
typedef void (*PF_OPEN)(void *);
typedef void (*PF_CLOSE)(void *);
typedef uint8 (*PF_IOCTL)(pvoid);
typedef uint8 (*PF_IO)(uint8 *, unsigned short, unsigned short *);
typedef void (*PF_INT)(void);

Any suggestions?

Body:
Use snprintf():

int to_hex(char *output, size_t len, unsigned n)
{
    return snprintf(output, len, "%.4x", n);
}

Given the new information that it's a fairly basic embedded system, then if you're only interested in 16 bit numbers a minimal solution like this probably suffices:

/* output points to buffer of at least 5 chars */
void to_hex_16(char *output, unsigned n)
{
    static const char hex_digits[] = "0123456789abcdef";

    output[0] = hex_digits[(n >> 12) & 0xf];
    output[1] = hex_digits[(n >> 8) & 0xf];
    output[2] = hex_digits[(n >> 4) & 0xf];
    output[3] = hex_digits[n & 0xf];
    output[4] = '\0';
}

(It should be clear how to extend it to wider numbers).


问:
Get the content of an array of labels in Swift
I'm trying to check the content of an array of labels but it not works.

To explain the program: I have 4 arrays of 4 UIlabels each one and every label contains a number in String. This function returns true if one label contains the number 16. I tried to use the function "contains" but it doesn't work because "16" it's a string and not a label.

Thanks

Example of declaration of array of labels:

```<code>Fila1 = [UILabel]()
</code>```

Function Win:

```<code>func win() -> Bool {

    for i  in 0..<Fila1.count {

        if(Fila1[i].text == "16") {
            return true

         } else if(Fila2[i].text == "16") {
            return true

         } else if(Fila3[i].text == "16") {
            return true

         } else if(Fila4[i].text == "16") {
            return true

         } else {
            return false
         }
    }
    return false
}
</code>```

答:
The issue is that you shouldn't have that else statement return false.

It should be:

```<code>if(Fila1[i].text == "16") {
     return true

} else if(Fila2[i].text == "16") {
     return true

} else if(Fila3[i].text == "16") {
     return true

} else if(Fila4[i].text == "16") {
      return true

} // end if here
</code>```

You're exiting out of the loop too early. If the first element isn't what you are looking for you aren't checking the rest.

Body:
I'm trying to check the content of an array of labels but it not works.

To explain the program: I have 4 arrays of 4 UIlabels each one and every label contains a number in String. This function returns true if one label contains the number 16. I tried to use the function "contains" but it doesn't work because "16" it's a string and not a label.

Thanks

Example of declaration of array of labels:

Fila1 = [UILabel]()

Function Win:

func win() -> Bool {

    for i  in 0..<Fila1.count {

        if(Fila1[i].text == "16") {
            return true

         } else if(Fila2[i].text == "16") {
            return true

         } else if(Fila3[i].text == "16") {
            return true

         } else if(Fila4[i].text == "16") {
            return true

         } else {
            return false
         }
    }
    return false
}

Body:
The issue is that you shouldn't have that else statement return false.

It should be:

if(Fila1[i].text == "16") {
     return true

} else if(Fila2[i].text == "16") {
     return true

} else if(Fila3[i].text == "16") {
     return true

} else if(Fila4[i].text == "16") {
      return true

} // end if here

You're exiting out of the loop too early. If the first element isn't what you are looking for you aren't checking the rest.


问:
How do you take in key inputs without a text field in Java
I want to know how to be able to change a JLabel in java Swing to the button I press but I don't know what I'm missing something.  Please help.

What it should end up looking like is on the top of the screen it will show the key being pressed and will update the JLabel as you press it.  Don't worry about the Imports, I have them all in the actual code. Thanks :)

```<code>public class RandomFrame extends JFrame{
    Dimension Size = new Dimension(800,800);
    ListenForKeys LFK = new ListenForKeys();
    JLabel JInput = new JLabel("");
    JPanel P1 = new JPanel();
    public static void main(String[] args) {
        new RandomFrame();
    }

    public RandomFrame() {
        super("RandomFrame");
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setSize(Size);
        P1.add(JInput);
        this.add(P1);
        this.setVisible(true);
    }

    private class ListenForKeys implements KeyListener {
        @Override
        public void keyPressed(KeyEvent e) {
            String Key = String.valueOf(e.getKeyChar());
            JInput.setText(Key);
        }

        @Override
        public void keyReleased(KeyEvent e) {}
        @Override
        public void keyTyped(KeyEvent e) {}
    }
}
</code>```

答: Austin pointed out that LFK wasn't attached to anything and sure enough, I added it to the JFrame using the line this.addKeyListener(LFK) and sure enough it worked.  Thank you :)</p>

Body:
I want to know how to be able to change a JLabel in java Swing to the button I press but I don't know what I'm missing something.  Please help.

What it should end up looking like is on the top of the screen it will show the key being pressed and will update the JLabel as you press it.  Don't worry about the Imports, I have them all in the actual code. Thanks :)

public class RandomFrame extends JFrame{
    Dimension Size = new Dimension(800,800);
    ListenForKeys LFK = new ListenForKeys();
    JLabel JInput = new JLabel("");
    JPanel P1 = new JPanel();
    public static void main(String[] args) {
        new RandomFrame();
    }

    public RandomFrame() {
        super("RandomFrame");
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setSize(Size);
        P1.add(JInput);
        this.add(P1);
        this.setVisible(true);
    }

    private class ListenForKeys implements KeyListener {
        @Override
        public void keyPressed(KeyEvent e) {
            String Key = String.valueOf(e.getKeyChar());
            JInput.setText(Key);
        }

        @Override
        public void keyReleased(KeyEvent e) {}
        @Override
        public void keyTyped(KeyEvent e) {}
    }
}


答: Your code is fine, you just need to remove the else condition that contains return false and the code should work as expected.

Title: Get the content of an array of labels in Swift


问:
How can i pass multiple variables to my template in django?
Hey guys my files are organized as follows.

urls.py:

```<code>from django.conf.urls import url, include
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^contact/', views.eurusd, name='eur'),
    url(r'^contact/', views.VaR, name='lol'),

]
</code>```

views.py:

```<code>from django.shortcuts import render
from django.http import HttpResponse

from yahoo_finance import Currency

def eurusd (request):
    eur_usd = Currency('EURUSD')
    eur = ('EUR/USD Bid/Ask Price:    ' +eur_usd.get_bid() +' /   '+eur_usd.get_ask())
    return render(request, 'personal/basic.html', {'eur': eur})

def VaR (request):
    hallo = "this is a python sting"
    return render(request, 'personal/basic.html', {'lol': hallo})
</code>```

basic.html

```<code>{% extends "personal/header.html" %}

{% block content %}
<p>{{eur}}</p>
<p>{{lol}}</p>
{% endblock %}
</code>```

My question now is:
why is only the string from eur dictionary being returned in my template named basic.html and not the lol?
how can i pass multiple variables to my basic.html?

答:
You doesn`t need two functions, becouse you want to render template with two variables, so easiest way to do this - is write one functions that return in context two wariables. Some like this:

urls.py

```<code>from django.conf.urls import url, include
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^contact/', views.eurusd, name='eur'),
]
</code>```

views.py

```<code>eur_usd = Currency('EURUSD')
    eur = ('EUR/USD Bid/Ask Price:    ' +eur_usd.get_bid() +' /   '+eur_usd.get_ask())
hallo = 'This is the python string'
    return render(request, 'personal/basic.html', {'eur': eur, 'hallo' : hallo})
</code>```

With this code your tamplate will work fine

In your case django when try to find url, find first url that looks like your url, and then they do request to first function only.

Body:
Hey guys my files are organized as follows.

urls.py:

from django.conf.urls import url, include
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^contact/', views.eurusd, name='eur'),
    url(r'^contact/', views.VaR, name='lol'),

]

views.py:

from django.shortcuts import render
from django.http import HttpResponse

from yahoo_finance import Currency

def eurusd (request):
    eur_usd = Currency('EURUSD')
    eur = ('EUR/USD Bid/Ask Price:    ' +eur_usd.get_bid() +' /   '+eur_usd.get_ask())
    return render(request, 'personal/basic.html', {'eur': eur})

def VaR (request):
    hallo = "this is a python sting"
    return render(request, 'personal/basic.html', {'lol': hallo})

basic.html

{% extends "personal/header.html" %}

{% block content %}

{{eur}}

{{lol}}

{% endblock %}

My question now is:
why is only the string from eur dictionary being returned in my template named basic.html and not the lol?
how can i pass multiple variables to my basic.html?

Body:
You doesn`t need two functions, becouse you want to render template with two variables, so easiest way to do this - is write one functions that return in context two wariables. Some like this:

urls.py

from django.conf.urls import url, include
from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^contact/', views.eurusd, name='eur'),
]

views.py

eur_usd = Currency('EURUSD')
    eur = ('EUR/USD Bid/Ask Price:    ' +eur_usd.get_bid() +' /   '+eur_usd.get_ask())
hallo = 'This is the python string'
    return render(request, 'personal/basic.html', {'eur': eur, 'hallo' : hallo})

With this code your tamplate will work fine

In your case django when try to find url, find first url that looks like your url, and then they do request to first function only.