问:
Accessing members of structs in a list in C
I have been working through the exercises in K&R on my quest to learn C, and I've hit a strange problem. I wrote a program to count words, characters, and lines in a file, then draw a histogram displaying the count for each. Everything worked well until I tried to make my code a little more reusable with a struct. My struct is as follows:

```<code>struct category {
    char *name;
    int namelen;
    int count;
};
</code>```

and it's values are assigned by a constructor function:

```<code>struct category createCat(char *name) {
    struct category cat = {name, get_width(name), 0};
return cat;
}
</code>```

and finally I have a list comprised of all the categories, as follows:

```<code>struct category catList[] = {words, lines, characters};
</code>```

when I access the members of these structs by name, I have no issues. But if I try to access them in a loop, via catList[i].member, the member count always returns 0. the other two members, name and namelen, behave correctly withing the loop, and accessing count from outside the loops returns correctly. If anyone would be willing to help me understand what's going on I would greatly appreciate it.

if it is necessary, here is my full program:

```<code>#include <stdio.h>
#include <string.h>

int get_width(char* word) {
    return 15 - strlen(word);
}

struct category {
    char *name;
    int namelen;
    int count;
};

struct category createCat(char *name) {
    struct category cat = {name, get_width(name), 0};
    return cat;
}

int main () {
    int c;
    int inside_word;
    int i;
    int p;
    struct category words = createCat("words");
    struct category lines = createCat("lines");
    struct category characters = createCat("characters");

    struct category catList[] = {words, lines, characters};

    while ((c = getchar()) != EOF) {
        characters.count++;
        if (c != '\n' && c != ' ' && c != '\t') {
            putchar(c);
            if (!inside_word) {
                inside_word = 1;
                words.count++;
            }
        }

        else {
            if (inside_word)
                printf("\n");
            inside_word = 0;
            if (c == '\n')
                lines.count++;
        }
    }
    printf("\n%d words, %d lines, %d characters\n",
            words.count, lines.count, characters.count);

    for (i = 0; i < 3; i++) {
        printf("%s:%*s", catList[i].name, catList[i].namelen, " ");
        printf("%d", catList[i].count);
        for ( p = 0; p < catList[p].count; p++)
            printf("#");
        printf("\n");

    }
    return 0;
}
</code>```

答:
You are copying the words, lines, characters structures into your list.

But you do this before you process the data, so they never get updated.

If you want to maintain both sets of structures, you must update them in your loop:

```<code>words.count++;
catList[0].count++;
</code>```

If you want to maintain a single set, delete the other. (Pretty much what you have now, except for the top and bottom.)

If you want them to share data, then use pointers, so the list (or the stand-alone variables) point to the other structure.

Body:
I have been working through the exercises in K&R on my quest to learn C, and I've hit a strange problem. I wrote a program to count words, characters, and lines in a file, then draw a histogram displaying the count for each. Everything worked well until I tried to make my code a little more reusable with a struct. My struct is as follows:

struct category {
    char *name;
    int namelen;
    int count;
};

and it's values are assigned by a constructor function:

struct category createCat(char *name) {
    struct category cat = {name, get_width(name), 0};
return cat;
}

and finally I have a list comprised of all the categories, as follows:

struct category catList[] = {words, lines, characters};

when I access the members of these structs by name, I have no issues. But if I try to access them in a loop, via catList[i].member, the member count always returns 0. the other two members, name and namelen, behave correctly withing the loop, and accessing count from outside the loops returns correctly. If anyone would be willing to help me understand what's going on I would greatly appreciate it.

if it is necessary, here is my full program:

#include <stdio.h>
#include <string.h>

int get_width(char* word) {
    return 15 - strlen(word);
}

struct category {
    char *name;
    int namelen;
    int count;
};

struct category createCat(char *name) {
    struct category cat = {name, get_width(name), 0};
    return cat;
}

int main () {
    int c;
    int inside_word;
    int i;
    int p;
    struct category words = createCat("words");
    struct category lines = createCat("lines");
    struct category characters = createCat("characters");

    struct category catList[] = {words, lines, characters};

    while ((c = getchar()) != EOF) {
        characters.count++;
        if (c != '\n' && c != ' ' && c != '\t') {
            putchar(c);
            if (!inside_word) {
                inside_word = 1;
                words.count++;
            }
        }

        else {
            if (inside_word)
                printf("\n");
            inside_word = 0;
            if (c == '\n')
                lines.count++;
        }
    }
    printf("\n%d words, %d lines, %d characters\n",
            words.count, lines.count, characters.count);

    for (i = 0; i < 3; i++) {
        printf("%s:%*s", catList[i].name, catList[i].namelen, " ");
        printf("%d", catList[i].count);
        for ( p = 0; p < catList[p].count; p++)
            printf("#");
        printf("\n");

    }
    return 0;
}

Body:
You are copying the words, lines, characters structures into your list.

But you do this before you process the data, so they never get updated.

If you want to maintain both sets of structures, you must update them in your loop:

words.count++;
catList[0].count++;

If you want to maintain a single set, delete the other. (Pretty much what you have now, except for the top and bottom.)

If you want them to share data, then use pointers, so the list (or the stand-alone variables) point to the other structure.


来源: stackexchange

问:
How can i compare two datetimes in Django
I can`t compare two datetime variable. One of it is DateTimeField in my models.py

```<code>date_of_end_discount = models.DateTimeField()
</code>```

Second is datetime.now. This is sample of code of compare

```<code>from datetime import datetime

def is_discount(self):
    return self.date_of_end_discount > datetime.now()
</code>```

But i have TypeError:

```<code>can't compare offset-naive and offset-aware datetimes
</code>```

答:
AFAIK datetime.now() is not timezone aware.

Django comes with a helper for this, which requires pytz

```<code> naive = datetime.replace(tzinfo=None)
</code>```

or you can use timezone instead of datetime to fix this issue.

```<code>from django.utils import timezone
now = timezone.now()
</code>```

You should be able to compare your dates now.

ContentLicense: CC BY-SA 3.0

Body:
I can`t compare two datetime variable. One of it is DateTimeField in my models.py

date_of_end_discount = models.DateTimeField()

Second is datetime.now. This is sample of code of compare

from datetime import datetime

def is_discount(self):
    return self.date_of_end_discount > datetime.now()

But i have TypeError:

can't compare offset-naive and offset-aware datetimes

Body:
AFAIK datetime.now() is not timezone aware.

Django comes with a helper for this, which requires pytz

 naive = datetime.replace(tzinfo=None)

or you can use timezone instead of datetime to fix this issue.

from django.utils import timezone
now = timezone.now()

You should be able to compare your dates now.


问:
Load text file content using ajax
I have a HTML and CSS tab where i want to load the text content under each tab using ajax request from a .txt file. It means when we click on any tab then it loads the text content from .txt file. Content will be loaded first time a tabs get activated. First tab is already activated and text content loaded and showing under first tab but my issue is but when i click on second or third tab then it doesn't load the text content.
Code is live here: http://testweb.epizy.com/ajax-load/index.html

答:
Look at JQuery load function . Since you haven't supplied any code, I'm unable to help you better.

Here is your code :

```<code> $(document).ready(function() {
      if ($("#one").is(":checked")){
          $.ajax({
              url : "tab1.txt",
              dataType: "text",
              async:false,
              success : function (data) {
                  $(".tab1").html(data);
              }
          });
      };
      if ($("#two").is(":checked")){
          $.ajax({
              url : "tab2.txt",
              dataType: "text",
              async:false,
              success : function (data) {
                  $(".tab2").html(data);
              }
          });
      };
      if ($("#three").is(":checked")){
          $.ajax({
              url : "tab3.txt",
              dataType: "text",
              async:false,
              success : function (data) {
                  $(".tab3").html(data);
              }
          });
      };
    });
</code>```

You should do it like this, add:

```<code>  $(document).ready(function(){
    function loadText(){
      if ($("#one").is(":checked")){
           $.ajax({
             url : "tab1.txt",
             dataType: "text",
             async:false,
             success : function (data) {
               $(".tab1").html(data);
            }
         });
       }
       if ($("#two").is(":checked")){
          $.ajax({
            url : "tab2.txt",
            dataType: "text",
            async:false,
            success : function (data) {
              $(".tab2").html(data);
            }
         });
      }
      if ($("#three").is(":checked")){
          $.ajax({
          url : "tab3.txt",
          dataType: "text",
          async:false,
          success : function (data) {
              $(".tab3").html(data);
          }
        });
      }
    }
    $('input[type="radio"]').change(loadText);
  });
</code>```

Title: Load text file content using ajax

Body:
Look at JQuery load function . Since you haven't supplied any code, I'm unable to help you better.

Here is your code :

 $(document).ready(function() {
      if ($("#one").is(":checked")){
          $.ajax({
              url : "tab1.txt",
              dataType: "text",
              async:false,
              success : function (data) {
                  $(".tab1").html(data);
              }
          });
      };
      if ($("#two").is(":checked")){
          $.ajax({
              url : "tab2.txt",
              dataType: "text",
              async:false,
              success : function (data) {
                  $(".tab2").html(data);
              }
          });
      };
      if ($("#three").is(":checked")){
          $.ajax({
              url : "tab3.txt",
              dataType: "text",
              async:false,
              success : function (data) {
                  $(".tab3").html(data);
              }
          });
      };
    });

You should do it like this, add:

  $(document).ready(function(){
    function loadText(){
      if ($("#one").is(":checked")){
           $.ajax({
             url : "tab1.txt",
             dataType: "text",
             async:false,
             success : function (data) {
               $(".tab1").html(data);
            }
         });
       }
       if ($("#two").is(":checked")){
          $.ajax({
            url : "tab2.txt",
            dataType: "text",
            async:false,
            success : function (data) {
              $(".tab2").html(data);
            }
         });
      }
      if ($("#three").is(":checked")){
          $.ajax({
          url : "tab3.txt",
          dataType: "text",
          async:false,
          success : function (data) {
              $(".tab3").html(data);
          }
        });
      }
    }
    $('input[type="radio"]').change(loadText);
  });


问:
Pandas groupby custom function to each series
I am having hard time to apply a custom function to each set of groupby column in Pandas

My custom function takes series of numbers and takes the difference of consecutive pairs and returns the mean of all the differences. Below is the code

```<code>def mean_gap(a):
    b = []
    for i in range(0, len(a)-1):
        b.append((a[i+1]-a[i]))
    return np.mean(b)
</code>```

so if a = [1,3,7]
mean_gap(a) will give me ((3-1)+(7-3))/2) = 3.0

```<code> Dataframe:
   one two
    a  1
    a  3
    a  7
    b  8
    b  9

desired result
     Dataframe:
       one two
        a  3
        b  1
</code>```

df.groupby(['one'])['two'].???

I am new to pandas. I read that groupby takes values each row at a time, not full series. So I am not able to use lambda after groupby. Please help!

答:
With a custom function, you can do:

```<code>df.groupby('one')['two'].agg(lambda x: x.diff().mean())
one
a    3
b    1
Name: two, dtype: int64
</code>```

and reset the index:

```<code>df.groupby('one')['two'].agg(lambda x: x.diff().mean()).reset_index(name='two')

    one  two
0   a    3
1   b    1
</code>```

An alternative would be:

```<code>df.groupby('one')['two'].diff().groupby(df['one']).mean()
one
a    3.0
b    1.0
Name: two, dtype: float64
</code>```

Your approach would have also worked with the following:

```<code>def mean_gap(a):
    b = []
    a = np.asarray(a)
    for i in range(0, len(a)-1):
        b.append((a[i+1]-a[i]))
    return np.mean(b)

df.groupby('one')['two'].agg(mean_gap)
one
a    3
b    1
Name: two, dtype: int64
</code>```

a = np.asarray(a) is necessary because otherwise you would get KeyErrors in b.append((a[i+1]-a[i])).

Body:
I am having hard time to apply a custom function to each set of groupby column in Pandas

My custom function takes series of numbers and takes the difference of consecutive pairs and returns the mean of all the differences. Below is the code

def mean_gap(a):
    b = []
    for i in range(0, len(a)-1):
        b.append((a[i+1]-a[i]))
    return np.mean(b)

so if a = [1,3,7]
mean_gap(a) will give me ((3-1)+(7-3))/2) = 3.0

 Dataframe:
   one two
    a  1
    a  3
    a  7
    b  8
    b  9

desired result
     Dataframe:
       one two
        a  3
        b  1

df.groupby(['one'])['two'].???

I am new to pandas. I read that groupby takes values each row at a time, not full series. So I am not able to use lambda after groupby. Please help!

Body:
With a custom function, you can do:

df.groupby('one')['two'].agg(lambda x: x.diff().mean())
one
a    3
b    1
Name: two, dtype: int64

and reset the index:

df.groupby('one')['two'].agg(lambda x: x.diff().mean()).reset_index(name='two')

    one  two
0   a    3
1   b    1

An alternative would be:

df.groupby('one')['two'].diff().groupby(df['one']).mean()
one
a    3.0
b    1.0
Name: two, dtype: float64

Your approach would have also worked with the following:

def mean_gap(a):
    b = []
    a = np.asarray(a)
    for i in range(0, len(a)-1):
        b.append((a[i+1]-a[i]))
    return np.mean(b)

df.groupby('one')['two'].agg(mean_gap)
one
a    3
b    1
Name: two, dtype: int64

a = np.asarray(a) is necessary because otherwise you would get KeyErrors in b.append((a[i+1]-a[i])).


问:
How to enable build debugging in MSVS 2015?
I have a project in MSVS 2015 which keeps spuriously rebuilding every time, i.e. building always launches MSBuild which then gives a bunch of "All outputs are up-to-date." messages followed by "Build succeeded." instead of just doing nothing, as it should. In the previous versions of MSVS there was a (never documented AFAIK) way to enable verbose debug logging to quickly find the reason for this as explained e.g. here. Unfortunately this doesn't seem to do anything with MSVS 2015.

Does anybody know what has replaced it or some other way of debugging this problem?

答:
I had a very similar problem checking out and unzipping some files that had a future date on them.  This caused the entire project to rebuild even with no changes.

On *nix system, I would have used touch to fix, but on Windows I used the FOR command on cmd.exe:

```<code>FOR /R %I in (*.*) do copy /b "%I" +,,
</code>```

Which updates the timestamp to current (iirc).

Before I figured it out, I tried to change the verbosity of the build process.  You need to restart VS2015 after changing this setting:

options Projects&Settings->Build and Run;  Build Output : Verbose">

Also, turn on the startup banner using Configuration Properties -> C/C++ -> General. This gives you some more build commands.

Body:
I had a very similar problem checking out and unzipping some files that had a future date on them.  This caused the entire project to rebuild even with no changes.

On *nix system, I would have used touch to fix, but on Windows I used the FOR command on cmd.exe:

FOR /R %I in (*.*) do copy /b "%I" +,,

Which updates the timestamp to current (iirc).

Before I figured it out, I tried to change the verbosity of the build process.  You need to restart VS2015 after changing this setting:

Also, turn on the startup banner using Configuration Properties -> C/C++ -> General. This gives you some more build commands.


问:
How to find the largest power of 2 less than the given number
I need to find the largest power of 2 less than the given number.

And I stuck and can't find any solution.

Code:

```<code>public class MathPow {
   public int largestPowerOf2 (int n) {
        int res = 2;
        while (res < n) {
            res =(int) Math.pow(res, 2);
        }
        return res;
   }
}
</code>```

This doesn't work correctly.

Testing output:

```<code>Arguments Actual Expected
-------------------------
9         16     8
100       256    64
1000      65536  512
64        256    32
</code>```

How to solve this issue?

答:
I think this is the simplest way to do it.

Integer.highestOneBit(n-1);

ContentLicense: CC BY-SA 4.0

Body:
I need to find the largest power of 2 less than the given number.

And I stuck and can't find any solution.

Code:

public class MathPow {
   public int largestPowerOf2 (int n) {
        int res = 2;
        while (res < n) {
            res =(int) Math.pow(res, 2);
        }
        return res;
   }
}

This doesn't work correctly.

Testing output:

Arguments Actual Expected
-------------------------
9         16     8
100       256    64
1000      65536  512
64        256    32

How to solve this issue?


问:
Controlling the legend in ggplot
I have composed code that plots the density plots for a certain numeric variable for two Classes using ggplot.  But I can not handle the legend appearance. My code is the following:

```<code>mu <- ddply(german, "Class", summarise, grp.mean=mean(Credit_amount))

ggplot(german, aes(x=Credit_amount, fill=as.factor(Class))) +
  geom_histogram(aes(y=..density..), position="identity", alpha=0.3)+
  geom_density(alpha=0.6)+
  geom_vline(data=mu, aes(xintercept=grp.mean, color= as.factor(Class)),
             size = 2, alpha = 0.6)+
  labs(title="Credit_amount for the Two Classes (Good and Bad Creditors",x="Credit_amount", y = "Density") +
scale_fill_manual(limits=c("1", "0"), labels = c("Bad Creditors", "Good Creditors"), values = c("blue", "red"))
+ labs(fill="Class of Customers")
</code>```

The plot is the following. I have annotated the changes I am aiming for:

What I am doing wrong?  What should I do instead?

Your advice will be appreciated.

答:
Someone down-voted you probably because it is impossible to reproduce what you have done without the data set "german". You should try to translate your question to use a data set that everyone has access to.

This is roughly what you have, except using the data set mtcars:

```<code>library(plyr)
library(ggplot2)
data(mtcars)
mtcars$cyl = paste0(mtcars$cyl, ' cyl')
mu <- ddply(mtcars, "cyl", summarise, grp.mean=mean(mpg))
ggplot(mtcars, aes(x=mpg, fill=as.factor(cyl))) +
  geom_histogram(aes(y=..density..), position="identity", alpha=0.3)+
  geom_density(alpha=0.6)+
  geom_vline(data=mu, aes(xintercept=grp.mean, color= as.factor(cyl)),
             size = 2, alpha = 0.6)+
  labs(title="Title",x="mpg", y = "Density") +
  scale_fill_manual(limits=c('4 cyl', '6 cyl', '8 cyl'),
                    labels = c("4 cyl", "6 cyl", '8 cyl'),
                    values = c("red", "green", 'blue')) +
  labs(fill="Class of Customers")
</code>```

To change the order of the categories in the legend, include a line of code like this, which sets the levels for the factor cyl to be in the desired order:

```<code>mtcars$cyl = factor(mtcars$cyl, levels = c('8 cyl', '6 cyl', '4 cyl'))
mu <- ddply(mtcars, "cyl", summarise, grp.mean=mean(mpg))
</code>```

Then in the ggplot code, remove references to as.factor(cyl), and simply put cyl, since cyl is already a factor.  Also, add the line +guides(color=FALSE) at the end to remove the unwanted legend:

```<code>ggplot(mtcars, aes(x=mpg, fill=cyl)) +
  geom_histogram(aes(y=..density..), position="identity", alpha=0.3)+
  geom_density(alpha=0.6)+
  geom_vline(data=mu, aes(xintercept=grp.mean, color= cyl),
             size = 2, alpha = 0.6 )+
  labs(title="mtcars example",x="mpg", y = "Density") +
  scale_fill_manual(limits=c('8 cyl', '6 cyl', '4 cyl'),
                    labels = c("8 cyl", "6 cyl", '4 cyl'),
                    values = c("red", "green", 'blue')) +
  labs(fill="Class of Customers")+
  guides(color=FALSE)
</code>```

Title: Controlling the legend in ggplot

Body:
I have composed code that plots the density plots for a certain numeric variable for two Classes using ggplot.  But I can not handle the legend appearance. My code is the following:

mu <- ddply(german, "Class", summarise, grp.mean=mean(Credit_amount))

ggplot(german, aes(x=Credit_amount, fill=as.factor(Class))) +
  geom_histogram(aes(y=..density..), position="identity", alpha=0.3)+
  geom_density(alpha=0.6)+
  geom_vline(data=mu, aes(xintercept=grp.mean, color= as.factor(Class)),
             size = 2, alpha = 0.6)+
  labs(title="Credit_amount for the Two Classes (Good and Bad Creditors",x="Credit_amount", y = "Density") +
scale_fill_manual(limits=c("1", "0"), labels = c("Bad Creditors", "Good Creditors"), values = c("blue", "red"))
+ labs(fill="Class of Customers")

The plot is the following. I have annotated the changes I am aiming for:

What I am doing wrong?  What should I do instead?

Your advice will be appreciated.

Body:
Someone down-voted you probably because it is impossible to reproduce what you have done without the data set "german". You should try to translate your question to use a data set that everyone has access to.

This is roughly what you have, except using the data set mtcars:

library(plyr)
library(ggplot2)
data(mtcars)
mtcars$cyl = paste0(mtcars$cyl, ' cyl')
mu <- ddply(mtcars, "cyl", summarise, grp.mean=mean(mpg))
ggplot(mtcars, aes(x=mpg, fill=as.factor(cyl))) +
  geom_histogram(aes(y=..density..), position="identity", alpha=0.3)+
  geom_density(alpha=0.6)+
  geom_vline(data=mu, aes(xintercept=grp.mean, color= as.factor(cyl)),
             size = 2, alpha = 0.6)+
  labs(title="Title",x="mpg", y = "Density") +
  scale_fill_manual(limits=c('4 cyl', '6 cyl', '8 cyl'),
                    labels = c("4 cyl", "6 cyl", '8 cyl'),
                    values = c("red", "green", 'blue')) +
  labs(fill="Class of Customers")

To change the order of the categories in the legend, include a line of code like this, which sets the levels for the factor cyl to be in the desired order:

mtcars$cyl = factor(mtcars$cyl, levels = c('8 cyl', '6 cyl', '4 cyl'))
mu <- ddply(mtcars, "cyl", summarise, grp.mean=mean(mpg))

Then in the ggplot code, remove references to as.factor(cyl), and simply put cyl, since cyl is already a factor.  Also, add the line +guides(color=FALSE) at the end to remove the unwanted legend:

ggplot(mtcars, aes(x=mpg, fill=cyl)) +
  geom_histogram(aes(y=..density..), position="identity", alpha=0.3)+
  geom_density(alpha=0.6)+
  geom_vline(data=mu, aes(xintercept=grp.mean, color= cyl),
             size = 2, alpha = 0.6 )+
  labs(title="mtcars example",x="mpg", y = "Density") +
  scale_fill_manual(limits=c('8 cyl', '6 cyl', '4 cyl'),
                    labels = c("8 cyl", "6 cyl", '4 cyl'),
                    values = c("red", "green", 'blue')) +
  labs(fill="Class of Customers")+
  guides(color=FALSE)


问:
Overwriting SQLite Database on iOS
I have a database.sqlite file, I used NSlog to know where is the file located, hopefully I got the location

and the question is, I want to overwrite that database with a button, so when ever the user click the button, it overwrites the database, but instead of overwriting, it saves the database to the following path

/Users/MYUsername/Library/Developer/CoreSimulator/Devices/4453818A-0617-479B-B98C-3FC544A24D00/data/Containers/Bundle/Application/F15404E8-AB5B-40D6-A4D5-ED42F8F7A682/Documents/Database.sqlite

which is not what I want, I want to save the database to here

/Users/MYUsername/Library/Developer/CoreSimulator/Devices/4453818A-0617-479B-B98C-3FC544A24D00/data/Containers/Data/Application/BD3E2250-DF45-480F-AB06-F8E97D3B0B37/Documents

I tried the following code:

```<code>- (IBAction)updateDatabase:(id)sender {

    NSData *dbFile = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"file URL"]];

    NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle]  executablePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"]];

    NSString *filePath = [resourceDocPath stringByAppendingPathComponent:@"Database.sqlite"];

    [dbFile writeToFile:filePath atomically:YES];
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:filePath]) {
        NSLog(@"File Not exsists : %@",filePath);
    } else {
        NSLog(@"File exsits : %@",filePath);
    }
}
</code>```

答:
Each time you run your application a new UUID is created and the files are copied to this new directory to verify this add the following code in your  application:didFinishLaunchingWithOptions:

```<code>NSLog(@"executablePath: %@", [[NSBundle mainBundle] executablePath]);

NSURL *urlDocument = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
NSString *pathDatabase = [[urlDocument path] stringByAppendingPathComponent:@"Database.sqlite"];

BOOL databaseExists = [[NSFileManager defaultManager] fileExistsAtPath:pathDatabase];
NSLog(@"databaseExists: %@", databaseExists ? @"YES" : @"NO");
</code>```

by the way you should check if the file exists at filePath before writing the database content (dbFile) to the file at this location.

Title: Overwriting SQLite Database on iOS

Body:
I have a database.sqlite file, I used NSlog to know where is the file located, hopefully I got the location

and the question is, I want to overwrite that database with a button, so when ever the user click the button, it overwrites the database, but instead of overwriting, it saves the database to the following path

/Users/MYUsername/Library/Developer/CoreSimulator/Devices/4453818A-0617-479B-B98C-3FC544A24D00/data/Containers/Bundle/Application/F15404E8-AB5B-40D6-A4D5-ED42F8F7A682/Documents/Database.sqlite

which is not what I want, I want to save the database to here

/Users/MYUsername/Library/Developer/CoreSimulator/Devices/4453818A-0617-479B-B98C-3FC544A24D00/data/Containers/Data/Application/BD3E2250-DF45-480F-AB06-F8E97D3B0B37/Documents

I tried the following code:

- (IBAction)updateDatabase:(id)sender {

    NSData *dbFile = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:@"file URL"]];

    NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle]  executablePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"]];

    NSString *filePath = [resourceDocPath stringByAppendingPathComponent:@"Database.sqlite"];

    [dbFile writeToFile:filePath atomically:YES];
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:filePath]) {
        NSLog(@"File Not exsists : %@",filePath);
    } else {
        NSLog(@"File exsits : %@",filePath);
    }
}

Body:
Each time you run your application a new UUID is created and the files are copied to this new directory to verify this add the following code in your  application:didFinishLaunchingWithOptions:

NSLog(@"executablePath: %@", [[NSBundle mainBundle] executablePath]);

NSURL *urlDocument = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
NSString *pathDatabase = [[urlDocument path] stringByAppendingPathComponent:@"Database.sqlite"];

BOOL databaseExists = [[NSFileManager defaultManager] fileExistsAtPath:pathDatabase];
NSLog(@"databaseExists: %@", databaseExists ? @"YES" : @"NO");

by the way you should check if the file exists at filePath before writing the database content (dbFile) to the file at this location.


问:
Parsing a nested tag, moving it outside of the parent, and changing its type using Nokogiri
I have HTML coming from an API that I want to clean up and format it.

I'm trying to get any  tags that are the first element inside a
 tag, and change it to be the parent of the
 tag, and convert the
 tag to
.

For example:

```<code><p><strong>This is what I want to pull out to an h4 tag.</strong>Here's the rest of the paragraph.</p>
</code>```

becomes:

```<code><h4>This is what I want to pull out to an h4 tag.</h4><p>Here's the rest of the paragraph.</p>
</code>```

EDIT: Apologies for the nature of the question being too 'please write this for me'. I posted the solution I came up with below. I just had to take the time to really learn how Nokogiri works, but it is quite powerful and it seems like you can do almost anything with it.

答:
```<code>doc = Nokogiri::HTML::DocumentFragment.parse(html)

doc.css("p").map do |paragraph|
  first = paragraph.children.first
  if first.element? and first.name == "strong"
    first.name = 'h4'
    paragraph.add_previous_sibling(first)
  end
end
</code>```

Body:
I have HTML coming from an API that I want to clean up and format it.

I'm trying to get any  tags that are the first element inside a
 tag, and change it to be the parent of the
 tag, and convert the
 tag to
.

For example:

This is what I want to pull out to an h4 tag.Here's the rest of the paragraph.

becomes:

This is what I want to pull out to an h4 tag.

Here's the rest of the paragraph.

EDIT: Apologies for the nature of the question being too 'please write this for me'. I posted the solution I came up with below. I just had to take the time to really learn how Nokogiri works, but it is quite powerful and it seems like you can do almost anything with it.


问:
Proper way for Repainting JComponent
So, I've taken an AP class on java, and in the class, we never really went over repaint(), and how to properly use it. I've also searched through the internet, and I personally have not found any answers on the standard way of calling repaint(). Are we supposed to call the repaint() method from the main class like the following?

```<code>import java.awt.*;
import javax.swing.*;

public class RepaintExample{

    public static void main(String[] args){

        JFrame frame = new JFrame();
        JComponent component = new JComponent();
        frame.add(component);
        frame.repaint();
    }

}
</code>```

Or would I call the JComponent.repaint() Like this

```<code>import java.awt.*;
import javax.swing.*;

public class RepaintExample{

    public static void main(String[] args){

        JFrame frame = new JFrame();
        JComponent component = new JComponent();
        frame.add(component);
        component.repaint();
    }

}
</code>```

Or, are both approaches wrong, and JComponent.repaint() should be called from the paintComponent as shown here:

```<code>import java.awt.*;
import javax.swing.*;

public class ComponentRepaintExample extends JComponent{

    public void paintComponent(Graphics g){

        //Draw stuff
        for(int i = 0; i < 10; i++){
            //Draw stuff
            this.repaint();
        }
    }

}
</code>```

It is quite possible that all three approaches are wrong. Any help figuring out how to properly use the repaint() method is appreciated. The whole topic is very shrouded to me, so I apologize if any terminology I use is incorrect. All thanks in advance.

答:
Why do you think you need to call repaint()?

The repaint() method is invoked by a Swing component automatically when a property of the component is changed.

For example if you have a JLabel and you invoke setText(...) or setIcon(...), then those methods will automatically invoke repaint().

You would NEVER invoke repaint() from a painting method.

If you are doing custom painting, then your code should be structured like any other Swing component. That is you create getter/setter methods for your custom components to change properties of the component. In the setter method you invoke repaint().

Title: Proper way for Repainting JComponent

Body:
So, I've taken an AP class on java, and in the class, we never really went over repaint(), and how to properly use it. I've also searched through the internet, and I personally have not found any answers on the standard way of calling repaint(). Are we supposed to call the repaint() method from the main class like the following?

import java.awt.*;
import javax.swing.*;

public class RepaintExample{

    public static void main(String[] args){

        JFrame frame = new JFrame();
        JComponent component = new JComponent();
        frame.add(component);
        frame.repaint();
    }

}

Or would I call the JComponent.repaint() Like this

import java.awt.*;
import javax.swing.*;

public class RepaintExample{

    public static void main(String[] args){

        JFrame frame = new JFrame();
        JComponent component = new JComponent();
        frame.add(component);
        component.repaint();
    }

}

Or, are both approaches wrong, and JComponent.repaint() should be called from the paintComponent as shown here:

import java.awt.*;
import javax.swing.*;

public class ComponentRepaintExample extends JComponent{

    public void paintComponent(Graphics g){

        //Draw stuff
        for(int i = 0; i < 10; i++){
            //Draw stuff
            this.repaint();
        }
    }

}

It is quite possible that all three approaches are wrong. Any help figuring out how to properly use the repaint() method is appreciated. The whole topic is very shrouded to me, so I apologize if any terminology I use is incorrect. All thanks in advance.


问:
Unpacking data packets in c++
I'm doing a udp client server model thing and my issue basically comes down to not being able to print the number 65000 in this short program. The output I get is: 0

```<code>struct pHeader{
  uint16_t from = -1;
} pHead;

void formatPacket(pHeader header, char buffer[]) {
    uint16_t u16;
    u16 = header.from;
    memcpy(buffer+2, &u16, 2);
}

int main () {
cout << "buffer" << endl;

char buffer[10];

pHead.from = 65000;
formatPacket(pHead, buffer);

cout << atoi(buffer+2) << endl;
}
</code>```

The next thing I want to do is print off a value that's in the first element of the array that's also 16 bits.  I believe it's done like this:

```<code>.
.
.
buffer[2] = 0;
cout << atoi(buffer+0) << endl;
</code>```

答:
According to the documentation of atoi(), it will return zero "if no valid conversion could be performed".  So, the zero you are seeing is atoi() telling you that in the buffer that you gave it there was nothing that it could interpret as a number.

That's because the buffer was filled with memcpy() using &u16 with a size of 2.  u16 was 65000, so assuming a little-endian architecture, buffer[2] was E8, and buffer[3] was FD. That's not a number that atoi() can parse.

In order to read the value at buffer[2] you need to do the reverse of memcpy(), which is another memcpy(), as follows:

```<code>uint16_t u16;
memcpy(&u16, buffer+2, 2);
cout << u16 << endl;
</code>```

Title: Unpacking data packets in c++

Body:
I'm doing a udp client server model thing and my issue basically comes down to not being able to print the number 65000 in this short program. The output I get is: 0

struct pHeader{
  uint16_t from = -1;
} pHead;

void formatPacket(pHeader header, char buffer[]) {
    uint16_t u16;
    u16 = header.from;
    memcpy(buffer+2, &u16, 2);
}

int main () {
cout << "buffer" << endl;

char buffer[10];

pHead.from = 65000;
formatPacket(pHead, buffer);

cout << atoi(buffer+2) << endl;
}

The next thing I want to do is print off a value that's in the first element of the array that's also 16 bits.  I believe it's done like this:

.
.
.
buffer[2] = 0;
cout << atoi(buffer+0) << endl;

Body:
According to the documentation of atoi(), it will return zero "if no valid conversion could be performed".  So, the zero you are seeing is atoi() telling you that in the buffer that you gave it there was nothing that it could interpret as a number.

That's because the buffer was filled with memcpy() using &u16 with a size of 2.  u16 was 65000, so assuming a little-endian architecture, buffer[2] was E8, and buffer[3] was FD. That's not a number that atoi() can parse.

In order to read the value at buffer[2] you need to do the reverse of memcpy(), which is another memcpy(), as follows:

uint16_t u16;
memcpy(&u16, buffer+2, 2);
cout << u16 << endl;


问:
Python kivy - how to reduce height of TextInput
I am using kivy to make a very simple gui for an application. Nothing complex, very simple layout.

Nevertheless I am having a hard time with TextInputs...They always display with full height and I can't manage to make them adjust to a "reasonable" text-height like height.

I am using the kv files style since I find it cleaner and easier to integrate it in an already existing app...I would like to reduce as much as possible the gui-python code of the app.

Here is what I got for the TextInput (useless to add other parts of the gui).

Python code

```<code># textInput.py
from kivy import require
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang.builder import Builder

Builder.load_file('path/to/kv/file/textInput.kv')

require('1.10.0')

class MainScreen(BoxLayout):
    pass

class Test(App):
    def build(self):
        self.title = 'Testing textInput'
        return MainScreen()

if __name__ == '__main__':
    Test().run()
</code>```

KV code

```<code># textInput.kv
<MainScreen>
    orientation: 'vertical'

    # Third section title
    Label:
        size_hint: (1, .1)
        text: 'Setup Connection'
        font_size: 25

    # Third section Box
    BoxLayout:
        size_hint: (1, .2)
        padding: [100, 0, 100, 0]
        BoxLayout:
            Label:
                size_hint: (.2, 1)
                text: 'Host'
            TextInput:
                height: self.minimum_height
                multiline: False
                text: 'localhost'
            Label:
                size_hint: (.2, 1)
                text: ''
            Label:
                size_hint: (.2, 1)
                text: 'Port'
            TextInput:
                size_hint: (.2, 1)
                multiline: False
                text: '502'
</code>```

I have tried lot of stuff, in the code here I am trying both to use size_hint and height...but none works..

答: in addition to the answer size_hint_x and size_hint_y must be set to None respectively before  the height and width attribute can  be used i.e size_hint: (None, None) for less typing. If you want to set the width attribute, size_hint_x is set to None and vice-versa.

Body:
I am using kivy to make a very simple gui for an application. Nothing complex, very simple layout.

Nevertheless I am having a hard time with TextInputs...They always display with full height and I can't manage to make them adjust to a "reasonable" text-height like height.

I am using the kv files style since I find it cleaner and easier to integrate it in an already existing app...I would like to reduce as much as possible the gui-python code of the app.

Here is what I got for the TextInput (useless to add other parts of the gui).

Python code

# textInput.py
from kivy import require
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang.builder import Builder

Builder.load_file('path/to/kv/file/textInput.kv')

require('1.10.0')

class MainScreen(BoxLayout):
    pass

class Test(App):
    def build(self):
        self.title = 'Testing textInput'
        return MainScreen()

if __name__ == '__main__':
    Test().run()

KV code

# textInput.kv
<MainScreen>
    orientation: 'vertical'

    # Third section title
    Label:
        size_hint: (1, .1)
        text: 'Setup Connection'
        font_size: 25

    # Third section Box
    BoxLayout:
        size_hint: (1, .2)
        padding: [100, 0, 100, 0]
        BoxLayout:
            Label:
                size_hint: (.2, 1)
                text: 'Host'
            TextInput:
                height: self.minimum_height
                multiline: False
                text: 'localhost'
            Label:
                size_hint: (.2, 1)
                text: ''
            Label:
                size_hint: (.2, 1)
                text: 'Port'
            TextInput:
                size_hint: (.2, 1)
                multiline: False
                text: '502'

I have tried lot of stuff, in the code here I am trying both to use size_hint and height...but none works..


问:
Allow only numbers and special character(-) to be typed in a textbox
I need to Allow only numbers and special character minus "-" to be typed in a textbox, plz help me i already have a number restriction, but wanna minus sign too.

thanks in advance

```<code><script>
function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}
</script>

<input type="text" class="textfield" value="" id="extra7" name="extra7" onkeypress="return isNumber(event)" />
</code>```

答:
Adding !=45 is not sufficient. You need to prevent the acceptance of invalid key inputs too. Returning true/false will still allow user to type those keys and your code then will seem to do nothing.

```<code>if ((charCode < 48 || charCode > 57) && charCode != 45) {
   evt.preventDefault();
}
</code>```

This way only valid key inputs will appear in text box.

Body:
I need to Allow only numbers and special character minus "-" to be typed in a textbox, plz help me i already have a number restriction, but wanna minus sign too.

thanks in advance

<input type="text" class="textfield" value="" id="extra7" name="extra7" onkeypress="return isNumber(event)" />

Body:
Adding !=45 is not sufficient. You need to prevent the acceptance of invalid key inputs too. Returning true/false will still allow user to type those keys and your code then will seem to do nothing.

if ((charCode < 48 || charCode > 57) && charCode != 45) {
   evt.preventDefault();
}

This way only valid key inputs will appear in text box.


问:
Windows CLI use FINDSTR to return only everything after the string
I have my CLI query set to:

```<code>c:\>findstr /c:"TOTAL" Invoice.txt
TOTAL 80:00
</code>```

However I only want the search query to return everything after the query:

```<code>80.00
</code>```

Also if I use wild in the filename it returns the whole file name then the line. I want it again to only return everything after the string and not the filename as I want to pipe the results into a text file.

```<code>c:\>findstr /c:"TOTAL" *.txt
Invoice - Copy (2).txt:TOTAL 120.00
Invoice - Copy (3).txt:TOTAL 110.00
Invoice - Copy (4).txt:TOTAL 100.00
Invoice - Copy.txt:TOTAL 90.00
Invoice.txt:TOTAL 80.00
</code>```

Ideally I run my command and just get the following

```<code>120.00
110.00
100.00
90.00
80.00
</code>```

Ideas on how to do this? Powershell or CMD is fine. At the moment I am going to put it all into a batch script but a ps script would work.

Thanks!

Body:
I have my CLI query set to:

c:\>findstr /c:"TOTAL" Invoice.txt
TOTAL 80:00

However I only want the search query to return everything after the query:

80.00

Also if I use wild in the filename it returns the whole file name then the line. I want it again to only return everything after the string and not the filename as I want to pipe the results into a text file.

c:\>findstr /c:"TOTAL" *.txt
Invoice - Copy (2).txt:TOTAL 120.00
Invoice - Copy (3).txt:TOTAL 110.00
Invoice - Copy (4).txt:TOTAL 100.00
Invoice - Copy.txt:TOTAL 90.00
Invoice.txt:TOTAL 80.00

Ideally I run my command and just get the following

120.00
110.00
100.00
90.00
80.00

Ideas on how to do this? Powershell or CMD is fine. At the moment I am going to put it all into a batch script but a ps script would work.

Thanks!

Body:
Also easy in PowerShell.

PS C:\src\t> Get-Content .\Invoice.txt | Where-Object { $_ -match '.*TOTAL (.*)' } | % { $matches[1] }
120.00
110.00
100.00
90.00
80.00

PS C:\src\t> cat .\Invoice.txt | where { $_ -match '.*TOTAL (.*)' } | % { $matches[1] }
120.00
110.00
100.00
90.00
80.00


问:
When tracing in Haskell, how does one `show` a value whose data type is not known at compile-time?
I am using GHC version 8.0.2 on Windows 7, & module Debug.Trace.
 In the trace of the parse function below, my insertion of ++ show first results in the following error:

No instance for (Show a) arising from a use of `show'
Possible fix:
add (Show a) to the context of
  the type signature for:
    parse :: Parser a -> String -> [(a, String)]

In the first argument of (++)', namelyshow first'
In the second argument of (++)', namely
show first ++ "," ++ show second ++ ")]"'
In the second argument of (++)', namely
" -> [(" ++ show first ++ "," ++ show second ++ ")]"'

My question: is there a way to show the first element of the ordered pair (a,String) even though its type is not known at compile-time?

My source code is shown below:

```<code>{-# LANGUAGE MonomorphismRestriction #-}

import Data.Typeable
import Data.Char
import Debug.Trace

newtype Parser a = P ( String -> [(a,String)] )

parse :: Parser a -> String -> [(a,String)]
parse (P p) input | trace
  ( let result  = (p input)
        element = head result
        first   = fst element
        second  = snd element
    in  ("parse maps " ++ input ++ " -> [(" ++ show first ++ "," ++ show second ++ ")]")
  ) False = undefined
parse (P p) input = p input

nextChar :: Parser Char
nextChar = P ( \input -> case input of { [] -> [] ; (c:cs) -> [(c,cs)] } )
</code>```

I am hoping to trace evaluation of parse nextChar "ABCD".

答:
Yes, sure, just follow the instructions in the error:

```<code>parse :: Show a => Parser a -> String -> [(a,String)]
</code>```

Once you're done debugging, you can delete the call to trace and the Show constraint; then you'll be able to parse un-Showable things again.

Body:
I am using GHC version 8.0.2 on Windows 7, & module Debug.Trace.
 In the trace of the parse function below, my insertion of ++ show first results in the following error:

No instance for (Show a) arising from a use of `show'
Possible fix:
add (Show a) to the context of
  the type signature for:
    parse :: Parser a -> String -> [(a, String)]

In the first argument of (++)', namelyshow first'
In the second argument of (++)', namely
show first ++ "," ++ show second ++ ")]"'
In the second argument of (++)', namely
" -> [(" ++ show first ++ "," ++ show second ++ ")]"'

My question: is there a way to show the first element of the ordered pair (a,String) even though its type is not known at compile-time?

My source code is shown below:

{-# LANGUAGE MonomorphismRestriction #-}

import Data.Typeable
import Data.Char
import Debug.Trace

newtype Parser a = P ( String -> [(a,String)] )

parse :: Parser a -> String -> [(a,String)]
parse (P p) input | trace
  ( let result  = (p input)
        element = head result
        first   = fst element
        second  = snd element
    in  ("parse maps " ++ input ++ " -> [(" ++ show first ++ "," ++ show second ++ ")]")
  ) False = undefined
parse (P p) input = p input

nextChar :: Parser Char
nextChar = P ( \input -> case input of { [] -> [] ; (c:cs) -> [(c,cs)] } )

I am hoping to trace evaluation of parse nextChar "ABCD".

Body:
Yes, sure, just follow the instructions in the error:

parse :: Show a => Parser a -> String -> [(a,String)]

Once you're done debugging, you can delete the call to trace and the Show constraint; then you'll be able to parse un-Showable things again.


问:
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!

答: All XML resources are compiled into binary format for performance reasons. SO you would not be able to see them.</p>

ContentLicense: CC BY-SA 2.5

Title: How to update resources file in .apk


问:
Assign buses to routes base on their capacity
I am facing problem in assigning buses to routes. I have four buses and four routes with their capacities.

Bus capacity is the number of seats in each bus. Route capacity is number of people on each stop of a route. Route is actually a combination of multiple stops.

An example of a single test case is:

```<code>BUS CAPACITY          ROUTE CAPACITY
BUS 1 44 Seats        Route 1 30 Peoples
BUS 2 63 Seats        Route 2 50 Peoples
BUS 3 14 Seats        Route 3 40 Peoples
BUS 4 17 Seats        Route 4 17 Peoples
</code>```

There is a lot of test cases with multiple combinations for this problem. The numbers of routes and buses are always equal.

I am looking for a algorithm that helps out in solve this problem optimally.

答:
Try

https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm

or

https://en.wikipedia.org/wiki/Euclidean_distance

approaches basically you are looking for best match.

In layman's terms what you might want to do is find the best matching route to a bus where best matching is defined as where the bus capacity to route capacity is optimal i.e. busCapacity - routeCapacity is lowest positive number.

Once you find such matches they will be eliminated from the problem world.

Then repeat this for the remaining world.

The end product is that everything is matched.

However prepare of the unexpected:-

You may exhaust all the possible combination and left with smaller capacity and bigger route capacity. In this case you look for difference between  i.e.  routeCapacity - busCapacity to be least as the best match.

This is so that the number of people you gave to let know that they can't be served is minimal.

Body:
I am facing problem in assigning buses to routes. I have four buses and four routes with their capacities.

Bus capacity is the number of seats in each bus. Route capacity is number of people on each stop of a route. Route is actually a combination of multiple stops.

An example of a single test case is:

BUS CAPACITY          ROUTE CAPACITY
BUS 1 44 Seats        Route 1 30 Peoples
BUS 2 63 Seats        Route 2 50 Peoples
BUS 3 14 Seats        Route 3 40 Peoples
BUS 4 17 Seats        Route 4 17 Peoples

There is a lot of test cases with multiple combinations for this problem. The numbers of routes and buses are always equal.

I am looking for a algorithm that helps out in solve this problem optimally.


问:
Error when I create an object in blackjack java
I'm trying to do a blackJack in java but i have a problem trying to create an object from a class. The code is:

Participant: This class generate a hand for player and croupier.

```<code>public abstract class Participant {

protected Carta[] madecartes;
protected int sumacartes;
protected boolean plantat;

public Participant(Carta[] madecartes){
    this.madecartes = madecartes;
}
public int sumaCartes(){
    for(int i = 0; i< madecartes.length;i++){
        int sumacartes = madecartes[i].getValor();
    }
    return sumacartes;
}
}
</code>```

Player:

```<code>public class Jugador extends Participant {
private String nom;
public Jugador(Carta[] madecartes,String nom){
    super(madecartes);
    this.nom = nom;
    this.madecartes=madecartes;
}
public void setNom(){
    this.nom=nom;
}
public String getNom(){
    return this.nom;
}
}
</code>```

How can i create an object of Player(jugador) here:

```<code>public class BlackJack {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    BlackJack bj = new BlackJack();
    bj.inici();
}
public void inici(){
    Jugador j = new Jugador(madecartes,"nom");   <- error
}
}
</code>```

答:
Your class Jugador has a constructor like this Jugador(Carta[] madecartes,String nom) so you need to pass an array of Carta in the constructor:

```<code>public void inici(){
    Jugador j = new Jugador(new Carta[]{myCarta1, myCarta2,etc etc}, "nom");
}
</code>```

Body:
I'm trying to do a blackJack in java but i have a problem trying to create an object from a class. The code is:

Participant: This class generate a hand for player and croupier.

public abstract class Participant {

protected Carta[] madecartes;
protected int sumacartes;
protected boolean plantat;

public Participant(Carta[] madecartes){
    this.madecartes = madecartes;
}
public int sumaCartes(){
    for(int i = 0; i< madecartes.length;i++){
        int sumacartes = madecartes[i].getValor();
    }
    return sumacartes;
}
}

Player:

public class Jugador extends Participant {
private String nom;
public Jugador(Carta[] madecartes,String nom){
    super(madecartes);
    this.nom = nom;
    this.madecartes=madecartes;
}
public void setNom(){
    this.nom=nom;
}
public String getNom(){
    return this.nom;
}
}

How can i create an object of Player(jugador) here:

public class BlackJack {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    BlackJack bj = new BlackJack();
    bj.inici();
}
public void inici(){
    Jugador j = new Jugador(madecartes,"nom");   <- error
}
}

Body:
Your class Jugador has a constructor like this Jugador(Carta[] madecartes,String nom) so you need to pass an array of Carta in the constructor:

public void inici(){
    Jugador j = new Jugador(new Carta[]{myCarta1, myCarta2,etc etc}, "nom");
}


问:
webcomponents - hide dropdown menu on window.onclick
dropdown menu is created in shadowDOM

almost perfect,
but the problem is how to hide the dropdown menu when click on any where else in window

```<code>class NavComponent extends HTMLElement {
    constructor() {
        super();

        let template = document.currentScript.ownerDocument.querySelector('template');
        let clone = document.importNode(template.content, true);
        let root = this.attachShadow({ mode: 'open' });
        root.appendChild(clone);
    }

    connectedCallback() {
        let ddc = this.shadowRoot.querySelectorAll('.dropdowncontainer')
        let dd = this.shadowRoot.querySelectorAll('.dropdown');
        let ddc_length = ddc.length

        for (let index = 0; index < ddc_length; index++) {
            ddc[index].addEventListener('click', e => {
                dd[index].classList.toggle('show');
            });
        }

        /**   have to update the code ............ */
        window.onclick = function (event) {

        }  /**  END - have to update the code ............ */

    }
}

customElements.define('app-nav', NavComponent)
</code>```

please refer this demo for complete code

答:
The best solution, as @guitarino suggested is to define a dropdown menu custom element.

When the menu is clicked, call a (first) event handler that will show/hide the menu, and also add/remove a (second) dropdown event handler on window.

At its turn, the (second) dropdown event handler will call the first event handler only if the action is outside the custom element itself.

```<code>connectedCallback()
{
    //mousedown anywhere
    this.mouse_down = ev => !this.contains( ev.target ) && toggle_menu()

    //toggle menu and window listener
    var toggle_menu = () =>
    {
        if ( this.classList.toggle( 'show' ) )
            window.addEventListener( 'mousedown', this.mouse_down )
        else
            window.removeEventListener( 'mousedown', this.mouse_down )
    }

    //click on menu
    this.addEventListener( 'click', toggle_menu )
}
</code>```

It works with or without Shadow DOM:

customElements.define( 'drop-menu', class extends HTMLElement
{
  constructor ()
  {
    super()
    this.attachShadow( { mode: 'open'} )
        .innerHTML = '<slot></slot>'
  }

  connectedCallback()
  {
    //mousedown anywhere
    this.mouse_down = ev => !this.contains( ev.target ) && toggle_menu()

    //toggle menu and window listener
    var toggle_menu = () =>
    {
      if ( this.classList.toggle( 'show' ) )
        window.addEventListener( 'mousedown', this.mouse_down )
      else
        window.removeEventListener( 'mousedown', this.mouse_down )
    }

    //click on menu
    this.addEventListener( 'click', toggle_menu )
  }

  disconnectedCallback ()
  {
    this.removeEventListener( 'mousedown', this.mouse_down )
  }
} )```
<pre class="snippet-code-css lang-css prettyprint-override"><code>drop-menu  {
    position: relative ;
    cursor: pointer ;
    display: inline-block ;
}

drop-menu > output {
    border: 1px solid #ccc ;
    padding: 2px 5px ;
}

drop-menu > ul {
    box-sizing: content-box ;
    position: absolute ;
    top: 2px ; left: 5px ;
    width: 200px;
    list-style: none ;
    border: 1px solid #ccc ;
    padding: 0 ;
    opacity: 0 ;
    transition: all 0.2s ease-in-out ;
    background: white ;
    visibility: hidden ;
    z-index: 2 ;

}

drop-menu.show  > ul {
    opacity: 1 ;
    visibility: visible ;
}

drop-menu > ul > li {
    overflow: hidden ;
    transition: font 0.2s ease-in-out ;
    padding: 2px 5px ;
    background-color: #e7e7e7;
}

drop-menu:hover {
    cursor: pointer;
    background-color: #f2f2f2;
}

drop-menu  ul li:hover {
    background-color: #e0e0e0;
}

drop-menu ul li span {
    float: right;
    color: #f9f9f9;
    background-color: #f03861;
    padding: 2px 5px;
    border-radius: 3px;
    text-align: center;
    font-size: .8rem;
}

drop-menu ul li:hover span {
    background-color: #ee204e;
}</code>```

<drop-menu><output>Services</output>

Graphic desing

web design

app design

theme

</drop-menu>
<drop-menu><output>tutorial</output>

css 12 available

php 10 available

javascript 40 available

html 20 available

</drop-menu>```

Body:
dropdown menu is created in shadowDOM

almost perfect,
but the problem is how to hide the dropdown menu when click on any where else in window

class NavComponent extends HTMLElement {
    constructor() {
        super();

        let template = document.currentScript.ownerDocument.querySelector('template');
        let clone = document.importNode(template.content, true);
        let root = this.attachShadow({ mode: 'open' });
        root.appendChild(clone);
    }

    connectedCallback() {
        let ddc = this.shadowRoot.querySelectorAll('.dropdowncontainer')
        let dd = this.shadowRoot.querySelectorAll('.dropdown');
        let ddc_length = ddc.length

        for (let index = 0; index < ddc_length; index++) {
            ddc[index].addEventListener('click', e => {
                dd[index].classList.toggle('show');
            });
        }

        /**   have to update the code ............ */
        window.onclick = function (event) {

        }  /**  END - have to update the code ............ */

    }
}

customElements.define('app-nav', NavComponent)

please refer this demo for complete code

Body:
The best solution, as @guitarino suggested is to define a dropdown menu custom element.

When the menu is clicked, call a (first) event handler that will show/hide the menu, and also add/remove a (second) dropdown event handler on window.

At its turn, the (second) dropdown event handler will call the first event handler only if the action is outside the custom element itself.

connectedCallback()
{
    //mousedown anywhere
    this.mouse_down = ev => !this.contains( ev.target ) && toggle_menu()

    //toggle menu and window listener
    var toggle_menu = () =>
    {
        if ( this.classList.toggle( 'show' ) )
            window.addEventListener( 'mousedown', this.mouse_down )
        else
            window.removeEventListener( 'mousedown', this.mouse_down )
    }

    //click on menu
    this.addEventListener( 'click', toggle_menu )
}

It works with or without Shadow DOM:

customElements.define( 'drop-menu', class extends HTMLElement
{
  constructor ()
  {
    super()
    this.attachShadow( { mode: 'open'} )
        .innerHTML = '<slot></slot>'
  }

  connectedCallback()
  {
    //mousedown anywhere
    this.mouse_down = ev => !this.contains( ev.target ) && toggle_menu()

    //toggle menu and window listener
    var toggle_menu = () =>
    {
      if ( this.classList.toggle( 'show' ) )
        window.addEventListener( 'mousedown', this.mouse_down )
      else
        window.removeEventListener( 'mousedown', this.mouse_down )
    }

    //click on menu
    this.addEventListener( 'click', toggle_menu )
  }

  disconnectedCallback ()
  {
    this.removeEventListener( 'mousedown', this.mouse_down )
  }
} )

drop-menu  {
    position: relative ;
    cursor: pointer ;
    display: inline-block ;
}

drop-menu > output {
    border: 1px solid #ccc ;
    padding: 2px 5px ;
}

drop-menu > ul {
    box-sizing: content-box ;
    position: absolute ;
    top: 2px ; left: 5px ;
    width: 200px;
    list-style: none ;
    border: 1px solid #ccc ;
    padding: 0 ;
    opacity: 0 ;
    transition: all 0.2s ease-in-out ;
    background: white ;
    visibility: hidden ;
    z-index: 2 ;

}

drop-menu.show  > ul {
    opacity: 1 ;
    visibility: visible ;
}

drop-menu > ul > li {
    overflow: hidden ;
    transition: font 0.2s ease-in-out ;
    padding: 2px 5px ;
    background-color: #e7e7e7;
}

drop-menu:hover {
    cursor: pointer;
    background-color: #f2f2f2;
}

drop-menu  ul li:hover {
    background-color: #e0e0e0;
}

drop-menu ul li span {
    float: right;
    color: #f9f9f9;
    background-color: #f03861;
    padding: 2px 5px;
    border-radius: 3px;
    text-align: center;
    font-size: .8rem;
}

drop-menu ul li:hover span {
    background-color: #ee204e;
}

<drop-menu><output>Services</output>
  <ul>
    <li>Graphic desing</li>
    <li>web design</li>
    <li>app design</li>
    <li>theme</li>
  </ul>
</drop-menu>
<drop-menu><output>tutorial</output>
  <ul>
    <li>css <span>12 available</span></li>
    <li>php <span>10 available</span></li>
    <li>javascript <span>40 available</span></li>
    <li>html <span>20 available</span></li>
  </ul>
</drop-menu>


问:
How do I make my app confirm that the user wants to delete something using one of those notification boxes?
This is probably a very simple question, but here it is:  how do I make it so that when a user taps "Discard" (in the navigation bar) a little box pops up that makes him confirm that he wants to discard what he's working on?  I would like it to look like that notification box that tells you you're out of storage in the built in camera app, but instead, have it say something like "Are you sure you want to discard this layout?" and then have one button be "yes" and the other be "no".  What is the code for doing this?  I am using Swift.</p>

答:
You are looking for UIAlertController. Here's a example:

```<code>let alertController = UIAlertController(title: "Title Text",
                                           message: "Message Text",
                                    preferredStyle: UIAlertControllerStyle.alert)

let okButton = UIAlertAction(title: "OK",
                                    style: .default,
                                  handler: { (action:UIAlertAction!) in
     //do your action here
})
alertController.addAction(okButton)

let cancelButton = UIAlertAction(title: "Cancel", style: .cancel, handler: { (action:UIAlertAction!) in
    })
alertController.addAction(cancelButton)

self.present(alertController, animated: true, completion:nil)
</code>```

Body:
You are looking for UIAlertController. Here's a example:

let alertController = UIAlertController(title: "Title Text",
                                           message: "Message Text",
                                    preferredStyle: UIAlertControllerStyle.alert)

let okButton = UIAlertAction(title: "OK",
                                    style: .default,
                                  handler: { (action:UIAlertAction!) in
     //do your action here
})
alertController.addAction(okButton)

let cancelButton = UIAlertAction(title: "Cancel", style: .cancel, handler: { (action:UIAlertAction!) in
    })
alertController.addAction(cancelButton)

self.present(alertController, animated: true, completion:nil)


问:
RAII vs. Garbage Collector
I recently watched a great talk by Herb Sutter about "Leak Free C++..." at CppCon 2016 where he talked about using smart pointers to implement RAII (Resource acquisition is initialization) - Concepts and how they solve most of the memory leaks issues.

Now I was wondering. If I strictly follow RAII rules, which seems to be a good thing, why would that be any different from having a garbage collector in C++? I know that with RAII the programmer is in full control of when the resources are freed again, but is that in any case beneficial to just having a garbage collector? Would it really be less efficient? I even heard that having a garbage collector can be more efficient, as it can free larger chunks of memory at a time instead of freeing small memory pieces all over the code.

答:
Garbage collection and RAII each support one common construct for which the other is not really suitable.

In a garbage-collected system, code may efficiently treat references to immutable objects (such as strings) as proxies for the data contained therein; passing around such references is almost as cheap as passing around "dumb" pointers, and is faster than making a separate copy of the data for each owner, or trying to track ownership of a shared copy of the data.  In addition, garbage-collected systems make it easy to create immutable object types by writing a class which creates a mutable object, populating it as desired, and providing accessor methods, all while refraining from leaking references to anything that might mutate it once the constructor finishes.  In cases where references to immutable objects need to be widely copied but the objects themselves don't, GC beats RAII hands down.

On the other hand, RAII is excellent at handling situations where an object needs to acquire exclusive services from outside entities.  While many GC systems allow objects to define "Finalize" methods and request notification when they are found to be abandoned, and such methods may sometimes manage to release outside services that are no longer needed, they are seldom reliable enough to provide a satisfactory way of ensuring timely release of outside services.  For management of non-fungible outside resources, RAII beats GC hands down.

The key difference between the cases where GC wins versus those where RAII wins is that GC is good at managing fungible memory that can be freed on an as-needed basis, but poor at handling non-fungible resources.  RAII is good at handling objects with clear ownership, but bad at handling ownerless immutable data holders which have no real identity apart from the data they contain.

Because neither GC nor RAII handles all scenarios well, it would be helpful for languages to provide good support for both of them.  Unfortunately, languages which focus on one tend to treat the other as an afterthought.

Title: RAII vs. Garbage Collector


问:
Compile Linux kernel module (lincan)
I use Ubuntu 10.10 - 2.6.35.23-generic

I want to compile the lincan-module (http://sourceforge.net/projects/ocera/), but it doesn't work like I want... That's my first compilation of a kernel module. I did this:

First unzipped the lincan-sources to my home directory. Then excecuted "make" with this output:

```<code>make -C /home/x/can/lincan-0.3.4/src SOURCES_DIR=/home/x/can/lincan-0.3.4/src default ;   make -C /home/x/can/lincan-0.3.4/utils SOURCES_DIR=/home/x/can/lincan-0.3.4/utils default ;
awk: cannot open /lib/modules/2.6.35-23-generic/build/include/linux/autoconf.h (No such file or directory)
awk: cannot open /lib/modules/2.6.35-23-generic/build/include/linux/autoconf.h (No such file or directory)
grep: /lib/modules/2.6.35-23-generic/build/include/linux/utsrelease.h: No such file or directory
make[1]: Betrete Verzeichnis '/home/x/can/lincan-0.3.4/src'
Makefile:216: /lib/modules/2.6.35-23-generic/build/Rules.make: No such file or directory
make[1]: *** Keine Regel, um »/lib/modules/2.6.35-23-generic/build/Rules.make« zu erstellen.  Schluss.
make[1]: Verlasse Verzeichnis '/home/x/can/lincan-0.3.4/src'
make[1]: Betrete Verzeichnis '/home/x/can/lincan-0.3.4/utils'
cc -I../include -O2 -Wall   -c -o rxtx.o rxtx.c
rxtx.c: In function ‘main’:
rxtx.c:49: warning: format not a string literal and no format arguments
rxtx.c:73: warning: format not a string literal and no format arguments
rxtx.c:51: warning: ignoring return value of ‘fgets’, declared with attribute warn_unused_result
rxtx.c:58: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result
rxtx.c:62: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result
rxtx.c:67: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result
rxtx.c:75: warning: ignoring return value of ‘fgets’, declared with attribute warn_unused_result
rxtx.c:81: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result
cc   rxtx.o   -o rxtx
cc -I../include -O2 -Wall   -c -o sendburst.o sendburst.c
cc   sendburst.o   -o sendburst
cc -I../include -O2 -Wall   -c -o readburst.o readburst.c
cc   readburst.o   -o readburst
cc -I../include -O2 -Wall   -c -o send.o send.c
send.c: In function ‘main’:
send.c:25: warning: format not a string literal and no format arguments
send.c:27: warning: ignoring return value of ‘fgets’, declared with attribute warn_unused_result
send.c:33: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result
send.c:35: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result
send.c:40: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result
cc   send.o   -o send
cc -I../include -O2 -Wall    can-proxy.c   -o can-proxy
make[1]: Verlasse Verzeichnis '/home/x/can/lincan-0.3.4/utils'
</code>```

Then I type "make install":

```<code>make -C /home/x/can/lincan-0.3.4/src SOURCES_DIR=/home/x/can/lincan-0.3.4/src install ;   make -C /home/x/can/lincan-0.3.4/utils SOURCES_DIR=/home/x/can/lincan-0.3.4/utils install ;
awk: cannot open /lib/modules/2.6.35-23-generic/build/include/linux/autoconf.h (No such file or directory)
awk: cannot open /lib/modules/2.6.35-23-generic/build/include/linux/autoconf.h (No such file or directory)
grep: /lib/modules/2.6.35-23-generic/build/include/linux/utsrelease.h: No such file or directory
make[1]: Betrete Verzeichnis '/home/x/can/lincan-0.3.4/src'
Makefile:216: /lib/modules/2.6.35-23-generic/build/Rules.make: No such file or directory
make[1]: *** Keine Regel, um »/lib/modules/2.6.35-23-generic/build/Rules.make« zu erstellen.  Schluss.
make[1]: Verlasse Verzeichnis '/home/x/can/lincan-0.3.4/src'
make[1]: Betrete Verzeichnis '/home/x/can/lincan-0.3.4/utils'
echo Nothing to install
Nothing to install
make[1]: Verlasse Verzeichnis '/home/x/can/lincan-0.3.4/utils'
</code>```

And it happend nothing. I find no kernel module. What did I wrong? Why is there no autoconf.h and the other files? Have you any hints for me? Thanks!

Now I created hardlinks for the missing files (autoconf.h and utsrelease.h). They are in /usr/src/linux-headers-2.6.35.23-generic/include/generated/

Now it compile much more. This is the first error that appears:

```<code>In file included from /home/x/can/lincan-0.3.4/src/../include/main.h:38,
                 from /home/x/can/lincan-0.3.4/src/proc.c:37:
/home/x/can/lincan-0.3.4/src/../include/./can_queue.h: In function ‘canque_edge_decref’:
/home/x/can/lincan-0.3.4/src/../include/./can_queue.h:652: error: invalid initializer
/home/x/can/lincan-0.3.4/src/../include/./can_queue.h:652: error: invalid initializer
/home/x/can/lincan-0.3.4/src/../include/./can_queue.h:652: error: incompatible types when assigning to type ‘int’ from type ‘atomic_t’
make[3]: *** [/home/x/can/lincan-0.3.4/src/proc.o] Fehler 1
make[2]: *** [_module_/home/x/can/lincan-0.3.4/src] Fehler 2
make[2]: Verlasse Verzeichnis '/usr/src/linux-headers-2.6.35-23-generic'
make[1]: *** [make_this_module] Fehler 2
</code>```

答: Please install kernel build prerequisites given here. This would install necessary tools for building/compiling the kernel modules.</p>

Title: Compile Linux kernel module (lincan)

Body:
I use Ubuntu 10.10 - 2.6.35.23-generic

I want to compile the lincan-module (http://sourceforge.net/projects/ocera/), but it doesn't work like I want... That's my first compilation of a kernel module. I did this:

First unzipped the lincan-sources to my home directory. Then excecuted "make" with this output:

make -C /home/x/can/lincan-0.3.4/src SOURCES_DIR=/home/x/can/lincan-0.3.4/src default ;   make -C /home/x/can/lincan-0.3.4/utils SOURCES_DIR=/home/x/can/lincan-0.3.4/utils default ;
awk: cannot open /lib/modules/2.6.35-23-generic/build/include/linux/autoconf.h (No such file or directory)
awk: cannot open /lib/modules/2.6.35-23-generic/build/include/linux/autoconf.h (No such file or directory)
grep: /lib/modules/2.6.35-23-generic/build/include/linux/utsrelease.h: No such file or directory
make[1]: Betrete Verzeichnis '/home/x/can/lincan-0.3.4/src'
Makefile:216: /lib/modules/2.6.35-23-generic/build/Rules.make: No such file or directory
make[1]: *** Keine Regel, um »/lib/modules/2.6.35-23-generic/build/Rules.make« zu erstellen.  Schluss.
make[1]: Verlasse Verzeichnis '/home/x/can/lincan-0.3.4/src'
make[1]: Betrete Verzeichnis '/home/x/can/lincan-0.3.4/utils'
cc -I../include -O2 -Wall   -c -o rxtx.o rxtx.c
rxtx.c: In function ‘main’:
rxtx.c:49: warning: format not a string literal and no format arguments
rxtx.c:73: warning: format not a string literal and no format arguments
rxtx.c:51: warning: ignoring return value of ‘fgets’, declared with attribute warn_unused_result
rxtx.c:58: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result
rxtx.c:62: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result
rxtx.c:67: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result
rxtx.c:75: warning: ignoring return value of ‘fgets’, declared with attribute warn_unused_result
rxtx.c:81: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result
cc   rxtx.o   -o rxtx
cc -I../include -O2 -Wall   -c -o sendburst.o sendburst.c
cc   sendburst.o   -o sendburst
cc -I../include -O2 -Wall   -c -o readburst.o readburst.c
cc   readburst.o   -o readburst
cc -I../include -O2 -Wall   -c -o send.o send.c
send.c: In function ‘main’:
send.c:25: warning: format not a string literal and no format arguments
send.c:27: warning: ignoring return value of ‘fgets’, declared with attribute warn_unused_result
send.c:33: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result
send.c:35: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result
send.c:40: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result
cc   send.o   -o send
cc -I../include -O2 -Wall    can-proxy.c   -o can-proxy
make[1]: Verlasse Verzeichnis '/home/x/can/lincan-0.3.4/utils'

Then I type "make install":

make -C /home/x/can/lincan-0.3.4/src SOURCES_DIR=/home/x/can/lincan-0.3.4/src install ;   make -C /home/x/can/lincan-0.3.4/utils SOURCES_DIR=/home/x/can/lincan-0.3.4/utils install ;
awk: cannot open /lib/modules/2.6.35-23-generic/build/include/linux/autoconf.h (No such file or directory)
awk: cannot open /lib/modules/2.6.35-23-generic/build/include/linux/autoconf.h (No such file or directory)
grep: /lib/modules/2.6.35-23-generic/build/include/linux/utsrelease.h: No such file or directory
make[1]: Betrete Verzeichnis '/home/x/can/lincan-0.3.4/src'
Makefile:216: /lib/modules/2.6.35-23-generic/build/Rules.make: No such file or directory
make[1]: *** Keine Regel, um »/lib/modules/2.6.35-23-generic/build/Rules.make« zu erstellen.  Schluss.
make[1]: Verlasse Verzeichnis '/home/x/can/lincan-0.3.4/src'
make[1]: Betrete Verzeichnis '/home/x/can/lincan-0.3.4/utils'
echo Nothing to install
Nothing to install
make[1]: Verlasse Verzeichnis '/home/x/can/lincan-0.3.4/utils'

And it happend nothing. I find no kernel module. What did I wrong? Why is there no autoconf.h and the other files? Have you any hints for me? Thanks!

Now I created hardlinks for the missing files (autoconf.h and utsrelease.h). They are in /usr/src/linux-headers-2.6.35.23-generic/include/generated/

Now it compile much more. This is the first error that appears:

In file included from /home/x/can/lincan-0.3.4/src/../include/main.h:38,
                 from /home/x/can/lincan-0.3.4/src/proc.c:37:
/home/x/can/lincan-0.3.4/src/../include/./can_queue.h: In function ‘canque_edge_decref’:
/home/x/can/lincan-0.3.4/src/../include/./can_queue.h:652: error: invalid initializer
/home/x/can/lincan-0.3.4/src/../include/./can_queue.h:652: error: invalid initializer
/home/x/can/lincan-0.3.4/src/../include/./can_queue.h:652: error: incompatible types when assigning to type ‘int’ from type ‘atomic_t’
make[3]: *** [/home/x/can/lincan-0.3.4/src/proc.o] Fehler 1
make[2]: *** [_module_/home/x/can/lincan-0.3.4/src] Fehler 2
make[2]: Verlasse Verzeichnis '/usr/src/linux-headers-2.6.35-23-generic'
make[1]: *** [make_this_module] Fehler 2


问:
Retrieve Value of Arbitrary Button OnClick
My attempt

HTML:

```<code><button class="btn btn-info">7</button>
</code>```

Jquery:

```<code>$(document).ready(() => {
  $('button').click(() => {
     console.log($(this));
     console.log($(this).html());
     console.log($(this).val());
  });
});
</code>```

Desired result:

7

答:
You can use .text():

```<code>$(this).text()
</code>```

$('button').on('click', function(e) {
        console.log($(this).text());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<button class="btn btn-info">7</button></code>```

Body:
My attempt

HTML:

<button class="btn btn-info">7</button>

Jquery:

$(document).ready(() => {
  $('button').click(() => {
     console.log($(this));
     console.log($(this).html());
     console.log($(this).val());
  });
});

Desired result:

7

Body:
You can use .text():

$(this).text()

$('button').on('click', function(e) {
        console.log($(this).text());
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<button class="btn btn-info">7</button>


问:
Lambda variable names - to short name, or not to short name?
Typically, when I use lambdas, I just use "a, b, c, d..." as variable names as the types are easily inferred, and I find short names to be easier to read.  Here is an example:

```<code>var someEnumerable = GetSomeEnumerable();
var somethingElseList = someEnumerable.Select(a => a.SomeProperty)
                                      .OrderBy(a => a.SomePropertyField);
var someDictionary = somethingElseList.ToDictionary(a => new SomeClass(a.Prop1),
                                                    a => a);
</code>```

Some question this naming, and would prefer to see long typed out names, like this:

```<code>var someEnumerable = GetSomeEnumerable();
var somethingElseList = someEnumerable.Select(importantObj => importantObj.SomeProperty)
                                      .OrderBy(objsInfo => objsInfo.SomePropertyField);
var someDictionary = somethingElseList.ToDictionary(theInfoId => new SomeClass(theInfoId.Prop1),
                                                    theInfoId2 => theInfoId2);
</code>```

Since the scope is so narrow (between the parens), unless you're getting stupid and nesting them, I find it easier to read short names.

Without getting caught up in the silly naming examples I used above, what is the general consensus on Lambda variable names?  To short name, or not to short name?

答:
I try to use single-word but meaningful names. So I would tend to use "person" rather than "p" but wouldn't go for "newlyAddedPerson".

This goes for query expressions as well - I may well violate this in quick throwaway examples, but I don't generally like:

```<code>from p in source
where p.Age > 10
select p.Name;
</code>```

I'd far rather see

```<code>from person in source
where person.Age > 10
select person.Name;
</code>```

OwnerDisplayName: TheSoftwareJedi

Body:
Typically, when I use lambdas, I just use "a, b, c, d..." as variable names as the types are easily inferred, and I find short names to be easier to read.  Here is an example:

var someEnumerable = GetSomeEnumerable();
var somethingElseList = someEnumerable.Select(a => a.SomeProperty)
                                      .OrderBy(a => a.SomePropertyField);
var someDictionary = somethingElseList.ToDictionary(a => new SomeClass(a.Prop1),
                                                    a => a);

Some question this naming, and would prefer to see long typed out names, like this:

var someEnumerable = GetSomeEnumerable();
var somethingElseList = someEnumerable.Select(importantObj => importantObj.SomeProperty)
                                      .OrderBy(objsInfo => objsInfo.SomePropertyField);
var someDictionary = somethingElseList.ToDictionary(theInfoId => new SomeClass(theInfoId.Prop1),
                                                    theInfoId2 => theInfoId2);

Since the scope is so narrow (between the parens), unless you're getting stupid and nesting them, I find it easier to read short names.

Without getting caught up in the silly naming examples I used above, what is the general consensus on Lambda variable names?  To short name, or not to short name?

LastEditorDisplayName: TheSoftwareJedi

Body:
I try to use single-word but meaningful names. So I would tend to use "person" rather than "p" but wouldn't go for "newlyAddedPerson".

This goes for query expressions as well - I may well violate this in quick throwaway examples, but I don't generally like:

from p in source
where p.Age > 10
select p.Name;

I'd far rather see

from person in source
where person.Age > 10
select person.Name;

OwnerDisplayName: Jon Skeet


问:
Ascertaining the highest power of 2 for a given integer
When I run this method with n = 64, it gives me x = 64, but instead of running the if statement it runs the else statement. The actual answer needs to be 32, but it returns 64.</p>
```<code>/**
 * Complete the method to find the largest power of 2 less than the given number
 * Use a loop
 */

public class MathUtil {
  public int largestPowerOf2(int n) {
    // TODO: implement this method.
    int i = 0;
    while(n > 1) {
      n = n / 2;
      i ++;
    }
    System.out.printf("i = %d\n" , i);
    int x = (int)Math.pow(2,i);
    System.out.println(x);
    if(x == n) {
      return (int)Math.pow(2,i - 1);
    } else {
      return (int)Math.pow(2, i);
    }
  }
}
</code>```

答:
This should work.</p>

```<code>public int largestPowerOf2(int n){

    return Integer.highestOneBit(n-1);

}
</code>```

Body:
When I run this method with n = 64, it gives me x = 64, but instead of running the if statement it runs the else statement. The actual answer needs to be 32, but it returns 64.

/**
 * Complete the method to find the largest power of 2 less than the given number
 * Use a loop
 */

public class MathUtil {
  public int largestPowerOf2(int n) {
    // TODO: implement this method.
    int i = 0;
    while(n > 1) {
      n = n / 2;
      i ++;
    }
    System.out.printf("i = %d\n" , i);
    int x = (int)Math.pow(2,i);
    System.out.println(x);
    if(x == n) {
      return (int)Math.pow(2,i - 1);
    } else {
      return (int)Math.pow(2, i);
    }
  }
}

Body:
This should work.

public int largestPowerOf2(int n){

    return Integer.highestOneBit(n-1);

}


问:
Storing variable passed from node server to EJS file as input data for form
I'm trying to store a variable called from the server as the default value of a form. The for loop I used is correctly displaying all the data and even calling the data directly inside a paragraph is displaying the data. But I'm getting a "Cannot read property 'email' of undefined". All of this is in an .ejs file.

  // Testing retrieving email - Works

<%= garage[0].email %>

  // Function and Form to plugin email into form - Failing on undefined email

        <form action="http://ec2-52-23-218-165.compute-1.amazonaws.com:3000/admingarage" method="post">
          <input class="input" data-name="uname" id="myemail" maxlength="256" name="uname" type="email">
          <input class="btn-floating btn-large waves-effect waves-light red" data-wait="Please wait..." type="submit" name="action">replay</input>
        </form>

    // Displaying Garage - Works

            <% for(var i=0; i < garage.length; i++) {%>

                          Car <%= i + 1 %>

Year: <%= garage[i].year %>

Make: <%= garage[i].make %>

Model: <%= garage[i].model %>

Exterior: <%= garage[i].exterior %>

Interior:  <%= garage[i].interior %>

            <% } %>

```

答:
This should do the trick</p>

```<code>document.getElementById('myemail').value = <%- JSON.stringify(garage[0].email) %>;
</code>```

Body:
This should do the trick

document.getElementById('myemail').value = <%- JSON.stringify(garage[0].email) %>;


问:
codeigniter angular ajax file uploading return null value of file

Ajax file uploader using angular codeigniter return null value of file data

$http({
 method: 'POST',
 url: 'add',
 headers: {'Content-Type': false,'data-type': 'json'},

 data: $scope.setting
 }).success(function (data) {
 console.log(data);
 $scope.messageEdit = data;
 $scope.message="";
 });
```

<pre class="lang-html prettyprint-override"><code><form method="POST" enctype="multipart/form-data" ng-submit="submitForm()">
    Select File To Upload:<br />
    <input type="file" name="st_logo" ng-model="setting.file" />
    <br /><br />
    <input type="submit" name="submit" value="Upload"  class="btn btn-success" />
</form>
</code>```

答:
I got an  answer

var myFormData = new FormData();
 var photo=document.getElementById('st_logo');
 var file=photo.files[0];
 console.log(file.name+"   "+file.size);

myFormData.append("currency", $scope.setting.st_currency);
    myFormData.append('bgcolor', $scope.setting.st_billingbgcolor);
    myFormData.append('textcolor', $scope.setting.st_billingtextcolor);
 myFormData.append('logo',file );```

Body:
Ajax file uploader using angular codeigniter return null value of file data

$http({
 method: 'POST',
 url: 'add',
 headers: {'Content-Type': false,'data-type': 'json'},

 data: $scope.setting
 }).success(function (data) {
 console.log(data);
 $scope.messageEdit = data;
 $scope.message="";
 });

<form method="POST" enctype="multipart/form-data" ng-submit="submitForm()">
    Select File To Upload:

    <input type="file" name="st_logo" ng-model="setting.file" />

    <input type="submit" name="submit" value="Upload"  class="btn btn-success" />
</form>


问:
Confusion about Printing string arrays in C
This is probably a beginner question but it has been confusing me.  I understand that in c an array is itself a pointer to the first element of the array.  So consider the following example

```<code>char *words[LENGTH];
words[0] = "zero";
words[1] = "one";
words[2] = "two";
printf("%s\n",*words);
</code>```

What ends up printing is zero.  However, my understanding is that words is a pointer to the first element of the words array which is a char pointer => words is a pointer to a pointer to a char.  Therefore *words would be a pointer to char.  Therefore I would expect a memory address to be printed here and not an actual string.  What am I misunderstanding here?

答:
You are close in fact you are right, c-string are a pointer that contain the address of the first char of the string. The c-string is not the bytes but the address. And printf flag %s expect the address of these bytes. So you indeed give an address to printf() but you ask to printf() to show the value of the c-string. So "zero". Your only error is that you didn't read the manual of printf().

If you want the address try:

```<code>printf("%p\n", (void *)*words);
</code>```

Body:
This is probably a beginner question but it has been confusing me.  I understand that in c an array is itself a pointer to the first element of the array.  So consider the following example

char *words[LENGTH];
words[0] = "zero";
words[1] = "one";
words[2] = "two";
printf("%s\n",*words);

What ends up printing is zero.  However, my understanding is that words is a pointer to the first element of the words array which is a char pointer => words is a pointer to a pointer to a char.  Therefore *words would be a pointer to char.  Therefore I would expect a memory address to be printed here and not an actual string.  What am I misunderstanding here?

Body:
You are close in fact you are right, c-string are a pointer that contain the address of the first char of the string. The c-string is not the bytes but the address. And printf flag %s expect the address of these bytes. So you indeed give an address to printf() but you ask to printf() to show the value of the c-string. So "zero". Your only error is that you didn't read the manual of printf().

If you want the address try:

printf("%p\n", (void *)*words);


问:
Read all lines at the same time individually - Solaris ksh
I need some help with a script. Solaris 10 and ksh.

I Have a file called /temp.list with this content:

```<code>192.168.0.1
192.168.0.2
192.168.0.3
</code>```

So, I have a script which reads this list and executes some commands using the lines values:

```<code>FILE_TMP="/temp.list"
while IFS= read line
do
ping $line
done < "$FILE_TMP"
</code>```

It works, but it executes the command on line 1. When it's over, it goes to the line 2, and it goes successively until the end. I would like to find a way to execute the command ping at the same time in each line of the list. Is there a way to do it?

Thank you in advance!

Marcus Quintella

答:
As Ari's suggested, googling ksh multithreading will produce a lot of ideas/solutions.

A simple example:

```<code>FILE_TMP="/temp.list"
while IFS= read line
do
ping $line &
done < "$FILE_TMP"
</code>```

The trailing '&' says to kick the ping command off in the background, allowing loop processing to continue while the ping command is running in the background.

'course, this is just the tip of the proverbial iceberg as you now need to consider:

multiple ping commands are going to be dumping output to stdout (ie, you're going to get a mish-mash of ping output in your console), so you'll need to give some thought as to what to do with multiple streams of output (eg, redirect to a common file? redirect to separate files?)

you need to have some idea as to how you want to go about managing and (possibly) terminating commands running in the background [ see jobs, ps, fg, bg, kill ]

if running in a shell script you'll likely find yourself wanting to suspend the main shell script processing until all background jobs have completed [ see wait ]

Body:
I need some help with a script. Solaris 10 and ksh.

I Have a file called /temp.list with this content:

192.168.0.1
192.168.0.2
192.168.0.3

So, I have a script which reads this list and executes some commands using the lines values:

FILE_TMP="/temp.list"
while IFS= read line
do
ping $line
done < "$FILE_TMP"

It works, but it executes the command on line 1. When it's over, it goes to the line 2, and it goes successively until the end. I would like to find a way to execute the command ping at the same time in each line of the list. Is there a way to do it?

Thank you in advance!

Marcus Quintella

Body:
As Ari's suggested, googling ksh multithreading will produce a lot of ideas/solutions.

A simple example:

FILE_TMP="/temp.list"
while IFS= read line
do
ping $line &
done < "$FILE_TMP"

The trailing '&' says to kick the ping command off in the background, allowing loop processing to continue while the ping command is running in the background.

'course, this is just the tip of the proverbial iceberg as you now need to consider:

multiple ping commands are going to be dumping output to stdout (ie, you're going to get a mish-mash of ping output in your console), so you'll need to give some thought as to what to do with multiple streams of output (eg, redirect to a common file? redirect to separate files?)

you need to have some idea as to how you want to go about managing and (possibly) terminating commands running in the background [ see jobs, ps, fg, bg, kill ]

if running in a shell script you'll likely find yourself wanting to suspend the main shell script processing until all background jobs have completed [ see wait ]